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.
This commit is contained in:
Parsa Aghayi committed 2026-10-01 17:41:49 -04:00
1 parent 6f6640330a
commit 6b03c0fbc3
6 files changed
+351

No files matched your search

@@ -0,0 +1,79 @@
<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreMediaRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class MediaController extends Controller
{
/**
* Disk that uploaded images are written to. It is configured with
* `visibility => 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.']);
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class StoreMediaRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, array<int, mixed>>
*/
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' => 'تصویر'];
}
}
+10
View File
@@ -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
+9
View File
@@ -0,0 +1,9 @@
<?php
/*
|--------------------------------------------------------------------------
| Admin CRUD
|--------------------------------------------------------------------------
| Registered from bootstrap/app.php. Content types that have no write
| endpoints yet are added here.
*/
+27
View File
@@ -0,0 +1,27 @@
<?php
use App\Http\Controllers\Api\Admin\MediaController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Media upload
|--------------------------------------------------------------------------
| Registered from bootstrap/app.php. Kept apart from routes/api.php so the
| upload surface can be reviewed, throttled and locked down on its own.
|
| Uploads are far more expensive than a JSON write and are the most likely
| place for a disk-exhaustion attack, so this group gets its own, much
| tighter rate limit than the general admin API.
*/
Route::middleware(['auth:sanctum', 'admin', 'throttle:12,1'])->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');
});
+175
View File
@@ -0,0 +1,175 @@
<?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class MediaUploadTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('public');
}
public function test_anonymous_requests_cannot_upload(): void
{
$this->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', '<?php echo 1;'),
])->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',
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></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];
}
}