Skip to content

Redirect Jellyfin image routes to upstream URLs - #101

Merged
Quick104 merged 3 commits into
mainfrom
codex/jellyfin-s3-images
Jun 9, 2026
Merged

Quick104 merged 3 commits into
mainfrom
codex/jellyfin-s3-images

Conversation

@Quick104

@Quick104 Quick104 commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Switch Jellyfin-compatible image responses from proxying to HTTP redirects
  • Remove the image proxy HTTP client and related header-copying logic
  • Keep upstream URL validation strict and add coverage for redirect behavior

Testing

  • Added unit tests for redirect handling and non-HTTP URL rejection
  • Updated image route tests to verify redirects instead of proxied responses

Summary by CodeRabbit

  • New Features

    • Image requests now typically return HTTP 302 redirects to resolved image URLs with no-store cache headers; select routes still proxy content when required.
    • JSON responses are rewritten for certain client compatibility, adjusting image tag fields and primary image references for better client support.
  • Bug Fixes

    • Upstream image failures are surfaced as upstream errors instead of silent failures.
  • Tests

    • Test suite updated to assert redirect behavior, headers, and tag/ID canonicalization.

@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Handlers now call serveImageURL which either proxies upstream bytes or issues an HTTP 302 redirect based on request classification. Adds redirectImageURL/parseRemoteImageURL, a compat image proxy route/ID scheme, middleware to rewrite image tags in JSON responses, tag canonicalization, codec/DTO updates, and tests adjusted for redirect behavior.

Changes

Image compat delivery to proxy-or-redirect with tag middleware

Layer / File(s) Summary
ImagesHandler: serveImageURL, redirectImageURL, and handler updates
internal/jellycompat/handlers_images.go
Adds serveImageURL to choose proxy vs redirect, implements redirectImageURL and parseRemoteImageURL, updates item/person image handlers to use serveImageURL, and reorders NewImagesHandler to accept httpClient last.
compat proxy routing, route IDs, and proxy response behavior
internal/jellycompat/images.go
Implements compat image proxy route/ID encoding/decoding, request-classification for proxying, selective conditional-header copying, and proxyImage behavior that enforces no-store route headers and maps upstream failures to 502.
Compat image-proxy tag variant middleware and JSON rewrites
internal/jellycompat/image_proxy_tags.go
New middleware buffers JSON GET responses for compat clients and rewrites image tag fields (PrimaryImageTag, ImageTag(s), ImageBlurHashes), and can inject PrimaryImageItemId proxy route IDs using the codec.
Codec, cache, DTO, and tag-signer adjustments
internal/jellycompat/idcodec.go, internal/jellycompat/image_cache.go, internal/jellycompat/dto.go, internal/jellycompat/image_tag_signer.go
Adds EncodedIDImageProxy constant, canonicalizes tags for ImageCache lookups, adds PrimaryImageItemID to DTO, and canonicalizes imageTagSigner.Equal input before comparison.
Updated image compat tests (redirect-focused)
internal/jellycompat/images_test.go
Reworks tests to assert 302 redirects with Cache-Control: no-store, adds TestRedirectImageURLRejectsNonHTTPURL and assertImageRedirect, and retains one proxy-path test that still expects proxied bytes and canonical-route caching.
Tests for compat image proxy tag middleware
internal/jellycompat/image_proxy_tags_test.go
Adds tests validating Infuse user-agent tag suffixing, non-Infuse passthrough, and numeric route canonicalization without registration.
Router wiring and Dependencies reordering/defaults
internal/jellycompat/router.go, internal/jellycompat/server.go
Installs compatImageProxyTagVariantMiddleware, removes passing deps.HTTPClient into NewImagesHandler wiring, reorders defaulting, and removes the default HTTPClient initialization from NewDependencies.

Sequence Diagram(s)

sequenceDiagram
  Client->>compatImageProxyTagVariantMiddleware: GET /api/... (JSON responses)
  compatImageProxyTagVariantMiddleware->>ImagesHandler: forwarded request (possibly wrapped)
  ImagesHandler->>ImageCache: lookup (tag/route canonicalization)
  ImagesHandler->>ImagesHandler: shouldProxyCompatImageRequest?
  alt proxy
    ImagesHandler->>HTTPClient: fetch upstream image (proxyImage)
    HTTPClient->>UpstreamOrigin: GET image URL
    UpstreamOrigin-->>HTTPClient: response (status, headers, body)
    HTTPClient-->>ImagesHandler: proxied response streamed
    ImagesHandler-->>Client: proxied bytes (no-store headers)
  else redirect
    ImagesHandler-->>Client: 302 Redirect (Location: upstream URL, no-store)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Silo-Server/silo-server#14: Overlaps ImagesHandler tag-based image resolution and signed tag handling which feed into the compat image delivery changes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: switching Jellyfin image route handlers from proxying upstream image bytes to redirecting to upstream URLs.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/jellyfin-s3-images

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3bf0367eec

ℹ️ 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".

// Do not let clients cache the temporary redirect itself. The object-store
// response can still carry its own cache headers after the client follows it.
w.Header().Set("Cache-Control", "no-store")
http.Redirect(w, r, imageURL, http.StatusFound)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep server-only presigned endpoints behind the proxy

When the public asset bucket uses the default presigned URL auth and s3.public_endpoint points at an object-store endpoint that is only reachable from the Silo server/container, this now sends Jellyfin clients directly to that internal host. The S3 client signs presigned URLs against its configured endpoint unless URL auth is public/cloudflare_token, so deployments that previously worked because the compat handler fetched the image server-side will start returning unusable redirects for cached/plugin/library artwork.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
internal/jellycompat/handlers_images.go (1)

456-459: 💤 Low value

Redundant nil check for httpClient.

The NewImagesHandler constructor already defaults httpClient to http.DefaultClient when nil (lines 54-56). This defensive check is unnecessary unless proxyImageURL might be called on a zero-valued ImagesHandler.

♻️ Suggested simplification
-	client := h.httpClient
-	if client == nil {
-		client = http.DefaultClient
-	}
-	resp, err := client.Do(req)
+	resp, err := h.httpClient.Do(req)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/jellycompat/handlers_images.go` around lines 456 - 459, The
nil-check for httpClient in proxyImageURL is redundant because NewImagesHandler
already sets h.httpClient to http.DefaultClient when nil; remove the defensive
check in proxyImageURL (the block referencing client := h.httpClient and the if
client == nil branch) and use h.httpClient directly, or alternatively ensure
proxyImageURL is only ever called on a properly constructed ImagesHandler; keep
references to ImagesHandler, NewImagesHandler, and proxyImageURL to locate the
change.
internal/jellycompat/image_proxy_tags.go (1)

41-54: 💤 Low value

Consider memory implications of buffering entire JSON responses.

The middleware buffers the complete response body in memory (line 53) before rewriting. For large paginated result sets or detailed item metadata, this could consume significant memory under load. While this approach is necessary for JSON rewriting without a streaming parser, consider documenting the memory trade-off or enforcing reasonable pagination limits upstream.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/jellycompat/image_proxy_tags.go` around lines 41 - 54,
compatImageProxyTagResponseWriter.Write buffers the entire JSON response into
compatImageProxyTagResponseWriter.body which can blow memory for large
responses; update the implementation to guard against that by checking buffered
size and switching to passthrough (set passthrough true and forward writes to
ResponseWriter) once a configurable maxBufferBytes is exceeded, and add a clear
comment/doc on the memory trade-off and the new maxBufferBytes config; reference
the Write method, the body buffer, passthrough flag, and isJSONResponse check so
reviewers can locate and validate the change.
internal/jellycompat/images_test.go (1)

67-144: ⚡ Quick win

Consider adding test coverage for 304 Not Modified responses.

The test forwards the If-None-Match header (line 110) and verifies it reaches upstream (lines 138-140), but the upstream always returns 200 OK. According to the AI summary, TestProxyImageRelaysNotModified was removed.

Consider adding test coverage to verify that when the upstream returns 304 Not Modified, the proxy correctly relays this status and headers to the client.

Test case suggestion

Add a test where the upstream returns 304:

func TestHandleItemImageProxyRelays304NotModified(t *testing.T) {
    upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("If-None-Match") == `"poster-v1"` {
            w.Header().Set("ETag", `"poster-v1"`)
            w.Header().Set("Cache-Control", "public, max-age=14400")
            w.WriteHeader(http.StatusNotModified)
            return
        }
        w.WriteHeader(http.StatusOK)
    }))
    defer upstream.Close()
    
    // ... setup handler with Infuse user-agent and httpClient ...
    // ... make request with If-None-Match header ...
    // Assert response is 304 with proper headers
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/jellycompat/images_test.go` around lines 67 - 144, Add a new test
(e.g., TestHandleItemImageProxyRelays304NotModified) that mirrors
TestHandleItemImageProxiesInfuseSignedTagWithoutSessionOrCache but uses an
upstream httptest.Server that returns http.StatusNotModified (304) when the
forwarded If-None-Match equals `"poster-v1"`; construct the same ImagesHandler
(reuse NewResourceIDCodec, newImageTagSigner(cfg.Auth.JWTSecret), NewImageCache,
fakeImageItemRepo, and set httpClient to upstream.Client()), send the request
with the Infuse User-Agent and If-None-Match header, call
ImagesHandler.HandleItemImage, and assert the response code is 304, the ETag and
Cache-Control headers from upstream are relayed (and
compatImageRouteCacheControl/CDN-Cache-Control/X-Accel-Expires are set
appropriately), the body is empty, and no Location header is set.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/jellycompat/handlers_images.go`:
- Around line 456-459: The nil-check for httpClient in proxyImageURL is
redundant because NewImagesHandler already sets h.httpClient to
http.DefaultClient when nil; remove the defensive check in proxyImageURL (the
block referencing client := h.httpClient and the if client == nil branch) and
use h.httpClient directly, or alternatively ensure proxyImageURL is only ever
called on a properly constructed ImagesHandler; keep references to
ImagesHandler, NewImagesHandler, and proxyImageURL to locate the change.

In `@internal/jellycompat/image_proxy_tags.go`:
- Around line 41-54: compatImageProxyTagResponseWriter.Write buffers the entire
JSON response into compatImageProxyTagResponseWriter.body which can blow memory
for large responses; update the implementation to guard against that by checking
buffered size and switching to passthrough (set passthrough true and forward
writes to ResponseWriter) once a configurable maxBufferBytes is exceeded, and
add a clear comment/doc on the memory trade-off and the new maxBufferBytes
config; reference the Write method, the body buffer, passthrough flag, and
isJSONResponse check so reviewers can locate and validate the change.

In `@internal/jellycompat/images_test.go`:
- Around line 67-144: Add a new test (e.g.,
TestHandleItemImageProxyRelays304NotModified) that mirrors
TestHandleItemImageProxiesInfuseSignedTagWithoutSessionOrCache but uses an
upstream httptest.Server that returns http.StatusNotModified (304) when the
forwarded If-None-Match equals `"poster-v1"`; construct the same ImagesHandler
(reuse NewResourceIDCodec, newImageTagSigner(cfg.Auth.JWTSecret), NewImageCache,
fakeImageItemRepo, and set httpClient to upstream.Client()), send the request
with the Infuse User-Agent and If-None-Match header, call
ImagesHandler.HandleItemImage, and assert the response code is 304, the ETag and
Cache-Control headers from upstream are relayed (and
compatImageRouteCacheControl/CDN-Cache-Control/X-Accel-Expires are set
appropriately), the body is empty, and no Location header is set.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a4ef9dc2-d14e-4265-bd17-e4b000af6d1f

📥 Commits

Reviewing files that changed from the base of the PR and between 3bf0367 and 51960c2.

📒 Files selected for processing (11)
  • internal/jellycompat/dto.go
  • internal/jellycompat/handlers_images.go
  • internal/jellycompat/idcodec.go
  • internal/jellycompat/image_cache.go
  • internal/jellycompat/image_proxy_tags.go
  • internal/jellycompat/image_proxy_tags_test.go
  • internal/jellycompat/image_tag_signer.go
  • internal/jellycompat/images.go
  • internal/jellycompat/images_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go

@Quick104
Quick104 merged commit 14f6860 into main Jun 9, 2026
2 checks passed
@Quick104
Quick104 deleted the codex/jellyfin-s3-images branch June 9, 2026 02:36
Quick104 added a commit that referenced this pull request Jun 11, 2026
* Redirect Jellyfin image routes to upstream URLs

* fix(jellycompat): proxy images for incompatible clients
Quick104 added a commit that referenced this pull request Jun 17, 2026
* Redirect Jellyfin image routes to upstream URLs

* fix(jellycompat): proxy images for incompatible clients
Quick104 added a commit that referenced this pull request Nov 19, 2026
Generated from silo-translations main at 8b0ffaa (#101). Re-pin to the
published release before merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Quick104 added a commit that referenced this pull request Nov 19, 2026
…3611)

* feat(plugins): apply plugin task bindings and lifecycle changes live

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* fix(taskmanager): keep firings that a schedule change or unregister raced

- The trigger loop ignores an update signal whose generation it has already
  read, so a signal left from an edit during a run no longer discards the new
  trigger's firing.
- A worker retired after its trigger fired returns before claiming the
  firing, so other servers don't skip a firing that runs nowhere.
- A startup trigger stopped before it fires arms again on the next Start, so
  the rearm after a run keeps a startup schedule installed during that run.
- Unregistering a task publishes task.updated, so task lists drop it.
- API and architecture text now says how plugin task edits reach other
  servers and that disabling a binding cancels a run in progress.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(web): sync translations for the plugin task panel text

Generated from silo-translations main at 8b0ffaa (#101). Re-pin to the
published release before merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(tasks): coordinate live schedules with firing and retirement

* chore(api): retire the consumed playback history approval

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant