| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws\S3; |
| 4 |
|
| 5 |
use Dudlewebs\WPMCS\s3\Aws\CommandInterface; |
| 6 |
use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface; |
| 7 |
/** |
| 8 |
* Simplifies the SSE-C process by encoding and hashing the key. |
| 9 |
* @internal |
| 10 |
*/ |
| 11 |
class SSECMiddleware |
| 12 |
{ |
| 13 |
private $endpointScheme; |
| 14 |
private $nextHandler; |
| 15 |
/** |
| 16 |
* Provide the URI scheme of the client sending requests. |
| 17 |
* |
| 18 |
* @param string $endpointScheme URI scheme (http/https). |
| 19 |
* |
| 20 |
* @return callable |
| 21 |
*/ |
| 22 |
public static function wrap($endpointScheme) |
| 23 |
{ |
| 24 |
return function (callable $handler) use($endpointScheme) { |
| 25 |
return new self($endpointScheme, $handler); |
| 26 |
}; |
| 27 |
} |
| 28 |
public function __construct($endpointScheme, callable $nextHandler) |
| 29 |
{ |
| 30 |
$this->nextHandler = $nextHandler; |
| 31 |
$this->endpointScheme = $endpointScheme; |
| 32 |
} |
| 33 |
public function __invoke(CommandInterface $command, RequestInterface $request = null) |
| 34 |
{ |
| 35 |
// Allows only HTTPS connections when using SSE-C |
| 36 |
if (($command['SSECustomerKey'] || $command['CopySourceSSECustomerKey']) && $this->endpointScheme !== 'https') { |
| 37 |
throw new \RuntimeException('You must configure your S3 client to ' . 'use HTTPS in order to use the SSE-C features.'); |
| 38 |
} |
| 39 |
// Prepare the normal SSE-CPK headers |
| 40 |
if ($command['SSECustomerKey']) { |
| 41 |
$this->prepareSseParams($command); |
| 42 |
} |
| 43 |
// If it's a copy operation, prepare the SSE-CPK headers for the source. |
| 44 |
if ($command['CopySourceSSECustomerKey']) { |
| 45 |
$this->prepareSseParams($command, 'CopySource'); |
| 46 |
} |
| 47 |
$f = $this->nextHandler; |
| 48 |
return $f($command, $request); |
| 49 |
} |
| 50 |
private function prepareSseParams(CommandInterface $command, $prefix = '') |
| 51 |
{ |
| 52 |
// Base64 encode the provided key |
| 53 |
$key = $command[$prefix . 'SSECustomerKey']; |
| 54 |
$command[$prefix . 'SSECustomerKey'] = \base64_encode($key); |
| 55 |
// Base64 the provided MD5 or, generate an MD5 if not provided |
| 56 |
if ($md5 = $command[$prefix . 'SSECustomerKeyMD5']) { |
| 57 |
$command[$prefix . 'SSECustomerKeyMD5'] = \base64_encode($md5); |
| 58 |
} else { |
| 59 |
$command[$prefix . 'SSECustomerKeyMD5'] = \base64_encode(\md5($key, \true)); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|