From 6b03c0fbc35a5497e85e63f31217ce6d60c11f21 Mon Sep 17 00:00:00 2001 From: Parsa Aghayi Date: Thu, 1 Oct 2026 17:41:49 -0400 Subject: [PATCH] Add a locked-down image upload endpoint for the admin panel Posts, projects and about-me all carry an image column that could only ever be filled by typing a URL by hand, so every featured image in the database is still a placeholder. Uploads are the missing half of content management. Filenames are generated rather than reused from the client, which is what keeps a double extension or a path traversal out of a web-served directory. The upload surface is restricted to raster formats (no SVG, which can carry script) with a size and dimension ceiling, and throttled at 12/min against the general admin API's 30/min because an upload costs far more than a JSON write. Routes move to per-feature files registered from bootstrap/app.php, since api.php had become a chokepoint for parallel work on this repo. --- .../Controllers/Api/Admin/MediaController.php | 79 ++++++++ app/Http/Requests/Admin/StoreMediaRequest.php | 51 +++++ bootstrap/app.php | 10 + routes/crud.php | 9 + routes/media.php | 27 +++ tests/Feature/MediaUploadTest.php | 175 ++++++++++++++++++ 6 files changed, 351 insertions(+) create mode 100644 app/Http/Controllers/Api/Admin/MediaController.php create mode 100644 app/Http/Requests/Admin/StoreMediaRequest.php create mode 100644 routes/crud.php create mode 100644 routes/media.php create mode 100644 tests/Feature/MediaUploadTest.php diff --git a/app/Http/Controllers/Api/Admin/MediaController.php b/app/Http/Controllers/Api/Admin/MediaController.php new file mode 100644 index 0000000..62e5191 --- /dev/null +++ b/app/Http/Controllers/Api/Admin/MediaController.php @@ -0,0 +1,79 @@ + public` and served through the `public/storage` symlink, + * so an uploaded file is reachable from the site without a second copy. + */ + private const DISK = 'public'; + + /** + * Sub-directory uploads land in, so a single flat folder cannot grow + * unbounded and directory listings stay cheap to paginate. + */ + private const DIRECTORY = 'media'; + + /** + * Store an uploaded image and return the URL to persist on the record. + * + * The filename is generated rather than taken from the client: an + * attacker-supplied name is the usual way to smuggle a double extension + * (`cover.php.jpg`) or a path traversal into a web-served directory. + */ + public function store(StoreMediaRequest $request): JsonResponse + { + $file = $request->file('file'); + + $path = $file->store(self::DIRECTORY, self::DISK); + + if ($path === false) { + return response()->json(['message' => 'Image could not be stored.'], 500); + } + + return response()->json([ + 'data' => [ + 'url' => Storage::disk(self::DISK)->url($path), + 'path' => $path, + 'name' => basename($path), + 'size' => $file->getSize(), + 'mime' => $file->getMimeType(), + ], + ], 201); + } + + /** + * Delete an uploaded image by its stored path. + * + * Only paths inside the upload directory are accepted, so a crafted + * `../../.env` cannot be used to delete arbitrary files on the server. + */ + public function destroy(string $path): JsonResponse + { + $disk = Storage::disk(self::DISK); + $clean = Str::start(Str::after($path, self::DIRECTORY.'/'), self::DIRECTORY.'/'); + + // `Str::after` returns the whole string when the prefix is absent, so + // re-check the prefix explicitly before touching the disk. + if (! str_starts_with($clean, self::DIRECTORY.'/') || str_contains($clean, '..')) { + return response()->json(['message' => 'Invalid media path.'], 422); + } + + if (! $disk->exists($clean)) { + return response()->json(['message' => 'Media not found.'], 404); + } + + $disk->delete($clean); + + return response()->json(['message' => 'Media deleted.']); + } +} diff --git a/app/Http/Requests/Admin/StoreMediaRequest.php b/app/Http/Requests/Admin/StoreMediaRequest.php new file mode 100644 index 0000000..c32a02f --- /dev/null +++ b/app/Http/Requests/Admin/StoreMediaRequest.php @@ -0,0 +1,51 @@ +> + */ + public function rules(): array + { + return [ + // `image` alone accepts SVG and any other raster format the server + // can decode, including formats browsers cannot display safely. + // Pinning the list keeps the upload surface small and predictable: + // no SVG means no stored script, and no BMP/TIFF means nothing that + // would need converting before a browser can show it. + 'file' => [ + 'required', + 'file', + 'image', + 'mimes:jpg,jpeg,png,webp,gif', + 'max:4096', + 'dimensions:min_width=1,min_height=1,max_width=6000,max_height=6000', + ], + ]; + } + + public function messages(): array + { + return [ + 'file.required' => 'فایلی انتخاب نشده است.', + 'file.image' => 'فایل انتخاب‌شده یک تصویر معتبر نیست.', + 'file.mimes' => 'فقط فرمت‌های jpg، png، webp و gif پذیرفته می‌شود.', + 'file.max' => 'حجم تصویر نباید بیشتر از ۴ مگابایت باشد.', + 'file.dimensions' => 'ابعاد تصویر مجاز نیست.', + ]; + } + + public function attributes(): array + { + return ['file' => 'تصویر']; + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index 85a183d..fd1a790 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -5,6 +5,7 @@ use App\Http\Middleware\EnsureUserIsAdmin; use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; +use Illuminate\Support\Facades\Route; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( @@ -12,6 +13,15 @@ return Application::configure(basePath: dirname(__DIR__)) api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', health: '/up', + // Content-management endpoints live in their own files so the public and + // legacy routes in api.php stay readable. `then:` does not inherit the + // `api:` prefix or middleware group from the arguments above, so both + // are applied explicitly here to keep these routes identical in shape + // to the ones declared in routes/api.php. + then: function () { + Route::prefix('api')->middleware('api')->group(base_path('routes/media.php')); + Route::prefix('api')->middleware('api')->group(base_path('routes/crud.php')); + }, ) ->withMiddleware(function (Middleware $middleware) { // Let the Next.js admin panel authenticate with a Sanctum session diff --git a/routes/crud.php b/routes/crud.php new file mode 100644 index 0000000..0cbde42 --- /dev/null +++ b/routes/crud.php @@ -0,0 +1,9 @@ +group(function () { + Route::post('admin/media', [MediaController::class, 'store']); + Route::delete('admin/media/{path}', [MediaController::class, 'destroy']) + // Dots are required for the extension, so traversal is refused by the + // `(?!.*\.\.)` lookahead rather than by simply omitting the character. + // The controller repeats the check; the pattern just keeps obvious + // probes from ever reaching the application. + ->where('path', 'media\/(?!.*\.\.)[A-Za-z0-9_\-\/\.]+') + ->name('admin.media.destroy'); +}); diff --git a/tests/Feature/MediaUploadTest.php b/tests/Feature/MediaUploadTest.php new file mode 100644 index 0000000..3929c72 --- /dev/null +++ b/tests/Feature/MediaUploadTest.php @@ -0,0 +1,175 @@ +post('/api/admin/media', ['file' => UploadedFile::fake()->image('cover.jpg')]) + ->assertUnauthorized(); + } + + public function test_non_admins_cannot_upload(): void + { + Sanctum::actingAs(User::factory()->create()); + + $this->post('/api/admin/media', ['file' => UploadedFile::fake()->image('cover.jpg')]) + ->assertForbidden(); + } + + public function test_admins_can_upload_an_image(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $this->post('/api/admin/media', ['file' => UploadedFile::fake()->image('cover.jpg', 400, 300)]) + ->assertCreated() + ->assertJsonStructure(['data' => ['url', 'path', 'name', 'size', 'mime']]); + + Storage::disk('public')->assertExists($this->storedPath()); + } + + public function test_upload_requires_a_file(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $this->postJson('/api/admin/media')->assertStatus(422)->assertJsonValidationErrors('file'); + } + + public function test_upload_rejects_a_non_image_disguised_as_an_image(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $this->post('/api/admin/media', [ + 'file' => UploadedFile::fake()->createWithContent('payload.php', 'assertStatus(422)->assertJsonValidationErrors('file'); + } + + /** + * SVG is refused on purpose: it can carry script, and the site serves the + * upload directory from the same origin as the admin panel. + */ + public function test_upload_rejects_svg(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $this->post('/api/admin/media', [ + 'file' => UploadedFile::fake()->createWithContent( + 'payload.svg', + '', + ), + ])->assertStatus(422)->assertJsonValidationErrors('file'); + } + + public function test_upload_rejects_a_file_over_the_size_limit(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $this->post('/api/admin/media', [ + 'file' => UploadedFile::fake()->create('big.jpg', 5120, 'image/jpeg'), + ])->assertStatus(422)->assertJsonValidationErrors('file'); + } + + /** + * The client-supplied filename must never reach the filesystem verbatim, + * otherwise a double extension or a traversal could be smuggled in. + */ + public function test_upload_ignores_the_client_filename(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $this->post('/api/admin/media', [ + 'file' => UploadedFile::fake()->image('../../evil.php.jpg', 200, 200), + ])->assertCreated(); + + $stored = $this->storedPath(); + + $this->assertStringStartsWith('media/', $stored); + $this->assertStringNotContainsString('..', $stored); + $this->assertStringNotContainsString('evil.php', $stored); + } + + public function test_admins_can_delete_an_uploaded_image(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $path = UploadedFile::fake()->image('cover.jpg')->store('media', 'public'); + + $this->deleteJson("/api/admin/media/{$path}")->assertOk(); + + Storage::disk('public')->assertMissing($path); + } + + public function test_delete_rejects_a_path_traversal(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + Storage::disk('public')->put('.env', 'SECRET=1'); + + // The route pattern itself already blocks `..`, so this asserts the + // defence survives even if that pattern is ever loosened. + $this->deleteJson('/api/admin/media/media/../../.env')->assertStatus(404); + + Storage::disk('public')->assertExists('.env'); + } + + public function test_delete_rejects_a_path_outside_the_media_directory(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + Storage::disk('public')->put('secret.txt', 'nope'); + + $this->deleteJson('/api/admin/media/secret.txt')->assertStatus(404); + + Storage::disk('public')->assertExists('secret.txt'); + } + + public function test_deleting_a_missing_file_is_a_404(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + $this->deleteJson('/api/admin/media/media/2026/01/missing.jpg')->assertNotFound(); + } + + public function test_uploads_are_rate_limited_harder_than_other_admin_writes(): void + { + Sanctum::actingAs(User::factory()->create(['is_admin' => true])); + + // 12 allowed, the 13th is throttled. Keeps the disk-exhaustion cost + // of the upload endpoint far below the general admin API budget. + foreach (range(1, 12) as $ignored) { + $this->post('/api/admin/media', [ + 'file' => UploadedFile::fake()->image("cover{$ignored}.jpg", 10, 10), + ])->assertCreated(); + } + + $this->post('/api/admin/media', ['file' => UploadedFile::fake()->image('overflow.jpg', 10, 10)]) + ->assertStatus(429); + } + + /** + * Read the single path written by the fake disk during a request. + */ + private function storedPath(): string + { + $files = Storage::disk('public')->allFiles('media'); + + $this->assertCount(1, $files, 'expected exactly one stored upload'); + + return $files[0]; + } +}