Skip to content

feat(security): add opt-in strictMediaOrigins to refuse unconfigured media origins - #308

Open
rabesss wants to merge 3 commits into
mainfrom
feat/strict-media-origins
Open

rabesss wants to merge 3 commits into
mainfrom
feat/strict-media-origins

Conversation

@rabesss

@rabesss rabesss commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Description

What does this PR do?

Adds an opt-in strictMediaOrigins config option (IMPARTUS_STRICT_MEDIA_ORIGINS). When it is on, playlist, segment, decryption-key, slide and redirect requests to any origin other than baseUrl and mediaOrigins are refused before anything is sent: no DNS lookup, no connection, no request. Without the option, behaviour is unchanged: an unlisted origin is still contacted, with the bearer withheld.

The refusal is the existing *client.UnconfiguredMediaOriginError, with a new Strict field set. That means every surface that already explains "not in mediaOrigins" instead of "wrong credentials" handles it with no new plumbing (download summary, pipeline, playback failures channel, server sanitizeUpstreamErr):

media origin https://cdn.example.com is not in mediaOrigins (IMPARTUS_MEDIA_ORIGINS); strictMediaOrigins refused the request before it was sent
  • A strict refusal matches ErrUnconfiguredMediaOrigin (through Unwrap, which keeps its single-error contract) and ErrMediaOrigin (through a new Is method). It never matches ErrAuthentication, and retry.Retryable never retries it.
  • The message carries only scheme://host[:port]. If that origin contains any representation of the bearer (or credential-shaped text), in any letter case, the refusal keeps its type and classification but leaves Origin empty and says the origin was withheld. Chunk errors drop the chunk URL for strict refusals and for any other strict-mode ErrMediaOrigin refusal, so a signed path or query never reaches logs.
  • Redirect hops are checked before and after a caller-supplied CheckRedirect hook runs, so a hook that rewrites an allowed hop to an unlisted origin is refused too. Only refusals built internally are passed through unsanitized: they travel inside an unexported carrier, so a hook cannot forge a "trusted" UnconfiguredMediaOriginError with arbitrary fields.
  • New client API: GetAuthorizedWithMediaPolicy(ctx, url, token, client.MediaRequestPolicy{Origins, Strict}). GetAuthorizedWithTokenForOrigins is now a thin wrapper around it (non-strict).

Why opt-in (default false)

Refusing by default would break real users today. The README ships "mediaOrigins": [], and HLS playlists from the upstream can name segment and key URLs on a CDN origin the user has never listed. With strict mode on by default, those lectures would stop downloading on upgrade, with no change on the user's side. Off by default, they keep working exactly as before, and the bearer is still withheld from those origins (#245/#297). Users who want "never contact anything I didn't list" can turn it on and get an actionable error naming the origin to add. Issue #248 proposes it as an option, and flipping the default later is a one-line change once users have had a release to populate mediaOrigins. This is documented in the README config table, the env table and a new "Strict media origins" section.

Related Issue(s):

Type of Change

  • ✨ New feature (non-breaking change that adds functionality)
  • 📚 Documentation update

Testing Done

Unit Tests:

  • Added new tests
  • All tests pass (go vet ./..., go test -race -count=1 ./..., golangci-lint v2.12.1 → 0 issues; run on a clean instabox because the workstation is overloaded)

New tests (all use local httptest servers or a routing transport with hit counters; nothing contacts the real LMS):

  • internal/client/media_origin_strict_test.go: the issue's five variants refused with 0 requests; configured origins still get the bearer; non-strict mode still contacts unlisted origins without the bearer; redirect to an unlisted origin (with and without a token); a caller hook rewriting an allowed redirect; an allowed redirect is followed; a bearer inside the host, including mixed case on the first request and on a redirect Location, is never echoed and the refusal stays typed with the origin withheld; GetPlaylists refuses an unlisted playlist origin; a forged hook error is not trusted; Error/Is/Unwrap contract.
  • internal/downloader/strict_media_origin_test.go: chunk, decryption key, DownloadPlaylist (serial and pipeline), playback key startup and playback segment failure reporting. Each checks 0 requests, the typed refusal, and that the refused URL's path or query never appears in the error. Also: a bearer-carrying chunk and playback-segment origin is refused typed with the origin withheld, and a same-origin redirect whose Location carries the bearer drops the chunk URL.
  • internal/server: a strict slide redirect is refused with the named origin; sanitizeUpstreamErr explains a strict refusal without the URL or "authentication failed".
  • internal/config: default false, JSON key, env override in both directions, invalid env rejected, ApplyDefaults preserves the value.

Mutation checks: disabling the strict check in client.go/http.go, the URL-dropping branch in download_chunks.go, or the type-preserving branch in play.go each makes the matching new tests fail.

Code Quality Checklist

  • No new linting errors
  • No hardcoded secrets or credentials (test tokens are obvious placeholders)
  • Complex logic is documented with comments
  • Error messages are clear and actionable

Documentation

  • README.md updated (config table, env table, new "Strict media origins" section)
  • sample.config.json gains "strictMediaOrigins": false
  • Changelog: release-please generates it from the squash title.

Additional Context

The plan was reviewed before implementation (Terra xhigh). Its findings were fixed: hook-forged typed errors, chunk-URL leakage, the Unwrap contract, playback key type preservation, and the extra boundary tests.

Council round 1 (head 37d62d7) fixes: errcheck lint on two test type assertions; a mixed-case bearer in a hostname is now caught (Opus P2); a bearer-carrying origin keeps the typed strict refusal with the origin withheld, so playback reports it and chunk errors stay URL-free (Terra P1/P2); chunk errors also drop the URL for any other strict-mode policy refusal; README now says default mode already refuses redirects to unlisted origins (Opus P3); server job errors no longer report a generic ErrMediaOrigin policy refusal as "upstream authentication failed" (Muse P2).

Council round 2 (head ce29a5f): Opus and Muse Spark approved with no P0/P1. Terra's run stopped before giving a verdict, so it is rerun in round 3. Fixes in round 3's head: CI dogsled lint in two downloader tests; clearer wording for a withheld origin and for the server's policy message (Opus P3); the README now documents the withheld-origin case (Muse P3). The branch was rebased on main (55a95db) with no change to this PR's diff (git range-diff shows identical commits), and it merges cleanly with the open #311.

Deferred P3 findings are tracked in #317. The Factory droid-review check fails on Factory's own usage quota. It is not a required check, and it is not related to this change.

Council round 3 (head 08be14b, rebased on main 55a95db): Opus high and Muse Spark xhigh approved with no findings. Terra xhigh reported one P1 and one P2. The P1 (a hostname containing a hex-encoded token is named in the strict refusal) is triaged to P2 hardening and does not block this PR. Main's default-mode refusal already names the origin with no token check at all. No redaction path in internal/secrets knows hex or base64 token forms. Default mode also contacts that host, which strict mode never does, so this PR narrows the exposure rather than widening it. Both Terra items are tracked in #317, with the fix belonging in internal/secrets.

Not merged yet: #311 merged to main (4a9bb6f) after round 3 and touches six of this PR's files. A trial merge with 4a9bb6f is conflict-free, and go vet plus go test pass for client, downloader, server, config and watch. This PR's rule is to rebase after #311 and rerun all three seats on the rebased head before merging, so the PR is waiting for that one rebase-and-review round.

@rabesss rabesss changed the title feat(client): add opt-in strictMediaOrigins to refuse unconfigured media origins feat(security): add opt-in strictMediaOrigins to refuse unconfigured media origins Nov 8, 2026
@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo reviews are paused because your trial has ended. Ask your workspace admin to add credits to resume reviews. Manage billing

@factory-droid

factory-droid Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Droid encountered an error —— View job


@rabesss
rabesss force-pushed the feat/strict-media-origins branch from a5657ca to 37d62d7 Compare November 8, 2026 12:37
@greptile-apps

greptile-apps Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The setting reaches media requests across downloading, playback, and slide workflows.

The PR appears safe to merge, with a non-blocking gap in keeping refused chunk paths out of logs.

Findings

  1. P2 Security Refused paths still reach logs ▶

Summary

Adds opt-in strictMediaOrigins through JSON and IMPARTUS_STRICT_MEDIA_ORIGINS.

  • Media requests can now stop at origins users have not allowed.
  • Users can turn strict media-origin checks on in config.
  • Downloads and playback use the strict origin rule.
  • Slide downloads use the strict origin rule too.

Acknowledged limitation: rabesss states that generic ErrMediaOrigin refusals do not reach the playback failures channel; segment requests still fail closed with a 502.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Media request] --> B{Origin configured?}
  B -->|Yes| C[Send under existing credential rules]
  B -->|No| D{Strict enabled?}
  D -->|No| E[Send without bearer]
  D -->|Yes| F[Refuse before sending]
  F --> G{Origin safe to show?}
  G -->|Yes| H[Typed origin refusal]
  G -->|No| I[Generic policy error]
  H --> J[Chunk error omits URL]
  I --> K[Chunk fallback adds redacted URL]
Loading

Reviews (1) · Last reviewed commit: "feat(client): add opt-in strictMediaOrig..." · Reviewed by Greptile

Comment on lines +63 to +66
if strictErr := strictOriginRefusal(err); strictErr != nil {
// Nothing was sent. Report only the refused origin, never the
// chunk URL, whose path or query may carry signing material.
return "", nil, 0, fmt.Errorf("chunk %d request refused: %w", chunk, strictErr)

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 security Refused paths still reach logs

This branch misses strict refusals that return MediaOriginError. For example, with bearer test-token, strict mode refuses https://test-token.cdn.example/private-signed-path/segment.ts, but strictOriginRefusal(err) returns nil because the client deliberately omitted the typed origin error. The fallback then includes the URL in the chunk error. RedactURLWithToken removes the bearer but keeps the private path, so signed paths can still reach errors and logs. Drop the chunk URL for generic policy errors in strict mode too.

How this was verified: The bearer-bearing host selects the generic refusal, which misses the typed check and reaches a URL formatter that preserves the path.

@factory-droid

factory-droid Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Droid encountered an error —— View job

Droid could not run because a usage limit was reached: You've reached your 5-hour Droid Core usage limit (resets in 3h 37min).
Reload Extra Usage credits or wait for your limits to reset.

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

ℹ️ No critical issues — one small test-helper gap inline.

Reviewed changes

  • Strict pre-send refusal in the client: new GetAuthorizedWithMediaPolicy with MediaRequestPolicy{Origins, Strict} refuses an unlisted origin before anything is sent — both on the initial request and on each redirect hop, checked before and after a caller-supplied CheckRedirect hook. GetAuthorizedWithTokenForOrigins becomes a thin non-strict wrapper, so default behavior is unchanged.
  • Typed refusal reuses existing plumbing: the refusal is *UnconfiguredMediaOriginError{Strict: true} carrying only scheme://host[:port]; via the new Is method it also matches ErrMediaOrigin, and it flows through the download summary, pipeline failures, playback failures channel, and sanitizeUpstreamErr without new code. retry.Retryable's allowlist correctly never retries it.
  • Unforgeable redirect carrier: strict redirect refusals leave http.Client.Do inside the unexported strictRedirectRefusal type, so a hook cannot forge a trusted refusal; hook errors still take the sanitizing branch. Origins containing any representation of the bearer fall back to the generic ErrMediaOrigin rather than echoing it.
  • Wiring: strictMediaOrigins config (JSON + IMPARTUS_STRICT_MEDIA_ORIGINS, default false, invalid env rejected), downloader mediaPolicy() for chunks/keys/playback segments, GetPlaylists, and server slide redirects; chunk errors drop the refused URL so signed paths/queries never reach logs.
  • Tests: ~450 lines across client, downloader (serial + pipeline + playback), server, and config — all pinning 0 network requests and no leakage of the refused URL or bearer. go vet ./... and go test -race -count=1 are green on all four touched packages in this environment.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using glm-5.3 | 𝕏

Comment thread internal/config/config.go
applyStringEnv("IMPARTUS_RETRY_BUDGET", &cfg.RetryBudget)
applyStringEnv("IMPARTUS_LISTEN_ADDR", &cfg.ListenAddr)
for _, apply := range []func() error{
func() error { return applyBoolEnv("IMPARTUS_STRICT_MEDIA_ORIGINS", &cfg.StrictMediaOrigins) },

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.

IMPARTUS_STRICT_MEDIA_ORIGINS is missing from the unsetAllConfigEnv list in internal/config/config_test.go (around line 719), which deliberately enumerates every config env var to give tests a clean slate. No test today asserts strict-related state after that helper, so nothing can fail — but the list's contract is "all config env", and the new var belongs there.

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

ℹ️ The new commit is a pure amend of the reviewed head — nothing new to cover.

Reviewed changes

  • Re-checked the delta from a5657ca to 37d62d7: the PR's net diff is byte-identical, so this commit introduces no new code, docs, or test changes. The prior review covers the current head in full; its single inline suggestion (add IMPARTUS_STRICT_MEDIA_ORIGINS to unsetAllConfigEnv in internal/config/config_test.go) still stands.

Pullfrog  | Fix it ➔ | View workflow run | Using glm-5.3 | 𝕏

rabesss added a commit that referenced this pull request Nov 8, 2026
… bearer

Council round 1 on #308: catch a mixed-case bearer in a refused hostname,
keep the strict refusal typed with the origin withheld so playback reports it
and chunk errors stay URL-free, drop the chunk URL on any strict-mode policy
refusal, stop reporting ErrMediaOrigin as an authentication failure in job
errors, fix two errcheck type assertions, and correct the README on default
redirect handling.
@factory-droid

factory-droid Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Droid encountered an error —— View job

Droid could not run because a usage limit was reached: You've reached your 5-hour Droid Core usage limit (resets in 3h 22min).
Reload Extra Usage credits or wait for your limits to reset.

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

ℹ️ No new issues in this delta — approval is withheld only because the earlier unsetAllConfigEnv suggestion (internal/config/config_test.go) is still open; that thread is pre-existing, not a new blocker.

Reviewed changes

The delta 37d62d7..ce29a5f reworks how a strict refusal behaves when the refused origin itself carries the bearer, and tightens what strict-mode chunk errors and server job errors reveal.

  • Kept bearer-carrying strict refusals typed: strictOriginRefusal now returns *UnconfiguredMediaOriginError{Strict: true} with Origin empty instead of falling back to the generic ErrMediaOrigin, so playback, pipeline and download-summary surfaces all report it; detection covers a mixed-case bearer in both the raw and the folded host.
  • Added a withheld-origin message: Error() explains the origin was withheld because it contains the login token, keeping the refusal actionable without echoing it.
  • Dropped the chunk URL for every strict-mode policy refusal: chunk errors now omit the URL for any ErrMediaOrigin match when strict mode is on (e.g. a same-origin redirect whose Location carries the bearer), not only for typed strict refusals.
  • Stopped reporting policy refusals as login failures on the server: sanitizeUpstreamErr maps any other ErrMediaOrigin refusal to a fixed "media request refused by the media origin policy" message instead of "upstream authentication failed".
  • Extended tests and docs: mixed-case bearer in request and redirect hosts, withheld-origin chunk and playback reporting, the other-policy-refusal URL drop (pinning 0 redirect hits), and server sanitization; the README now states default mode already refuses redirects to unlisted origins. go vet and go test -race -count=1 are green on all four touched packages in this environment.

Pullfrog  | Fix it ➔ | View workflow run | Using glm-5.3 | 𝕏

@factory-droid

factory-droid Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Droid encountered an error —— View job

Droid could not run because a usage limit was reached: You've reached your 5-hour Droid Core usage limit (resets in 3h 8min).
Reload Extra Usage credits or wait for your limits to reset.

…media origins

strictMediaOrigins (IMPARTUS_STRICT_MEDIA_ORIGINS) refuses playlist,
segment, key, slide and redirect requests to any origin outside baseUrl
and mediaOrigins before they are sent. The refusal is an
UnconfiguredMediaOriginError with Strict set: it names only the refused
scheme://host[:port], matches ErrMediaOrigin and ErrUnconfiguredMediaOrigin,
and is never reported as a login failure.

Off by default so lectures whose playlists name an unlisted CDN keep
downloading; those origins are still contacted without the bearer.

Closes #248
… bearer

Council round 1 on #308: catch a mixed-case bearer in a refused hostname,
keep the strict refusal typed with the origin withheld so playback reports it
and chunk errors stay URL-free, drop the chunk URL on any strict-mode policy
refusal, stop reporting ErrMediaOrigin as an authentication failure in job
errors, fix two errcheck type assertions, and correct the README on default
redirect handling.
Assert the unused chunk results instead of discarding three values, describe a withheld origin as looking like a credential, name the media URL policy in server job errors, and document the withheld-origin case in the README.
@factory-droid

factory-droid Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Droid encountered an error —— View job

Droid could not run because a usage limit was reached: You've reached your 5-hour Droid Core usage limit (resets in 3h 7min).
Reload Extra Usage credits or wait for your limits to reset.

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

ℹ️ No new issues in this delta. Approval remains withheld only because the pre-existing unsetAllConfigEnv suggestion (internal/config/config_test.go) is still open — nothing in this delta blocks.

Reviewed changes

The delta ce29a5f..08be14b (the prior head amended to d6c90f3 with identical content, plus one new commit) is wording, documentation, and test hardening only — no control flow changed.

  • Clarified the withheld-origin refusal message: UnconfiguredMediaOriginError.Error() now says the origin was withheld because it "looks like a credential" rather than asserting it contains the login token, which matches what the detection actually establishes. Type, classification, and the loose "withheld" test assertion are unchanged.
  • Clarified the server's policy-refusal job error: mediaOriginPolicyRefusal now reads "media URL rejected by the media URL policy (check mediaOrigins / IMPARTUS_MEDIA_ORIGINS and that the URL is HTTPS without credentials)" — more accurate for a branch that also catches invalid-URL ErrMediaOrigin matches, and now tells the user what to check.
  • Hardened the refused-chunk tests: the two withheld-origin chunk tests now assert the refusal returns an empty path, nil data, and zero bytes written (also satisfying the dogsled linter).
  • Documented withheld origins in the README: the strict-media-origins section now explains that a refused origin which looks like it contains the login token is left out of the error.

go vet ./... and go test -race -count=1 are green on all four touched packages in this environment.

Pullfrog  | Fix it ➔ | View workflow run | Using glm-5.3 | 𝕏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant