diff --git a/config/storage-service.php b/config/storage-service.php index 6027847..2df2d21 100644 --- a/config/storage-service.php +++ b/config/storage-service.php @@ -9,5 +9,7 @@ return [ 'local', ], + 'prefix' => env('STORAGE_SERVICE_PREFIX', 'media'), + 'allowedExtensions' => ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx', 'csv', 'mp4', 'webm'], ]; diff --git a/src/Config/StorageServiceConfig.php b/src/Config/StorageServiceConfig.php index 287fbff..82d2191 100644 --- a/src/Config/StorageServiceConfig.php +++ b/src/Config/StorageServiceConfig.php @@ -17,6 +17,8 @@ final class StorageServiceConfig /** @var DiskName[] */ private array $eligibles; + private ?string $prefix = null; + /** * @param string[] $eligibleDisks * @param object{'disk':string,'driver':string}[] $laravelExistingDisks @@ -26,8 +28,61 @@ final class StorageServiceConfig private string $defaultDisk, private array $eligibleDisks, private array $laravelExistingDisks, - private array $allowedExtensions + private array $allowedExtensions, + ?string $prefix = null ) { + $this->validateAndSetDisks(); + $this->validateExtensions(); + $this->prefix = $this->parsePrefix($prefix); + } + + private function parsePrefix(?string $prefix): ?string + { + if ($prefix === null) { + return null; + } + + $trimmed = mb_trim($prefix); + $clean = trim($trimmed, '/'); + + if ($clean === '') { + return null; + } + + if (str_contains($clean, '..')) { + throw new UnexpectedStorageException('Prefix must not contain "..".'); + } + + if (str_contains($clean, '\\')) { + throw new UnexpectedStorageException('Prefix must not contain "\\".'); + } + + if (str_contains($clean, '//')) { + throw new UnexpectedStorageException('Prefix must not contain "//".'); + } + + return $clean; + } + + private function validateExtensions(): void + { + if (empty($this->allowedExtensions)) { + throw new UnexpectedStorageException('Allowed extensions cannot be empty'); + } + + foreach ($this->allowedExtensions as $extension) { + if (! is_string($extension) || empty(mb_trim($extension))) { + throw new UnexpectedStorageException("Allowed extension {$extension} is not valid"); + } + + if (in_array(strtolower(ltrim($extension, '.')), self::UNSUPPORTED_EXTENSIONS, true)) { + throw new UnexpectedStorageException("Extension '{$extension}' is forbidden: XML/SVG sanitization is currently not supported."); + } + } + } + + private function validateAndSetDisks(): void + { if (Utils::diskExists($this->defaultDisk) === false) { throw new UnexpectedStorageException('Default disk does not exist'); } @@ -85,20 +140,11 @@ final class StorageServiceConfig $disk->disk, $disk->driver ), $intersectWithDrivers); + } - if (empty($this->allowedExtensions)) { - throw new UnexpectedStorageException('Allowed extensions cannot be empty'); - } - - foreach ($this->allowedExtensions as $extension) { - if (! is_string($extension) || empty(mb_trim($extension))) { - throw new UnexpectedStorageException("Allowed extension {$extension} is not valid"); - } - - if (in_array(strtolower(ltrim($extension, '.')), self::UNSUPPORTED_EXTENSIONS, true)) { - throw new UnexpectedStorageException("Extension '{$extension}' is forbidden: XML/SVG sanitization is currently not supported."); - } - } + public function getPrefix(): ?string + { + return $this->prefix; } public function getDefaultDisk(): DiskName diff --git a/src/Lib/PathGenerators/DateHashPathGenerator.php b/src/Lib/PathGenerators/DateHashPathGenerator.php index e242cce..81bf54b 100644 --- a/src/Lib/PathGenerators/DateHashPathGenerator.php +++ b/src/Lib/PathGenerators/DateHashPathGenerator.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Uwil\Storage\Lib\PathGenerators; use Illuminate\Support\Str; +use Uwil\Storage\Config\StorageServiceConfig; use Uwil\Storage\Contracts\PathGenerator; use Uwil\Storage\Lib\ValueObjects\DiskName; use Uwil\Storage\Lib\ValueObjects\SanitizedFile; @@ -12,8 +13,13 @@ use Uwil\Storage\Lib\ValueObjects\StorageFilePath; class DateHashPathGenerator implements PathGenerator { + public function __construct( + private ?StorageServiceConfig $config = null + ) { + } + #[\Override] - public function generate(DiskName $disk, SanitizedFile $file, ?string $directory = null): StorageFilePath + public function generate(DiskName $disk, SanitizedFile $file): StorageFilePath { $extension = pathinfo($file->sanitizedName, PATHINFO_EXTENSION); $filename = pathinfo($file->sanitizedName, PATHINFO_FILENAME); @@ -30,7 +36,7 @@ class DateHashPathGenerator implements PathGenerator ); $pathSegments = array_filter([ - $directory ? trim($directory, '/') : null, + $this->config?->getPrefix(), gmdate('Y'), gmdate('m'), gmdate('d'), diff --git a/src/Lib/PathGenerators/UuidPathGenerator.php b/src/Lib/PathGenerators/UuidPathGenerator.php index 84ec14b..e7f484e 100644 --- a/src/Lib/PathGenerators/UuidPathGenerator.php +++ b/src/Lib/PathGenerators/UuidPathGenerator.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Uwil\Storage\Lib\PathGenerators; use Illuminate\Support\Str; +use Uwil\Storage\Config\StorageServiceConfig; use Uwil\Storage\Contracts\PathGenerator; use Uwil\Storage\Lib\ValueObjects\DiskName; use Uwil\Storage\Lib\ValueObjects\SanitizedFile; @@ -12,8 +13,13 @@ use Uwil\Storage\Lib\ValueObjects\StorageFilePath; class UuidPathGenerator implements PathGenerator { + public function __construct( + private ?StorageServiceConfig $config = null + ) { + } + #[\Override] - public function generate(DiskName $disk, SanitizedFile $file, ?string $directory = null): StorageFilePath + public function generate(DiskName $disk, SanitizedFile $file): StorageFilePath { $extension = pathinfo($file->sanitizedName, PATHINFO_EXTENSION); $uuid = Str::uuid()->toString(); @@ -21,7 +27,7 @@ class UuidPathGenerator implements PathGenerator $finalFilename = $uuid . (! empty($extension) ? '.' . $extension : ''); $pathSegments = array_filter([ - $directory ? trim($directory, '/') : null, + $this->config?->getPrefix(), $finalFilename, ]); diff --git a/src/StorageServiceProvider.php b/src/StorageServiceProvider.php index a3494c7..7052475 100644 --- a/src/StorageServiceProvider.php +++ b/src/StorageServiceProvider.php @@ -51,6 +51,9 @@ class StorageServiceProvider extends ServiceProvider fn ($ext) => is_string($ext) ); + $rawPrefix = Config::get('storage-service.prefix'); + $prefix = is_string($rawPrefix) ? $rawPrefix : null; + $disks = []; foreach ($rawDisks as $name => $diskConf) { $disks[] = (object) [ @@ -63,7 +66,8 @@ class StorageServiceProvider extends ServiceProvider Config::string('storage-service.default', 'local'), $eligibleDisks, $disks, - $allowedExtensions + $allowedExtensions, + $prefix ); } ); @@ -71,6 +75,20 @@ class StorageServiceProvider extends ServiceProvider $this->app->bind(MimeTypeChecker::class, MimeTypeCheckerImpl::class); $this->app->bind(FileSanitizer::class, FileSanitizerImpl::class); + $this->app->bind( + DateHashPathGenerator::class, + fn (Application $app) => new DateHashPathGenerator( + $app->make(StorageServiceConfig::class) + ) + ); + + $this->app->bind( + UuidPathGenerator::class, + fn (Application $app) => new UuidPathGenerator( + $app->make(StorageServiceConfig::class) + ) + ); + $this->app->bind( StorageGateway::class, fn (Application $app) => new StorageGatewayImpl( diff --git a/tests/Unit/Config/StorageServiceConfigTest.php b/tests/Unit/Config/StorageServiceConfigTest.php index d34cce6..cfef058 100644 --- a/tests/Unit/Config/StorageServiceConfigTest.php +++ b/tests/Unit/Config/StorageServiceConfigTest.php @@ -354,3 +354,64 @@ describe('StorageServiceConfig isExtensionAllowed', function (): void { '.svg' => '.svg', ]); }); + +describe('StorageServiceConfig prefix validation and retrieval', function (): void { + it('returns null when prefix is omitted or null', function (?string $prefix): void { + // GIVEN + $config = new StorageServiceConfig( + defaultDisk: 'local', + eligibleDisks: ['local'], + laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']], + allowedExtensions: ['pdf'], + prefix: $prefix + ); + + // THEN + expect($config->getPrefix())->toBeNull(); + })->with([ + 'null' => null, + 'empty' => '', + 'spaces' => ' ', + 'slashes' => '///', + ]); + + it('trims leading and trailing slashes and spaces from prefix', function (string $input, string $expected): void { + // GIVEN + $config = new StorageServiceConfig( + defaultDisk: 'local', + eligibleDisks: ['local'], + laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']], + allowedExtensions: ['pdf'], + prefix: $input + ); + + // THEN + expect($config->getPrefix())->toBe($expected); + })->with([ + 'simple' => ['media', 'media'], + 'leading slash' => ['/media', 'media'], + 'trailing slash' => ['media/', 'media'], + 'both slashes' => ['/media/', 'media'], + 'nested' => ['/uploads/images/', 'uploads/images'], + 'with spaces' => [' media ', 'media'], + ]); + + it('throws exception if prefix contains invalid sequences', function (string $invalidPrefix): void { + // GIVEN + $action = fn () => new StorageServiceConfig( + defaultDisk: 'local', + eligibleDisks: ['local'], + laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']], + allowedExtensions: ['pdf'], + prefix: $invalidPrefix + ); + + // THEN + expect($action)->toThrow(UnexpectedStorageException::class); + })->with([ + 'dot dot' => '../media', + 'nested dot dot' => 'media/../sub', + 'backslash' => 'media\\sub', + 'double slash' => 'media//sub', + ]); +}); diff --git a/tests/Unit/Lib/PathGenerators/DateHashPathGeneratorTest.php b/tests/Unit/Lib/PathGenerators/DateHashPathGeneratorTest.php index 1d240d5..09e681d 100644 --- a/tests/Unit/Lib/PathGenerators/DateHashPathGeneratorTest.php +++ b/tests/Unit/Lib/PathGenerators/DateHashPathGeneratorTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Uwil\Storage\Tests\Unit\Lib\PathGenerators; +use Uwil\Storage\Config\StorageServiceConfig; use Uwil\Storage\Lib\PathGenerators\DateHashPathGenerator; use Uwil\Storage\Lib\ValueObjects\DiskName; use Uwil\Storage\Lib\ValueObjects\FileStream; @@ -91,20 +92,26 @@ describe('DateHashPathGenerator generation without directory', function (): void }); }); -describe('DateHashPathGenerator generation with directory', function (): void { - it('prepends the given directory to the path', function (): void { +describe('DateHashPathGenerator generation with prefix', function (): void { + it('prepends the configured prefix to the path', function (): void { // GIVEN - $generator = new DateHashPathGenerator(); + $config = new StorageServiceConfig( + defaultDisk: 'local', + eligibleDisks: ['local'], + laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']], + allowedExtensions: ['png'], + prefix: 'avatars/users' + ); + $generator = new DateHashPathGenerator($config); $disk = new DiskName('local', 'local'); $sanitizedFile = new SanitizedFile( originalName: 'avatar.png', sanitizedName: 'avatar.png', contents: FileStream::fromString('image data') ); - $directory = 'avatars/users'; // WHEN - $result = $generator->generate($disk, $sanitizedFile, $directory); + $result = $generator->generate($disk, $sanitizedFile); // THEN $expectedHash = substr(hash('sha256', 'avatar.png'), 0, 2); @@ -117,49 +124,6 @@ describe('DateHashPathGenerator generation with directory', function (): void { ); expect($result->value)->toMatch($pattern); }); - - it('trims leading and trailing slashes from the directory', function (string $directory): void { - // GIVEN - $generator = new DateHashPathGenerator(); - $disk = new DiskName('local', 'local'); - $sanitizedFile = new SanitizedFile( - originalName: 'file.txt', - sanitizedName: 'file.txt', - contents: FileStream::fromString('txt') - ); - - // WHEN - $result = $generator->generate($disk, $sanitizedFile, $directory); - - // THEN - expect($result->value)->toStartWith('uploads/archive/'); - })->with([ - 'leading slash' => '/uploads/archive', - 'trailing slash' => 'uploads/archive/', - 'both slashes' => '/uploads/archive/', - 'multiple outer slashes' => '///uploads/archive///', - ]); - - it('ignores empty or slash-only directory', function (string $directory): void { - // GIVEN - $generator = new DateHashPathGenerator(); - $disk = new DiskName('local', 'local'); - $sanitizedFile = new SanitizedFile( - originalName: 'report.pdf', - sanitizedName: 'report.pdf', - contents: FileStream::fromString('pdf') - ); - - // WHEN - $result = $generator->generate($disk, $sanitizedFile, $directory); - - // THEN - expect($result->value)->toStartWith(gmdate('Y') . '/'); - })->with([ - 'empty string' => '', - 'single slash' => '/', - 'multi slashes' => '///', - ]); }); describe('DateHashPathGenerator filename slugging', function (): void { diff --git a/tests/Unit/Lib/PathGenerators/UuidPathGeneratorTest.php b/tests/Unit/Lib/PathGenerators/UuidPathGeneratorTest.php index ac57c0e..e03cacf 100644 --- a/tests/Unit/Lib/PathGenerators/UuidPathGeneratorTest.php +++ b/tests/Unit/Lib/PathGenerators/UuidPathGeneratorTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Uwil\Storage\Tests\Unit\Lib\PathGenerators; use Illuminate\Support\Str; +use Uwil\Storage\Config\StorageServiceConfig; use Uwil\Storage\Lib\PathGenerators\UuidPathGenerator; use Uwil\Storage\Lib\ValueObjects\DiskName; use Uwil\Storage\Lib\ValueObjects\FileStream; @@ -74,67 +75,30 @@ describe('UuidPathGenerator generation without directory', function (): void { }); }); -describe('UuidPathGenerator generation with directory', function (): void { - it('prepends the given directory to the generated UUID filename', function (): void { +describe('UuidPathGenerator generation with prefix', function (): void { + it('prepends the configured prefix to the generated UUID filename', function (): void { // GIVEN - $generator = new UuidPathGenerator(); + $config = new StorageServiceConfig( + defaultDisk: 'local', + eligibleDisks: ['local'], + laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']], + allowedExtensions: ['pdf'], + prefix: 'billing/invoices' + ); + $generator = new UuidPathGenerator($config); $disk = new DiskName('local', 'local'); $sanitizedFile = new SanitizedFile( originalName: 'invoice.pdf', sanitizedName: 'invoice.pdf', contents: FileStream::fromString('PDF DATA') ); - $directory = 'billing/invoices'; // WHEN - $result = $generator->generate($disk, $sanitizedFile, $directory); + $result = $generator->generate($disk, $sanitizedFile); // THEN expect($result)->toBeInstanceOf(StorageFilePath::class) ->and($result->value)->toStartWith('billing/invoices/') ->and($result->value)->toMatch('#^billing/invoices/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.pdf$#'); }); - - it('trims leading and trailing slashes from the directory', function (string $directory): void { - // GIVEN - $generator = new UuidPathGenerator(); - $disk = new DiskName('local', 'local'); - $sanitizedFile = new SanitizedFile( - originalName: 'file.txt', - sanitizedName: 'file.txt', - contents: FileStream::fromString('text') - ); - - // WHEN - $result = $generator->generate($disk, $sanitizedFile, $directory); - - // THEN - expect($result->value)->toStartWith('custom/path/'); - })->with([ - 'leading slash' => '/custom/path', - 'trailing slash' => 'custom/path/', - 'both slashes' => '/custom/path/', - 'multiple outer slashes' => '///custom/path///', - ]); - - it('ignores empty or slash-only directory', function (string $directory): void { - // GIVEN - $generator = new UuidPathGenerator(); - $disk = new DiskName('local', 'local'); - $sanitizedFile = new SanitizedFile( - originalName: 'file.txt', - sanitizedName: 'file.txt', - contents: FileStream::fromString('text') - ); - - // WHEN - $result = $generator->generate($disk, $sanitizedFile, $directory); - - // THEN - expect($result->value)->toMatch('#^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$#'); - })->with([ - 'empty string' => '', - 'single slash' => '/', - 'multi slashes' => '///', - ]); });