fix: GD memory safety check and redact tokens from exception context

This commit is contained in:
Paulo Castellano 2026-03-31 22:01:59 -03:00
parent 2883793441
commit 6e3dac7a66
2 changed files with 51 additions and 2 deletions

View file

@ -23,14 +23,36 @@ public function __construct(
public function context(): array
{
return [
'platform' => $this->platform(),
'platform' => static::platform(),
'category' => $this->category->value,
'platform_error_code' => $this->platformErrorCode,
'user_message' => $this->userMessage,
'raw_response' => $this->rawResponse,
'raw_response' => $this->redactTokens($this->rawResponse),
];
}
private function redactTokens(?string $text): ?string
{
if ($text === null) {
return null;
}
// Redact common token patterns from API error responses
return preg_replace(
[
'/access_token=([^&"\s]+)/',
'/"access_token"\s*:\s*"([^"]+)"/',
'/Bearer\s+\S+/',
],
[
'access_token=[REDACTED]',
'"access_token":"[REDACTED]"',
'Bearer [REDACTED]',
],
$text
);
}
abstract public static function fromApiResponse(mixed $response): static;
abstract public function platform(): string;

View file

@ -5,6 +5,7 @@
namespace App\Services\Media;
use App\Enums\SocialAccount\Platform;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
@ -24,6 +25,32 @@ public function __construct()
public function optimizeImage(string $filePath, Platform $platform): string
{
$config = $this->getImageConfig($platform);
// Check image dimensions to prevent GD memory overflow
$imageInfo = @getimagesize($filePath);
if ($imageInfo) {
$width = $imageInfo[0];
$height = $imageInfo[1];
$channels = $imageInfo['channels'] ?? 4;
$estimatedMemory = $width * $height * $channels * 1.5; // 1.5x safety margin
// If image would use more than 256MB of RAM, skip optimization and return as-is
if ($estimatedMemory > 256 * 1024 * 1024) {
Log::warning('MediaOptimizer: Image too large for GD processing', [
'width' => $width,
'height' => $height,
'estimated_memory' => $estimatedMemory,
'platform' => $platform->value,
]);
// Copy original file to temp location and return
$tempFile = tempnam(sys_get_temp_dir(), 'media_opt_');
copy($filePath, $tempFile);
return $tempFile;
}
}
$image = $this->manager->decodePath($filePath);
$maxWidth = data_get($config, 'max_width');