Skip to content

feat(jellycompat): sign image tags and accept them without session - #14

Merged
Quick104 merged 3 commits into
mainfrom
t3code/116da365
May 27, 2026
Merged

Quick104 merged 3 commits into
mainfrom
t3code/116da365

Conversation

@Quick104

@Quick104 Quick104 commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Sign Jellyfin-compat image tags with an HMAC keyed on the JWT secret so tags can be verified out-of-band.
  • Allow /Items/{id}/Images/{type} requests to authorize via a valid signed tag query param, bypassing session/cache lookups for items, episodes, and seasons.
  • Thread the signing secret through the router/handler wiring and refactor the mapper to use the shared signer.

Testing

  • go test ./internal/jellycompat/... — Not run
  • New unit tests cover signed-tag image fetch without a session and per-secret tag divergence — Not run

Note

Medium Risk
Introduces session-less image access gated only by tag verification (plus legacy cache), keyed on the JWT secret—important for client UX but worth reviewing for tag forgery and access boundaries on edge cases.

Overview
Jellyfin-compat image tags move from URL-derived hashes to HMAC-signed tags (keyed on the JWT secret) built from stable seeds: storage paths, thumbhashes, and updatedAt, so tags stay valid across presign rotation and server restarts.

/Items/{id}/Images/{type} can now serve artwork when the client passes a matching signed tag, without a session—after verifying the tag against catalog rows (items, episodes, seasons) or library poster paths, with a fallback to legacy URL tags in the image cache. Invalid or stale tags are rejected before route-cache hits.

DTO mapping and episode batch loading thread paths/thumbhashes through for tag generation; parent series artwork on episodes uses a seriesImageSet and episode detail always loads series metadata (no longer skipping that fetch when URLs are cached). Library views expose PosterPath for stable library primary tags.

Reviewed by Cursor Bugbot for commit 44f90dd. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Support signed image URLs so images can be resolved and served without an active session when a valid tag is provided; validated requests stream upstream image data and populate the image cache.
    • Improved handling of series/parent images to produce stable signed image tags across restarts.
  • Security

    • HMAC-based signed image tags added to validate image URLs and reject unsigned or tampered tags.

Review Change Stack

- HMAC-sign image tags using the configured JWT secret
- Serve item/season/episode images via signed tag without requiring a session or cache hit
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b72625d8-697f-4f18-8fc7-07eccc8e3b2e

📥 Commits

Reviewing files that changed from the base of the PR and between e3b8a4b and 44f90dd.

📒 Files selected for processing (11)
  • internal/jellycompat/batch_loaders.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/handlers_images.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/handlers_items_test.go
  • internal/jellycompat/image_cache.go
  • internal/jellycompat/images_test.go
  • internal/jellycompat/mapping.go
  • internal/jellycompat/mapping_images_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/upstream_types.go

📝 Walkthrough

Walkthrough

Adds HMAC-signed short image tags, verifies them in ImagesHandler for session-less image proxying, updates mapper/tag generation to use the signer, wires JWT secret through router defaults, extends episode/thumbhash handling and image cache tag API, and adds tests covering tag behavior and handler flows.

Changes

Signed Image Tag Feature

Layer / File(s) Summary
Image tag signer implementation
internal/jellycompat/image_tag_signer.go
imageTagSigner derives HMAC-SHA256 tags (8-byte truncation), returns nil for blank secrets, provides Tag and constant-time Equal verification with fallback behavior.
Mapper signed tag generation
internal/jellycompat/mapping.go
mapper stores imageTagSigner from config; image tag/backdrop helpers accept a signer and compute tags via signer.Tag(seed,imageURL); list/season/episode and series image tags now use signer-based generation.
Batch loader & upstream DTO updates
internal/jellycompat/batch_loaders.go, internal/jellycompat/upstream_types.go
Compat episode batch loader selects still_thumbhash and updated_at and includes series backdrop thumbhash; upstreamListItem and targets are populated with UpdatedAt, BackdropThumbhash, StillThumbhash and SeriesImages.
Handler tag-based image resolution
internal/jellycompat/handlers_images.go
ImagesHandler accepts repo interfaces, poster presigner, presignTTL and imageTagSecret; HandleItemImage prioritizes tag-based resolution/proxying, uses images.LookupTag fallback, and adds helpers to resolve and validate tags without session.
Episode series image enrichment
internal/jellycompat/handlers_items.go
Episode enrichment uses seriesImageSet (paths, thumbhashes, updatedAt), caches series images per series ID, applies series images to episode DTOs, and persists series backdrop as episode Thumb when available.
Image cache tag lookup API
internal/jellycompat/image_cache.go
Adds ImageCache.LookupTag(tag) (trim and nil-safe) and routes legacy tag lookups in LookupSized through the new exported method.
Tests and scaffolding
internal/jellycompat/images_test.go, internal/jellycompat/mapping_images_test.go
Adds handler tests for signed-tag acceptance/rejection, upstream streaming, caching, presign acceptance, legacy cached-URL tags, and route-cache revalidation; adds mapper tests asserting tags vary with configured secret and use still-thumbhash seeds; includes fakes and chi route helpers.
Router JWT secret wiring
internal/jellycompat/router.go
NewRouter now passes deps.JWTSecret into the images handler; withDefaults sources deps.JWTSecret from config when empty.
Library poster path propagation
internal/jellycompat/content_direct.go
ListUserLibraries now sets upstreamUserLibrary.PosterPath from folder records so poster path is available for presigning and tag seeding.
Episode handler test update
internal/jellycompat/handlers_items_test.go
Renames and updates an episode handler test to expect a series-detail fetch to produce stable signed parent image tags after restart.

Sequence Diagram

sequenceDiagram
  participant Client
  participant ImagesHandler as HandleItemImage
  participant Resolver as resolveItemImageURLFromTag
  participant Verifier as signedImageTagMatches
  participant Signer as imageTagSigner
  participant ItemRepo as ItemRepository
  Client->>ImagesHandler: GET /Items/{id}/Images?tag=...
  ImagesHandler->>Resolver: extract tag, id, imageType
  Resolver->>Verifier: request tag verification (seed, metadata)
  Verifier->>Signer: Equal(seed,fallbackURL,actual)
  Signer-->>Verifier: true/false
  alt tag valid
    Resolver->>ItemRepo: fetch artwork without session
    ItemRepo-->>Resolver: image URL
    Resolver-->>ImagesHandler: resolved URL
    ImagesHandler-->>Client: proxied image bytes
  else tag invalid
    Resolver-->>ImagesHandler: error
    ImagesHandler-->>Client: upstream compat error
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I stamped a tiny tag with secret care,
Thumbhash seeds tucked safe in there,
No session chase, just HMAC bright,
Images hop through, swift and light.
Cheers from the rabbit, code delight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% 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 'feat(jellycompat): sign image tags and accept them without session' accurately and concisely describes the main change: adding HMAC signing of image tags and accepting them as an alternative to session-based authorization.
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 t3code/116da365

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: 22bae2f09f

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

Comment thread internal/jellycompat/mapping.go Outdated
}
if tags := imageTagsWithSeed(
if tags := imageTagsWithSeed(m.imageTagSigner,
imageTagSeed(item.ContentID, "Primary", compatCardImageSize, firstNonEmpty(item.PosterPath, item.StillPath), item.PosterThumbhash, item.UpdatedAt),

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 episode image tag seeds consistent

For episode rows produced by the batch/direct list paths, the still art is assigned to PosterPath/StillPath but PosterThumbhash is not populated, while the new no-session verifier signs against episode.StillThumbhash in signedImageTagMatches. When an episode has a stored still thumbhash, the tag emitted here omits that value but verification includes it, so after an image-cache miss or server restart /Items/{episode}/Images/Primary?tag=... rejects an otherwise valid signed episode image tag and returns the auth-required path instead.

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.

Actionable comments posted: 3

🤖 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.

Inline comments:
In `@internal/jellycompat/handlers_images.go`:
- Around line 76-83: The branch that serves cached image URLs via
resolveItemImageURLFromTag may return stale cache hits for requests
authenticated via signed tags; update the handler to revalidate the tag before
using a cached URL (or skip cache hits for tag-authenticated requests).
Concretely, in the image request flow (the code calling
resolveItemImageURLFromTag and LookupSized), detect a non-empty tag in the
request (and the tag-authenticated path), then either (a) perform tag signature
validation using the current JWT secret/image seed before attempting to serve
any cached URL, or (b) bypass cache lookup and force fresh resolution when a tag
is present; adjust resolveItemImageURLFromTag or the calling logic to enforce
this so cached URLs aren’t returned for potentially invalidated tags.

In `@internal/jellycompat/image_tag_signer.go`:
- Around line 17-19: newImageTagSigner currently returns an imageTagSigner even
when given an empty secret, which allows JWT verification to be effectively
disabled; change newImageTagSigner to return nil when secret == "" (i.e., treat
a blank secret as "signing disabled") and update call sites that receive
*imageTagSigner to handle a nil signer (preserve existing unsigned fallback
paths) before calling any methods like Sign or Verify on imageTagSigner.

In `@internal/jellycompat/mapping.go`:
- Around line 108-113: The image tag seed currently always uses
item.PosterThumbhash even when firstNonEmpty chose item.StillPath; update the
thumbhash passed to imageTagSeed in the imageTagsWithSeed call so it matches the
selected primary path — i.e., use item.PosterThumbhash when item.PosterPath is
non-empty, otherwise use item.StillThumbhash (the call sites: imageTagsWithSeed,
imageTagSeed, imageTagSigner, firstNonEmpty, and the dto.ImageTags assignment in
itemFromList).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: aaf197d5-2398-4ee5-9aa1-6b4f21df8a75

📥 Commits

Reviewing files that changed from the base of the PR and between 1070c62 and 22bae2f.

📒 Files selected for processing (6)
  • internal/jellycompat/handlers_images.go
  • internal/jellycompat/image_tag_signer.go
  • internal/jellycompat/images_test.go
  • internal/jellycompat/mapping.go
  • internal/jellycompat/mapping_images_test.go
  • internal/jellycompat/router.go

Comment thread internal/jellycompat/handlers_images.go Resolved
Comment thread internal/jellycompat/mapping.go Resolved
Comment thread internal/jellycompat/handlers_images.go Resolved
Comment thread internal/jellycompat/handlers_images.go Resolved

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@internal/jellycompat/handlers_images.go`:
- Around line 79-80: The code is populating the route cache from a signed-tag
request which can make later unauthenticated /Items/{id}/Images/{type} requests
succeed; modify the logic around h.images.RememberSizedUntil(routeID, imageType,
imageURL.URL, imageSize, imageURL.ExpiresAt) so it is NOT called for signed-tag
requests (i.e., when a tag param is present), or alternatively write to a
tag-scoped cache path instead; ensure the guard checks the request's tag
presence before calling RememberSizedUntil so anonymous LookupSized(...) calls
cannot hit this entry.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2149659e-1da5-4ed2-b2be-51e63bf0f92b

📥 Commits

Reviewing files that changed from the base of the PR and between 22bae2f and e3b8a4b.

📒 Files selected for processing (7)
  • internal/jellycompat/batch_loaders.go
  • internal/jellycompat/handlers_images.go
  • internal/jellycompat/image_tag_signer.go
  • internal/jellycompat/images_test.go
  • internal/jellycompat/mapping.go
  • internal/jellycompat/mapping_images_test.go
  • internal/jellycompat/upstream_types.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/jellycompat/image_tag_signer.go

Comment thread internal/jellycompat/handlers_images.go Resolved
{"subject":"fix(jellycompat): stabilize signed image tags across restarts","body":"- Sign library poster and episode parent series image tags from canonical paths/thumbhashes instead of presigned URLs so tags survive restarts\n- Accept signed canonical tags in the image handler without a session and fall back to legacy URL-derived cache tags\n- Always fetch series detail for episodes to build stable parent image tags"}
@Quick104
Quick104 merged commit c4ea942 into main May 27, 2026
1 of 2 checks passed
@Quick104
Quick104 deleted the t3code/116da365 branch May 27, 2026 02:31

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 44f90dd. Configure here.


if tag = strings.TrimSpace(tag); tag != "" {
if url, ok := c.lookupTag(tag); ok {
return url, true

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.

LookupSized no longer falls back to route cache on tag miss

Medium Severity

LookupSized previously tried the tag cache first, then fell back to the route cache on a tag miss. Now it returns c.LookupTag(tag) directly, which means a tag-cache miss immediately returns ("", false) without ever consulting the route cache. Any existing caller of Lookup or LookupSized that passes a non-empty tag will lose the route-cache fallback behavior they previously relied on.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 44f90dd. Configure here.

}

return catalog.ResolvedImageURL{}, false, nil
}

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.

Signed-tag image path skips access control checks

Medium Severity

resolveItemImageURLFromReposWithoutSession fetches items, episodes, and seasons via their repos and serves images without calling EnsureAccessible. The session-based equivalent (resolveItemImageURLFromRepos) enforces library/rating access controls. A valid signed tag generated for one user can be used by another user who lacks access to that library, bypassing per-user access filtering.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 44f90dd. Configure here.

Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
feat(jellycompat): sign image tags and accept them without session
Quick104 added a commit that referenced this pull request Jun 11, 2026
feat(jellycompat): sign image tags and accept them without session
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