diff --git a/app/Actions/Promises/SetPromiseContentAction.php b/app/Actions/Promises/SetPromiseContentAction.php index 1354723..b495707 100644 --- a/app/Actions/Promises/SetPromiseContentAction.php +++ b/app/Actions/Promises/SetPromiseContentAction.php @@ -6,53 +6,72 @@ use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; +use RuntimeException; +use Throwable; class SetPromiseContentAction { - public function __construct( - protected ClearPromiseContentAction $clearPromiseContentAction, - ) {} - /** * @param string|UploadedFile|resource $content */ public function handle(PrintJobPromise $promise, mixed $content, ?string $name = null): void { - if ($content instanceof UploadedFile) { - $this->handleUploadedFile($promise, $content, $name); - } elseif (is_resource($content)) { - $this->handleResource($promise, $content, $name); - } else { - $this->handleString($promise, $content, $name); + $attributes = $promise->getAttributes(); + $previousFile = $promise->content_file; + + try { + if ($content instanceof UploadedFile) { + $this->handleUploadedFile($promise, $content, $name); + } elseif (is_resource($content)) { + $this->handleResource($promise, $content, $name); + } else { + $this->handleString($promise, $content, $name); + } + + if (! $promise->saveOrFail()) { + throw new RuntimeException('Unable to save promise content.'); + } + } catch (Throwable $exception) { + if ($promise->content_file && $promise->content_file !== $previousFile) { + Storage::delete($promise->content_file); + } + + $promise->setRawAttributes($attributes, true); + + throw $exception; + } + + if ($previousFile && $previousFile !== $promise->content_file) { + Storage::delete($previousFile); } } protected function handleUploadedFile(PrintJobPromise $promise, UploadedFile $content, ?string $name = null): void { - $this->clearPromiseContentAction->handle($promise); - - $promise->content_file = $content->store('jobs'); + $promise->content = null; + $promise->content_file = 'jobs/'.$content->hashName(); + if (! $content->storeAs('jobs', $content->hashName())) { + throw new RuntimeException('Unable to store uploaded promise content.'); + } $promise->size = $content->getSize(); $promise->file_name ??= $content->getClientOriginalName(); if ($name) { $promise->file_name = $name; } - - $promise->save(); } protected function handleString(PrintJobPromise $promise, string $content, ?string $name = null): void { - $this->clearPromiseContentAction->handle($promise); - if (strlen($content) < 1024 && ! preg_match('#[^\x20-\x7e\n]#', $content)) { $promise->content = $content; $promise->content_file = null; } else { $promise->content = null; $promise->content_file = 'jobs/'.Str::random(40).'.dat'; - Storage::put($promise->content_file, $content); + if (! Storage::put($promise->content_file, $content)) { + throw new RuntimeException('Unable to store promise content.'); + } } if ($name) { @@ -60,7 +79,6 @@ protected function handleString(PrintJobPromise $promise, string $content, ?stri } $promise->size = strlen($content); - $promise->save(); } /** @@ -68,18 +86,17 @@ protected function handleString(PrintJobPromise $promise, string $content, ?stri */ protected function handleResource(PrintJobPromise $promise, mixed $content, ?string $name = null): void { - $this->clearPromiseContentAction->handle($promise); - $tmp_file = Str::random(40).'.dat'; + $promise->content = null; $promise->content_file = 'jobs/'.$tmp_file; - Storage::writeStream($promise->content_file, $content); + if (! Storage::writeStream($promise->content_file, $content)) { + throw new RuntimeException('Unable to store streamed promise content.'); + } $promise->size = Storage::size($promise->content_file); $promise->file_name ??= $tmp_file; if ($name) { $promise->file_name = $name; } - - $promise->save(); } } diff --git a/app/Http/Controllers/PrintServiceApi/PrintJobsController.php b/app/Http/Controllers/PrintServiceApi/PrintJobsController.php index 1197f87..ee240db 100644 --- a/app/Http/Controllers/PrintServiceApi/PrintJobsController.php +++ b/app/Http/Controllers/PrintServiceApi/PrintJobsController.php @@ -117,7 +117,7 @@ public function update(Request $request, PrintJob $job) { $fields = $request->validate([ 'status' => ['required', Rule::in(['printing', 'finished', 'failed'])], - 'status_message' => ['required_if:status,failed'], + 'status_message' => ['required_if:status,failed', 'nullable', 'string', 'max:255'], ]); $job->status = $fields['status']; diff --git a/app/Http/Controllers/WebPrintApi/PrintDialogsController.php b/app/Http/Controllers/WebPrintApi/PrintDialogsController.php index 3f332a5..d4c6750 100644 --- a/app/Http/Controllers/WebPrintApi/PrintDialogsController.php +++ b/app/Http/Controllers/WebPrintApi/PrintDialogsController.php @@ -10,6 +10,7 @@ use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Http\Request; use Illuminate\Http\Response; +use RuntimeException; class PrintDialogsController extends Controller { @@ -58,19 +59,25 @@ public function store(Request $request, PrintJobPromise $promise): PrintDialogRe $validated = $request->validate([ 'restricted_ip' => ['nullable', 'ip'], - 'redirect_url' => ['nullable', 'url'], + 'redirect_url' => ['nullable', 'string', 'url', 'max:255'], 'auto_print' => ['nullable', 'boolean'], ]); - if ($promise->PrintDialog !== null) { - $promise->PrintDialog->delete(); - } + $dialog = $promise->getConnection()->transaction(function () use ($promise, $validated): PrintDialog { + if ($promise->PrintDialog !== null) { + $promise->PrintDialog->delete(); + } + + $dialog = new PrintDialog; + $dialog->auto_print = $validated['auto_print'] ?? true; + $dialog->redirect_url = $validated['redirect_url'] ?? null; + $dialog->restricted_ip = $validated['restricted_ip'] ?? null; + if (! $promise->PrintDialog()->save($dialog)) { + throw new RuntimeException('Unable to save print dialog.'); + } - $dialog = new PrintDialog; - $dialog->auto_print = $validated['auto_print'] ?? true; - $dialog->redirect_url = $validated['redirect_url'] ?? null; - $dialog->restricted_ip = $validated['restricted_ip'] ?? null; - $promise->PrintDialog()->save($dialog); + return $dialog; + }); return new PrintDialogResource($dialog->fresh()); } diff --git a/app/Http/Controllers/WebPrintApi/PrintJobPromisesContentController.php b/app/Http/Controllers/WebPrintApi/PrintJobPromisesContentController.php index 822a7e3..5e5d814 100644 --- a/app/Http/Controllers/WebPrintApi/PrintJobPromisesContentController.php +++ b/app/Http/Controllers/WebPrintApi/PrintJobPromisesContentController.php @@ -11,6 +11,7 @@ use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\HeaderUtils; use Symfony\Component\HttpFoundation\StreamedResponse; @@ -78,11 +79,15 @@ public function store( if ($request->hasFile('content')) { $file = $request->file('content'); + Validator::make(['name' => $file->getClientOriginalName()], [ + 'name' => ['required', 'string', 'max:255'], + ])->validate(); + $setPromiseContentAction->handle($promise, $file); } elseif ($request->has('content')) { $validated = $request->validate([ - 'content' => 'required', - 'name' => $promise->file_name ? 'nullable' : 'required', + 'content' => ['required', 'string'], + 'name' => [$promise->file_name ? 'nullable' : 'required', 'string', 'max:255'], ]); $setPromiseContentAction->handle( @@ -91,10 +96,14 @@ public function store( name: $validated['name'] ?? $promise->file_name ); } else { + $validated = Validator::make(['name' => $request->header('X-File-Name')], [ + 'name' => ['nullable', 'string', 'max:255'], + ])->validate(); + $setPromiseContentAction->handle( promise: $promise, content: $request->getContent(true), - name: $request->hasHeader('X-File-Name') && $request->header('X-File-Name') ? $request->header('X-File-Name') : null, + name: $validated['name'], ); } diff --git a/app/Http/Controllers/WebPrintApi/PrintJobPromisesController.php b/app/Http/Controllers/WebPrintApi/PrintJobPromisesController.php index a7bff06..620e392 100644 --- a/app/Http/Controllers/WebPrintApi/PrintJobPromisesController.php +++ b/app/Http/Controllers/WebPrintApi/PrintJobPromisesController.php @@ -75,17 +75,17 @@ public function store( ->pluck('ulid'); $validated = $request->validate([ - 'name' => ['required', 'string'], + 'name' => ['required', 'string', 'max:255'], 'printer' => ['nullable', Rule::in($client_printers_ulids)], 'available_printers' => ['nullable', 'array'], 'available_printers.*' => ['string', Rule::in($client_printers_ulids)], - 'type' => 'required', + 'type' => ['required', 'string', 'max:255'], 'ppd_options' => ['nullable', 'array'], 'ppd_options.*' => ['required', 'string'], 'meta' => ['nullable', 'array'], 'meta.*' => ['required', 'string'], - 'content' => 'nullable', - 'file_name' => 'required_with:content', + 'content' => ['nullable', $request->hasFile('content') ? 'file' : 'string'], + 'file_name' => ['required_with:content', 'nullable', 'string', 'max:255'], 'headless' => ['nullable', 'boolean'], ]); @@ -166,7 +166,7 @@ public function update( $available_printers = $promise->AvailablePrinters()->pluck('ulid'); $validated = $request->validate([ 'status' => ['nullable', 'in:ready'], - 'name' => ['nullable', 'string'], + 'name' => ['nullable', 'string', 'max:255'], 'printer' => ['nullable', Rule::in($available_printers)], 'ppd_options' => ['nullable', 'array'], 'ppd_options.*' => ['required', 'string'], diff --git a/tests/Feature/Actions/ReplacePromiseContentTest.php b/tests/Feature/Actions/ReplacePromiseContentTest.php new file mode 100644 index 0000000..cd97516 --- /dev/null +++ b/tests/Feature/Actions/ReplacePromiseContentTest.php @@ -0,0 +1,145 @@ +promise = PrintJobPromise::factory()->create([ + 'content' => null, + 'content_file' => 'jobs/original.dat', + 'file_name' => 'original.dat', + 'size' => 17, + 'print_job_id' => null, + ])->refresh(); + } + + private function content(string $kind): mixed + { + return match ($kind) { + 'inline' => 'New document', + 'file' => str_repeat('New document', 100), + 'upload' => UploadedFile::fake()->createWithContent('new.txt', 'New document'), + 'stream' => $this->stream(), + }; + } + + private function stream(): mixed + { + $stream = fopen('php://temp', 'r+'); + fwrite($stream, 'New document'); + rewind($stream); + + return $stream; + } + + public static function contentKinds(): array + { + return [['inline'], ['file'], ['upload'], ['stream']]; + } + + private function assertOriginalDocumentIsIntact(array $attributes): void + { + $this->assertEquals($attributes, $this->promise->fresh()->getAttributes()); + $this->assertSame('Original document', Storage::get('jobs/original.dat')); + $this->assertSame(['jobs/original.dat'], Storage::allFiles('jobs')); + } + + #[DataProvider('contentKinds')] + public function test_database_failure_preserves_the_original_document_and_cleans_up_new_files(string $kind): void + { + $attributes = $this->promise->getAttributes(); + Event::listen('eloquent.saved: '.PrintJobPromise::class, function (): void { + throw new RuntimeException('Simulated database failure'); + }); + + $content = $this->content($kind); + + try { + app(SetPromiseContentAction::class)->handle($this->promise, $content, 'new.txt'); + $this->fail('Expected the database failure to propagate.'); + } catch (RuntimeException $exception) { + $this->assertSame('Simulated database failure', $exception->getMessage()); + } finally { + Event::forget('eloquent.saved: '.PrintJobPromise::class); + if (is_resource($content)) { + fclose($content); + } + } + + $this->assertOriginalDocumentIsIntact($attributes); + } + + #[DataProvider('contentKinds')] + public function test_successful_replacement_saves_new_content_before_removing_the_old_file(string $kind): void + { + $content = $this->content($kind); + Event::listen('eloquent.saving: '.PrintJobPromise::class, function (): void { + Storage::assertExists('jobs/original.dat'); + }); + + try { + app(SetPromiseContentAction::class)->handle($this->promise, $content, 'new.txt'); + } finally { + Event::forget('eloquent.saving: '.PrintJobPromise::class); + if (is_resource($content)) { + fclose($content); + } + } + + $this->promise->refresh(); + $expected = $kind === 'file' ? str_repeat('New document', 100) : 'New document'; + $this->assertSame($expected, $this->promise->content ?? Storage::get($this->promise->content_file)); + $this->assertEquals(strlen($expected), $this->promise->size); + $this->assertSame('new.txt', $this->promise->file_name); + Storage::assertMissing('jobs/original.dat'); + } + + #[DataProvider('failedWrites')] + public function test_storage_failure_preserves_the_original_document(string $kind, string $method): void + { + $attributes = $this->promise->getAttributes(); + $content = $this->content($kind); + $disk = Mockery::mock(Storage::disk('local')); + $disk->shouldReceive($method)->once()->andReturn(false); + Storage::set('local', $disk); + + try { + app(SetPromiseContentAction::class)->handle($this->promise, $content, 'new.txt'); + $this->fail('Expected a storage failure.'); + } catch (RuntimeException $exception) { + $this->assertStringContainsString('Unable to store', $exception->getMessage()); + } finally { + if (is_resource($content)) { + fclose($content); + } + } + + $this->assertOriginalDocumentIsIntact($attributes); + } + + public static function failedWrites(): array + { + return [['file', 'put'], ['upload', 'putFileAs'], ['stream', 'writeStream']]; + } +} diff --git a/tests/Feature/PrintServiceApi/SetJobsStatusTest.php b/tests/Feature/PrintServiceApi/SetJobsStatusTest.php index ed89850..aef8091 100755 --- a/tests/Feature/PrintServiceApi/SetJobsStatusTest.php +++ b/tests/Feature/PrintServiceApi/SetJobsStatusTest.php @@ -9,6 +9,7 @@ use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Laravel\Sanctum\Sanctum; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\TestCase; class SetJobsStatusTest extends TestCase @@ -128,6 +129,52 @@ public function test_cannot_be_updated_to_failed_without_message(): void ])->assertJsonValidationErrorFor('status_message'); } + #[DataProvider('invalidMessages')] + public function test_invalid_message_does_not_change_the_job(string $status, mixed $message): void + { + Sanctum::actingAs($server = PrintServer::factory()->create(), guard: 'print_service_api'); + $printer = Printer::factory()->for($server, 'Server')->create(); + $job = PrintJob::factory()->recycle($printer)->create(); + + $this->putJson('/api/print-service/jobs/'.$job->ulid, [ + 'status' => $status, + 'status_message' => $message, + ])->assertUnprocessable()->assertJsonValidationErrors('status_message'); + + $this->assertSame(PrintJobStatusEnum::New, $job->fresh()->status); + $this->assertNull($job->fresh()->status_message); + } + + public static function invalidMessages(): \Generator + { + foreach (['failed', 'printing'] as $status) { + yield $status.' ASCII' => [$status, str_repeat('a', 256)]; + yield $status.' multibyte' => [$status, str_repeat('ą', 256)]; + yield $status.' array' => [$status, ['invalid']]; + } + } + + #[DataProvider('boundaryMessages')] + public function test_message_accepts_255_characters(string $message): void + { + Sanctum::actingAs($server = PrintServer::factory()->create(), guard: 'print_service_api'); + $printer = Printer::factory()->for($server, 'Server')->create(); + $job = PrintJob::factory()->recycle($printer)->create(); + + $this->putJson('/api/print-service/jobs/'.$job->ulid, [ + 'status' => 'failed', + 'status_message' => $message, + ])->assertNoContent(); + + $this->assertSame(PrintJobStatusEnum::Failed, $job->fresh()->status); + $this->assertSame($message, $job->fresh()->status_message); + } + + public static function boundaryMessages(): array + { + return [[str_repeat('a', 255)], [str_repeat('ą', 255)]]; + } + public function test_cannot_update_others_jobs(): void { Sanctum::actingAs( diff --git a/tests/Feature/WebPrintApi/CreateDialogsTest.php b/tests/Feature/WebPrintApi/CreateDialogsTest.php index 4c9f8fe..e398dcf 100755 --- a/tests/Feature/WebPrintApi/CreateDialogsTest.php +++ b/tests/Feature/WebPrintApi/CreateDialogsTest.php @@ -8,8 +8,10 @@ use App\Models\PrintServer; use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Event; use Laravel\Sanctum\Sanctum; use PHPUnit\Framework\Attributes\DataProvider; +use RuntimeException; use Tests\TestCase; class CreateDialogsTest extends TestCase @@ -171,6 +173,70 @@ public function test_sets_correct_values(array $post, array $expected): void ]); } + #[DataProvider('invalidRedirects')] + public function test_invalid_redirect_keeps_the_existing_dialog(mixed $redirect): void + { + Sanctum::actingAs($client = ClientApplication::factory()->create(), guard: 'web_print_api'); + $promise = PrintJobPromise::factory()->for($client)->withoutContent()->create(); + $dialog = PrintDialog::factory()->for($promise, 'JobPromise')->create(); + $original = $dialog->getAttributes(); + + $this->postJson('/api/web-print/promises/'.$promise->ulid.'/dialog', [ + 'redirect_url' => $redirect, + ])->assertUnprocessable()->assertJsonValidationErrors('redirect_url'); + + $this->assertEquals($original, $dialog->fresh()->getAttributes()); + $this->assertDatabaseCount('print_dialogs', 1); + } + + public static function invalidRedirects(): array + { + return [ + ['https://example.com/?q='.str_repeat('a', 233)], + ['https://example.com/?q='.str_repeat('ą', 233)], + [['https://example.com/']], + ]; + } + + public function test_redirect_accepts_255_characters(): void + { + Sanctum::actingAs($client = ClientApplication::factory()->create(), guard: 'web_print_api'); + $promise = PrintJobPromise::factory()->for($client)->withoutContent()->create(); + $url = 'https://example.com/?q='.str_repeat('a', 232); + $this->assertSame(255, strlen($url)); + + $this->postJson('/api/web-print/promises/'.$promise->ulid.'/dialog', [ + 'redirect_url' => $url, + ])->assertOk()->assertJsonPath('data.redirect_url', $url); + } + + public function test_database_failure_rolls_back_dialog_replacement(): void + { + Sanctum::actingAs($client = ClientApplication::factory()->create(), guard: 'web_print_api'); + $promise = PrintJobPromise::factory()->for($client)->withoutContent()->create(); + $dialog = PrintDialog::factory()->for($promise, 'JobPromise')->create(); + $original = $dialog->getAttributes(); + $this->withoutExceptionHandling(); + + Event::listen('eloquent.creating: '.PrintDialog::class, function (): void { + throw new RuntimeException('Simulated database failure'); + }); + + try { + $this->postJson('/api/web-print/promises/'.$promise->ulid.'/dialog', [ + 'redirect_url' => 'https://example.com/', + ]); + $this->fail('Expected the database failure to propagate.'); + } catch (RuntimeException $exception) { + $this->assertSame('Simulated database failure', $exception->getMessage()); + } finally { + Event::forget('eloquent.creating: '.PrintDialog::class); + } + + $this->assertEquals($original, $dialog->fresh()?->getAttributes()); + $this->assertDatabaseCount('print_dialogs', 1); + } + public static function correctValues(): \Generator { yield 'auto_print' => [ diff --git a/tests/Feature/WebPrintApi/PrintJobNameValidationTest.php b/tests/Feature/WebPrintApi/PrintJobNameValidationTest.php new file mode 100644 index 0000000..881919e --- /dev/null +++ b/tests/Feature/WebPrintApi/PrintJobNameValidationTest.php @@ -0,0 +1,102 @@ +client = ClientApplication::factory()->create(); + Sanctum::actingAs($this->client, guard: 'web_print_api'); + } + + #[DataProvider('nameCharacters')] + public function test_create_rejects_a_name_longer_than_255_characters(string $character): void + { + $this->postJson('/api/web-print/promises', [ + 'name' => str_repeat($character, 256), + 'type' => 'ppd', + ])->assertUnprocessable()->assertJsonValidationErrors('name'); + + $this->assertDatabaseCount('print_job_promises', 0); + $this->assertDatabaseCount('print_jobs', 0); + } + + #[DataProvider('nameCharacters')] + public function test_update_rejects_a_long_name_without_changing_the_promise(string $character): void + { + $promise = PrintJobPromise::factory()->for($this->client)->withoutContent()->create([ + 'name' => 'Original name', + 'print_job_id' => null, + 'printer_id' => null, + ]); + + $this->putJson('/api/web-print/promises/'.$promise->ulid, [ + 'name' => str_repeat($character, 256), + ])->assertUnprocessable()->assertJsonValidationErrors('name'); + + $this->assertSame('Original name', $promise->fresh()->name); + $this->assertDatabaseCount('print_jobs', 0); + } + + #[DataProvider('nameCharacters')] + public function test_create_preserves_a_255_character_name_in_the_print_job(string $character): void + { + $name = str_repeat($character, 255); + $server = PrintServer::factory()->recycle($this->client->Team)->create(); + $printer = Printer::factory()->active()->ppd()->for($server, 'Server')->create(); + $this->client->Printers()->attach($printer); + + $this->postJson('/api/web-print/promises', [ + 'name' => $name, + 'type' => 'ppd', + 'headless' => true, + 'printer' => $printer->ulid, + 'content' => 'Test document', + 'file_name' => 'test.txt', + ])->assertCreated() + ->assertJsonPath('data.name', $name) + ->assertJsonPath('data.job.name', $name); + + $this->assertDatabaseHas('print_jobs', ['name' => $name]); + } + + #[DataProvider('nameCharacters')] + public function test_update_accepts_a_255_character_name(string $character): void + { + $name = str_repeat($character, 255); + $promise = PrintJobPromise::factory()->for($this->client)->withoutContent()->create([ + 'print_job_id' => null, + 'printer_id' => null, + ]); + + $this->putJson('/api/web-print/promises/'.$promise->ulid, [ + 'name' => $name, + ])->assertNoContent(); + + $this->assertSame($name, $promise->fresh()->name); + } + + public static function nameCharacters(): array + { + return [ + 'ASCII' => ['a'], + 'multibyte' => ['ą'], + ]; + } +} diff --git a/tests/Feature/WebPrintApi/PromiseContentValidationTest.php b/tests/Feature/WebPrintApi/PromiseContentValidationTest.php new file mode 100644 index 0000000..39977c4 --- /dev/null +++ b/tests/Feature/WebPrintApi/PromiseContentValidationTest.php @@ -0,0 +1,103 @@ +client = ClientApplication::factory()->create(); + Sanctum::actingAs($this->client, guard: 'web_print_api'); + } + + private function promise(array $attributes = []): PrintJobPromise + { + return PrintJobPromise::factory()->for($this->client)->withoutContent()->create(array_replace([ + 'print_job_id' => null, + 'printer_id' => null, + ], $attributes))->refresh(); + } + + private function sendContent(PrintJobPromise $promise, string $transport, mixed $name, mixed $content = 'New document'): TestResponse + { + $url = '/api/web-print/promises/'.$promise->ulid.'/content'; + + return match ($transport) { + 'json' => $this->postJson($url, ['name' => $name, 'content' => $content]), + 'multipart' => $this->call('POST', $url, files: [ + 'content' => UploadedFile::fake()->createWithContent($name, $content), + ], server: ['HTTP_ACCEPT' => 'application/json']), + 'header' => $this->call('POST', $url, server: [ + 'HTTP_X_FILE_NAME' => $name, + 'HTTP_ACCEPT' => 'application/json', + ], content: $content), + }; + } + + #[DataProvider('invalidPayloads')] + public function test_invalid_content_preserves_the_previous_document(string $transport, mixed $name, mixed $content, string $error): void + { + Storage::put('jobs/original.dat', 'Original document'); + $promise = $this->promise([ + 'file_name' => 'original.dat', + 'content_file' => 'jobs/original.dat', + 'size' => 17, + ]); + $original = $promise->getAttributes(); + + $this->sendContent($promise, $transport, $name, $content) + ->assertUnprocessable()->assertJsonValidationErrors($error); + + $this->assertEquals($original, $promise->fresh()->getAttributes()); + $this->assertSame('Original document', Storage::get('jobs/original.dat')); + $this->assertSame(['jobs/original.dat'], Storage::allFiles('jobs')); + } + + public static function invalidPayloads(): \Generator + { + foreach (['json', 'multipart', 'header'] as $transport) { + foreach (['a', 'ą'] as $character) { + yield $transport.' '.$character => [$transport, str_repeat($character, 256), 'New document', 'name']; + } + } + yield 'array name' => ['json', ['invalid'], 'New document', 'name']; + yield 'array content' => ['json', 'valid.txt', ['invalid'], 'content']; + } + + #[DataProvider('boundaryNames')] + public function test_content_accepts_a_255_character_filename(string $transport, string $name): void + { + $promise = $this->promise(); + + $this->sendContent($promise, $transport, $name)->assertNoContent(); + + $promise->refresh(); + $this->assertSame($name, $promise->file_name); + $this->assertSame('New document', $promise->content ?? Storage::get($promise->content_file)); + } + + public static function boundaryNames(): \Generator + { + foreach (['json', 'multipart', 'header'] as $transport) { + yield $transport.' ASCII' => [$transport, str_repeat('a', 255)]; + yield $transport.' multibyte' => [$transport, str_repeat('ą', 255)]; + } + } +} diff --git a/tests/Feature/WebPrintApi/PromiseInputValidationTest.php b/tests/Feature/WebPrintApi/PromiseInputValidationTest.php new file mode 100644 index 0000000..7a17d08 --- /dev/null +++ b/tests/Feature/WebPrintApi/PromiseInputValidationTest.php @@ -0,0 +1,67 @@ +create(), guard: 'web_print_api'); + } + + #[DataProvider('invalidFields')] + public function test_invalid_fields_are_rejected_before_creating_a_promise(string $field, mixed $value): void + { + $this->postJson('/api/web-print/promises', array_replace([ + 'name' => 'Test job', + 'type' => 'ppd', + 'file_name' => 'test.txt', + 'content' => 'Test document', + ], [$field => $value]))->assertUnprocessable()->assertJsonValidationErrors($field); + + $this->assertDatabaseCount('print_job_promises', 0); + $this->assertDatabaseCount('print_jobs', 0); + } + + public static function invalidFields(): \Generator + { + foreach (['type', 'file_name'] as $field) { + yield $field.' ASCII' => [$field, str_repeat('a', 256)]; + yield $field.' multibyte' => [$field, str_repeat('ą', 256)]; + yield $field.' array' => [$field, ['invalid']]; + } + yield 'array content' => ['content', ['invalid']]; + yield 'object content' => ['content', ['document' => 'invalid']]; + } + + #[DataProvider('boundaryFields')] + public function test_fields_accept_255_characters(string $field, string $value): void + { + $this->postJson('/api/web-print/promises', array_replace([ + 'name' => 'Test job', + 'type' => 'ppd', + 'file_name' => 'test.txt', + 'content' => 'Test document', + ], [$field => $value]))->assertCreated()->assertJsonPath('data.'.$field, $value); + + $this->assertDatabaseHas('print_job_promises', [$field => $value]); + } + + public static function boundaryFields(): \Generator + { + foreach (['type', 'file_name'] as $field) { + yield $field.' ASCII' => [$field, str_repeat('a', 255)]; + yield $field.' multibyte' => [$field, str_repeat('ą', 255)]; + } + } +}