You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
253 lines
9.8 KiB
PHP
253 lines
9.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
/** Minimal AWS Signature Version 4 signer for S3 control requests. */
|
|
final class CloudS3Signer
|
|
{
|
|
private const EMPTY_PAYLOAD_HASH =
|
|
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
|
private const UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD';
|
|
|
|
/**
|
|
* Return the request headers required for an AWS Signature Version 4 call.
|
|
*
|
|
* @param array<string,string> $metadata S3 user metadata without the
|
|
* x-amz-meta- prefix. Every entry is included in SignedHeaders.
|
|
* @return array<string, string>
|
|
*/
|
|
public static function sign(
|
|
string $method,
|
|
string $url,
|
|
string $region,
|
|
string $accessKeyId,
|
|
string $secretAccessKey,
|
|
int $timestamp,
|
|
?string $payloadHash = null,
|
|
array $metadata = []
|
|
): array {
|
|
$parts = parse_url($url);
|
|
if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])) {
|
|
throw new \InvalidArgumentException('Invalid S3 request URL');
|
|
}
|
|
|
|
$method = strtoupper($method);
|
|
$payloadHash = $payloadHash ?? self::EMPTY_PAYLOAD_HASH;
|
|
if (preg_match('/^[a-f0-9]{64}$/D', $payloadHash) !== 1) {
|
|
throw new \InvalidArgumentException('Invalid S3 payload hash');
|
|
}
|
|
|
|
$amzDate = gmdate('Ymd\THis\Z', $timestamp);
|
|
$date = gmdate('Ymd', $timestamp);
|
|
$host = self::hostHeader($parts);
|
|
$headers = [
|
|
'host' => $host,
|
|
'x-amz-content-sha256' => $payloadHash,
|
|
'x-amz-date' => $amzDate,
|
|
];
|
|
foreach ($metadata as $name => $value) {
|
|
if (!is_string($name) || !is_string($value)) {
|
|
throw new \InvalidArgumentException('Invalid S3 metadata');
|
|
}
|
|
$name = strtolower(trim($name));
|
|
if (preg_match('/^[a-z0-9][a-z0-9-]{0,63}$/D', $name) !== 1
|
|
|| $value === '' || strlen($value) > 2048
|
|
|| preg_match('/[\x00-\x1f\x7f]/', $value) === 1) {
|
|
throw new \InvalidArgumentException('Invalid S3 metadata');
|
|
}
|
|
$header = 'x-amz-meta-' . $name;
|
|
if (isset($headers[$header])) {
|
|
throw new \InvalidArgumentException('Duplicate S3 metadata');
|
|
}
|
|
$headers[$header] = trim($value);
|
|
}
|
|
ksort($headers, SORT_STRING);
|
|
$canonicalHeaders = '';
|
|
foreach ($headers as $name => $value) {
|
|
$canonicalHeaders .= $name . ':' . $value . "\n";
|
|
}
|
|
$signedHeaders = implode(';', array_keys($headers));
|
|
$canonicalRequest = $method . "\n"
|
|
. self::canonicalUri((string) ($parts['path'] ?? '/')) . "\n"
|
|
. self::canonicalQuery((string) ($parts['query'] ?? '')) . "\n"
|
|
. $canonicalHeaders . "\n"
|
|
. $signedHeaders . "\n"
|
|
. $payloadHash;
|
|
$scope = $date . '/' . $region . '/s3/aws4_request';
|
|
$stringToSign = "AWS4-HMAC-SHA256\n" . $amzDate . "\n"
|
|
. $scope . "\n" . hash('sha256', $canonicalRequest);
|
|
$dateKey = hash_hmac('sha256', $date, 'AWS4' . $secretAccessKey, true);
|
|
$regionKey = hash_hmac('sha256', $region, $dateKey, true);
|
|
$serviceKey = hash_hmac('sha256', 's3', $regionKey, true);
|
|
$signingKey = hash_hmac('sha256', 'aws4_request', $serviceKey, true);
|
|
$signature = hash_hmac('sha256', $stringToSign, $signingKey);
|
|
|
|
$result = [
|
|
'Host' => $host,
|
|
'X-Amz-Content-Sha256' => $payloadHash,
|
|
'X-Amz-Date' => $amzDate,
|
|
'Authorization' => 'AWS4-HMAC-SHA256 Credential=' . $accessKeyId
|
|
. '/' . $scope . ',SignedHeaders=' . $signedHeaders
|
|
. ',Signature=' . $signature,
|
|
];
|
|
foreach ($metadata as $name => $value) {
|
|
$result['x-amz-meta-' . strtolower(trim((string) $name))] =
|
|
trim((string) $value);
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Create a query-authenticated S3 capability URL.
|
|
*
|
|
* Only the host header is signed. Callers must not add another Host value
|
|
* or follow redirects, and must treat the returned URL as a secret until
|
|
* it expires. S3 verifies the request payload as UNSIGNED-PAYLOAD, which
|
|
* is required for streaming UploadPart and CompleteMultipartUpload calls.
|
|
*/
|
|
public static function presign(
|
|
string $method,
|
|
string $url,
|
|
string $region,
|
|
string $accessKeyId,
|
|
string $secretAccessKey,
|
|
int $timestamp,
|
|
int $expiresSeconds
|
|
): string {
|
|
if ($expiresSeconds < 1 || $expiresSeconds > 604800) {
|
|
throw new \InvalidArgumentException(
|
|
'S3 presigned URL lifetime must be between 1 and 604800 seconds'
|
|
);
|
|
}
|
|
$parts = parse_url($url);
|
|
if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])
|
|
|| isset($parts['user']) || isset($parts['pass'])
|
|
|| isset($parts['fragment'])) {
|
|
throw new \InvalidArgumentException('Invalid S3 request URL');
|
|
}
|
|
$method = strtoupper($method);
|
|
if (!in_array($method, ['GET', 'PUT', 'POST', 'DELETE', 'HEAD'], true)) {
|
|
throw new \InvalidArgumentException('Invalid S3 presigned method');
|
|
}
|
|
$amzDate = gmdate('Ymd\THis\Z', $timestamp);
|
|
$date = gmdate('Ymd', $timestamp);
|
|
$scope = $date . '/' . $region . '/s3/aws4_request';
|
|
$query = self::queryPairs((string) ($parts['query'] ?? ''));
|
|
foreach ($query as $pair) {
|
|
if (str_starts_with(strtolower(rawurldecode($pair[0])), 'x-amz-')) {
|
|
throw new \InvalidArgumentException(
|
|
'S3 request URL already contains authentication parameters'
|
|
);
|
|
}
|
|
}
|
|
$query[] = ['X-Amz-Algorithm', 'AWS4-HMAC-SHA256'];
|
|
$query[] = ['X-Amz-Credential', $accessKeyId . '/' . $scope];
|
|
$query[] = ['X-Amz-Date', $amzDate];
|
|
$query[] = ['X-Amz-Expires', (string) $expiresSeconds];
|
|
$query[] = ['X-Amz-SignedHeaders', 'host'];
|
|
$canonicalQuery = self::canonicalPairs($query);
|
|
$host = self::hostHeader($parts);
|
|
$canonicalRequest = $method . "\n"
|
|
. self::canonicalUri((string) ($parts['path'] ?? '/')) . "\n"
|
|
. $canonicalQuery . "\n"
|
|
. 'host:' . $host . "\n\n"
|
|
. "host\n"
|
|
. self::UNSIGNED_PAYLOAD;
|
|
$stringToSign = "AWS4-HMAC-SHA256\n" . $amzDate . "\n"
|
|
. $scope . "\n" . hash('sha256', $canonicalRequest);
|
|
$signature = hash_hmac(
|
|
'sha256',
|
|
$stringToSign,
|
|
self::signingKey($secretAccessKey, $date, $region)
|
|
);
|
|
$query[] = ['X-Amz-Signature', $signature];
|
|
return self::urlWithoutQuery($parts) . '?' . self::canonicalPairs($query);
|
|
}
|
|
|
|
/** @param array<string, mixed> $parts */
|
|
private static function hostHeader(array $parts): string
|
|
{
|
|
$host = strtolower(trim((string) $parts['host'], '[]'));
|
|
if (str_contains($host, ':')) {
|
|
$host = '[' . $host . ']';
|
|
}
|
|
$port = isset($parts['port']) ? (int) $parts['port'] : null;
|
|
$scheme = strtolower((string) $parts['scheme']);
|
|
if ($port !== null && !(($scheme === 'https' && $port === 443)
|
|
|| ($scheme === 'http' && $port === 80))) {
|
|
$host .= ':' . $port;
|
|
}
|
|
return $host;
|
|
}
|
|
|
|
private static function canonicalUri(string $path): string
|
|
{
|
|
if ($path === '') {
|
|
return '/';
|
|
}
|
|
return implode('/', array_map(
|
|
static fn (string $segment): string => rawurlencode(rawurldecode($segment)),
|
|
explode('/', str_starts_with($path, '/') ? $path : '/' . $path)
|
|
));
|
|
}
|
|
|
|
private static function canonicalQuery(string $query): string
|
|
{
|
|
return self::canonicalPairs(self::queryPairs($query));
|
|
}
|
|
|
|
/** @return list<array{0:string,1:string}> */
|
|
private static function queryPairs(string $query): array
|
|
{
|
|
if ($query === '') {
|
|
return [];
|
|
}
|
|
$pairs = [];
|
|
foreach (explode('&', $query) as $part) {
|
|
[$name, $value] = array_pad(explode('=', $part, 2), 2, '');
|
|
$pairs[] = [rawurldecode($name), rawurldecode($value)];
|
|
}
|
|
return $pairs;
|
|
}
|
|
|
|
/** @param list<array{0:string,1:string}> $pairs */
|
|
private static function canonicalPairs(array $pairs): string
|
|
{
|
|
$pairs = array_map(static fn (array $pair): array => [
|
|
rawurlencode($pair[0]), rawurlencode($pair[1]),
|
|
], $pairs);
|
|
usort($pairs, static fn (array $left, array $right): int =>
|
|
$left[0] <=> $right[0] ?: $left[1] <=> $right[1]);
|
|
return implode('&', array_map(
|
|
static fn (array $pair): string => $pair[0] . '=' . $pair[1],
|
|
$pairs
|
|
));
|
|
}
|
|
|
|
private static function signingKey(
|
|
string $secretAccessKey,
|
|
string $date,
|
|
string $region
|
|
): string {
|
|
$dateKey = hash_hmac('sha256', $date, 'AWS4' . $secretAccessKey, true);
|
|
$regionKey = hash_hmac('sha256', $region, $dateKey, true);
|
|
$serviceKey = hash_hmac('sha256', 's3', $regionKey, true);
|
|
return hash_hmac('sha256', 'aws4_request', $serviceKey, true);
|
|
}
|
|
|
|
/** @param array<string,mixed> $parts */
|
|
private static function urlWithoutQuery(array $parts): string
|
|
{
|
|
$host = (string) $parts['host'];
|
|
if (str_contains($host, ':') && !str_starts_with($host, '[')) {
|
|
$host = '[' . $host . ']';
|
|
}
|
|
$authority = strtolower((string) $parts['scheme']) . '://'
|
|
. strtolower($host);
|
|
if (isset($parts['port'])) {
|
|
$authority .= ':' . (int) $parts['port'];
|
|
}
|
|
return $authority . (string) ($parts['path'] ?? '/');
|
|
}
|
|
}
|