| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316 |
- <?php
- /**
- * Minimal S3 client for Hetzner Object Storage (or any S3-compatible store).
- * Implements AWS Signature v4 in plain PHP — no SDK, no Composer.
- *
- * - Presigned GET → visitors load gallery images directly from S3
- * - Signed PUT → the webhost streams uploaded originals/thumbs to S3
- * - Signed DELETE → server-side cleanup when images/galleries are removed
- *
- * Addressing style is configurable via s3.path_style:
- * path-style (default) → https://<endpoint-host>/<bucket>/<key>
- * virtual-hosted-style → https://<bucket>.<endpoint-host>/<key>
- * Hetzner Object Storage serves path-style reliably; virtual-hosted-style
- * requires the bucket to resolve as a TLS subdomain of the endpoint.
- */
- declare(strict_types=1);
- /** Percent-encode an object key, keeping the "/" separators. */
- function s3_encode_key(string $key): string
- {
- return implode('/', array_map('rawurlencode', explode('/', $key)));
- }
- /** Bare host of the configured endpoint, e.g. "fsn1.your-objectstorage.com". */
- function s3_endpoint_host(): string
- {
- return (string)parse_url(config('s3.endpoint'), PHP_URL_HOST);
- }
- /** ":port" suffix when the endpoint pins a non-default port, else "". */
- function s3_endpoint_port_suffix(): string
- {
- $port = parse_url(config('s3.endpoint'), PHP_URL_PORT);
- return $port ? ':' . $port : '';
- }
- /** Whether to address the bucket in the path (true) or as a subdomain (false). */
- function s3_use_path_style(): bool
- {
- return (bool)config('s3.path_style', true);
- }
- /**
- * Request host. Path-style keeps the bare endpoint host; virtual-hosted-style
- * prepends the bucket as a DNS label (never percent-encoded).
- */
- function s3_host(): string
- {
- $host = s3_endpoint_host();
- $host = s3_use_path_style() ? $host : config('s3.bucket') . '.' . $host;
- // The signed Host header and the request host must match, port included.
- return $host . s3_endpoint_port_suffix();
- }
- /** Base URL for object requests: scheme + host, no trailing slash. */
- function s3_base_url(): string
- {
- $scheme = parse_url(config('s3.endpoint'), PHP_URL_SCHEME) ?: 'https';
- return $scheme . '://' . s3_host();
- }
- /**
- * Canonical (and actual) request path for a key. Path-style prefixes the
- * bucket as the first, percent-encoded path segment; virtual-hosted-style
- * does not, because the bucket lives in the host instead.
- */
- function s3_canonical_uri(string $key): string
- {
- $path = '/' . s3_encode_key($key);
- return s3_use_path_style() ? '/' . rawurlencode(config('s3.bucket')) . $path : $path;
- }
- /**
- * Key prefix under which one gallery's objects live: "<prefix>/<slug>".
- * The prefix is configurable via s3.prefix (default "galleries"); an empty
- * prefix puts galleries at the bucket root.
- */
- function s3_gallery_prefix(string $slug): string
- {
- $prefix = trim((string)config('s3.prefix', 'galleries'), '/');
- return $prefix !== '' ? "$prefix/$slug" : $slug;
- }
- /** HMAC-SHA256 chain producing the SigV4 signing key. */
- function s3_signing_key(string $date): string
- {
- $k = hash_hmac('sha256', $date, 'AWS4' . config('s3.secret_key'), true);
- $k = hash_hmac('sha256', config('s3.region'), $k, true);
- $k = hash_hmac('sha256', 's3', $k, true);
- return hash_hmac('sha256', 'aws4_request', $k, true);
- }
- /**
- * SigV4 query-string signing core. Separated from s3_presign() so the
- * algorithm can be verified against the official AWS example vectors.
- * Returns the full query string including X-Amz-Signature.
- */
- function s3_presign_query(
- string $method,
- string $host,
- string $canonicalUri,
- string $accessKey,
- string $secretKey,
- string $region,
- int $ttl,
- string $amzDate
- ): string {
- $date = substr($amzDate, 0, 8);
- $scope = $date . '/' . $region . '/s3/aws4_request';
- $query = [
- 'X-Amz-Algorithm' => 'AWS4-HMAC-SHA256',
- 'X-Amz-Credential' => $accessKey . '/' . $scope,
- 'X-Amz-Date' => $amzDate,
- 'X-Amz-Expires' => (string)$ttl,
- 'X-Amz-SignedHeaders' => 'host',
- ];
- ksort($query);
- $canonicalQuery = implode('&', array_map(
- fn($k, $v) => rawurlencode($k) . '=' . rawurlencode($v),
- array_keys($query),
- $query
- ));
- $canonicalRequest = implode("\n", [
- strtoupper($method),
- $canonicalUri,
- $canonicalQuery,
- 'host:' . $host,
- '',
- 'host',
- 'UNSIGNED-PAYLOAD',
- ]);
- $stringToSign = implode("\n", [
- 'AWS4-HMAC-SHA256',
- $amzDate,
- $scope,
- hash('sha256', $canonicalRequest),
- ]);
- $k = hash_hmac('sha256', $date, 'AWS4' . $secretKey, true);
- $k = hash_hmac('sha256', $region, $k, true);
- $k = hash_hmac('sha256', 's3', $k, true);
- $k = hash_hmac('sha256', 'aws4_request', $k, true);
- $signature = hash_hmac('sha256', $stringToSign, $k);
- return $canonicalQuery . '&X-Amz-Signature=' . $signature;
- }
- /**
- * Build a presigned URL for an object key. Only the Host header is signed.
- * Used for GET so visitors' browsers can load private images directly; uploads
- * go through the webhost (s3_put_file), never a presigned PUT.
- */
- function s3_presign(string $method, string $key, ?int $ttl = null): string
- {
- $ttl ??= (int)config('s3.url_ttl', 3600);
- $canonicalUri = s3_canonical_uri($key);
- $query = s3_presign_query(
- $method,
- s3_host(),
- $canonicalUri,
- config('s3.access_key'),
- config('s3.secret_key'),
- config('s3.region'),
- $ttl,
- gmdate('Ymd\THis\Z')
- );
- return s3_base_url() . $canonicalUri . '?' . $query;
- }
- function s3_presign_get(string $key, ?int $ttl = null): string
- {
- return s3_presign('GET', $key, $ttl);
- }
- /**
- * Stream a local file to S3 with a signed PUT (header auth). The payload is sent
- * as UNSIGNED-PAYLOAD so the body is never hashed or buffered into memory — curl
- * streams it straight from the file handle, letting the webhost proxy originals
- * far larger than memory_limit. Content-Type is sent but not signed.
- * Returns [httpStatus, responseBody].
- */
- function s3_put_file(string $key, string $filePath, string $contentType = 'application/octet-stream'): array
- {
- $host = s3_host();
- $amzDate = gmdate('Ymd\THis\Z');
- $date = substr($amzDate, 0, 8);
- $scope = $date . '/' . config('s3.region') . '/s3/aws4_request';
- $canonicalUri = s3_canonical_uri($key);
- $payloadHash = 'UNSIGNED-PAYLOAD';
- $canonicalRequest = implode("\n", [
- 'PUT',
- $canonicalUri,
- '',
- 'host:' . $host,
- 'x-amz-content-sha256:' . $payloadHash,
- 'x-amz-date:' . $amzDate,
- '',
- 'host;x-amz-content-sha256;x-amz-date',
- $payloadHash,
- ]);
- $stringToSign = implode("\n", [
- 'AWS4-HMAC-SHA256',
- $amzDate,
- $scope,
- hash('sha256', $canonicalRequest),
- ]);
- $signature = hash_hmac('sha256', $stringToSign, s3_signing_key($date));
- $authorization = 'AWS4-HMAC-SHA256 Credential=' . config('s3.access_key') . '/' . $scope
- . ', SignedHeaders=host;x-amz-content-sha256;x-amz-date'
- . ', Signature=' . $signature;
- $fh = fopen($filePath, 'rb');
- if ($fh === false) {
- return [0, 'Cannot open upload for reading'];
- }
- $ch = curl_init(s3_base_url() . $canonicalUri);
- curl_setopt_array($ch, [
- CURLOPT_UPLOAD => true, // sets method to PUT and streams CURLOPT_INFILE
- CURLOPT_INFILE => $fh,
- CURLOPT_INFILESIZE => filesize($filePath),
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_CONNECTTIMEOUT => 30,
- CURLOPT_TIMEOUT => 0, // no cap: originals can be large
- CURLOPT_HTTPHEADER => [
- 'Authorization: ' . $authorization,
- 'x-amz-content-sha256: ' . $payloadHash,
- 'x-amz-date: ' . $amzDate,
- 'Content-Type: ' . $contentType,
- 'Expect:', // skip 100-continue round-trip
- ],
- ]);
- $body = curl_exec($ch);
- $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
- fclose($fh);
- return [$status, (string)$body];
- }
- /**
- * Server-side signed request (header auth). Used for DELETE.
- * Returns [httpStatus, responseBody].
- */
- function s3_request(string $method, string $key): array
- {
- $host = s3_host();
- $amzDate = gmdate('Ymd\THis\Z');
- $date = substr($amzDate, 0, 8);
- $scope = $date . '/' . config('s3.region') . '/s3/aws4_request';
- $canonicalUri = s3_canonical_uri($key);
- $payloadHash = hash('sha256', '');
- $canonicalRequest = implode("\n", [
- strtoupper($method),
- $canonicalUri,
- '', // no query string
- 'host:' . $host,
- 'x-amz-content-sha256:' . $payloadHash,
- 'x-amz-date:' . $amzDate,
- '',
- 'host;x-amz-content-sha256;x-amz-date',
- $payloadHash,
- ]);
- $stringToSign = implode("\n", [
- 'AWS4-HMAC-SHA256',
- $amzDate,
- $scope,
- hash('sha256', $canonicalRequest),
- ]);
- $signature = hash_hmac('sha256', $stringToSign, s3_signing_key($date));
- $authorization = 'AWS4-HMAC-SHA256 Credential=' . config('s3.access_key') . '/' . $scope
- . ', SignedHeaders=host;x-amz-content-sha256;x-amz-date'
- . ', Signature=' . $signature;
- $ch = curl_init(s3_base_url() . $canonicalUri);
- curl_setopt_array($ch, [
- CURLOPT_CUSTOMREQUEST => strtoupper($method),
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_TIMEOUT => 30,
- CURLOPT_HTTPHEADER => [
- 'Authorization: ' . $authorization,
- 'x-amz-content-sha256: ' . $payloadHash,
- 'x-amz-date: ' . $amzDate,
- ],
- ]);
- $body = curl_exec($ch);
- $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
- return [$status, (string)$body];
- }
- /** Delete one object. S3 returns 204 for success and for already-gone keys. */
- function s3_delete(string $key): bool
- {
- [$status] = s3_request('DELETE', $key);
- return $status === 204 || $status === 200 || $status === 404;
- }
- /** Delete every S3 object referenced by a gallery (originals + thumbs). */
- function s3_delete_gallery_objects(array $gallery): void
- {
- foreach ($gallery['images'] ?? [] as $img) {
- if (!empty($img['key'])) {
- s3_delete($img['key']);
- }
- if (!empty($img['thumb'])) {
- s3_delete($img['thumb']);
- }
- }
- }
|