| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Services\FileSystem\Drivers\S3; |
| 4 |
|
| 5 |
class S3InputValidator |
| 6 |
{ |
| 7 |
private const REGION_PATTERN = '/^(af|ap|ca|cn|eu|il|me|mx|sa|us)(-gov)?-[a-z0-9-]+-\d+$/'; |
| 8 |
|
| 9 |
public static function isValidBucket($bucket): bool |
| 10 |
{ |
| 11 |
if (!is_string($bucket)) { |
| 12 |
return false; |
| 13 |
} |
| 14 |
|
| 15 |
$bucket = trim($bucket); |
| 16 |
|
| 17 |
if ($bucket === '' || strlen($bucket) < 3 || strlen($bucket) > 63) { |
| 18 |
return false; |
| 19 |
} |
| 20 |
|
| 21 |
if (!preg_match('/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/', $bucket)) { |
| 22 |
return false; |
| 23 |
} |
| 24 |
|
| 25 |
if (strpos($bucket, '..') !== false || strpos($bucket, '.-') !== false || strpos($bucket, '-.') !== false) { |
| 26 |
return false; |
| 27 |
} |
| 28 |
|
| 29 |
if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $bucket)) { |
| 30 |
return false; |
| 31 |
} |
| 32 |
|
| 33 |
return true; |
| 34 |
} |
| 35 |
|
| 36 |
public static function isValidRegion($region): bool |
| 37 |
{ |
| 38 |
if (!is_string($region)) { |
| 39 |
return false; |
| 40 |
} |
| 41 |
|
| 42 |
$region = trim($region); |
| 43 |
|
| 44 |
if ($region === '' || strlen($region) > 32) { |
| 45 |
return false; |
| 46 |
} |
| 47 |
|
| 48 |
return (bool) preg_match(self::REGION_PATTERN, $region); |
| 49 |
} |
| 50 |
|
| 51 |
public static function validateBucket($bucket) |
| 52 |
{ |
| 53 |
if (self::isValidBucket($bucket)) { |
| 54 |
return true; |
| 55 |
} |
| 56 |
|
| 57 |
return new \WP_Error( |
| 58 |
'invalid_bucket', |
| 59 |
__('Invalid S3 bucket name.', 'fluent-cart') |
| 60 |
); |
| 61 |
} |
| 62 |
|
| 63 |
public static function validateRegion($region) |
| 64 |
{ |
| 65 |
if (self::isValidRegion($region)) { |
| 66 |
return true; |
| 67 |
} |
| 68 |
|
| 69 |
return new \WP_Error( |
| 70 |
'invalid_region', |
| 71 |
__('Invalid S3 region.', 'fluent-cart') |
| 72 |
); |
| 73 |
} |
| 74 |
|
| 75 |
public static function validateBucketAndRegion($bucket, $region) |
| 76 |
{ |
| 77 |
$bucketValidation = self::validateBucket($bucket); |
| 78 |
if (is_wp_error($bucketValidation)) { |
| 79 |
return $bucketValidation; |
| 80 |
} |
| 81 |
|
| 82 |
$regionValidation = self::validateRegion($region); |
| 83 |
if (is_wp_error($regionValidation)) { |
| 84 |
return $regionValidation; |
| 85 |
} |
| 86 |
|
| 87 |
return true; |
| 88 |
} |
| 89 |
} |
| 90 |
|