Skip to content
Merged
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,26 @@ $encoder = new Encoder(

Use `['https', 'tls', 'tcp']` as the protocols for a source read from a URL.

### Sources read from a URL

ffmpeg asks an HTTP source for everything from an offset to the end of the file. A source that
answers in pieces of its own choosing, or that wants a credential the URL cannot carry, is told so
with protocol options and headers. Both go before each URL input on the ffmpeg and ffprobe command
lines; a local file is opened without them.

```php
$options = ['request_size' => 16 * 1024 * 1024, 'multiple_requests' => 1];
$headers = ['X-Api-Key' => $key];

$encoder = new Encoder(
new FFmpeg(options: $options, headers: $headers),
new FFprobe(options: $options, headers: $headers),
);
```

Options are named as ffmpeg names them. Headers are treated as a secret: the command a failure
reports carries `***` in their place.

### How much a backend says

Every adapter has a display level, defaulting to `Adapter::ERROR` — only what went wrong, because
Expand Down
97 changes: 95 additions & 2 deletions src/Video/Adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ abstract class Adapter
/** @var list<string> Demuxers an input may be read with; empty allows any. */
protected readonly array $formats;

/** @var array<string, string> Protocol options a URL input is opened with. */
protected readonly array $options;

/** @var array<string, string> Headers a URL input is requested with; treated as a secret. */
protected readonly array $headers;

/**
* Who reads media details for this adapter.
*
Expand Down Expand Up @@ -144,6 +150,17 @@ abstract class Adapter
* `matroska`, ...); empty allows any. Leaving
* out playlist formats such as `hls` and
* `concat` stops a source from opening others.
* @param array<string, int|string> $options Protocol options a URL input is
* opened with, by ffmpeg's name for
* them (`request_size`,
* `multiple_requests`). A local
* file is opened without them: it
* has no such options, and ffmpeg
* refuses a command that names one.
* @param array<string, string> $headers Headers a URL input is requested
* with, for a source that wants a
* credential the URL cannot carry.
* Kept out of every exception.
*
* @throws Unsupported
* @throws Input
Expand All @@ -155,21 +172,28 @@ public function __construct(
?string $level = null,
array $protocols = [],
array $formats = [],
array $options = [],
array $headers = [],
) {
$this->binary = $binary ?? static::BINARY;
$this->timeout = $timeout ?? static::TIMEOUT;
$this->threads = $threads;
$this->level = $level === null ? static::LEVEL : self::graded($level);
$this->protocols = self::names($protocols);
$this->formats = self::names($formats);
$this->options = self::settings($options);
$this->headers = self::fields($headers);
}

/**
* Options that restrict how the next input is opened, placed before it.
* Options that decide how the next input is opened, placed before it.
*
* The whitelists restrict any input. Protocol options and headers belong to
* a URL alone, so a local path is opened without them.
*
* @return list<string>
*/
protected function opens(): array
protected function opens(string $path): array
{
$args = [];

Expand All @@ -183,9 +207,78 @@ protected function opens(): array
$args[] = \implode(',', $this->formats);
}

if (! Source::remote($path)) {
return $args;
}

foreach ($this->options as $name => $value) {
$args[] = '-'.$name;
$args[] = $value;
}

if ($this->headers !== []) {
$lines = '';
foreach ($this->headers as $name => $value) {
$lines .= $name.': '.$value."\r\n";
}

$args[] = Process::HEADERS;
$args[] = $lines;
}

return $args;
}

/**
* @param array<mixed> $options
* @return array<string, string>
*
* @throws Input
*/
private static function settings(array $options): array
{
$settings = [];

foreach ($options as $name => $value) {
// Each becomes a flag of its own, so a name must be nothing but a name.
if (! \is_string($name) || \preg_match('/^[a-z0-9_]+$/', $name) !== 1) {
throw new Input('Invalid input option name: '.\var_export($name, true));
}
if (! \is_int($value) && (! \is_string($value) || \preg_match('/^[A-Za-z0-9_.:\/-]+$/', $value) !== 1)) {
throw new Input('Invalid value for input option "'.$name.'"');
}
$settings[$name] = (string) $value;
}

return $settings;
}

/**
* @param array<mixed> $headers
* @return array<string, string>
*
* @throws Input
*/
private static function fields(array $headers): array
{
$fields = [];

foreach ($headers as $name => $value) {
if (! \is_string($name) || \preg_match('/^[A-Za-z0-9-]+$/', $name) !== 1) {
throw new Input('Invalid header name: '.\var_export($name, true));
}
// Joined into one argument a line each, so a value that carried a
// line break would add a header of its own. The value is not echoed:
// it is a credential.
if (! \is_string($value) || $value === '' || \preg_match('/[\x00-\x1F\x7F]/', $value) === 1) {
throw new Input('Invalid value for header "'.$name.'"');
}
$fields[$name] = $value;
}

return $fields;
}

/**
* @param array<mixed> $names
* @return list<string>
Expand Down
10 changes: 5 additions & 5 deletions src/Video/Adapter/FFmpeg.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public function encode(string $path): string
$video = $info->hasVideo && ($rep === null || $rep->scaled());

$args = $this->prefix();
\array_push($args, ...$this->opens());
\array_push($args, ...$this->opens($source));
$args[] = '-i';
$args[] = $source;

Expand Down Expand Up @@ -178,7 +178,7 @@ public function pack(string $dir): Package
$args = $this->prefix();

foreach ($this->paths() as $input) {
\array_push($args, ...$this->opens());
\array_push($args, ...$this->opens($input));
$args[] = '-i';
$args[] = $input;
}
Expand Down Expand Up @@ -238,7 +238,7 @@ public function grab(string $path, string $output, ?Thumb $options = null): stri
$args[] = self::number($at);
}

\array_push($args, ...$this->opens());
\array_push($args, ...$this->opens($path));
$args[] = '-i';
$args[] = $path;
$args[] = '-map';
Expand Down Expand Up @@ -299,7 +299,7 @@ public function subtitle(string $path, int $stream, string $output, ?int $timeou
$this->directory(\dirname($output));

$args = $this->prefix(progress: false);
\array_push($args, ...$this->opens());
\array_push($args, ...$this->opens($path));
$args[] = '-i';
$args[] = $path;
$args[] = '-map';
Expand Down Expand Up @@ -338,7 +338,7 @@ public function tile(string $path, string $dir, ?Tile $options = null): Spritesh
$height += $height % 2;

$args = $this->prefix(progress: false);
\array_push($args, ...$this->opens());
\array_push($args, ...$this->opens($path));
$args[] = '-i';
$args[] = $path;
$args[] = '-fps_mode';
Expand Down
2 changes: 1 addition & 1 deletion src/Video/Adapter/FFprobe.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function read(string $path): Info
'-show_format',
'-show_streams',
'-show_chapters',
...$this->opens(),
...$this->opens($path),
$this->source($path),
]);

Expand Down
31 changes: 28 additions & 3 deletions src/Video/Process.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ final class Process
/** Bytes of collected output to hold before giving up on a command. */
private const OUTPUT = 8388608;

/**
* The flag whose value is request headers, which may carry a credential.
* A failure reports the command that failed, so that value is left out of it.
*/
public const HEADERS = '-headers';

private const MASK = '***';

/**
* @param list<string> $command
* @param callable(string):void|null $stdout Called once per line written to stdout.
Expand Down Expand Up @@ -69,7 +77,7 @@ public static function run(
$process = @\proc_open($command, $descriptors, $pipes);

if (! \is_resource($process)) {
throw new Runtime('Unable to start "'.$command[0].'"', $command);
throw new Runtime('Unable to start "'.$command[0].'"', self::masked($command));
}

\fclose($pipes[0]);
Expand Down Expand Up @@ -183,7 +191,7 @@ public static function run(
if ($status !== 0) {
throw new Runtime(
'Command "'.$command[0].'" failed with exit code '.$status,
$command,
self::masked($command),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Redact headers from captured error output too

At DEBUG, libavformat can write its serialized HTTP request, including custom headers, to stderr. This passes that tail unchanged into Runtime::output(), so a failed request can expose the credential even though command() is masked; redact header values in captured diagnostics too.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Video/Process.php
Line: 194

Comment:
**Redact headers from captured error output too**

At `DEBUG`, libavformat can write its serialized HTTP request, including custom headers, to stderr. This passes that tail unchanged into `Runtime::output()`, so a failed request can expose the credential even though `command()` is masked; redact header values in captured diagnostics too.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · security · Reply if this doesn't apply.

\trim($errors),
$status,
);
Expand Down Expand Up @@ -318,7 +326,24 @@ private static function halt(

\proc_close($process);

return new Runtime($message, $command, \trim($errors), self::ended($status));
return new Runtime($message, self::masked($command), \trim($errors), self::ended($status));
}

/**
* The command as a failure may report it: without its request headers.
*
* @param list<string> $command
* @return list<string>
*/
private static function masked(array $command): array
{
foreach ($command as $index => $argument) {
if ($argument === self::HEADERS && isset($command[$index + 1])) {
$command[$index + 1] = self::MASK;
}
}

return $command;
}

/**
Expand Down
63 changes: 63 additions & 0 deletions tests/Video/E2E/RemoteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

namespace Utopia\Tests\E2E;

use Utopia\Video\Adapter\FFmpeg;
use Utopia\Video\Adapter\FFprobe;
use Utopia\Video\Encoder;
use Utopia\Video\Exception\Runtime;
use Utopia\Video\Format\X264;
use Utopia\Video\Output\Hls;
use Utopia\Video\Packager;
Expand Down Expand Up @@ -170,4 +173,64 @@ public function testASingleFileIsEncodedFromAUrl(): void

$this->assertWritten($path);
}

/**
* Left alone, ffmpeg asks for everything from an offset to the end of the
* file. A source that answers in pieces of its own choosing needs to be
* asked for pieces, and the request size is what does that.
*/
public function testAUrlIsReadInRequestsOfTheGivenSize(): void
{
$options = ['request_size' => 65536, 'multiple_requests' => 1];
$encoder = new Encoder(new FFmpeg(options: $options), new FFprobe(options: $options));

$path = $encoder
->open($this->url())
->format((new X264())->crf(30)->params(['-preset', 'ultrafast']))
->encode($this->dir.'/out.mp4');

$this->assertWritten($path);
$this->assertNotEmpty($this->ranges(), 'ffmpeg never asked for a byte range');

foreach ($this->ranges() as $range) {
[$start, $end] = \array_map(\intval(...), \explode('-', $range));
$this->assertLessThanOrEqual(65536, $end - $start + 1, 'range '.$range.' is larger than the request size');
}
}

public function testAUrlIsRequestedWithTheGivenHeaders(): void
{
$url = self::$url.'/source.mp4?guard=letmein';

$this->assertFalse((new Packager())->valid($url), 'the guarded source was served without its header');

$headers = ['X-Guard' => 'letmein'];
$encoder = new Encoder(new FFmpeg(headers: $headers), new FFprobe(headers: $headers));

$this->assertEqualsWithDelta(8.0, $encoder->probe($url)->duration, 0.2);

$sheet = $encoder->tile($url, $this->dir, new Tile());
$this->assertNotEmpty($sheet->images());
}

/**
* A failure carries the command that failed, and a header is where a
* credential goes when the URL cannot hold it.
*/
public function testAFailedCommandDoesNotReportItsHeaders(): void
{
$probe = new FFprobe(headers: ['X-Guard' => 'a-secret-value']);

try {
$probe->read(self::$url.'/nothing.mp4');
$this->fail('a source that answers not found was read');
} catch (Runtime $error) {
$command = \implode(' ', $error->command());

$this->assertStringContainsString('-headers ***', $command);
$this->assertStringNotContainsString('a-secret-value', $command);
$this->assertStringNotContainsString('a-secret-value', $error->getMessage());
$this->assertStringNotContainsString('a-secret-value', $error->output());
}
}
}
13 changes: 13 additions & 0 deletions tests/Video/E2E/serve.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
* whose index sits at the end cannot be read without seeking, so this honours
* single byte ranges with a 206. Every ranged answer is appended to the log
* named by UTOPIA_SERVE_LOG, which is how a test proves seeking happened.
*
* A URL carrying `guard=<value>` is only served to a request whose X-Guard
* header says the same, standing in for a source that wants a credential.
*/
$root = (string) \getenv('UTOPIA_SERVE_ROOT');
$log = (string) \getenv('UTOPIA_SERVE_LOG');
Expand All @@ -22,6 +25,16 @@
return true;
}

$query = [];
\parse_str((string) \parse_url(\is_string($uri) ? $uri : '', PHP_URL_QUERY), $query);
$guard = $query['guard'] ?? null;

if (\is_string($guard) && ($_SERVER['HTTP_X_GUARD'] ?? '') !== $guard) {
\http_response_code(401);

return true;
}

$size = (int) \filesize($path);
$start = 0;
$end = $size - 1;
Expand Down
Loading