diff --git a/README.md b/README.md index b58b1d16..c5137be0 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ protection manually with `chmod 600 config.json`. | `password` | string | Yes | - | Impartus password | | `baseUrl` | string | Yes | - | Impartus API base URL | | `mediaOrigins` | array of strings | No | `[]` | Additional exact HTTPS origins allowed for authenticated playlist/media requests; loopback HTTP is allowed for local testing | +| `strictMediaOrigins` | bool | No | `false` | Refuse playlist, segment, key, slide and redirect requests to any origin other than `baseUrl` and `mediaOrigins` before they are sent. Off by default, so media on a CDN origin you have not listed keeps working: such an origin is contacted without the login. Turn it on once `mediaOrigins` lists every CDN your lectures use. A refusal names the origin to add (see [Strict media origins](#strict-media-origins)) | | `quality` | string | No | `"720"` | Video quality: `144`, `450`, `720` | | `views` | string | No | `"both"` | Views: `left`, `right`, `both`, `first`, `second` | | `downloadLocation` | string | No | `"./downloads"` | Output directory | @@ -269,6 +270,7 @@ Only the settings listed below have environment-variable overrides. Settings abs | `IMPARTUS_PASSWORD` | `password` | Required unless supplied in JSON | | `IMPARTUS_BASE_URL` | `baseUrl` | Required unless supplied in JSON | | `IMPARTUS_MEDIA_ORIGINS` | `mediaOrigins` | Comma-separated exact origins; remote origins must use HTTPS | +| `IMPARTUS_STRICT_MEDIA_ORIGINS` | `strictMediaOrigins` | Boolean | | `IMPARTUS_QUALITY` | `quality` | `144`, `450`, or `720` | | `IMPARTUS_VIEWS` | `views` | `left`, `right`, `both`, `first`, or `second` | | `IMPARTUS_DOWNLOAD_LOCATION` | `downloadLocation` | Output directory | @@ -297,6 +299,31 @@ Only the settings listed below have environment-variable overrides. Settings abs | `IMPARTUS_WATCH_VIEWS` | `watch.views` | `left`, `right`, or `both` | | `IMPARTUS_WATCH_AUDIO_FORMAT` | `watch.audioFormat` | `mp3`, `m4a`, `aac`, or `opus` | +#### Strict media origins + +By default, a media request whose URL names an origin outside `baseUrl` and +`mediaOrigins` is still sent, but without the login (the bearer token is +withheld). Public CDN segments keep working, and a 401 or 403 from such an +origin is reported as "not in mediaOrigins" rather than as a login failure. A +redirect from a listed origin to an unlisted one is already refused by default, +with a generic error. + +Set `strictMediaOrigins: true` (or `IMPARTUS_STRICT_MEDIA_ORIGINS=true`) to +refuse requests to unlisted origins before anything is sent. Refused requests +and redirects then return an error that names only the refused +`scheme://host[:port]`, for example: + +```text +media origin https://cdn.example.com is not in mediaOrigins (IMPARTUS_MEDIA_ORIGINS); strictMediaOrigins refused the request before it was sent +``` + +If the refused origin looks like it contains the login token, the error leaves +the origin out and says it was withheld; it is still the same strict refusal. + +Add that origin to `mediaOrigins` if you trust it. The option is off by default +because lectures whose playlists name a CDN not yet listed in `mediaOrigins` +would otherwise stop downloading. + #### Validation Rules - `username` and `password` are required diff --git a/internal/client/auth_error.go b/internal/client/auth_error.go index aeab6261..76ed0d5b 100644 --- a/internal/client/auth_error.go +++ b/internal/client/auth_error.go @@ -33,13 +33,30 @@ func (e *AuthenticationError) Unwrap() error { // started, the origin to configure. RespondingOrigin is set only when a // redirect ended at a different origin, which then returned StatusCode. Both // are scheme://host[:port] only and never carry a path or query. +// +// Strict is set when strictMediaOrigins refused the request (or a redirect +// hop) before it was sent. Origin is then the refused destination and +// StatusCode and RespondingOrigin are unset. Origin is empty when the refused +// origin carries the bearer (for example in a hostname label) and so cannot +// be shown. A strict refusal also matches ErrMediaOrigin, since it is a +// media-origin policy decision. type UnconfiguredMediaOriginError struct { Origin string RespondingOrigin string StatusCode int + Strict bool } func (e *UnconfiguredMediaOriginError) Error() string { + if e.Strict { + if e.Origin == "" { + return "media origin (withheld: it looks like a credential) is not in mediaOrigins (IMPARTUS_MEDIA_ORIGINS); strictMediaOrigins refused the request before it was sent" + } + return fmt.Sprintf( + "media origin %s is not in mediaOrigins (IMPARTUS_MEDIA_ORIGINS); strictMediaOrigins refused the request before it was sent", + e.Origin, + ) + } if e.RespondingOrigin != "" && e.RespondingOrigin != e.Origin { return fmt.Sprintf( "media origin %s is not in mediaOrigins (IMPARTUS_MEDIA_ORIGINS), so the request was sent without the login; it ended in HTTP %d from %s", @@ -55,3 +72,9 @@ func (e *UnconfiguredMediaOriginError) Error() string { func (e *UnconfiguredMediaOriginError) Unwrap() error { return ErrUnconfiguredMediaOrigin } + +// Is reports a strict refusal as ErrMediaOrigin too, keeping the single-error +// Unwrap contract for errors.Unwrap callers. +func (e *UnconfiguredMediaOriginError) Is(target error) bool { + return e != nil && e.Strict && target == ErrMediaOrigin +} diff --git a/internal/client/client.go b/internal/client/client.go index 5a1fe320..4da2be93 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -108,11 +108,21 @@ func (c *Client) GetAuthorizedWithToken(ctx context.Context, rawURL, token strin // from it is returned as an *UnconfiguredMediaOriginError instead of a // response. func (c *Client) GetAuthorizedWithTokenForOrigins(ctx context.Context, rawURL, token string, origins ...string) (*http.Response, error) { - policy, err := newMediaOriginPolicy(origins...) + return c.GetAuthorizedWithMediaPolicy(ctx, rawURL, token, MediaRequestPolicy{Origins: origins}) +} + +// GetAuthorizedWithMediaPolicy is GetAuthorizedWithTokenForOrigins with an +// explicit strict mode. With policy.Strict set, a request or redirect hop to +// an origin outside policy.Origins is refused before it is sent and returns +// an *UnconfiguredMediaOriginError with Strict set, which matches both +// ErrUnconfiguredMediaOrigin and ErrMediaOrigin. +func (c *Client) GetAuthorizedWithMediaPolicy(ctx context.Context, rawURL, token string, policy MediaRequestPolicy) (*http.Response, error) { + originPolicy, err := newMediaOriginPolicy(policy.Origins...) if err != nil { return nil, err } - return c.getAuthorizedWithToken(ctx, rawURL, token, policy) + originPolicy.strict = policy.Strict + return c.getAuthorizedWithToken(ctx, rawURL, token, originPolicy) } func (c *Client) getAuthorizedWithToken(ctx context.Context, rawURL, token string, policy mediaOriginPolicy) (*http.Response, error) { @@ -129,6 +139,12 @@ func (c *Client) getAuthorizedWithToken(ctx context.Context, rawURL, token strin if validateErr := validateMediaURL(parsedURL, token != ""); validateErr != nil { return nil, validateErr } + if policy.strict && !policy.allows(parsedURL) { + // Strict mode refuses an unconfigured origin before anything is + // sent, with or without a bearer, so the origin never learns of the + // request. + return nil, strictOriginRefusal(parsedURL, redactionToken) + } if token == "" && policy.allows(parsedURL) && hasCredentialQuery(parsedURL) { // A tokenless call to a configured origin must not forward a @@ -310,6 +326,7 @@ func (c *Client) GetPlaylists(ctx context.Context, cfg *config.Config, lectures if err != nil { return nil, err } + policy.strict = cfg.StrictMediaOrigins token, err := c.resolveToken(cfg) if err != nil { diff --git a/internal/client/http.go b/internal/client/http.go index eaf9dcb4..bec4ac4f 100644 --- a/internal/client/http.go +++ b/internal/client/http.go @@ -75,6 +75,14 @@ func (c *Client) doRequestWithTokenClient(ctx context.Context, method, rawURL st if errors.As(err, &originErr) { return nil, originErr } + // A strict refusal of a redirect hop carries only a token-checked + // scheme://host[:port], so it is safe to return unwrapped. Only the + // unexported carrier is trusted: a caller hook could return a forged + // *UnconfiguredMediaOriginError with arbitrary fields. + var strictErr *strictRedirectRefusal + if errors.As(err, &strictErr) { + return nil, strictErr.err + } // http.Client.Do returns a *url.Error whose Error() embeds the full // request URL (including query tokens). Sanitize it before wrapping so // the token can never reach logs via %w/%v on this error. @@ -99,7 +107,7 @@ func (c *Client) handleMediaRedirect(initialURL *url.URL, redactionToken string, return errors.New("stopped after 10 redirects") } canonicalizeMediaRedirectScheme(next) - if err := validateMediaRedirect(initialURL, next.URL, policy); err != nil { + if err := validateMediaRedirect(initialURL, next.URL, policy, redactionToken); err != nil { return err } @@ -125,7 +133,7 @@ func (c *Client) handleMediaRedirect(initialURL *url.URL, redactionToken string, // A custom hook may rewrite the URL or add sensitive headers. Recheck // the policy and enforce the cross-origin header boundary after it runs. canonicalizeMediaRedirectScheme(next) - if err := validateMediaRedirect(initialURL, next.URL, policy); err != nil { + if err := validateMediaRedirect(initialURL, next.URL, policy, redactionToken); err != nil { return err } sameOrigin = sameMediaOrigin(initialURL, next.URL) @@ -253,7 +261,7 @@ func deleteHeaderCaseInsensitive(header http.Header, names ...string) { } } -func validateMediaRedirect(initial, destination *url.URL, policy mediaOriginPolicy) error { +func validateMediaRedirect(initial, destination *url.URL, policy mediaOriginPolicy, redactionToken string) error { // A tokenless compatibility request may legitimately begin on a public // HTTP origin. Preserve that public/loopback behavior for its redirects; // authenticated requests have already been rejected before this hook when @@ -263,6 +271,9 @@ func validateMediaRedirect(initial, destination *url.URL, policy mediaOriginPoli if err := validateMediaURL(destination, requireHTTPS); err != nil { return err } + if policy.strict && !policy.allows(destination) { + return strictRedirectOriginRefusal(destination, redactionToken) + } if !policy.allowsRedirect(initial, destination) { return newMediaOriginError(ErrMediaOrigin) } diff --git a/internal/client/media_origin.go b/internal/client/media_origin.go index e76c4b3f..7c118585 100644 --- a/internal/client/media_origin.go +++ b/internal/client/media_origin.go @@ -52,9 +52,22 @@ func newMediaOriginError(reason error) error { // mediaOriginPolicy is immutable after construction. Sharing it between // concurrent requests is safe because no request mutates the sorted origin -// slice. +// slice. strict refuses any request or redirect hop to an origin outside +// origins before it is sent, instead of sending it without the bearer. type mediaOriginPolicy struct { origins []string + strict bool +} + +// MediaRequestPolicy is the request-scoped origin policy for +// GetAuthorizedWithMediaPolicy. Origins is the exact-origin allowlist (the +// API base URL plus mediaOrigins). With Strict set, a request or redirect to +// any other origin is refused before it is sent, with an +// *UnconfiguredMediaOriginError naming the origin. Without it, such a request +// is sent without the bearer. +type MediaRequestPolicy struct { + Origins []string + Strict bool } func newMediaOriginPolicy(origins ...string) (mediaOriginPolicy, error) { @@ -367,6 +380,47 @@ func withholdBearerFromURL(rawURL, token string) (*url.URL, error) { return parsed, nil } +// strictOriginRefusal reports a request or redirect hop that strict mode +// refuses before sending. The error names the origin to add to mediaOrigins. +// An origin that carries any representation of the bearer (for example in a +// hostname label) is never echoed: the refusal keeps its type and +// classification but leaves Origin empty. +// requestOriginKey lower-cases the host, so the raw host is checked with the +// bearer as given, and the folded origin with the folded bearer. +func strictOriginRefusal(destination *url.URL, token string) error { + origin, err := requestOriginKey(destination) + if err != nil { + return err + } + if containsTokenRepresentation(origin, token) || + containsTokenRepresentation(destination.Host, token) || + (token != "" && containsTokenRepresentation(origin, strings.ToLower(token))) { + return &UnconfiguredMediaOriginError{Strict: true} + } + return &UnconfiguredMediaOriginError{Origin: origin, Strict: true} +} + +// strictRedirectRefusal carries a strict refusal of a redirect hop out of +// http.Client.Do. The type is unexported so a caller-supplied CheckRedirect +// hook cannot forge it: only refusals built by strictOriginRefusal are passed +// through to the caller unsanitized. +type strictRedirectRefusal struct { + err *UnconfiguredMediaOriginError +} + +func (e *strictRedirectRefusal) Error() string { return e.err.Error() } + +func (e *strictRedirectRefusal) Unwrap() error { return e.err } + +func strictRedirectOriginRefusal(destination *url.URL, token string) error { + err := strictOriginRefusal(destination, token) + var refusal *UnconfiguredMediaOriginError + if errors.As(err, &refusal) { + return &strictRedirectRefusal{err: refusal} + } + return err +} + // unconfiguredOriginRefusal turns a 401 or 403 to a request sent without the // bearer, because its origin is not in mediaOrigins, into an // UnconfiguredMediaOriginError so callers do not report it as a login failure. diff --git a/internal/client/media_origin_strict_test.go b/internal/client/media_origin_strict_test.go new file mode 100644 index 00000000..389e6571 --- /dev/null +++ b/internal/client/media_origin_strict_test.go @@ -0,0 +1,358 @@ +package client + +import ( + "context" + "encoding/base64" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/rabesss/impartus-cli/internal/config" +) + +const strictTestConfiguredOrigin = "https://api.example.test" + +func newCountingServer(t *testing.T) (*httptest.Server, *atomic.Int32) { + t.Helper() + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(server.Close) + return server, &hits +} + +func requireStrictRefusal(t *testing.T, err error, wantOrigin, token string) { + t.Helper() + if err == nil { + t.Fatal("error = nil, want strict media-origin refusal") + } + if !errors.Is(err, ErrMediaOrigin) { + t.Fatalf("errors.Is(err, ErrMediaOrigin) = false for %T %q", err, err) + } + if !errors.Is(err, ErrUnconfiguredMediaOrigin) { + t.Fatalf("errors.Is(err, ErrUnconfiguredMediaOrigin) = false for %T %q", err, err) + } + if errors.Is(err, ErrAuthentication) { + t.Fatalf("strict refusal %q must not be an authentication failure", err) + } + var originErr *UnconfiguredMediaOriginError + if !errors.As(err, &originErr) { + t.Fatalf("error = %T %q, want *UnconfiguredMediaOriginError", err, err) + } + if !originErr.Strict || originErr.StatusCode != 0 { + t.Fatalf("refusal = %+v, want Strict with no status", originErr) + } + if originErr.Origin != wantOrigin { + t.Fatalf("refusal origin = %q, want %q", originErr.Origin, wantOrigin) + } + message := err.Error() + if !strings.Contains(message, wantOrigin) || !strings.Contains(message, "strictMediaOrigins") { + t.Fatalf("message %q must name origin %q and strictMediaOrigins", message, wantOrigin) + } + if token != "" && containsTokenRepresentation(message, token) { + t.Fatalf("message %q leaks the bearer", message) + } +} + +func TestStrictMediaOriginsRefusesUnconfiguredOriginBeforeDialling(t *testing.T) { + const token = "secret-bearer-abc123" + server, hits := newCountingServer(t) + stdB64 := base64.StdEncoding.EncodeToString([]byte(token)) + urlB64 := base64.RawURLEncoding.EncodeToString([]byte(token)) + cases := []struct { + name string + path string + token string + }{ + {name: "plain", path: "/seg.ts", token: token}, + {name: "query token", path: "/seg.ts?x=" + token, token: token}, + {name: "query base64 token", path: "/seg.ts?x=" + url.QueryEscape(stdB64), token: token}, + {name: "path base64url token", path: "/" + urlB64 + "/seg.ts", token: token}, + {name: "tokenless", path: "/public.ts", token: ""}, + } + c := New(server.Client(), nil) + policy := MediaRequestPolicy{Origins: []string{strictTestConfiguredOrigin}, Strict: true} + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), server.URL+tc.path, tc.token, policy) + if resp != nil { + _ = resp.Body.Close() //nolint:errcheck + } + requireStrictRefusal(t, err, server.URL, token) + }) + } + if got := hits.Load(); got != 0 { + t.Fatalf("unconfigured origin received %d requests, want 0", got) + } +} + +func TestStrictMediaOriginsAllowsConfiguredOrigins(t *testing.T) { + const token = "strict-configured-bearer" + var authorization atomic.Value + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authorization.Store(r.Header.Get("Authorization")) + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + c := New(server.Client(), nil) + policy := MediaRequestPolicy{Origins: []string{strictTestConfiguredOrigin, server.URL}, Strict: true} + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), server.URL+"/seg.ts", token, policy) + if err != nil { + t.Fatalf("configured origin error = %v", err) + } + _ = resp.Body.Close() //nolint:errcheck + if got, ok := authorization.Load().(string); !ok || got != "Bearer "+token { + t.Fatalf("Authorization = %q, want bearer on configured origin", got) + } +} + +func TestNonStrictMediaOriginsStillContactsUnconfiguredOriginWithoutBearer(t *testing.T) { + const token = "non-strict-bearer" + var authorization atomic.Value + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + authorization.Store(r.Header.Get("Authorization")) + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + c := New(server.Client(), nil) + for _, call := range []func() (*http.Response, error){ + func() (*http.Response, error) { + return c.GetAuthorizedWithTokenForOrigins(context.Background(), server.URL+"/seg.ts", token, strictTestConfiguredOrigin) + }, + func() (*http.Response, error) { + return c.GetAuthorizedWithMediaPolicy(context.Background(), server.URL+"/seg.ts", token, MediaRequestPolicy{Origins: []string{strictTestConfiguredOrigin}}) + }, + } { + resp, err := call() + if err != nil { + t.Fatalf("non-strict error = %v", err) + } + _ = resp.Body.Close() //nolint:errcheck + if got, ok := authorization.Load().(string); !ok || got != "" { + t.Fatalf("Authorization = %q, want none on unconfigured origin", got) + } + } + if got := hits.Load(); got != 2 { + t.Fatalf("unconfigured origin hits = %d, want 2 (default stays permissive)", got) + } +} + +func TestStrictMediaOriginsRefusesRedirectToUnconfiguredOrigin(t *testing.T) { + const token = "strict-redirect-bearer" + unconfigured, hits := newCountingServer(t) + source := httptest.NewServer(http.RedirectHandler(unconfigured.URL+"/segment.ts", http.StatusFound)) + defer source.Close() + + c := New(source.Client(), nil) + for _, requestToken := range []string{token, ""} { + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), source.URL+"/playlist.m3u8", requestToken, MediaRequestPolicy{Origins: []string{source.URL}, Strict: true}) + if resp != nil { + _ = resp.Body.Close() //nolint:errcheck + } + requireStrictRefusal(t, err, unconfigured.URL, token) + } + if got := hits.Load(); got != 0 { + t.Fatalf("unconfigured redirect destination received %d requests, want 0", got) + } +} + +func TestStrictMediaOriginsRefusesRedirectRewrittenByCallerHook(t *testing.T) { + const token = "strict-hook-bearer" + unconfigured, hits := newCountingServer(t) + configured, configuredHits := newCountingServer(t) + source := httptest.NewServer(http.RedirectHandler(configured.URL+"/segment.ts", http.StatusFound)) + defer source.Close() + + httpClient := source.Client() + httpClient.CheckRedirect = func(next *http.Request, _ []*http.Request) error { + rewritten, err := url.Parse(unconfigured.URL + "/segment.ts") + if err != nil { + return err + } + next.URL = rewritten + return nil + } + c := New(httpClient, nil) + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), source.URL+"/playlist.m3u8", token, MediaRequestPolicy{Origins: []string{source.URL, configured.URL}, Strict: true}) + if resp != nil { + _ = resp.Body.Close() //nolint:errcheck + } + requireStrictRefusal(t, err, unconfigured.URL, token) + if got := hits.Load() + configuredHits.Load(); got != 0 { + t.Fatalf("redirect destinations received %d requests, want 0", got) + } +} + +func TestStrictMediaOriginsFollowsRedirectToConfiguredOrigin(t *testing.T) { + const token = "strict-allowed-redirect" + destination, hits := newCountingServer(t) + source := httptest.NewServer(http.RedirectHandler(destination.URL+"/segment.ts", http.StatusFound)) + defer source.Close() + + c := New(source.Client(), nil) + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), source.URL+"/playlist.m3u8", token, MediaRequestPolicy{Origins: []string{source.URL, destination.URL}, Strict: true}) + if err != nil { + t.Fatalf("configured redirect error = %v", err) + } + _ = resp.Body.Close() //nolint:errcheck + if got := hits.Load(); got != 1 { + t.Fatalf("configured redirect destination hits = %d, want 1", got) + } +} + +func TestStrictMediaOriginsDoesNotEchoBearerInOriginHost(t *testing.T) { + const token = "hostbearer" + transport := &mediaOriginCaptureTransport{} + c := New(&http.Client{Transport: transport}, nil) + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), "https://"+token+".cdn.example.test/seg.ts", token, MediaRequestPolicy{Origins: []string{strictTestConfiguredOrigin}, Strict: true}) + if resp != nil { + _ = resp.Body.Close() //nolint:errcheck + } + requireStrictBearerHostRefusal(t, err, token) + if transport.request != nil { + t.Fatalf("request sent to %s, want none", transport.request.URL) + } +} + +// requireStrictBearerHostRefusal checks that a strict refusal of an origin +// whose hostname carries the bearer, in any letter case, keeps its type and +// classification but never names that origin (which requestOriginKey +// lower-cases). +func requireStrictBearerHostRefusal(t *testing.T, err error, token string) { + t.Helper() + if err == nil || !errors.Is(err, ErrMediaOrigin) || !errors.Is(err, ErrUnconfiguredMediaOrigin) { + t.Fatalf("error = %v, want ErrMediaOrigin and ErrUnconfiguredMediaOrigin", err) + } + if errors.Is(err, ErrAuthentication) { + t.Fatalf("error = %v, must not be an authentication failure", err) + } + var originErr *UnconfiguredMediaOriginError + if !errors.As(err, &originErr) || !originErr.Strict || originErr.Origin != "" { + t.Fatalf("error = %#v, want a strict refusal with the origin withheld", originErr) + } + if !strings.Contains(err.Error(), "withheld") { + t.Fatalf("error %q does not say the origin was withheld", err) + } + if strings.Contains(strings.ToLower(err.Error()), strings.ToLower(token)) { + t.Fatalf("error %q leaks the bearer (case-folded)", err) + } +} + +func TestStrictMediaOriginsDoesNotEchoMixedCaseBearerInOriginHost(t *testing.T) { + const token = "MiXeDHostBearer" + transport := &mediaOriginCaptureTransport{} + c := New(&http.Client{Transport: transport}, nil) + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), "https://"+token+".cdn.example.test/seg.ts", token, MediaRequestPolicy{Origins: []string{strictTestConfiguredOrigin}, Strict: true}) + if resp != nil { + _ = resp.Body.Close() //nolint:errcheck + } + requireStrictBearerHostRefusal(t, err, token) + if transport.request != nil { + t.Fatalf("request sent to %s, want none", transport.request.URL) + } +} + +func TestStrictMediaOriginsDoesNotEchoMixedCaseBearerInRedirectHost(t *testing.T) { + const token = "MiXeDRedirectBearer" + source := httptest.NewServer(http.RedirectHandler("https://"+token+".cdn.example.test/segment.ts", http.StatusFound)) + defer source.Close() + + c := New(source.Client(), nil) + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), source.URL+"/playlist.m3u8", token, MediaRequestPolicy{Origins: []string{source.URL}, Strict: true}) + if resp != nil { + _ = resp.Body.Close() //nolint:errcheck + } + requireStrictBearerHostRefusal(t, err, token) +} + +func TestGetPlaylistsStrictMediaOriginsRefusesUnconfiguredPlaylistOrigin(t *testing.T) { + const token = "strict-playlist-bearer" + transport := &mediaOriginRoutingTransport{responses: map[string]string{ + "https://api.example.test/fetchvideo": "https://cdn.example.test/1280x720/master.m3u8\n", + "https://cdn.example.test/1280x720/master.m3u8": "#EXTM3U\n#EXTINF:1,\nsegment.ts\n", + }} + c := New(&http.Client{Transport: transport}, nil) + _, err := c.GetPlaylists(context.Background(), &config.Config{ + BaseURL: strictTestConfiguredOrigin, + StrictMediaOrigins: true, + Quality: "720", + Token: token, + }, Lectures{{TTID: 42, Topic: "Strict CDN"}}) + requireStrictRefusal(t, err, "https://cdn.example.test", token) + for _, request := range transport.requests { + if request.URL.Host != "api.example.test" { + t.Fatalf("request sent to %s, want only the configured API origin", request.URL) + } + } +} + +func TestUnconfiguredMediaOriginErrorStrictUnwrap(t *testing.T) { + strict := &UnconfiguredMediaOriginError{Origin: "https://cdn.example.test", Strict: true} + if !errors.Is(strict, ErrMediaOrigin) || !errors.Is(strict, ErrUnconfiguredMediaOrigin) { + t.Fatalf("strict refusal must match ErrMediaOrigin and ErrUnconfiguredMediaOrigin") + } + want := "media origin https://cdn.example.test is not in mediaOrigins (IMPARTUS_MEDIA_ORIGINS); strictMediaOrigins refused the request before it was sent" + if strict.Error() != want { + t.Fatalf("Error() = %q, want %q", strict.Error(), want) + } + + if got := errors.Unwrap(strict); got != ErrUnconfiguredMediaOrigin { //nolint:errorlint // checks the single-error Unwrap contract + t.Fatalf("errors.Unwrap(strict) = %v, want ErrUnconfiguredMediaOrigin", got) + } + + refused := &UnconfiguredMediaOriginError{Origin: "https://cdn.example.test", StatusCode: http.StatusForbidden} + if got := errors.Unwrap(refused); got != ErrUnconfiguredMediaOrigin { //nolint:errorlint // checks the single-error Unwrap contract + t.Fatalf("errors.Unwrap(refused) = %v, want ErrUnconfiguredMediaOrigin", got) + } + if errors.Is(refused, ErrMediaOrigin) { + t.Fatal("a refusal after sending must not match ErrMediaOrigin") + } + if !errors.Is(refused, ErrUnconfiguredMediaOrigin) { + t.Fatal("a refusal after sending must match ErrUnconfiguredMediaOrigin") + } +} + +// A caller-supplied CheckRedirect hook can return the exported error type with +// arbitrary fields. It must not be passed through as a trusted strict refusal. +func TestStrictMediaOriginsDoesNotTrustForgedHookRefusal(t *testing.T) { + const token = "forged-hook-bearer" + destination, hits := newCountingServer(t) + source := httptest.NewServer(http.RedirectHandler(destination.URL+"/segment.ts", http.StatusFound)) + defer source.Close() + + forgedOrigin := "https://" + token + ".example.test/private/path?sig=signed-query-value" + httpClient := source.Client() + httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { + return &UnconfiguredMediaOriginError{Origin: forgedOrigin, RespondingOrigin: forgedOrigin, Strict: true} + } + c := New(httpClient, nil) + resp, err := c.GetAuthorizedWithMediaPolicy(context.Background(), source.URL+"/playlist.m3u8", token, MediaRequestPolicy{Origins: []string{source.URL, destination.URL}, Strict: true}) + if resp != nil { + _ = resp.Body.Close() //nolint:errcheck + } + if err == nil { + t.Fatal("forged hook refusal error = nil, want an error") + } + var originErr *UnconfiguredMediaOriginError + if errors.As(err, &originErr) { + t.Fatalf("forged hook refusal passed through as %#v", originErr) + } + // The hook's own message is sanitized like any hook error; it must not + // carry the bearer. + if strings.Contains(err.Error(), token) { + t.Fatalf("error %q leaks the bearer", err.Error()) + } + if got := hits.Load(); got != 0 { + t.Fatalf("redirect destination hits = %d, want 0", got) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 9bd8094b..035ba02a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -44,10 +44,16 @@ type Config struct { // MediaOrigins lists additional exact origins (typically a CDN) that may // receive the upstream bearer token for playlist and media requests. The // API base URL is always authorized separately. - MediaOrigins []string `json:"mediaOrigins,omitempty"` - Quality string `json:"quality"` - Views string `json:"views"` - DownloadLocation string `json:"downloadLocation"` + MediaOrigins []string `json:"mediaOrigins,omitempty"` + // StrictMediaOrigins refuses playlist, segment, key, slide and redirect + // requests to any origin other than BaseURL and MediaOrigins before they + // are sent. Off by default: an unconfigured origin (for example a public + // CDN named by an upstream playlist) is then contacted without the + // bearer token. + StrictMediaOrigins bool `json:"strictMediaOrigins,omitempty"` + Quality string `json:"quality"` + Views string `json:"views"` + DownloadLocation string `json:"downloadLocation"` // Token is populated by client.LoginAndSetToken for backwards compatibility. // Config values, including Token, are caller-owned and must not be read or // mutated concurrently with login. Concurrent API requests should leave @@ -469,6 +475,7 @@ func applyEnvOverrides(cfg *Config) error { 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) }, func() error { return applyBoolEnv("IMPARTUS_AUDIO_ONLY", &cfg.AudioOnly) }, func() error { return applyBoolEnv("IMPARTUS_SLIDES", &cfg.Slides) }, func() error { return applyBoolEnv("IMPARTUS_SKIP_NO_AUDIO", &cfg.SkipNoAudio) }, diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 7ff5cf6b..90258b81 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -828,3 +828,80 @@ func TestNormalizeViews(t *testing.T) { }) } } + +func TestLoadResolvedStrictMediaOriginsDefaultsFalse(t *testing.T) { + unsetConfigEnv(t, "IMPARTUS_STRICT_MEDIA_ORIGINS") + path := writeTempConfig(t, `{ + "username": "u", "password": "p", "baseUrl": "https://example.com", + "quality": "450", "views": "both" + }`) + cfg, err := LoadResolved(path) + if err != nil { + t.Fatalf("LoadResolved: %v", err) + } + if cfg.StrictMediaOrigins { + t.Error("expected StrictMediaOrigins to default false so CDN media keeps working") + } +} + +func TestLoadResolvedStrictMediaOriginsFromFile(t *testing.T) { + unsetConfigEnv(t, "IMPARTUS_STRICT_MEDIA_ORIGINS") + path := writeTempConfig(t, `{ + "username": "u", "password": "p", "baseUrl": "https://example.com", + "quality": "450", "views": "both", "strictMediaOrigins": true + }`) + cfg, err := LoadResolved(path) + if err != nil { + t.Fatalf("LoadResolved: %v", err) + } + if !cfg.StrictMediaOrigins { + t.Error("expected strictMediaOrigins: true to enable strict media origins") + } +} + +func TestLoadResolvedStrictMediaOriginsEnvOverridesFileValue(t *testing.T) { + for _, tc := range []struct { + env string + file string + want bool + }{ + {env: "true", file: "false", want: true}, + {env: "false", file: "true", want: false}, + } { + t.Run(tc.env, func(t *testing.T) { + t.Setenv("IMPARTUS_STRICT_MEDIA_ORIGINS", tc.env) + path := writeTempConfig(t, `{ + "username": "u", "password": "p", "baseUrl": "https://example.com", + "quality": "450", "views": "both", "strictMediaOrigins": `+tc.file+` + }`) + cfg, err := LoadResolved(path) + if err != nil { + t.Fatalf("LoadResolved: %v", err) + } + if cfg.StrictMediaOrigins != tc.want { + t.Errorf("StrictMediaOrigins = %t, want %t", cfg.StrictMediaOrigins, tc.want) + } + }) + } +} + +func TestLoadResolvedRejectsInvalidStrictMediaOriginsEnvironment(t *testing.T) { + t.Setenv("IMPARTUS_STRICT_MEDIA_ORIGINS", "sometimes") + path := writeTempConfig(t, `{ + "username": "u", "password": "p", "baseUrl": "https://example.com", + "quality": "450", "views": "both" + }`) + if _, err := LoadResolved(path); err == nil || !strings.Contains(err.Error(), "IMPARTUS_STRICT_MEDIA_ORIGINS") { + t.Fatalf("LoadResolved error = %v, want an invalid IMPARTUS_STRICT_MEDIA_ORIGINS error", err) + } +} + +func TestApplyDefaultsPreservesStrictMediaOrigins(t *testing.T) { + for _, want := range []bool{false, true} { + cfg := &Config{StrictMediaOrigins: want} + cfg.ApplyDefaults() + if cfg.StrictMediaOrigins != want { + t.Errorf("ApplyDefaults changed StrictMediaOrigins from %t", want) + } + } +} diff --git a/internal/downloader/decryption_key.go b/internal/downloader/decryption_key.go index d1500859..68e2aa32 100644 --- a/internal/downloader/decryption_key.go +++ b/internal/downloader/decryption_key.go @@ -75,7 +75,7 @@ func (d *Downloader) fetchDecryptionKeyOnce(ctx context.Context, keyURL string) if err := d.rateLimiter.WaitForAPI(ctx); err != nil { return nil, err } - resp, err := d.client.GetAuthorizedWithTokenForOrigins(ctx, keyURL, d.config.Token, d.mediaOrigins...) + resp, err := d.client.GetAuthorizedWithMediaPolicy(ctx, keyURL, d.config.Token, d.mediaPolicy()) if err != nil { return nil, err } diff --git a/internal/downloader/download_chunks.go b/internal/downloader/download_chunks.go index 1550f421..043fe63c 100644 --- a/internal/downloader/download_chunks.go +++ b/internal/downloader/download_chunks.go @@ -58,8 +58,17 @@ func (d *Downloader) doDownloadChunkWithLimit(ctx context.Context, url string, i return "", nil, 0, err } - resp, err := d.client.GetAuthorizedWithTokenForOrigins(ctx, url, d.config.Token, d.mediaOrigins...) + resp, err := d.client.GetAuthorizedWithMediaPolicy(ctx, url, d.config.Token, d.mediaPolicy()) if err != nil { + 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) + } + if d.config.StrictMediaOrigins && errors.Is(err, client.ErrMediaOrigin) { + // Any other strict-mode policy refusal also drops the chunk URL. + return "", nil, 0, fmt.Errorf("chunk %d request refused by the media origin policy: %w", chunk, err) + } return "", nil, 0, fmt.Errorf("chunk request failed for URL %s: %w", secrets.RedactURLWithToken(url, d.config.Token), err) } defer func() { closeErr := resp.Body.Close(); _ = closeErr }() diff --git a/internal/downloader/downloader.go b/internal/downloader/downloader.go index e49fba14..da9bb9eb 100644 --- a/internal/downloader/downloader.go +++ b/internal/downloader/downloader.go @@ -158,6 +158,23 @@ func newDownloader(cfg *config.Config, apiClient *client.Client, diagnostics *lo } } +// strictOriginRefusal returns the strictMediaOrigins refusal in err, if any. +// It carries only the refused scheme://host[:port], so it is safe to report. +func strictOriginRefusal(err error) *client.UnconfiguredMediaOriginError { + var originErr *client.UnconfiguredMediaOriginError + if errors.As(err, &originErr) && originErr.Strict { + return originErr + } + return nil +} + +// mediaPolicy is the request-scoped origin policy for playlist, segment and +// key requests: the API base URL plus mediaOrigins, refused before sending +// when strictMediaOrigins is set. +func (d *Downloader) mediaPolicy() client.MediaRequestPolicy { + return client.MediaRequestPolicy{Origins: d.mediaOrigins, Strict: d.config.StrictMediaOrigins} +} + func (d *Downloader) logDiagnostic(format string, args ...any) { diagnostics := d.diagnostics if diagnostics == nil { diff --git a/internal/downloader/play.go b/internal/downloader/play.go index 9fd047b2..16a1e129 100644 --- a/internal/downloader/play.go +++ b/internal/downloader/play.go @@ -111,6 +111,11 @@ func (d *Downloader) StartPlaybackStream(ctx context.Context, playlist client.Pa if playlist.KeyURL != "" { decryptionKey, err := d.fetchPlaybackDecryptionKey(ctx, playlist.KeyURL) if err != nil { + if strictErr := strictOriginRefusal(err); strictErr != nil { + // Keep the typed refusal so callers report the origin to + // configure rather than a generic key failure. + return PlaybackStream{}, fmt.Errorf("failed to fetch decryption key: %w", strictErr) + } return PlaybackStream{}, fmt.Errorf("failed to fetch decryption key: %w", sanitizedPlaybackError(err)) } keyStore = newPlaybackKey(decryptionKey) @@ -251,7 +256,7 @@ func (d *Downloader) handleSegment(playlist client.ParsedPlaylist, keyStore *pla return } - resp, err := d.client.GetAuthorizedWithTokenForOrigins(r.Context(), realURL, d.config.Token, d.mediaOrigins...) + resp, err := d.client.GetAuthorizedWithMediaPolicy(r.Context(), realURL, d.config.Token, d.mediaPolicy()) if err != nil { // A refusal by an origin outside mediaOrigins is not an // authorization failure: the segment was sent without the login. diff --git a/internal/downloader/strict_media_origin_test.go b/internal/downloader/strict_media_origin_test.go new file mode 100644 index 00000000..7b8e50f0 --- /dev/null +++ b/internal/downloader/strict_media_origin_test.go @@ -0,0 +1,282 @@ +package downloader + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/rabesss/impartus-cli/internal/client" + "github.com/rabesss/impartus-cli/internal/config" + "github.com/rabesss/impartus-cli/internal/retry" +) + +const ( + strictPathMarker = "private-strict-path" + strictQueryMarker = "signed-strict-query" +) + +func newStrictCountingServer(t *testing.T) (*httptest.Server, *atomic.Int32) { + t.Helper() + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(server.Close) + return server, &hits +} + +func strictMediaURL(origin string) string { + return origin + "/" + strictPathMarker + "/media.ts?sig=" + strictQueryMarker +} + +// assertStrictDownloaderRefusal checks a strictMediaOrigins refusal: the typed +// origin error, the policy identity, and no trace of the refused URL beyond +// its origin. +func assertStrictDownloaderRefusal(t *testing.T, err error, origin string) { + t.Helper() + assertDownloaderOriginRefusal(t, err, origin) + var originErr *client.UnconfiguredMediaOriginError + if !errors.As(err, &originErr) || !originErr.Strict { + t.Fatalf("error = %q, want a strict refusal", err) + } + if !errors.Is(err, client.ErrMediaOrigin) { + t.Fatalf("error = %q, want errors.Is(ErrMediaOrigin)", err) + } + for _, leaked := range []string{strictPathMarker, strictQueryMarker} { + if strings.Contains(err.Error(), leaked) { + t.Fatalf("error = %q, leaks refused URL part %q", err, leaked) + } + } +} + +func TestDownloadChunkStrictMediaOriginsRefusesUnconfiguredOrigin(t *testing.T) { + server, hits := newStrictCountingServer(t) + + d := testLimitDownloader(t.TempDir(), client.New(server.Client(), nil)) + d.config.StrictMediaOrigins = true + path, data, written, err := d.doDownloadChunkWithLimit(t.Context(), strictMediaURL(server.URL), 1, 0, "left", true, 8) + if path != "" || data != nil || written != 0 { + t.Fatalf("refused chunk returned path=%q data=%v written=%d", path, data, written) + } + assertStrictDownloaderRefusal(t, err, server.URL) + if got := hits.Load(); got != 0 { + t.Fatalf("unconfigured origin hits = %d, want 0", got) + } +} + +func TestFetchDecryptionKeyStrictMediaOriginsRefusesUnconfiguredOrigin(t *testing.T) { + server, hits := newStrictCountingServer(t) + + d := New(&config.Config{Token: "test-token", StrictMediaOrigins: true}, client.New(server.Client(), nil)) + d.retry = retry.Policy{} + key, err := d.fetchDecryptionKey(t.Context(), strictMediaURL(server.URL)) + if key != nil { + t.Fatalf("refused key fetch returned %d bytes", len(key)) + } + assertStrictDownloaderRefusal(t, err, server.URL) + if got := hits.Load(); got != 0 { + t.Fatalf("unconfigured origin hits = %d, want 0", got) + } +} + +func TestDownloadPlaylistStrictMediaOriginsReportsRefusedChunkOrigin(t *testing.T) { + for _, enablePipeline := range []bool{false, true} { + t.Run(fmt.Sprintf("pipeline=%t", enablePipeline), func(t *testing.T) { + key := []byte("0123456789abcdef") + configured := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/key" { + writeDownloadSpeedResponse(w, fakeKeyResponse(key)) + return + } + http.NotFound(w, r) + })) + defer configured.Close() + cdn, cdnHits := newStrictCountingServer(t) + + cfg := &config.Config{ + BaseURL: configured.URL, + Token: "test-token", + StrictMediaOrigins: true, + TempDirLocation: t.TempDir(), + Views: "left", + EnablePipeline: enablePipeline, + DownloadWorkersPerLecture: 1, + DecryptWorkersPerLecture: 1, + RateLimit: 100, + APIRateLimit: 20, + } + d := New(cfg, client.New(configured.Client(), nil)) + d.retry = retry.Policy{} + + _, err := d.DownloadPlaylist(t.Context(), client.ParsedPlaylist{ + ID: 42, + SeqNo: 1, + KeyURL: configured.URL + "/key", + FirstViewURLs: []string{strictMediaURL(cdn.URL)}, + }, nil, nil) + assertStrictDownloaderRefusal(t, err, cdn.URL) + if got := cdnHits.Load(); got != 0 { + t.Fatalf("unconfigured chunk origin hits = %d, want 0", got) + } + }) + } +} + +func TestStartPlaybackStreamStrictMediaOriginsKeepsKeyRefusalType(t *testing.T) { + server, hits := newStrictCountingServer(t) + + d := New(&config.Config{Views: "left", Token: "test-token", StrictMediaOrigins: true}, client.New(nil, nil)) + d.retry = retry.Policy{} + stream, err := d.StartPlaybackStream(context.Background(), client.ParsedPlaylist{ + KeyURL: strictMediaURL(server.URL), + FirstViewURLs: []string{server.URL + "/segment"}, + }) + if err == nil { + stream.Cleanup() + t.Fatal("StartPlaybackStream() error = nil, want strict key refusal") + } + assertStrictDownloaderRefusal(t, err, server.URL) + if got := hits.Load(); got != 0 { + t.Fatalf("unconfigured key origin hits = %d, want 0", got) + } +} + +func TestPlaybackStreamStrictMediaOriginsReportsRefusedSegmentOrigin(t *testing.T) { + key := []byte("0123456789abcdef") + configured := newPlayTestUpstream(t, key, http.StatusOK) + defer configured.Close() + cdn, cdnHits := newStrictCountingServer(t) + + d := New(&config.Config{BaseURL: configured.URL, Views: "left", Token: "test-token", StrictMediaOrigins: true}, client.New(nil, nil)) + stream, err := d.StartPlaybackStream(context.Background(), client.ParsedPlaylist{ + KeyURL: configured.URL + "/key", + FirstViewURLs: []string{strictMediaURL(cdn.URL)}, + }) + if err != nil { + t.Fatalf("StartPlaybackStream() error = %v", err) + } + defer stream.Cleanup() + + segmentURL := strings.TrimSuffix(stream.URL, "master.m3u8") + "segment/left/0" + resp, err := http.Get(segmentURL) //nolint:noctx // test-only local request + if err != nil { + t.Fatalf("request segment: %v", err) + } + defer resp.Body.Close() //nolint:errcheck + if resp.StatusCode != http.StatusBadGateway { + t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusBadGateway) + } + + select { + case failure := <-stream.Failures: + assertStrictDownloaderRefusal(t, failure, cdn.URL) + default: + t.Fatal("playback stream did not report the strict origin refusal") + } + if got := cdnHits.Load(); got != 0 { + t.Fatalf("unconfigured segment origin hits = %d, want 0", got) + } +} + +// assertWithheldStrictRefusal checks a strict refusal whose origin carries the +// bearer: typed and classified, origin withheld, and no trace of the URL. +func assertWithheldStrictRefusal(t *testing.T, err error, token string) { + t.Helper() + var originErr *client.UnconfiguredMediaOriginError + if !errors.As(err, &originErr) || !originErr.Strict || originErr.Origin != "" { + t.Fatalf("error = %v, want a strict refusal with the origin withheld", err) + } + if !errors.Is(err, client.ErrMediaOrigin) || errors.Is(err, client.ErrAuthentication) { + t.Fatalf("error = %v, want ErrMediaOrigin and not ErrAuthentication", err) + } + for _, leaked := range []string{strings.ToLower(token), strictPathMarker, strictQueryMarker} { + if strings.Contains(strings.ToLower(err.Error()), leaked) { + t.Fatalf("error = %q, leaks %q", err, leaked) + } + } +} + +func TestDownloadChunkStrictMediaOriginsWithholdsBearerOrigin(t *testing.T) { + d := testLimitDownloader(t.TempDir(), client.New(nil, nil)) + d.config.StrictMediaOrigins = true + d.config.Token = "MiXeDChunkBearer" + path, data, written, err := d.doDownloadChunkWithLimit(t.Context(), strictMediaURL("https://"+d.config.Token+".cdn.example.test"), 1, 0, "left", true, 8) + if path != "" || data != nil || written != 0 { + t.Fatalf("refused chunk returned path=%q data=%v written=%d", path, data, written) + } + assertWithheldStrictRefusal(t, err, d.config.Token) +} + +func TestDownloadChunkStrictMediaOriginsDropsURLOnOtherPolicyRefusal(t *testing.T) { + var redirectedHits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/"+strictPathMarker+"/") { + // A same-origin redirect whose Location carries the bearer: the + // redirect credential boundary refuses it with the generic + // policy error, not a typed strict refusal. + http.Redirect(w, r, "/placeholder-token/next.ts", http.StatusFound) + return + } + redirectedHits.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + d := testLimitDownloader(t.TempDir(), client.New(server.Client(), nil)) + d.config.StrictMediaOrigins = true + d.mediaOrigins = []string{server.URL} + path, data, written, err := d.doDownloadChunkWithLimit(t.Context(), strictMediaURL(server.URL), 1, 0, "left", true, 8) + if path != "" || data != nil || written != 0 { + t.Fatalf("refused chunk returned path=%q data=%v written=%d", path, data, written) + } + if err == nil || !errors.Is(err, client.ErrMediaOrigin) { + t.Fatalf("error = %v, want ErrMediaOrigin", err) + } + for _, leaked := range []string{d.config.Token, strictPathMarker, strictQueryMarker} { + if strings.Contains(err.Error(), leaked) { + t.Fatalf("error = %q, leaks %q", err, leaked) + } + } + if got := redirectedHits.Load(); got != 0 { + t.Fatalf("redirect destination hits = %d, want 0", got) + } +} + +func TestPlaybackStreamStrictMediaOriginsReportsWithheldBearerOrigin(t *testing.T) { + const token = "MiXeDPlaybackBearer" + key := []byte("0123456789abcdef") + configured := newPlayTestUpstream(t, key, http.StatusOK) + defer configured.Close() + + d := New(&config.Config{BaseURL: configured.URL, Views: "left", Token: token, StrictMediaOrigins: true}, client.New(nil, nil)) + stream, err := d.StartPlaybackStream(context.Background(), client.ParsedPlaylist{ + KeyURL: configured.URL + "/key", + FirstViewURLs: []string{strictMediaURL("https://" + token + ".cdn.example.test")}, + }) + if err != nil { + t.Fatalf("StartPlaybackStream() error = %v", err) + } + defer stream.Cleanup() + + segmentURL := strings.TrimSuffix(stream.URL, "master.m3u8") + "segment/left/0" + resp, err := http.Get(segmentURL) //nolint:noctx // test-only local request + if err != nil { + t.Fatalf("request segment: %v", err) + } + defer resp.Body.Close() //nolint:errcheck + if resp.StatusCode != http.StatusBadGateway { + t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusBadGateway) + } + select { + case failure := <-stream.Failures: + assertWithheldStrictRefusal(t, failure, token) + default: + t.Fatal("playback stream did not report the strict origin refusal") + } +} diff --git a/internal/server/job_executor_errors.go b/internal/server/job_executor_errors.go index 18dedfdf..b388d4ff 100644 --- a/internal/server/job_executor_errors.go +++ b/internal/server/job_executor_errors.go @@ -50,6 +50,11 @@ func sanitizeUpstreamErr(err error) string { if errors.Is(err, client.ErrAuthentication) { return "upstream authentication failed" } + // Any other media-origin policy refusal is not a login failure either, + // although ErrMediaOrigin's text mentions authorization. + if errors.Is(err, client.ErrMediaOrigin) { + return mediaOriginPolicyRefusal + } // HTTP status code errors — extract status code from formatted error messages errStr := err.Error() if match := httpStatusRe.FindStringSubmatch(errStr); len(match) > 1 { @@ -62,6 +67,10 @@ func sanitizeUpstreamErr(err error) string { return "upstream API error" } +// mediaOriginPolicyRefusal is the job error for a media URL rejected by the +// media origin policy, without the URL, which may carry signing material. +const mediaOriginPolicyRefusal = "media URL rejected by the media URL policy (check mediaOrigins / IMPARTUS_MEDIA_ORIGINS and that the URL is HTTPS without credentials)" + func containsAny(s string, substrs []string) bool { for _, sub := range substrs { if strings.Contains(strings.ToLower(s), sub) { diff --git a/internal/server/job_executor_slide_test.go b/internal/server/job_executor_slide_test.go index 9c913265..48ed4bf4 100644 --- a/internal/server/job_executor_slide_test.go +++ b/internal/server/job_executor_slide_test.go @@ -512,3 +512,44 @@ func TestDownloadLectureSlideOmitsEncodedPartialToken(t *testing.T) { t.Fatalf("slide error = %v, want the encoded token body omitted", err) } } + +func TestDownloadLectureSlideStrictMediaOriginsNamesRefusedRedirectOrigin(t *testing.T) { + const token = "slide-strict-secret" + var unconfiguredRequests int + unconfigured := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + unconfiguredRequests++ + w.WriteHeader(http.StatusOK) + })) + defer unconfigured.Close() + redirectSource := httptest.NewServer(http.RedirectHandler(unconfigured.URL+"/private-slide-path/slide.pdf?sig=signed-slide-query", http.StatusFound)) + defer redirectSource.Close() + + cfg := &config.Config{ + BaseURL: redirectSource.URL, + DownloadLocation: t.TempDir(), + Token: token, + StrictMediaOrigins: true, + } + err := downloadLectureSlideWithLimit(context.Background(), client.New(redirectSource.Client(), nil), cfg, client.Lecture{VideoID: 12, SeqNo: 1, Topic: "Strict"}, 8) + var originErr *client.UnconfiguredMediaOriginError + if !errors.As(err, &originErr) || !originErr.Strict || originErr.Origin != unconfigured.URL { + t.Fatalf("strict slide redirect error = %v, want a strict refusal naming %s", err, unconfigured.URL) + } + if !errors.Is(err, client.ErrMediaOrigin) { + t.Fatalf("strict slide redirect error = %v, want errors.Is(ErrMediaOrigin)", err) + } + if unconfiguredRequests != 0 { + t.Fatalf("unconfigured-origin requests = %d, want 0", unconfiguredRequests) + } + got := sanitizeUpstreamErr(err) + for _, want := range []string{unconfigured.URL, "IMPARTUS_MEDIA_ORIGINS", "strictMediaOrigins"} { + if !strings.Contains(got, want) { + t.Fatalf("sanitizeUpstreamErr(strict refusal) = %q, want it to mention %q", got, want) + } + } + for _, leaked := range []string{token, "private-slide-path", "signed-slide-query", "authentication failed"} { + if strings.Contains(got, leaked) { + t.Fatalf("sanitizeUpstreamErr(strict refusal) = %q, must not contain %q", got, leaked) + } + } +} diff --git a/internal/server/job_executor_slides.go b/internal/server/job_executor_slides.go index ef3c1c82..11bbdfec 100644 --- a/internal/server/job_executor_slides.go +++ b/internal/server/job_executor_slides.go @@ -53,7 +53,7 @@ func downloadLectureSlideWithLimit(ctx context.Context, c *client.Client, cfg *c return err } origins := append([]string{cfg.BaseURL}, cfg.MediaOrigins...) - resp, err := c.GetAuthorizedWithTokenForOrigins(ctx, url, cfg.Token, origins...) + resp, err := c.GetAuthorizedWithMediaPolicy(ctx, url, cfg.Token, client.MediaRequestPolicy{Origins: origins, Strict: cfg.StrictMediaOrigins}) if err != nil { return err } diff --git a/internal/server/job_executor_test.go b/internal/server/job_executor_test.go index f4ae99b9..4a5a165b 100644 --- a/internal/server/job_executor_test.go +++ b/internal/server/job_executor_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" "github.com/rabesss/impartus-cli/internal/client" @@ -243,3 +244,70 @@ func TestContainsAny(t *testing.T) { t.Error("expected no match for clean message") } } + +func TestSanitizeUpstreamErrDoesNotReportMediaOriginPolicyAsAuthentication(t *testing.T) { + err := fmt.Errorf("chunk 0 request refused by the media origin policy: %w", client.ErrMediaOrigin) + if got := sanitizeUpstreamErr(err); got != mediaOriginPolicyRefusal { + t.Fatalf("sanitizeUpstreamErr() = %q, want %q", got, mediaOriginPolicyRefusal) + } + withheld := fmt.Errorf("chunk 0 request refused: %w", &client.UnconfiguredMediaOriginError{Strict: true}) + got := sanitizeUpstreamErr(withheld) + if strings.Contains(got, "authentication failed") || !strings.Contains(got, "withheld") { + t.Fatalf("sanitizeUpstreamErr() = %q, want the withheld strict refusal", got) + } +} + +func TestSanitizeUpstreamErrExplainsStrictOriginRefusal(t *testing.T) { + const urlMarker = "strict-chunk-path-marker" + keyResponse := append([]byte{0, 0}, []byte("fedcba9876543210")...) + configured := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/key" { + if _, err := w.Write(keyResponse); err != nil { + t.Errorf("write key response: %v", err) + } + return + } + http.NotFound(w, r) + })) + defer configured.Close() + var cdnRequests atomic.Int32 + cdn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + cdnRequests.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer cdn.Close() + + cfg := &config.Config{ + BaseURL: configured.URL, + Token: "request-token", + StrictMediaOrigins: true, + TempDirLocation: t.TempDir(), + Views: "left", + EnablePipeline: true, + DownloadWorkersPerLecture: 1, + DecryptWorkersPerLecture: 1, + RateLimit: 100, + APIRateLimit: 100, + } + d := downloader.NewWithDiagnosticWriter(cfg, client.New(configured.Client(), nil), io.Discard) + _, err := d.DownloadPlaylist(t.Context(), client.ParsedPlaylist{ + ID: 42, + SeqNo: 1, + KeyURL: configured.URL + "/key", + FirstViewURLs: []string{cdn.URL + "/" + urlMarker + "?sig=strict-query-marker"}, + }, nil, nil) + got := sanitizeUpstreamErr(err) + for _, want := range []string{cdn.URL, "IMPARTUS_MEDIA_ORIGINS", "strictMediaOrigins"} { + if !strings.Contains(got, want) { + t.Fatalf("sanitizeUpstreamErr(strict refusal) = %q, want it to mention %q", got, want) + } + } + for _, leaked := range []string{urlMarker, "strict-query-marker", "authentication failed"} { + if strings.Contains(got, leaked) { + t.Fatalf("sanitizeUpstreamErr(strict refusal) = %q, must not contain %q", got, leaked) + } + } + if got := cdnRequests.Load(); got != 0 { + t.Fatalf("unconfigured CDN requests = %d, want 0", got) + } +} diff --git a/sample.config.json b/sample.config.json index bea212bf..6a704396 100644 --- a/sample.config.json +++ b/sample.config.json @@ -3,6 +3,7 @@ "password": "your_impartus_password", "baseUrl": "https://a.impartus.com/api", "mediaOrigins": [], + "strictMediaOrigins": false, "quality": "720", "views": "both", "downloadLocation": "./downloads",