feat(web): add S3 object storage configuration
parent
1a5362511d
commit
d7d3c621c9
@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Admin;
|
||||
|
||||
use App\Controllers\AdminController;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudInput;
|
||||
use App\Services\Cloud\CloudObjectStorageConfig;
|
||||
|
||||
final class ObjectStorageController extends AdminController
|
||||
{
|
||||
public function index($request, $response, $args)
|
||||
{
|
||||
$state = null;
|
||||
$error = '';
|
||||
$status = 200;
|
||||
try {
|
||||
$state = CloudObjectStorageConfig::view();
|
||||
} catch (CloudError $exception) {
|
||||
$error = $exception->getMessage();
|
||||
$status = $exception->httpStatus;
|
||||
} catch (\Throwable $exception) {
|
||||
error_log('Object storage settings read failed: ' . get_class($exception));
|
||||
$error = '对象存储配置暂时无法读取,请检查数据库状态。';
|
||||
$status = 503;
|
||||
}
|
||||
|
||||
$smarty = $this->view()->assign([
|
||||
'object_storage' => $state,
|
||||
'object_storage_error' => $error,
|
||||
]);
|
||||
$response->getBody()->write($smarty->fetch('admin/object_storage.tpl'));
|
||||
return $response->withStatus($status)
|
||||
->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function save($request, $response, $args)
|
||||
{
|
||||
try {
|
||||
$state = CloudObjectStorageConfig::save(CloudInput::object($request));
|
||||
return $this->json($response, 1, '对象存储配置已保存,请执行连接验证。', 200, $state);
|
||||
} catch (CloudError $exception) {
|
||||
return $this->json($response, 0, $exception->getMessage(), $exception->httpStatus);
|
||||
} catch (\Throwable $exception) {
|
||||
error_log('Object storage settings save failed: ' . get_class($exception));
|
||||
return $this->json($response, 0, '对象存储配置保存失败,请稍后重试。', 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function test($request, $response, $args)
|
||||
{
|
||||
try {
|
||||
$input = CloudInput::object($request);
|
||||
CloudInput::only($input, ['expected_revision']);
|
||||
$state = CloudObjectStorageConfig::testAndEnable(
|
||||
$input['expected_revision'] ?? null
|
||||
);
|
||||
return $this->json($response, 1, '连接验证成功,对象存储已启用。', 200, $state);
|
||||
} catch (CloudError $exception) {
|
||||
return $this->json($response, 0, $exception->getMessage(), $exception->httpStatus);
|
||||
} catch (\Throwable $exception) {
|
||||
error_log('Object storage connection test failed: ' . get_class($exception));
|
||||
return $this->json($response, 0, '连接验证失败,请稍后重试。', 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function disable($request, $response, $args)
|
||||
{
|
||||
try {
|
||||
$input = CloudInput::object($request);
|
||||
CloudInput::only($input, ['expected_revision']);
|
||||
$state = CloudObjectStorageConfig::disable(
|
||||
$input['expected_revision'] ?? null
|
||||
);
|
||||
return $this->json($response, 1, '对象存储已停用,已保存的凭据仍保持加密。', 200, $state);
|
||||
} catch (CloudError $exception) {
|
||||
return $this->json($response, 0, $exception->getMessage(), $exception->httpStatus);
|
||||
} catch (\Throwable $exception) {
|
||||
error_log('Object storage disable failed: ' . get_class($exception));
|
||||
return $this->json($response, 0, '对象存储停用失败,请稍后重试。', 500);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, mixed>|null $state */
|
||||
private function json($response, int $ret, string $message, int $status, ?array $state = null)
|
||||
{
|
||||
$payload = ['ret' => $ret, 'msg' => $message];
|
||||
if ($state !== null) {
|
||||
$payload['object_storage'] = $state;
|
||||
}
|
||||
return $response->withJson($payload, $status)
|
||||
->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** Stable, non-secret error returned by an S3 connectivity check. */
|
||||
final class CloudObjectStorageTestError extends \RuntimeException
|
||||
{
|
||||
public function __construct(
|
||||
string $message,
|
||||
public readonly string $publicCode
|
||||
) {
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** Minimal AWS Signature Version 4 signer for S3 control requests. */
|
||||
final class CloudS3Signer
|
||||
{
|
||||
private const EMPTY_PAYLOAD_HASH =
|
||||
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
||||
|
||||
/**
|
||||
* Return the request headers required for an AWS Signature Version 4 call.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function sign(
|
||||
string $method,
|
||||
string $url,
|
||||
string $region,
|
||||
string $accessKeyId,
|
||||
string $secretAccessKey,
|
||||
int $timestamp,
|
||||
?string $payloadHash = null
|
||||
): 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);
|
||||
$canonicalHeaders = 'host:' . $host . "\n"
|
||||
. 'x-amz-content-sha256:' . $payloadHash . "\n"
|
||||
. 'x-amz-date:' . $amzDate . "\n";
|
||||
$signedHeaders = 'host;x-amz-content-sha256;x-amz-date';
|
||||
$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);
|
||||
|
||||
return [
|
||||
'Host' => $host,
|
||||
'X-Amz-Content-Sha256' => $payloadHash,
|
||||
'X-Amz-Date' => $amzDate,
|
||||
'Authorization' => 'AWS4-HMAC-SHA256 Credential=' . $accessKeyId
|
||||
. '/' . $scope . ',SignedHeaders=' . $signedHeaders
|
||||
. ',Signature=' . $signature,
|
||||
];
|
||||
}
|
||||
|
||||
/** @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
|
||||
{
|
||||
if ($query === '') {
|
||||
return '';
|
||||
}
|
||||
$pairs = [];
|
||||
foreach (explode('&', $query) as $part) {
|
||||
[$name, $value] = array_pad(explode('=', $part, 2), 2, '');
|
||||
$pairs[] = [rawurlencode(rawurldecode($name)), rawurlencode(rawurldecode($value))];
|
||||
}
|
||||
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
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$contents = file_get_contents($root . '/' . $path);
|
||||
if ($contents === false) {
|
||||
throw new RuntimeException('Unable to read ' . $path);
|
||||
}
|
||||
return $contents;
|
||||
};
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$routes = $read('config/routes.php');
|
||||
$controller = $read('app/Controllers/Admin/ObjectStorageController.php');
|
||||
$service = $read('app/Services/Cloud/CloudObjectStorageConfig.php');
|
||||
$client = $read('app/Services/Cloud/CloudObjectStorageS3Client.php');
|
||||
$template = $read('resources/views/venix/admin/object_storage.tpl');
|
||||
$sidebar = $read('resources/views/venix/admin/static_header.tpl');
|
||||
$deployment = file_get_contents(dirname($root) . '/docs/DEPLOYMENT.md');
|
||||
$validation = file_get_contents(dirname($root) . '/docs/VALIDATION.md');
|
||||
|
||||
$assert(str_contains($routes,
|
||||
"get('/object-storage', 'App\\Controllers\\Admin\\ObjectStorageController:index')"),
|
||||
'Object-storage admin page route is missing.');
|
||||
foreach (['config' => 'save', 'test' => 'test', 'disable' => 'disable'] as $path => $action) {
|
||||
$needle = "post('/object-storage/{$path}', 'App\\Controllers\\Admin\\ObjectStorageController:{$action}')->add(new SuperAdmin())";
|
||||
$assert(str_contains($routes, $needle),
|
||||
'Object-storage mutation lost SuperAdmin/CSRF middleware: ' . $action);
|
||||
}
|
||||
$assert(str_contains($sidebar, 'href="/admin/object-storage"')
|
||||
&& str_contains($sidebar, '<span>对象存储</span>'),
|
||||
'Object-storage navigation entry is missing.');
|
||||
$assert(str_contains($service, "CloudSecrets::encrypt([")
|
||||
&& str_contains($service, "'object-storage-credentials'")
|
||||
&& str_contains($service, "lockForUpdate()")
|
||||
&& str_contains($service, "tested_revision")
|
||||
&& str_contains($service, "expected_revision"),
|
||||
'Object-storage encryption, revision, or readiness gate is missing.');
|
||||
$assert(str_contains($client, "request('HEAD'")
|
||||
&& str_contains($client, "'allow_redirects' => false")
|
||||
&& str_contains($client, "'verify' => true")
|
||||
&& str_contains($client, "'proxy' => ''")
|
||||
&& !str_contains($client, "request('PUT'")
|
||||
&& !str_contains($client, "request('DELETE'"),
|
||||
'Connectivity test is no longer a bounded, read-only, TLS-strict HeadBucket call.');
|
||||
$assert(substr_count($template, 'name="access_key_id" type="password" value=""') === 1
|
||||
&& substr_count($template, 'name="secret_access_key" type="password" value=""') === 1
|
||||
&& !str_contains($template, '$object_storage.access_key_id')
|
||||
&& !str_contains($template, '$object_storage.secret_access_key')
|
||||
&& str_contains($template, 'data-can-manage=')
|
||||
&& str_contains($template, 's3:ListBucket'),
|
||||
'Admin UI can expose credentials or lost its permission/test boundary.');
|
||||
$assert(str_contains($controller, "'Cache-Control', 'private, no-store'")
|
||||
&& preg_match('/error_log\\([^\\n]*getMessage/', $controller) !== 1,
|
||||
'Object-storage responses lost no-store or may log raw exception messages.');
|
||||
$assert(is_string($deployment) && str_contains($deployment, '### 对象存储应用')
|
||||
&& str_contains($deployment, '尚未接入云备份上传')
|
||||
&& is_string($validation) && str_contains($validation, '对象存储配置页面不得回显'),
|
||||
'Deployment or validation boundaries are not documented.');
|
||||
|
||||
echo "Object-storage admin routes, UI, security, and documentation contract passed.\n";
|
||||
@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services {
|
||||
final class Config
|
||||
{
|
||||
public static string $dataKey = '';
|
||||
|
||||
public static function get($name, $default = null)
|
||||
{
|
||||
return $name === 'cloud_data_key' ? self::$dataKey : $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\Configurations;
|
||||
use App\Services\Config;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudObjectStorageConfig;
|
||||
use App\Services\Cloud\CloudObjectStorageS3Client;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
if (!function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
|
||||
echo "SKIPPED CloudObjectStorageConfigTest: runtime lacks sodium.\n";
|
||||
exit(0);
|
||||
}
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$expectCloudError = static function (callable $callback, int $status) use ($assert): CloudError {
|
||||
try {
|
||||
$callback();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status,
|
||||
'Unexpected object-storage error status: ' . $error->httpStatus);
|
||||
return $error;
|
||||
}
|
||||
throw new RuntimeException('Expected object-storage error was not raised.');
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:']);
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$capsule->schema()->create('configurations', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('name')->unique();
|
||||
$table->text('value')->nullable();
|
||||
});
|
||||
Config::$dataKey = base64_encode(str_repeat('o', 32));
|
||||
|
||||
$payload = [
|
||||
'name' => '测试对象存储',
|
||||
'endpoint' => 'https://minio.internal:9000',
|
||||
'region' => 'us-east-1',
|
||||
'bucket' => 'test-bucket',
|
||||
'prefix' => 'virt-cloud/backups',
|
||||
'path_style' => 'true',
|
||||
'access_key_id' => 'TESTACCESSKEY',
|
||||
'secret_access_key' => 'test-secret-key-value',
|
||||
'expected_revision' => 0,
|
||||
];
|
||||
$saved = CloudObjectStorageConfig::save($payload);
|
||||
$databaseValues = Configurations::pluck('value')->map(
|
||||
static fn ($value): string => (string) $value
|
||||
)->implode("\n");
|
||||
$publicJson = json_encode($saved, JSON_THROW_ON_ERROR);
|
||||
$assert($saved['revision'] === 1 && !$saved['enabled'] && !$saved['ready']
|
||||
&& $saved['credentials_configured']
|
||||
&& !str_contains($databaseValues, 'TESTACCESSKEY')
|
||||
&& !str_contains($databaseValues, 'test-secret-key-value')
|
||||
&& !str_contains($publicJson, 'TESTACCESSKEY')
|
||||
&& !str_contains($publicJson, 'test-secret-key-value')
|
||||
&& !array_key_exists('sealed_credentials', $saved)
|
||||
&& !array_key_exists('access_key_id', $saved)
|
||||
&& !array_key_exists('secret_access_key', $saved),
|
||||
'Object-storage save did not seal credentials or leaked them in its DTO.');
|
||||
|
||||
$healthyClient = new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create(new MockHandler([new Response(200)])),
|
||||
]));
|
||||
$ready = CloudObjectStorageConfig::testAndEnable(1, $healthyClient);
|
||||
$assert($ready['enabled'] && $ready['ready']
|
||||
&& $ready['tested_revision'] === 1
|
||||
&& $ready['last_test_status'] === 'healthy',
|
||||
'Successful current-revision connectivity test did not enable storage.');
|
||||
|
||||
$changed = $payload;
|
||||
$changed['bucket'] = 'second-bucket';
|
||||
$changed['access_key_id'] = '';
|
||||
$changed['secret_access_key'] = '';
|
||||
$changed['expected_revision'] = '1';
|
||||
$changedState = CloudObjectStorageConfig::save($changed);
|
||||
$assert($changedState['revision'] === 2 && !$changedState['enabled']
|
||||
&& !$changedState['ready'] && $changedState['last_test_status'] === 'never'
|
||||
&& $changedState['credentials_configured'],
|
||||
'Configuration change did not preserve sealed credentials and invalidate readiness.');
|
||||
|
||||
$expectCloudError(static function () use ($changed): void {
|
||||
$changed['expected_revision'] = '1';
|
||||
CloudObjectStorageConfig::save($changed);
|
||||
}, 409);
|
||||
$expectCloudError(static function () use ($changed): void {
|
||||
$changed['endpoint'] = 'http://127.0.0.1:9000';
|
||||
$changed['expected_revision'] = '2';
|
||||
CloudObjectStorageConfig::save($changed);
|
||||
}, 422);
|
||||
|
||||
$deniedClient = new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create(new MockHandler([new Response(403)])),
|
||||
]));
|
||||
$denied = $expectCloudError(static function () use ($deniedClient): void {
|
||||
CloudObjectStorageConfig::testAndEnable(2, $deniedClient);
|
||||
}, 502);
|
||||
$failed = CloudObjectStorageConfig::view();
|
||||
$assert($failed['last_test_status'] === 'failed'
|
||||
&& $failed['last_error_code'] === 'auth_or_permission_denied'
|
||||
&& !$failed['enabled'] && !$failed['ready']
|
||||
&& !str_contains($denied->getMessage(), 'test-secret'),
|
||||
'Failed test was not persisted safely or exposed credential material.');
|
||||
|
||||
$recovered = CloudObjectStorageConfig::testAndEnable(2,
|
||||
new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create(new MockHandler([new Response(200)])),
|
||||
])));
|
||||
$assert($recovered['ready'], 'A later successful test did not recover readiness.');
|
||||
$disabled = CloudObjectStorageConfig::disable('2');
|
||||
$assert($disabled['revision'] === 3 && !$disabled['enabled']
|
||||
&& !$disabled['ready'] && $disabled['credentials_configured']
|
||||
&& $disabled['last_test_status'] === 'disabled'
|
||||
&& $disabled['status_label'] === '已停用',
|
||||
'Disable did not invalidate an in-flight test generation or preserve credentials.');
|
||||
|
||||
$ipv6Virtual = $changed;
|
||||
$ipv6Virtual['endpoint'] = 'https://[2001:db8::2]:9000';
|
||||
$ipv6Virtual['path_style'] = 'false';
|
||||
$ipv6Virtual['expected_revision'] = '3';
|
||||
$expectCloudError(static function () use ($ipv6Virtual): void {
|
||||
CloudObjectStorageConfig::save($ipv6Virtual);
|
||||
}, 422);
|
||||
|
||||
echo "Object-storage encrypted configuration and revision gate passed.\n";
|
||||
}
|
||||
@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
|
||||
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING | E_DEPRECATED))) {
|
||||
throw new ErrorException($message, 0, $severity, $file, $line);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
$smarty = new Smarty();
|
||||
$compileDir = sys_get_temp_dir() . '/object-storage-view-' . bin2hex(random_bytes(6));
|
||||
mkdir($compileDir);
|
||||
$smarty->setCompileDir($compileDir);
|
||||
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
|
||||
$smarty->assign('config', ['appName' => 'Virt Test']);
|
||||
$smarty->assign('cdn', '');
|
||||
$smarty->assign('user', (object) ['isLogin' => false]);
|
||||
$smarty->assign('admin_csrf_token', str_repeat('c', 64));
|
||||
$smarty->assign('admin_display_user_name', 'admin');
|
||||
$state = [
|
||||
'name' => '"><script>window.__objectStorageXss=1</script>测试存储',
|
||||
'driver' => 's3',
|
||||
'endpoint' => 'https://minio.example.com:9000',
|
||||
'region' => 'us-east-1',
|
||||
'bucket' => 'test-bucket',
|
||||
'prefix' => 'virt-cloud/backups',
|
||||
'path_style' => true,
|
||||
'enabled' => true,
|
||||
'ready' => true,
|
||||
'configured' => true,
|
||||
'credentials_configured' => true,
|
||||
'revision' => 7,
|
||||
'tested_revision' => 7,
|
||||
'last_test_status' => 'healthy',
|
||||
'last_error_code' => '',
|
||||
'last_error' => '',
|
||||
'last_tested_at' => 1792876800,
|
||||
'last_tested_at_text' => '2026-10-25 00:00:00',
|
||||
'status_label' => '已启用',
|
||||
'status_class' => 'success',
|
||||
];
|
||||
$render = static function (bool $canManage) use ($smarty, $state): string {
|
||||
$smarty->assign('admin_can_manage', $canManage);
|
||||
$smarty->assign('object_storage', $state);
|
||||
$smarty->assign('object_storage_error', '');
|
||||
return $smarty->fetch('admin/object_storage.tpl');
|
||||
};
|
||||
$html = $render(true);
|
||||
$readonlyHtml = $render(false);
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$parse = static function (string $document): DOMXPath {
|
||||
$dom = new DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $document);
|
||||
return new DOMXPath($dom);
|
||||
};
|
||||
$one = static function (DOMXPath $xpath, string $query) use ($assert): DOMElement {
|
||||
$nodes = $xpath->query($query);
|
||||
$assert($nodes->length === 1 && $nodes->item(0) instanceof DOMElement,
|
||||
'Expected one element matching ' . $query);
|
||||
return $nodes->item(0);
|
||||
};
|
||||
|
||||
$xpath = $parse($html);
|
||||
$form = $one($xpath, '//form[@id="objectStorageForm"]');
|
||||
$assert($form->getAttribute('action') === '/admin/object-storage/config'
|
||||
&& $form->getAttribute('method') === 'post'
|
||||
&& $form->getAttribute('data-can-manage') === '1',
|
||||
'Object-storage form method, endpoint, or permission marker changed.');
|
||||
$assert($one($xpath, '//input[@id="osName"]')->getAttribute('value') === $state['name']
|
||||
&& $xpath->query('//script[contains(.,"__objectStorageXss")]')->length === 0,
|
||||
'Object-storage application name escaped its value attribute.');
|
||||
foreach (['osAccessKey', 'osSecretKey'] as $id) {
|
||||
$secret = $one($xpath, '//input[@id="' . $id . '"]');
|
||||
$assert($secret->getAttribute('type') === 'password'
|
||||
&& $secret->getAttribute('value') === '',
|
||||
'A stored object-storage credential can be rendered into the browser.');
|
||||
}
|
||||
$assert($one($xpath, '//input[@name="expected_revision"]')->getAttribute('value') === '7'
|
||||
&& !$one($xpath, '//button[@id="osSave"]')->hasAttribute('disabled')
|
||||
&& !$one($xpath, '//button[@id="osTest"]')->hasAttribute('disabled')
|
||||
&& !$one($xpath, '//button[@id="osDisable"]')->hasAttribute('disabled'),
|
||||
'Writable object-storage state did not render its current revision and actions.');
|
||||
|
||||
$readonly = $parse($readonlyHtml);
|
||||
$assert($one($readonly, '//fieldset')->hasAttribute('disabled')
|
||||
&& $one($readonly, '//button[@id="osSave"]')->hasAttribute('disabled')
|
||||
&& $one($readonly, '//button[@id="osTest"]')->hasAttribute('disabled')
|
||||
&& $one($readonly, '//button[@id="osDisable"]')->hasAttribute('disabled'),
|
||||
'Ordinary administrator object-storage controls are not read-only.');
|
||||
$assert(str_contains($html, 'window.ADMIN_CSRF_TOKEN ='),
|
||||
'Shared administrator CSRF bootstrap is missing from object-storage page.');
|
||||
|
||||
echo "Object-storage administrator template rendering passed.\n";
|
||||
@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudObjectStorageS3Client;
|
||||
use App\Services\Cloud\CloudObjectStorageTestError;
|
||||
use App\Services\Cloud\CloudS3Signer;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Middleware;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$timestamp = strtotime('2013-05-24T00:00:00Z');
|
||||
$secret = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
|
||||
$expected = 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/'
|
||||
. '20130524/us-east-1/s3/aws4_request,'
|
||||
. 'SignedHeaders=host;x-amz-content-sha256;x-amz-date,'
|
||||
. 'Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7';
|
||||
$headers = CloudS3Signer::sign(
|
||||
'GET',
|
||||
'https://examplebucket.s3.amazonaws.com/?max-keys=2&prefix=J',
|
||||
'us-east-1',
|
||||
'AKIAIOSFODNN7EXAMPLE',
|
||||
$secret,
|
||||
$timestamp
|
||||
);
|
||||
$assert($headers['Authorization'] === $expected,
|
||||
'AWS published Signature Version 4 example no longer matches.');
|
||||
$reordered = CloudS3Signer::sign(
|
||||
'GET',
|
||||
'https://examplebucket.s3.amazonaws.com/?prefix=J&max-keys=2',
|
||||
'us-east-1',
|
||||
'AKIAIOSFODNN7EXAMPLE',
|
||||
$secret,
|
||||
$timestamp
|
||||
);
|
||||
$assert($reordered['Authorization'] === $expected,
|
||||
'S3 query parameters were not canonicalized before signing.');
|
||||
|
||||
$history = [];
|
||||
$stack = HandlerStack::create(new MockHandler([
|
||||
new Response(200, ['x-amz-bucket-region' => 'us-east-1']),
|
||||
]));
|
||||
$stack->push(Middleware::history($history));
|
||||
$client = new CloudObjectStorageS3Client(new Client(['handler' => $stack]));
|
||||
$result = $client->headBucket([
|
||||
'endpoint' => 'https://minio.example.com:9000',
|
||||
'region' => 'us-east-1',
|
||||
'bucket' => 'test-bucket',
|
||||
'path_style' => true,
|
||||
], [
|
||||
'access_key_id' => 'TESTACCESSKEY',
|
||||
'secret_access_key' => 'test-secret-key-value',
|
||||
]);
|
||||
$assert($result['status'] === 'healthy' && count($history) === 1,
|
||||
'Successful HeadBucket response was not accepted.');
|
||||
$transaction = $history[0];
|
||||
$assert($transaction['request']->getMethod() === 'HEAD'
|
||||
&& (string) $transaction['request']->getUri()
|
||||
=== 'https://minio.example.com:9000/test-bucket/'
|
||||
&& str_starts_with($transaction['request']->getHeaderLine('Authorization'),
|
||||
'AWS4-HMAC-SHA256 ')
|
||||
&& $transaction['options']['allow_redirects'] === false
|
||||
&& $transaction['options']['verify'] === true
|
||||
&& $transaction['options']['proxy'] === '',
|
||||
'Object-storage check lost its signed, read-only, TLS-strict request contract.');
|
||||
|
||||
$denied = new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create(new MockHandler([new Response(403)])),
|
||||
]));
|
||||
try {
|
||||
$denied->headBucket([
|
||||
'endpoint' => 'https://s3.example.com',
|
||||
'region' => 'us-east-1',
|
||||
'bucket' => 'test-bucket',
|
||||
'path_style' => true,
|
||||
], [
|
||||
'access_key_id' => 'TESTACCESSKEY',
|
||||
'secret_access_key' => 'never-leak-this-secret',
|
||||
]);
|
||||
throw new RuntimeException('Denied HeadBucket response was accepted.');
|
||||
} catch (CloudObjectStorageTestError $error) {
|
||||
$assert($error->publicCode === 'auth_or_permission_denied'
|
||||
&& !str_contains($error->getMessage(), 'never-leak'),
|
||||
'HeadBucket error mapping leaked credentials or changed its stable code.');
|
||||
}
|
||||
|
||||
echo "S3 Signature Version 4 and read-only HeadBucket contract passed.\n";
|
||||
Loading…
Reference in New Issue