Restore media-rule parity and release failed MCP upload tokens.

Keep Instagram feed requiring media and Discord/Telegram accepting GIFs after centralization, skip the empty workspace rate-limit bucket, and clear the signed upload claim when persistence fails so retries work.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Paulo Castellano 2026-07-24 22:37:57 -03:00
parent 491895cbd9
commit 0d4e5fd963
7 changed files with 111 additions and 27 deletions

View file

@ -224,7 +224,8 @@ public function minMediaCount(): int
public function acceptsGif(): bool
{
return match ($this) {
self::XPost, self::BlueskyPost, self::MastodonPost => true,
self::XPost, self::BlueskyPost, self::MastodonPost,
self::DiscordMessage, self::TelegramPost => true,
default => false,
};
}
@ -458,7 +459,6 @@ public function requiresMedia(): bool
self::MastodonPost => false,
self::TelegramPost => false,
self::FacebookPost => false,
self::InstagramFeed => false,
self::DiscordMessage => false,
default => true,
};

View file

@ -13,6 +13,7 @@
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
class UploadController extends Controller
{
@ -26,7 +27,9 @@ public function store(StoreUploadRequest $request, string $token): JsonResponse
$expiresAt - now()->timestamp + self::CACHE_TTL_BUFFER_SECONDS,
);
if (! Cache::add("mcp_upload:{$token}", true, $ttl)) {
$cacheKey = "mcp_upload:{$token}";
if (! Cache::add($cacheKey, true, $ttl)) {
abort(Response::HTTP_CONFLICT);
}
@ -34,29 +37,37 @@ public function store(StoreUploadRequest $request, string $token): JsonResponse
abort(Response::HTTP_CONFLICT);
}
$workspace = Workspace::findOrFail((string) $request->query('workspace_id'));
$file = $request->file('media');
$path = $file->getRealPath();
try {
$workspace = Workspace::findOrFail((string) $request->query('workspace_id'));
$file = $request->file('media');
$path = $file->getRealPath();
// Stream from PHP's temp upload path — do not load the whole file into
// memory (addMedia() uses file_get_contents; videos can be up to 1GB).
if ($path === false) {
abort(Response::HTTP_UNPROCESSABLE_ENTITY, 'Unable to read uploaded file.');
// Stream from PHP's temp upload path — do not load the whole file into
// memory (addMedia() uses file_get_contents; videos can be up to 1GB).
if ($path === false) {
abort(Response::HTTP_UNPROCESSABLE_ENTITY, 'Unable to read uploaded file.');
}
$media = DB::transaction(function () use ($workspace, $file, $path, $token): Media {
$media = $workspace->addMediaFromPath(
$path,
$file->getClientOriginalName(),
'assets',
mimeType: (string) $file->getMimeType(),
);
$media->upload_token = $token;
$media->save();
return $media;
});
} catch (Throwable $e) {
// Claim is only permanent after Media is stored — release so the
// signed URL can be retried after a transient disk/storage failure.
Cache::forget($cacheKey);
throw $e;
}
$media = DB::transaction(function () use ($workspace, $file, $path, $token): Media {
$media = $workspace->addMediaFromPath(
$path,
$file->getClientOriginalName(),
'assets',
mimeType: (string) $file->getMimeType(),
);
$media->upload_token = $token;
$media->save();
return $media;
});
return MediaUploadResource::make($media)
->response()
->setStatusCode(Response::HTTP_CREATED);

View file

@ -164,10 +164,15 @@ protected function configureRateLimiting(): void
// workspace_id (bound into the signed URL) so tenants don't share a bucket.
RateLimiter::for('mcp-uploads', function (Request $request) {
$workspaceId = (string) $request->query('workspace_id');
$ipLimit = Limit::perMinute(1200)->by('ip:'.$request->ip());
if ($workspaceId === '') {
return $ipLimit;
}
return [
Limit::perMinute(60)->by('workspace:'.$workspaceId),
Limit::perMinute(1200)->by('ip:'.$request->ip()),
Limit::perMinute(60)->by("workspace:{$workspaceId}"),
$ipLimit,
];
});
}

View file

@ -12,13 +12,14 @@ export type { MediaRules };
/**
* Fallback only when Inertia once-props have not synced yet (or unknown type).
* Real limits live in App\Enums\PostPlatform\ContentType::mediaRules().
* Keep this fail-closed (no GIF) — most content types reject animated GIFs.
*/
const DEFAULT_RULES: MediaRules = {
maxFiles: 10,
acceptImages: true,
acceptVideos: true,
requiresMedia: false,
acceptsGif: true,
acceptsGif: false,
};
export const getMediaRulesForContentType = (contentType: string): MediaRules => {

View file

@ -8,6 +8,7 @@
use App\Models\Workspace;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
@ -158,6 +159,23 @@ function signedUploadUrl(Workspace $ws, string $token, ?int $expiresInMinutes =
->and(Storage::exists($media->path))->toBeTrue();
});
test('releases the upload token when media persistence fails', function () {
$token = (string) Str::uuid();
$file = UploadedFile::fake()->create('clip.mp4', 256, 'video/mp4');
$cacheKey = "mcp_upload:{$token}";
DB::shouldReceive('transaction')
->once()
->andThrow(new RuntimeException('disk unavailable'));
$this->postJson(signedUploadUrl($this->workspace, $token), [
'media' => $file,
])->assertServerError();
expect(Cache::has($cacheKey))->toBeFalse()
->and(Media::where('upload_token', $token)->exists())->toBeFalse();
});
test('rejects disallowed mime type', function () {
$token = (string) Str::uuid();
$file = UploadedFile::fake()->create('evil.exe', 10, 'application/octet-stream');

View file

@ -23,6 +23,8 @@
->where('contentTypeMediaRules.instagram_reel.max_video_duration_sec', 900)
->where('contentTypeMediaRules.instagram_reel.max_video_bytes', 1 * 1024 * 1024 * 1024)
->where('contentTypeMediaRules.instagram_reel.accept_images', false)
->where('contentTypeMediaRules.instagram_feed.requires_media', true)
->where('contentTypeMediaRules.discord_message.accepts_gif', true)
->where('contentTypeMediaRules.facebook_reel.max_video_duration_sec', 90)
->where('contentTypeMediaRules.tiktok_video.max_video_duration_sec', null)
->where('contentTypeMediaRules.linkedin_post.max_document_bytes', 100 * 1024 * 1024)

View file

@ -55,6 +55,9 @@
expect($rules['linkedin_post']['max_document_bytes'])->toBe(100 * 1024 * 1024);
expect($rules['pinterest_carousel']['min_files'])->toBe(2);
expect($rules['x_post']['accepts_gif'])->toBeTrue();
expect($rules['instagram_feed']['requires_media'])->toBeTrue();
expect($rules['discord_message']['accepts_gif'])->toBeTrue();
expect($rules['telegram_post']['accepts_gif'])->toBeTrue();
});
test('media rules reuse enum capability helpers', function () {
@ -135,10 +138,10 @@
test('content type requires media correctly', function () {
expect(ContentType::InstagramReel->requiresMedia())->toBeTrue();
expect(ContentType::InstagramFeed->requiresMedia())->toBeTrue();
expect(ContentType::TikTokVideo->requiresMedia())->toBeTrue();
expect(ContentType::YouTubeShort->requiresMedia())->toBeTrue();
expect(ContentType::PinterestPin->requiresMedia())->toBeTrue();
expect(ContentType::InstagramFeed->requiresMedia())->toBeFalse();
expect(ContentType::LinkedInPost->requiresMedia())->toBeFalse();
expect(ContentType::XPost->requiresMedia())->toBeFalse();
expect(ContentType::ThreadsPost->requiresMedia())->toBeFalse();
@ -146,6 +149,50 @@
expect(ContentType::MastodonPost->requiresMedia())->toBeFalse();
});
test('media rules keep editor parity for gif and requires_media flags', function () {
expect(ContentType::DiscordMessage->acceptsGif())->toBeTrue();
expect(ContentType::TelegramPost->acceptsGif())->toBeTrue();
expect(ContentType::InstagramFeed->mediaRules()['requires_media'])->toBeTrue();
expect(ContentType::DiscordMessage->mediaRules()['accepts_gif'])->toBeTrue();
});
/**
* Lock the flags that used to live in the Vue CONTENT_TYPE_RULES map so a
* future centralization drift cannot silently flip editor behavior again.
*/
test('media rules preserve pre-centralization requires_media and accepts_gif for mapped types', function () {
$expected = [
'instagram_feed' => [true, false],
'instagram_reel' => [true, false],
'instagram_story' => [true, false],
'facebook_post' => [false, false],
'facebook_reel' => [true, false],
'facebook_story' => [true, false],
'linkedin_post' => [false, false],
'linkedin_page_post' => [false, false],
'tiktok_video' => [true, false],
'tiktok_photo' => [true, false],
'youtube_short' => [true, false],
'pinterest_pin' => [true, false],
'pinterest_video_pin' => [true, false],
'pinterest_carousel' => [true, false],
'x_post' => [false, true],
'threads_post' => [false, false],
'bluesky_post' => [false, true],
'mastodon_post' => [false, true],
// Previously fell through to DEFAULT_RULES (acceptsGif true).
'discord_message' => [false, true],
'telegram_post' => [false, true],
];
foreach ($expected as $type => [$requiresMedia, $acceptsGif]) {
$rules = ContentType::from($type)->mediaRules();
expect($rules['requires_media'])->toBe($requiresMedia, "{$type}.requires_media")
->and($rules['accepts_gif'])->toBe($acceptsGif, "{$type}.accepts_gif");
}
});
test('can get content types for platform', function () {
$instagramTypes = ContentType::forPlatform(Platform::Instagram);