Beautiful Open-Source Form Builder
Enhance PDF image handling and form submission features (#1136)
Chirag Chhatralaac3171fed40e
diff --git a/api/app/Service/Pdf/PdfCacheService.php b/api/app/Service/Pdf/PdfCacheService.phpindex 5c2dc34e1..2ad16c63c 100644--- a/api/app/Service/Pdf/PdfCacheService.php+++ b/api/app/Service/Pdf/PdfCacheService.php@@ -12,7 +12,7 @@ class PdfCacheService{private const CACHE_TTL = 3600; // 1 hour- private const LOCK_TTL = 30; // 30 seconds max lock time+ private const LOCK_TTL = 120; // seconds; must exceed slow PDF generation with remote images// Use same temp folder as generator for lifecycle cleanupprivate const TEMP_FOLDER = 'tmp/pdf-output';diff --git a/api/app/Service/Pdf/PdfImageResolver.php b/api/app/Service/Pdf/PdfImageResolver.phpindex b7bd76670..a56cfb264 100644--- a/api/app/Service/Pdf/PdfImageResolver.php+++ b/api/app/Service/Pdf/PdfImageResolver.php@@ -4,35 +4,64 @@ namespace App\Service\Pdf;use App\Http\Controllers\Forms\FormController;use App\Models\Forms\Form;+use App\Service\Storage\FilenameUrlEncoder;use App\Service\Storage\FileUploadPathService;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;+use League\Flysystem\UnableToCheckFileExistence;class PdfImageResolver{+ private array $resolvedContentCache = [];+ private ?array $allowedAssetHosts = null;+public function __construct(- private readonly ?Form $form = null+ private readonly ?Form $form = null,+ private readonly ?PdfSafeImageFetcher $remoteFetcher = null,) {}/**- * Resolve a zone image value to binary content from storage.- *- * URL-shaped values are treated as references to previously uploaded files- * by filename only. They are never fetched over the network.+ * Resolve a zone image value to binary content from storage or a safe remote URL.*/public function resolveContent(string $imageValue): ?string+ {+ $normalized = trim($imageValue);+ if ($normalized === '') {+ return null;+ }++ if (array_key_exists($normalized, $this->resolvedContentCache)) {+ return $this->resolvedContentCache[$normalized];+ }++ $content = $this->resolveUncachedContent($normalized);+ $this->resolvedContentCache[$normalized] = $content;++ return $content;+ }++ private function resolveUncachedContent(string $normalized): ?string{try {- foreach ($this->candidatePaths($imageValue) as $path) {- if (Storage::exists($path)) {- return Storage::get($path);+ foreach ($this->candidatePaths($normalized) as $path) {+ $content = $this->readFromStorage($path);+ if ($content !== null) {+ return $content;}}++ if ($this->isUrl($normalized)) {+ if (!$this->shouldRemoteFetch($normalized)) {+ return null;+ }++ return $this->remoteFetcher()->fetch($normalized);+ }} catch (\Throwable $e) {Log::debug('PDF image resolve failed', ['form_id' => $this->form?->id,- 'value' => $imageValue,+ 'value' => $normalized,'error' => $e->getMessage(),]);}@@ -42,37 +71,203 @@ class PdfImageResolverprivate function candidatePaths(string $imageValue): array{+ if ($this->isUrl($imageValue)) {+ if (!$this->hasAssetPath($imageValue) || !$this->matchesAppAssetOrigin($imageValue)) {+ return [];+ }+ }+$candidates = [];- $normalized = trim($imageValue);+ $restrictToFormAssets = $this->isUrl($imageValue);- if ($normalized === '') {- return $candidates;+ foreach ($this->extractFileNames($imageValue) as $fileName) {+ if (!$restrictToFormAssets && $this->form) {+ $candidates[] = FileUploadPathService::getFileUploadPath($this->form->id, $fileName);+ }++ $candidates[] = FormController::ASSETS_UPLOAD_PATH . '/' . $fileName;}- if (filter_var($normalized, FILTER_VALIDATE_URL) !== false) {- $path = parse_url($normalized, PHP_URL_PATH);- $fileName = $path ? basename($path) : null;- if ($fileName) {- $candidates[] = FormController::ASSETS_UPLOAD_PATH . '/' . $fileName;- if ($this->form) {- $candidates[] = FileUploadPathService::getFileUploadPath($this->form->id, $fileName);+ return array_values(array_unique($candidates));+ }++ /**+ * @return array<int, string>+ */+ private function extractFileNames(string $value): array+ {+ $fileNames = [];++ if ($this->isUrl($value)) {+ $path = parse_url($value, PHP_URL_PATH);+ if (is_string($path) && $path !== '') {+ if (preg_match('#/forms/assets/([^/]+)$#', $path, $matches) === 1) {+ $fileNames[] = $this->sanitizeFileName(rawurldecode($matches[1]));+ }++ if ($this->hasAssetPath($value)) {+ $fileNames[] = $this->sanitizeFileName(rawurldecode(basename($path)));}}+ } else {+ $fileNames[] = $this->sanitizeFileName(rawurldecode(basename($value)));+ }++ $resolved = [];+ foreach ($fileNames as $fileName) {+ if ($fileName === null) {+ continue;+ }++ $resolved[] = $fileName;++ if (FilenameUrlEncoder::isEncoded($fileName)) {+ $sanitized = $this->sanitizeFileName(FilenameUrlEncoder::decode($fileName));+ if ($sanitized !== null) {+ $resolved[] = $sanitized;+ }+ }+ }++ return array_values(array_unique($resolved));+ }++ private function readFromStorage(string $path): ?string+ {+ try {+ if (!Storage::exists($path)) {+ return null;+ }++ return Storage::get($path);+ } catch (UnableToCheckFileExistence $e) {+ Log::debug('PDF image storage lookup skipped', [+ 'form_id' => $this->form?->id,+ 'path' => $path,+ 'error' => $e->getMessage(),+ ]);++ return null;+ } catch (\Throwable $e) {+ Log::debug('PDF image storage lookup failed', [+ 'form_id' => $this->form?->id,+ 'path' => $path,+ 'error' => $e->getMessage(),+ ]);++ return null;+ }+ }++ private function remoteFetcher(): PdfSafeImageFetcher+ {+ return $this->remoteFetcher ?? new PdfSafeImageFetcher();+ }++ private function isUrl(string $value): bool+ {+ return filter_var($value, FILTER_VALIDATE_URL) !== false;+ }++ private function shouldRemoteFetch(string $url): bool+ {+ return !$this->matchesAppAssetOrigin($url);+ }++ private function hasAssetPath(string $url): bool+ {+ $path = parse_url($url, PHP_URL_PATH);++ return is_string($path) && preg_match('#/forms/assets/([^/]+)$#', $path) === 1;+ }++ private function matchesAppAssetOrigin(string $url): bool+ {+ $host = $this->normalizedHostFromUrl($url);+ if ($host === null) {+ return false;+ }++ return in_array($host, $this->allowedAssetHosts(), true);+ }++ /**+ * @return array<int, string>+ */+ private function allowedAssetHosts(): array+ {+ if ($this->allowedAssetHosts !== null) {+ return $this->allowedAssetHosts;+ }++ $hosts = [];++ foreach ([config('app.url'), config('app.front_url')] as $baseUrl) {+ if (!is_string($baseUrl) || $baseUrl === '') {+ continue;+ }- // Storage-only mode: we do not fetch remote URLs.- return $candidates;+ $host = $this->normalizedHostFromUrl($baseUrl);+ if ($host !== null) {+ $hosts[] = $host;+ }}- if (str_contains($normalized, '/')) {- $candidates[] = ltrim($normalized, '/');+ $routeHost = $this->normalizedHostFromUrl(route('forms.assets.show', ['__probe__']));+ if ($routeHost !== null) {+ $hosts[] = $routeHost;}- if ($this->form) {- $candidates[] = FileUploadPathService::getFileUploadPath($this->form->id, $normalized);+ $this->allowedAssetHosts = array_values(array_unique($hosts));++ return $this->allowedAssetHosts;+ }++ private function normalizedHostFromUrl(string $url): ?string+ {+ $host = parse_url($url, PHP_URL_HOST);++ if (!is_string($host) || $host === '') {+ return null;}- $candidates[] = FormController::ASSETS_UPLOAD_PATH . '/' . $normalized;+ return $this->normalizeHost($host);+ }++ private function normalizeHost(string $host): string+ {+ $host = strtolower($host);- return array_values(array_unique($candidates));+ if (in_array($host, ['127.0.0.1', '::1'], true)) {+ return 'localhost';+ }++ if (str_starts_with($host, 'www.')) {+ return substr($host, 4);+ }++ return $host;+ }++ private function sanitizeFileName(?string $fileName): ?string+ {+ if ($fileName === null) {+ return null;+ }++ $fileName = trim($fileName);+ if ($fileName === '' || $fileName === '.' || $fileName === '..') {+ return null;+ }++ if (+ str_contains($fileName, '/')+ || str_contains($fileName, '\\')+ || str_contains($fileName, '..')+ ) {+ return null;+ }++ return $fileName;}}diff --git a/api/app/Service/Pdf/PdfRemoteImageUrl.php b/api/app/Service/Pdf/PdfRemoteImageUrl.phpnew file mode 100644index 000000000..f59006258--- /dev/null+++ b/api/app/Service/Pdf/PdfRemoteImageUrl.php@@ -0,0 +1,43 @@+<?php++namespace App\Service\Pdf;++use App\Service\Security\PublicWebhookUrl;++/**+ * SSRF policy for PDF remote image fetches.+ *+ * Unlike webhook URLs, submitter-controlled PDF image values must never trigger+ * fetches to private network targets, even when opnform.webhooks.allow_private_urls+ * is enabled for integrations.+ */+class PdfRemoteImageUrl+{+ /** @var array<string, true> */+ private static array $validatedUrls = [];++ public static function assertSafe(string $url): void+ {+ self::rememberValidated($url);+ }++ /**+ * @return array<string, mixed>+ */+ public static function requestOptions(string $url): array+ {+ self::rememberValidated($url);++ return PublicWebhookUrl::requestOptionsPublicOnly($url);+ }++ private static function rememberValidated(string $url): void+ {+ if (isset(self::$validatedUrls[$url])) {+ return;+ }++ PublicWebhookUrl::assertPublicOnly($url);+ self::$validatedUrls[$url] = true;+ }+}diff --git a/api/app/Service/Pdf/PdfSafeImageFetcher.php b/api/app/Service/Pdf/PdfSafeImageFetcher.phpnew file mode 100644index 000000000..bbc559d79--- /dev/null+++ b/api/app/Service/Pdf/PdfSafeImageFetcher.php@@ -0,0 +1,137 @@+<?php++namespace App\Service\Pdf;++use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Log;+use InvalidArgumentException;+use Psr\Http\Message\ResponseInterface;+use RuntimeException;++class PdfSafeImageFetcher+{+ private const CONNECT_TIMEOUT_SECONDS = 3;++ private const TIMEOUT_SECONDS = 5;++ private const MAX_BYTES = 5 * 1024 * 1024;++ public function fetch(string $url): ?string+ {+ try {+ $requestOptions = PdfRemoteImageUrl::requestOptions($url);+ } catch (InvalidArgumentException $e) {+ Log::debug('PDF remote image URL rejected', [+ 'url' => $url,+ 'error' => $e->getMessage(),+ ]);++ return null;+ }++ try {+ $bodyStream = fopen('php://temp/maxmemory:' . self::MAX_BYTES, 'w+');+ if ($bodyStream === false) {+ throw new RuntimeException('PDF remote image download buffer unavailable.');+ }++ $httpOptions = array_merge($requestOptions, [+ 'sink' => $bodyStream,+ 'on_headers' => function (ResponseInterface $response): void {+ if (!$this->responseHeadersAreSafeFromPsr($response)) {+ throw new RuntimeException('PDF remote image response rejected.');+ }+ },+ 'progress' => function ($downloadTotal, $downloadedBytes, $uploadTotal, $uploadedBytes): void {+ if ($downloadTotal > self::MAX_BYTES || $downloadedBytes > self::MAX_BYTES) {+ throw new RuntimeException('PDF remote image download exceeded size limit.');+ }+ },+ ]);++ $response = Http::connectTimeout(self::CONNECT_TIMEOUT_SECONDS)+ ->timeout(self::TIMEOUT_SECONDS)+ ->accept('image/*')+ ->withOptions($httpOptions)+ ->get($url);++ if (!$response->successful()) {+ return null;+ }++ if (!$this->responseHeadersAreSafe($response)) {+ return null;+ }++ $body = $this->responseBody($response, $bodyStream);+ if ($body === '' || strlen($body) > self::MAX_BYTES) {+ return null;+ }++ return $body;+ } catch (RuntimeException $e) {+ Log::debug('PDF remote image download rejected', [+ 'url' => $url,+ 'error' => $e->getMessage(),+ ]);++ return null;+ } catch (\Throwable $e) {+ Log::debug('PDF remote image download failed', [+ 'url' => $url,+ 'error' => $e->getMessage(),+ ]);++ return null;+ } finally {+ if (isset($bodyStream) && is_resource($bodyStream)) {+ fclose($bodyStream);+ }+ }+ }++ private function responseHeadersAreSafe(\Illuminate\Http\Client\Response $response): bool+ {+ $contentLength = $response->header('Content-Length');+ if ($contentLength !== null && $contentLength !== '' && (int) $contentLength > self::MAX_BYTES) {+ return false;+ }++ $contentType = strtolower((string) $response->header('Content-Type', ''));+ if ($contentType !== '' && !str_starts_with($contentType, 'image/')) {+ return false;+ }++ return true;+ }++ private function responseHeadersAreSafeFromPsr(ResponseInterface $response): bool+ {+ $contentLength = $response->getHeaderLine('Content-Length');+ if ($contentLength !== '' && (int) $contentLength > self::MAX_BYTES) {+ return false;+ }++ $contentType = strtolower($response->getHeaderLine('Content-Type'));+ if ($contentType !== '' && !str_starts_with($contentType, 'image/')) {+ return false;+ }++ return true;+ }++ /**+ * @param resource $bodyStream+ */+ private function responseBody(\Illuminate\Http\Client\Response $response, $bodyStream): string+ {+ rewind($bodyStream);+ $body = stream_get_contents($bodyStream);++ if ($body !== false && $body !== '') {+ return $body;+ }++ return $response->body();+ }+}diff --git a/api/app/Service/Security/PublicWebhookUrl.php b/api/app/Service/Security/PublicWebhookUrl.phpindex 6c9dfcf75..e6bd4c015 100644--- a/api/app/Service/Security/PublicWebhookUrl.php+++ b/api/app/Service/Security/PublicWebhookUrl.php@@ -8,19 +8,51 @@ class PublicWebhookUrl{public static function assertSafe(string $url): void{- self::validatedIp($url);+ self::validatedIp($url, self::allowPrivateUrlsFromConfig());+ }++ public static function assertPublicOnly(string $url): void+ {+ self::validatedIp($url, false);}/*** @return array<string, mixed>*/public static function requestOptions(string $url): array+ {+ return self::buildRequestOptions($url, self::allowPrivateUrlsFromConfig());+ }++ /**+ * @return array<string, mixed>+ */+ public static function requestOptionsPublicOnly(string $url): array+ {+ return self::buildRequestOptions($url, false);+ }++ public static function validate(string $url): ?string+ {+ try {+ self::validatedIp($url, self::allowPrivateUrlsFromConfig());+ } catch (InvalidArgumentException $e) {+ return $e->getMessage();+ }++ return null;+ }++ /**+ * @return array<string, mixed>+ */+ private static function buildRequestOptions(string $url, bool $allowPrivateUrls): array{$options = ['allow_redirects' => false,];- $ip = self::validatedIp($url);+ $ip = self::validatedIp($url, $allowPrivateUrls);if ($ip === null) {return $options;}@@ -37,20 +69,14 @@ class PublicWebhookUrlreturn $options;}- public static function validate(string $url): ?string+ private static function allowPrivateUrlsFromConfig(): bool{- try {- self::validatedIp($url);- } catch (InvalidArgumentException $e) {- return $e->getMessage();- }-- return null;+ return (bool) config('opnform.webhooks.allow_private_urls', false);}- private static function validatedIp(string $url): ?string+ private static function validatedIp(string $url, bool $allowPrivateUrls): ?string{- if (config('opnform.webhooks.allow_private_urls', false)) {+ if ($allowPrivateUrls) {self::assertUrlShape($url);return null;@@ -77,6 +103,20 @@ class PublicWebhookUrl}}+ return self::selectPinnedIp($ips);+ }++ /**+ * @param array<int, string> $ips+ */+ private static function selectPinnedIp(array $ips): string+ {+ foreach ($ips as $ip) {+ if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {+ return $ip;+ }+ }+return $ips[0];}@@ -149,6 +189,6 @@ class PublicWebhookUrlprivate static function formatCurlResolveIp(string $ip): string{- return str_contains($ip, ':') ? '['.$ip.']' : $ip;+ return str_contains($ip, ':') ? '[' . $ip . ']' : $ip;}}diff --git a/api/app/Service/Storage/FilenameUrlEncoder.php b/api/app/Service/Storage/FilenameUrlEncoder.phpindex ceea7deab..8d344fde2 100644--- a/api/app/Service/Storage/FilenameUrlEncoder.php+++ b/api/app/Service/Storage/FilenameUrlEncoder.php@@ -50,4 +50,32 @@ class FilenameUrlEncoderreturn $decoded;}++ public static function isEncoded(string $value): bool+ {+ if ($value === '') {+ return false;+ }++ $decoded = self::decode($value);+ if ($decoded === $value) {+ return false;+ }++ if (self::encode($decoded) !== $value) {+ return false;+ }++ return self::isPlausibleFilename($decoded);+ }++ public static function isPlausibleFilename(string $filename): bool+ {+ if ($filename === '' || !mb_check_encoding($filename, 'UTF-8')) {+ return false;+ }++ // Keep in sync with S3KeyCleaner allowed filename characters (excluding "/").+ return preg_match('/^[\p{L}\p{N}\.\s_\-\(\)\'!*]+$/u', $filename) === 1;+ }}diff --git a/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php b/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.phpindex 948a7af95..4dc1cad47 100644--- a/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php+++ b/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php@@ -220,8 +220,14 @@ describe('PdfGeneratorService', function () {expect(Storage::exists($resultPath))->toBeTrue();});- it('generates pdf without fetching static image urls unavailable in storage', function () {- Http::fake();+ it('generates pdf with static image from unsplash-like url', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ tinyPngBytes(),+ 200,+ ['Content-Type' => 'image/png']+ ),+ ]);$pdfContent = createTestPdf();$templatePath = 'pdf-templates/1/template.pdf';@@ -263,7 +269,7 @@ describe('PdfGeneratorService', function () {expect(Storage::exists($resultPath))->toBeTrue();expect(Storage::get($resultPath))->toStartWith('%PDF');- Http::assertNothingSent();+ Http::assertSentCount(1);});});@@ -294,23 +300,23 @@ describe('Image resolving', function () {expect($content)->toBe('img-bytes');});- it('does not fetch remote image urls', function () {+ it('does not fetch unsafe remote image urls', function () {Http::fake();$resolver = new PdfImageResolver();- $content = $resolver->resolveContent('https://example.com/image.png');+ $content = $resolver->resolveContent('https://169.254.169.254/latest/meta-data/');expect($content)->toBeNull();Http::assertNothingSent();});- it('resolves url-shaped image values by storage filename only', function () {+ it('resolves local asset urls from storage without remote fetch', function () {Http::fake();Storage::put('assets/forms/image.png', 'stored-image-bytes');$resolver = new PdfImageResolver();- $content = $resolver->resolveContent('https://example.com/image.png');+ $content = $resolver->resolveContent(route('forms.assets.show', ['image.png']));expect($content)->toBe('stored-image-bytes');Http::assertNothingSent();diff --git a/api/tests/Feature/Security/PublicWebhookUrlTest.php b/api/tests/Feature/Security/PublicWebhookUrlTest.phpindex 2306895dc..f587db407 100644--- a/api/tests/Feature/Security/PublicWebhookUrlTest.php+++ b/api/tests/Feature/Security/PublicWebhookUrlTest.php@@ -25,3 +25,17 @@ it('rejects link local metadata addresses', function () {expect(PublicWebhookUrl::validate('https://169.254.169.254/latest/meta-data/'))->toBe('The webhook URL must resolve only to public IP addresses.');});++it('still rejects private urls when public-only validation is requested', function () {+ config(['opnform.webhooks.allow_private_urls' => true]);++ expect(fn () => PublicWebhookUrl::assertPublicOnly('https://127.0.0.1/webhook'))+ ->toThrow(\InvalidArgumentException::class, 'The webhook URL must resolve only to public IP addresses.');+});++it('does not allow private webhook destinations through public-only request options', function () {+ config(['opnform.webhooks.allow_private_urls' => true]);++ expect(fn () => PublicWebhookUrl::requestOptionsPublicOnly('https://127.0.0.1/webhook'))+ ->toThrow(\InvalidArgumentException::class);+});diff --git a/api/tests/Unit/Service/Pdf/PdfImageResolverTest.php b/api/tests/Unit/Service/Pdf/PdfImageResolverTest.phpnew file mode 100644index 000000000..8ad57c603--- /dev/null+++ b/api/tests/Unit/Service/Pdf/PdfImageResolverTest.php@@ -0,0 +1,351 @@+<?php++use App\Http\Controllers\Forms\FormController;+use App\Models\Forms\Form;+use App\Models\User;+use App\Models\Workspace;+use App\Service\Pdf\PdfImageResolver;+use App\Service\Pdf\PdfRemoteImageUrl;+use App\Service\Pdf\PdfSafeImageFetcher;+use App\Service\Storage\FileUploadPathService;+use App\Service\Storage\FilenameUrlEncoder;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++uses(TestCase::class);++beforeEach(function () {+ Storage::fake('local');+ config(['opnform.webhooks.allow_private_urls' => false]);+});++function createPdfImageResolverTestForm(): Form+{+ $user = User::factory()->create();+ $workspace = Workspace::create(['name' => 'PDF Test Workspace', 'icon' => '📝']);+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);++ return Form::factory()+ ->forWorkspace($workspace)+ ->createdBy($user)+ ->withProperties([+ ['id' => 'name', 'name' => 'Name', 'type' => 'text'],+ ])+ ->create();+}++function pdfResolverTinyPngBytes(): string+{+ return base64_decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAgMBAQEAAP8AAAAASUVORK5CYII=',+ true+ ) ?: '';+}++describe('PdfImageResolver', function () {+ it('does not fetch unsafe remote image urls', function () {+ Http::fake();++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent('https://169.254.169.254/latest/meta-data/iam/security-credentials/');++ expect($content)->toBeNull();+ Http::assertNothingSent();+ });++ it('fetches safe public remote image urls when not in storage', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ pdfResolverTinyPngBytes(),+ 200,+ ['Content-Type' => 'image/png']+ ),+ ]);++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent(+ 'https://images.unsplash.com/photo-1779638715091-90c701d94efd?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=1080'+ );++ expect($content)->toBe(pdfResolverTinyPngBytes());+ Http::assertSentCount(1);+ });++ it('does not treat unsplash photo ids as encoded storage filenames', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ pdfResolverTinyPngBytes(),+ 200,+ ['Content-Type' => 'image/png']+ ),+ ]);++ expect(FilenameUrlEncoder::isEncoded('photo-1779638715091-90c701d94efd'))->toBeFalse();++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent(+ 'https://images.unsplash.com/photo-1779638715091-90c701d94efd?fm=jpg&w=1080'+ );++ expect($content)->toBe(pdfResolverTinyPngBytes());+ Http::assertSentCount(1);+ });++ it('prefers storage over remote fetch for local asset urls', function () {+ Http::fake();+ Storage::put('assets/forms/photo.png', 'stored-image-bytes');++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent(route('forms.assets.show', ['photo.png']));++ expect($content)->toBe('stored-image-bytes');+ Http::assertNothingSent();+ });++ it('prefers form assets over submission storage for local asset urls', function () {+ Http::fake();+ $form = createPdfImageResolverTestForm();+ $fileName = 'photo.png';+ Storage::put(FileUploadPathService::getFileUploadPath($form->id, $fileName), 'submission-bytes');+ Storage::put(FormController::ASSETS_UPLOAD_PATH . '/' . $fileName, 'asset-bytes');++ $resolver = new PdfImageResolver($form);+ $content = $resolver->resolveContent(route('forms.assets.show', [$fileName]));++ expect($content)->toBe('asset-bytes');+ Http::assertNothingSent();+ });++ it('resolves asset path urls from storage when host matches front url', function () {+ Http::fake();+ config(['app.url' => 'http://api.test']);+ config(['app.front_url' => 'http://frontend.test']);+ Storage::put(FormController::ASSETS_UPLOAD_PATH . '/photo.png', 'asset-bytes');++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent('http://frontend.test/forms/assets/photo.png');++ expect($content)->toBe('asset-bytes');+ Http::assertNothingSent();+ });++ it('treats localhost and 127.0.0.1 as the same app origin', function () {+ Http::fake();+ config(['app.url' => 'http://localhost']);+ Storage::put(FormController::ASSETS_UPLOAD_PATH . '/photo.png', 'asset-bytes');++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent('http://127.0.0.1/forms/assets/photo.png');++ expect($content)->toBe('asset-bytes');+ Http::assertNothingSent();+ });++ it('does not remote-fetch app-origin urls regardless of scheme', function () {+ Http::fake();+ config(['app.url' => 'http://api.test']);+ Storage::put(FormController::ASSETS_UPLOAD_PATH . '/photo.png', 'asset-bytes');++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent('https://api.test/forms/assets/photo.png');++ expect($content)->toBe('asset-bytes');+ Http::assertNothingSent();+ });++ it('caches repeated image lookups within the same resolver instance', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ pdfResolverTinyPngBytes(),+ 200,+ ['Content-Type' => 'image/png']+ ),+ ]);++ $resolver = new PdfImageResolver();+ $url = 'https://images.unsplash.com/photo-12345?auto=format&fit=crop&w=900';++ expect($resolver->resolveContent($url))->toBe(pdfResolverTinyPngBytes());+ expect($resolver->resolveContent($url))->toBe(pdfResolverTinyPngBytes());+ Http::assertSentCount(1);+ });++ it('does not remote-fetch app-origin urls that miss storage', function () {+ Http::fake();++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent(route('forms.assets.show', ['missing.png']));++ expect($content)->toBeNull();+ Http::assertNothingSent();+ });++ it('does not treat remote urls with asset-like paths as local', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ pdfResolverTinyPngBytes(),+ 200,+ ['Content-Type' => 'image/png']+ ),+ ]);+ Storage::put(FormController::ASSETS_UPLOAD_PATH . '/photo.png', 'colliding-local-asset');++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent('https://images.unsplash.com/forms/assets/photo.png');++ expect($content)->toBe(pdfResolverTinyPngBytes());+ Http::assertSentCount(1);+ });++ it('resolves uploaded form asset urls from storage', function () {+ Http::fake();+ $fileName = 'logo_550e8400-e29b-41d4-a716-446655440000.png';+ Storage::put(FormController::ASSETS_UPLOAD_PATH . '/' . $fileName, 'asset-bytes');++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent(route('forms.assets.show', [$fileName]));++ expect($content)->toBe('asset-bytes');+ Http::assertNothingSent();+ });++ it('resolves image content from form submission storage', function () {+ $form = createPdfImageResolverTestForm();+ $fileName = 'avatar-test.png';+ Storage::put(FileUploadPathService::getFileUploadPath($form->id, $fileName), 'form-upload-bytes');++ $resolver = new PdfImageResolver($form);+ $content = $resolver->resolveContent($fileName);++ expect($content)->toBe('form-upload-bytes');+ });++ it('resolves encoded submission filenames from storage', function () {+ $form = createPdfImageResolverTestForm();+ $fileName = 'my (file)_550e8400-e29b-41d4-a716-446655440000.png';+ Storage::put(FileUploadPathService::getFileUploadPath($form->id, $fileName), 'encoded-upload-bytes');++ $resolver = new PdfImageResolver($form);+ $content = $resolver->resolveContent(FilenameUrlEncoder::encode($fileName));++ expect($content)->toBe('encoded-upload-bytes');+ });++ it('resolves encoded submission filenames containing exclamation marks', function () {+ $form = createPdfImageResolverTestForm();+ $fileName = 'Important!-document_550e8400-e29b-41d4-a716-446655440000.png';+ Storage::put(FileUploadPathService::getFileUploadPath($form->id, $fileName), 'important-upload-bytes');++ $resolver = new PdfImageResolver($form);+ $content = $resolver->resolveContent(FilenameUrlEncoder::encode($fileName));++ expect($content)->toBe('important-upload-bytes');+ });++ it('resolves encoded submission filenames containing asterisks', function () {+ $form = createPdfImageResolverTestForm();+ $fileName = 'star*file_550e8400-e29b-41d4-a716-446655440000.png';+ Storage::put(FileUploadPathService::getFileUploadPath($form->id, $fileName), 'star-upload-bytes');++ $resolver = new PdfImageResolver($form);+ $content = $resolver->resolveContent(FilenameUrlEncoder::encode($fileName));++ expect($content)->toBe('star-upload-bytes');+ });++ it('does not probe arbitrary storage keys for slash-containing values', function () {+ Storage::put('private/nested/photo.png', 'private-bytes');++ $resolver = new PdfImageResolver();+ $content = $resolver->resolveContent('private/nested/photo.png');++ expect($content)->toBeNull();+ });+});++describe('PdfSafeImageFetcher', function () {+ it('pins the validated public destination ip for remote image requests', function () {+ $options = PdfRemoteImageUrl::requestOptions('https://93.184.216.34/image.png');++ expect($options['allow_redirects'])->toBeFalse()+ ->and($options['curl'][CURLOPT_RESOLVE])->toBe(['93.184.216.34:443:93.184.216.34']);+ });++ it('rejects non-image content types', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ '<html></html>',+ 200,+ ['Content-Type' => 'text/html']+ ),+ ]);++ $fetcher = new PdfSafeImageFetcher();+ $content = $fetcher->fetch('https://images.unsplash.com/photo-12345');++ expect($content)->toBeNull();+ });++ it('rejects private urls even when private webhook urls are allowed', function () {+ config(['opnform.webhooks.allow_private_urls' => true]);+ Http::fake();++ $fetcher = new PdfSafeImageFetcher();+ $content = $fetcher->fetch('https://127.0.0.1/internal.png');++ expect($content)->toBeNull();+ Http::assertNothingSent();+ });++ it('rejects responses whose content-length exceeds the download limit', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ 'ignored',+ 200,+ [+ 'Content-Type' => 'image/png',+ 'Content-Length' => (string) (6 * 1024 * 1024),+ ]+ ),+ ]);++ $fetcher = new PdfSafeImageFetcher();+ $content = $fetcher->fetch('https://images.unsplash.com/photo-12345');++ expect($content)->toBeNull();+ });++ it('rejects response bodies that exceed the download limit', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ str_repeat('a', (5 * 1024 * 1024) + 1),+ 200,+ ['Content-Type' => 'image/png']+ ),+ ]);++ $fetcher = new PdfSafeImageFetcher();+ $content = $fetcher->fetch('https://images.unsplash.com/photo-12345');++ expect($content)->toBeNull();+ });++ it('rejects chunked response bodies that exceed the download limit', function () {+ Http::fake([+ 'https://images.unsplash.com/*' => Http::response(+ str_repeat('a', (5 * 1024 * 1024) + 1),+ 200,+ [+ 'Content-Type' => 'image/png',+ 'Transfer-Encoding' => 'chunked',+ ]+ ),+ ]);++ $fetcher = new PdfSafeImageFetcher();+ $content = $fetcher->fetch('https://images.unsplash.com/photo-12345');++ expect($content)->toBeNull();+ });+});diff --git a/api/tests/Unit/Service/Storage/FilenameUrlEncoderTest.php b/api/tests/Unit/Service/Storage/FilenameUrlEncoderTest.phpindex 02eacae23..82756de09 100644--- a/api/tests/Unit/Service/Storage/FilenameUrlEncoderTest.php+++ b/api/tests/Unit/Service/Storage/FilenameUrlEncoderTest.php@@ -119,4 +119,35 @@ describe('FilenameUrlEncoder', function () {}});});++ describe('isEncoded', function () {+ it('detects encoded upload filenames', function () {+ $filename = 'my (file)_550e8400-e29b-41d4-a716-446655440000.png';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect(FilenameUrlEncoder::isEncoded($encoded))->toBeTrue();+ });++ it('does not treat unsplash photo ids as encoded filenames', function () {+ expect(FilenameUrlEncoder::isEncoded('photo-1779638715091-90c701d94efd'))->toBeFalse();+ });++ it('does not treat plain upload filenames as encoded filenames', function () {+ expect(FilenameUrlEncoder::isEncoded('avatar-test.png'))->toBeFalse();+ });++ it('detects encoded filenames with exclamation marks', function () {+ $filename = 'Important!-document_uuid.pdf';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect(FilenameUrlEncoder::isEncoded($encoded))->toBeTrue();+ });++ it('detects encoded filenames with asterisks', function () {+ $filename = 'star*file_uuid.pdf';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect(FilenameUrlEncoder::isEncoded($encoded))->toBeTrue();+ });+ });});