Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions internal/client/auth_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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
}
21 changes: 19 additions & 2 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
17 changes: 14 additions & 3 deletions internal/client/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}

Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
Expand Down
56 changes: 55 additions & 1 deletion internal/client/media_origin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading