From 1fdaa6f1cfff34c463711648478243988774951b Mon Sep 17 00:00:00 2001 From: shimon Date: Thu, 19 Nov 2026 18:41:41 +0200 Subject: [PATCH] feat: open URL inputs with protocol options and headers Adapters take optional options and headers, placed before every URL input on the ffmpeg and ffprobe command lines. A local file is opened without them, since ffmpeg refuses a protocol option it has no use for. Header values are a credential, so the command a failure reports carries a mask in their place. Co-Authored-By: Claude Fable 5.2 --- README.md | 20 +++++++ src/Video/Adapter.php | 97 +++++++++++++++++++++++++++++++- src/Video/Adapter/FFmpeg.php | 10 ++-- src/Video/Adapter/FFprobe.php | 2 +- src/Video/Process.php | 31 +++++++++- tests/Video/E2E/RemoteTest.php | 63 +++++++++++++++++++++ tests/Video/E2E/serve.php | 13 +++++ tests/Video/Unit/AdapterTest.php | 81 ++++++++++++++++++++++++++ 8 files changed, 306 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 4a45c6e..5ea30b0 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/Video/Adapter.php b/src/Video/Adapter.php index 66d964d..843c6e1 100644 --- a/src/Video/Adapter.php +++ b/src/Video/Adapter.php @@ -111,6 +111,12 @@ abstract class Adapter /** @var list Demuxers an input may be read with; empty allows any. */ protected readonly array $formats; + /** @var array Protocol options a URL input is opened with. */ + protected readonly array $options; + + /** @var array Headers a URL input is requested with; treated as a secret. */ + protected readonly array $headers; + /** * Who reads media details for this adapter. * @@ -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 $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 $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 @@ -155,6 +172,8 @@ public function __construct( ?string $level = null, array $protocols = [], array $formats = [], + array $options = [], + array $headers = [], ) { $this->binary = $binary ?? static::BINARY; $this->timeout = $timeout ?? static::TIMEOUT; @@ -162,14 +181,19 @@ public function __construct( $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 */ - protected function opens(): array + protected function opens(string $path): array { $args = []; @@ -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 $options + * @return array + * + * @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 $headers + * @return array + * + * @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 $names * @return list diff --git a/src/Video/Adapter/FFmpeg.php b/src/Video/Adapter/FFmpeg.php index cb019d6..6ed7909 100644 --- a/src/Video/Adapter/FFmpeg.php +++ b/src/Video/Adapter/FFmpeg.php @@ -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; @@ -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; } @@ -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'; @@ -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'; @@ -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'; diff --git a/src/Video/Adapter/FFprobe.php b/src/Video/Adapter/FFprobe.php index 7620c66..e1077ff 100644 --- a/src/Video/Adapter/FFprobe.php +++ b/src/Video/Adapter/FFprobe.php @@ -43,7 +43,7 @@ public function read(string $path): Info '-show_format', '-show_streams', '-show_chapters', - ...$this->opens(), + ...$this->opens($path), $this->source($path), ]); diff --git a/src/Video/Process.php b/src/Video/Process.php index ceb5a05..8457b85 100644 --- a/src/Video/Process.php +++ b/src/Video/Process.php @@ -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 $command * @param callable(string):void|null $stdout Called once per line written to stdout. @@ -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]); @@ -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), \trim($errors), $status, ); @@ -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 $command + * @return list + */ + 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; } /** diff --git a/tests/Video/E2E/RemoteTest.php b/tests/Video/E2E/RemoteTest.php index 3136971..503b4d3 100644 --- a/tests/Video/E2E/RemoteTest.php +++ b/tests/Video/E2E/RemoteTest.php @@ -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; @@ -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()); + } + } } diff --git a/tests/Video/E2E/serve.php b/tests/Video/E2E/serve.php index 1c2fcf4..698bbfb 100644 --- a/tests/Video/E2E/serve.php +++ b/tests/Video/E2E/serve.php @@ -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=` 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'); @@ -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; diff --git a/tests/Video/Unit/AdapterTest.php b/tests/Video/Unit/AdapterTest.php index 751e842..122d95f 100644 --- a/tests/Video/Unit/AdapterTest.php +++ b/tests/Video/Unit/AdapterTest.php @@ -4,6 +4,7 @@ namespace Utopia\Tests\Unit; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Utopia\Video\Adapter; use Utopia\Video\Adapter\Encoder as EncoderAdapter; @@ -348,6 +349,86 @@ public function command(): array ); } + /** + * Protocol options and headers belong to a URL. A local file has no such + * options, and ffmpeg refuses a command that names one. + */ + public function testInputOptionsAndHeadersReachOnlyAUrl(): void + { + $adapter = new class (options: ['request_size' => 1024, 'multiple_requests' => 1], headers: ['X-Key' => 'secret', 'X-Other' => 'value']) extends FFmpeg { + /** @return list */ + public function before(string $path): array + { + return $this->opens($path); + } + }; + + $this->assertSame( + ['-request_size', '1024', '-multiple_requests', '1', '-headers', "X-Key: secret\r\nX-Other: value\r\n"], + $adapter->before('https://example.com/source.mp4?signature=abc'), + ); + $this->assertSame([], $adapter->before('/tmp/source.mp4')); + } + + public function testInputOptionsFollowTheWhitelists(): void + { + $adapter = new class (protocols: ['https', 'tls', 'tcp'], options: ['request_size' => 1024]) extends FFprobe { + /** @return list */ + public function before(string $path): array + { + return $this->opens($path); + } + }; + + $this->assertSame( + ['-protocol_whitelist', 'https,tls,tcp', '-request_size', '1024'], + $adapter->before('https://example.com/source.mp4'), + ); + $this->assertSame(['-protocol_whitelist', 'https,tls,tcp'], $adapter->before('/tmp/source.mp4')); + } + + /** + * @param array $options + * @param array $headers + */ + #[DataProvider('unusable')] + public function testAnUnusableInputOptionOrHeaderIsRejected(array $options, array $headers): void + { + $this->expectException(Input::class); + + // @phpstan-ignore argument.type, argument.type (the point is that these are the wrong shape) + new FFmpeg(options: $options, headers: $headers); + } + + /** + * @return array, array}> + */ + public static function unusable(): array + { + return [ + 'an option that is a flag of its own' => [['-y' => 1], []], + 'an option without a name' => [[1024], []], + 'an option value with a space' => [['request_size' => '1 -i /etc/passwd'], []], + 'a header name with a colon' => [[], ['X-Key: other' => 'value']], + 'a header value with a line break' => [[], ['X-Key' => "value\r\nX-Other: injected"]], + 'an empty header value' => [[], ['X-Key' => '']], + ]; + } + + /** + * The message says which header was refused, never what it held. + */ + public function testARejectedHeaderIsNotEchoed(): void + { + try { + new FFmpeg(headers: ['X-Key' => "a-secret\nvalue"]); + $this->fail('a header value with a line break was accepted'); + } catch (Input $error) { + $this->assertStringContainsString('X-Key', $error->getMessage()); + $this->assertStringNotContainsString('a-secret', $error->getMessage()); + } + } + /** * A quiet backend has nothing to say, but still reports its progress — * progress is structured data, not commentary.