Upload images through the API, and from the MCP server
POST /api/v1/media stores an image where the panel keeps a page's and answers with the path to send as `featured_image`. Without it the MCP server could create a page but never give it a picture. The file goes through Media::for(), so it is processed, served and pruned like one uploaded in the panel. Two ways in, one per request: a multipart `file`, or JSON with a `url` the API downloads itself. JPEG, PNG, WebP, GIF or AVIF only, decided from the bytes; no SVG, which is a document that can carry script. The URL is fetched from inside the stack's network, so RemoteImage guards it: HTTPS only, every resolved address must be public, the connection is pinned to the checked address with CURLOPT_RESOLVE so a changing DNS answer cannot swap in a private one, redirects are not followed, and the body is read to a ceiling whatever its headers say. Uploading needs permission to write pages. MediaPolicy::create stays false, so the panel gains no free-standing "new file" button. In the MCP server a multipart binary field becomes `<field>_path` over stdio: the server reads the file from the caller's disk and sends it as multipart, instead of the model pushing base64 through its context. Over HTTP the server's disk is not the caller's, so only `body.url` is offered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
85
app/Http/Controllers/Api/V1/MediaController.php
Normal file
85
app/Http/Controllers/Api/V1/MediaController.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Api\V1\MediaRequest;
|
||||
use App\Http\Resources\MediaResource;
|
||||
use App\Models\Media;
|
||||
use App\Services\Media\RemoteImage;
|
||||
use finfo;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* POST /api/v1/media
|
||||
*
|
||||
* Stores an image and answers with the path a record points at — what the
|
||||
* panel's upload field does on a form, without the form. It exists for the MCP
|
||||
* server, which otherwise could create a page but never give it a picture.
|
||||
*
|
||||
* The file lands where the panel puts a page's images and goes through
|
||||
* `Media::for()`, so it is processed, served and eventually pruned exactly
|
||||
* like one uploaded there.
|
||||
*/
|
||||
class MediaController extends Controller
|
||||
{
|
||||
/**
|
||||
* Extension by detected type. Chosen from the bytes, never from the name
|
||||
* the client sent.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected const EXTENSIONS = [
|
||||
'image/jpeg' => 'jpg',
|
||||
'image/png' => 'png',
|
||||
'image/webp' => 'webp',
|
||||
'image/gif' => 'gif',
|
||||
'image/avif' => 'avif',
|
||||
];
|
||||
|
||||
public function store(MediaRequest $request, RemoteImage $remote): JsonResponse
|
||||
{
|
||||
$this->authorize('upload', Media::class);
|
||||
|
||||
$field = $request->hasFile('file') ? 'file' : 'url';
|
||||
|
||||
$contents = $field === 'file'
|
||||
? (string) $request->file('file')->get()
|
||||
: $remote->fetch((string) $request->string('url'));
|
||||
|
||||
$mime = (new finfo(FILEINFO_MIME_TYPE))->buffer($contents) ?: null;
|
||||
$size = @getimagesizefromstring($contents);
|
||||
|
||||
// Both, because each catches what the other misses: the type is read
|
||||
// from the magic bytes, and a file that has them but does not decode
|
||||
// is not an image anybody can render.
|
||||
if ($size === false || ! in_array($mime, (array) config('media.upload.mimes'), true)) {
|
||||
throw ValidationException::withMessages([$field => [__('rules.media.not_an_image')]]);
|
||||
}
|
||||
|
||||
$path = config('media.upload.directory').'/'.Str::random(40).'.'.self::EXTENSIONS[$mime];
|
||||
|
||||
Storage::disk((string) config('media.disk'))->put($path, $contents);
|
||||
|
||||
$media = Media::for($path);
|
||||
|
||||
// What is already known, so the answer carries dimensions straight
|
||||
// away rather than after the queue has run. The processor writes the
|
||||
// same values, and the rest, when it does.
|
||||
if (! $media->isProcessed()) {
|
||||
$media->forceFill([
|
||||
'mime' => $mime,
|
||||
'size' => strlen($contents),
|
||||
'width' => $size[0],
|
||||
'height' => $size[1],
|
||||
])->save();
|
||||
}
|
||||
|
||||
return MediaResource::make($media->fresh())->response()->setStatusCode(201);
|
||||
}
|
||||
}
|
||||
45
app/Http/Requests/Api/V1/MediaRequest.php
Normal file
45
app/Http/Requests/Api/V1/MediaRequest.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\Api\V1;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* An image arrives one of two ways: as the request's `file` (multipart), or as
|
||||
* a `url` the API downloads itself (JSON). Exactly one.
|
||||
*
|
||||
* What the declared type says is only a first filter. The controller looks at
|
||||
* the bytes, because a client names the type of what it sends and a URL's
|
||||
* server names the type of what it answers — and neither has to be telling
|
||||
* the truth.
|
||||
*/
|
||||
class MediaRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Authorisation is the controller's, as everywhere else in this API — and
|
||||
* it has to happen before a URL is fetched, which is after validation.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'file' => [
|
||||
'required_without:url',
|
||||
'prohibits:url',
|
||||
'file',
|
||||
'max:'.(int) config('media.upload.max_kb'),
|
||||
'mimetypes:'.implode(',', (array) config('media.upload.mimes')),
|
||||
],
|
||||
'url' => ['required_without:file', 'string', 'url:https', 'max:2048'],
|
||||
];
|
||||
}
|
||||
}
|
||||
35
app/Http/Resources/MediaResource.php
Normal file
35
app/Http/Resources/MediaResource.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\Media;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin Media
|
||||
*/
|
||||
class MediaResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
// What a record stores — `featured_image` on a page — and so the one
|
||||
// field a caller has to keep.
|
||||
'path' => $this->path,
|
||||
'url' => $this->url(),
|
||||
'mime' => $this->mime,
|
||||
'size' => $this->size,
|
||||
'width' => $this->width,
|
||||
'height' => $this->height,
|
||||
// False until the queue has derived the smaller versions and the
|
||||
// placeholder. The image serves either way.
|
||||
'processed' => $this->isProcessed(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,19 @@ class MediaPolicy extends ResourcePolicy
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploading through the API, which has no form to attach a file to.
|
||||
*
|
||||
* Still true to the rule above in spirit: through the API the one record
|
||||
* that holds an image is a page, so whoever may write pages may upload the
|
||||
* image for one — and nobody else, whatever their `media.*` permissions,
|
||||
* which only ever described looking after files that already exist.
|
||||
*/
|
||||
public function upload(User $user): bool
|
||||
{
|
||||
return $user->can('pages.create') || $user->can('pages.update');
|
||||
}
|
||||
|
||||
/**
|
||||
* A file something still points at cannot be deleted from here: doing so
|
||||
* would leave a broken image on the public site, which is precisely what
|
||||
|
||||
26
app/Services/Media/HostResolver.php
Normal file
26
app/Services/Media/HostResolver.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Media;
|
||||
|
||||
/**
|
||||
* Every address a hostname resolves to, IPv4 and IPv6.
|
||||
*
|
||||
* Its own class so the tests can answer for hosts that do not exist, and so
|
||||
* `RemoteImage` can refuse a name that points anywhere private before a single
|
||||
* byte is requested.
|
||||
*/
|
||||
class HostResolver
|
||||
{
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function resolve(string $host): array
|
||||
{
|
||||
$v4 = gethostbynamel($host) ?: [];
|
||||
$v6 = array_column(@dns_get_record($host, DNS_AAAA) ?: [], 'ipv6');
|
||||
|
||||
return array_values(array_unique([...$v4, ...$v6]));
|
||||
}
|
||||
}
|
||||
130
app/Services/Media/RemoteImage.php
Normal file
130
app/Services/Media/RemoteImage.php
Normal file
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Media;
|
||||
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Downloads an image from a URL someone handed the API, without letting that
|
||||
* URL reach anything it should not.
|
||||
*
|
||||
* The request is made by this server, from inside the stack's network, so an
|
||||
* unchecked URL is a way to make it fetch `http://postgres:5432`, the cloud
|
||||
* metadata service, or the application itself. Hence:
|
||||
*
|
||||
* - HTTPS only.
|
||||
* - Every address the host resolves to must be a public one — a single private
|
||||
* address among several is enough to refuse.
|
||||
* - The connection is pinned to the address that was checked (CURLOPT_RESOLVE),
|
||||
* so a DNS answer that changes between the check and the request — DNS
|
||||
* rebinding — cannot swap in a private one.
|
||||
* - Redirects are not followed: the target of one would need all of the above
|
||||
* again, and "use the final address" is an easy thing to ask for.
|
||||
* - The body is read to a ceiling and no further, whatever the headers claim.
|
||||
*/
|
||||
class RemoteImage
|
||||
{
|
||||
public function __construct(protected HostResolver $resolver) {}
|
||||
|
||||
/**
|
||||
* @return string The file's bytes.
|
||||
*
|
||||
* @throws ValidationException With the reason, on the `url` field.
|
||||
*/
|
||||
public function fetch(string $url): string
|
||||
{
|
||||
$parts = parse_url($url);
|
||||
$host = $parts['host'] ?? null;
|
||||
|
||||
if (($parts['scheme'] ?? null) !== 'https' || blank($host)) {
|
||||
$this->fail('https_only');
|
||||
}
|
||||
|
||||
$host = trim((string) $host, '[]');
|
||||
$port = (int) ($parts['port'] ?? 443);
|
||||
$address = $this->publicAddressFor($host);
|
||||
$maxBytes = (int) config('media.upload.max_kb') * 1024;
|
||||
|
||||
try {
|
||||
$response = Http::withOptions([
|
||||
'allow_redirects' => false,
|
||||
'stream' => true,
|
||||
'connect_timeout' => 5,
|
||||
'timeout' => (int) config('media.upload.remote_timeout', 15),
|
||||
'curl' => [CURLOPT_RESOLVE => [sprintf(
|
||||
'%s:%d:%s',
|
||||
$host,
|
||||
$port,
|
||||
str_contains($address, ':') ? "[{$address}]" : $address,
|
||||
)]],
|
||||
])
|
||||
->withHeaders(['Accept' => 'image/*'])
|
||||
->get($url);
|
||||
} catch (ConnectionException) {
|
||||
$this->fail('unreachable');
|
||||
}
|
||||
|
||||
if ($response->redirect()) {
|
||||
$this->fail('redirect');
|
||||
}
|
||||
|
||||
if ($response->status() !== 200) {
|
||||
$this->fail('status', ['status' => $response->status()]);
|
||||
}
|
||||
|
||||
if ((int) $response->header('Content-Length') > $maxBytes) {
|
||||
$this->fail('too_large', ['max' => (int) config('media.upload.max_kb')]);
|
||||
}
|
||||
|
||||
$body = $response->toPsrResponse()->getBody();
|
||||
$contents = '';
|
||||
|
||||
while (! $body->eof()) {
|
||||
$contents .= $body->read(65536);
|
||||
|
||||
if (strlen($contents) > $maxBytes) {
|
||||
$this->fail('too_large', ['max' => (int) config('media.upload.max_kb')]);
|
||||
}
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* The address to connect to, once every address the host has is known to
|
||||
* be public.
|
||||
*/
|
||||
protected function publicAddressFor(string $host): string
|
||||
{
|
||||
$addresses = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : $this->resolver->resolve($host);
|
||||
|
||||
if ($addresses === []) {
|
||||
$this->fail('unresolvable');
|
||||
}
|
||||
|
||||
foreach ($addresses as $address) {
|
||||
// GLOBAL_RANGE is the strict one: besides the private and reserved
|
||||
// blocks it refuses shared (100.64/10), link-local and the
|
||||
// IPv4-mapped IPv6 spelling of any of them.
|
||||
if (! filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE)) {
|
||||
$this->fail('private');
|
||||
}
|
||||
}
|
||||
|
||||
return $addresses[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $replace
|
||||
*/
|
||||
protected function fail(string $reason, array $replace = []): never
|
||||
{
|
||||
throw ValidationException::withMessages([
|
||||
'url' => [__("rules.media.remote.{$reason}", $replace)],
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user