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.
308 lines
15 KiB
PHTML
308 lines
15 KiB
PHTML
|
2 months ago
|
<?php
|
||
|
|
|
||
|
|
// Static API contract for the administrator billing read model. The real
|
||
|
|
// application tests need a configured MySQL database and an authenticated
|
||
|
|
// Slim session; keeping the security, pagination and query-shape guarantees
|
||
|
|
// here makes them runnable in the same dependency-light way as the other
|
||
|
|
// browser/API contract tests.
|
||
|
|
$root = dirname(__DIR__);
|
||
|
|
$read = static function (string $relative) use ($root): string {
|
||
|
|
$path = $root . '/' . $relative;
|
||
|
|
$contents = is_file($path) ? file_get_contents($path) : false;
|
||
|
|
if ($contents === false) {
|
||
|
|
throw new RuntimeException('Cannot read ' . $relative);
|
||
|
|
}
|
||
|
|
return $contents;
|
||
|
|
};
|
||
|
|
$assert = static function ($condition, string $message): void {
|
||
|
|
if (!$condition) {
|
||
|
|
throw new RuntimeException($message);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
$method = static function (string $source, string $name): string {
|
||
|
|
if (preg_match('/\bfunction\s+' . preg_quote($name, '/')
|
||
|
|
. '\s*\([^)]*\)\s*(?::\s*[^\{]+)?\{/m', $source, $match,
|
||
|
|
PREG_OFFSET_CAPTURE) !== 1) {
|
||
|
|
return '';
|
||
|
|
}
|
||
|
|
$start = (int) $match[0][1];
|
||
|
|
$open = strpos($source, '{', $start);
|
||
|
|
if ($open === false) {
|
||
|
|
return '';
|
||
|
|
}
|
||
|
|
$depth = 0;
|
||
|
|
$length = strlen($source);
|
||
|
|
for ($offset = $open; $offset < $length; $offset++) {
|
||
|
|
if ($source[$offset] === '{') {
|
||
|
|
$depth++;
|
||
|
|
} elseif ($source[$offset] === '}') {
|
||
|
|
$depth--;
|
||
|
|
if ($depth === 0) {
|
||
|
|
return substr($source, $start, $offset - $start + 1);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return '';
|
||
|
|
};
|
||
|
|
$foreachBodies = static function (string $source): array {
|
||
|
|
$bodies = [];
|
||
|
|
$offset = 0;
|
||
|
|
while (preg_match('/\bforeach\s*\([^)]*\)\s*\{/m', $source, $match,
|
||
|
|
PREG_OFFSET_CAPTURE, $offset) === 1) {
|
||
|
|
$start = (int) $match[0][1];
|
||
|
|
$open = strpos($source, '{', $start);
|
||
|
|
if ($open === false) {
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
$depth = 0;
|
||
|
|
$length = strlen($source);
|
||
|
|
$close = null;
|
||
|
|
for ($cursor = $open; $cursor < $length; $cursor++) {
|
||
|
|
if ($source[$cursor] === '{') {
|
||
|
|
$depth++;
|
||
|
|
} elseif ($source[$cursor] === '}') {
|
||
|
|
$depth--;
|
||
|
|
if ($depth === 0) {
|
||
|
|
$close = $cursor;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if ($close === null) {
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
$bodies[] = substr($source, $open + 1, $close - $open - 1);
|
||
|
|
$offset = $close + 1;
|
||
|
|
}
|
||
|
|
return $bodies;
|
||
|
|
};
|
||
|
|
|
||
|
|
$routes = $read('config/routes_cloud.php');
|
||
|
|
$middleware = $read('app/Middleware/CloudApi.php');
|
||
|
|
$controller = $read('app/Controllers/CloudAdminBillingController.php');
|
||
|
|
$service = $read('app/Services/Cloud/CloudAdminBillingService.php');
|
||
|
|
$client = $read('public/cloud/admin-billing.js');
|
||
|
|
$schema = $read('sql/cloud.sql');
|
||
|
|
|
||
|
|
$routeContracts = [
|
||
|
|
'/admin/billing/invoices' => 'App\\Controllers\\CloudAdminBillingController:invoices',
|
||
|
|
'/admin/billing/invoices/{id:[0-9]+}' => 'App\\Controllers\\CloudAdminBillingController:invoice',
|
||
|
|
'/admin/billing/orders' => 'App\\Controllers\\CloudAdminBillingController:orders',
|
||
|
|
'/admin/billing/payments' => 'App\\Controllers\\CloudAdminBillingController:payments',
|
||
|
|
];
|
||
|
|
foreach ($routeContracts as $path => $target) {
|
||
|
|
$routeStart = "\$this->get('{$path}',";
|
||
|
|
$offset = strpos($routes, $routeStart);
|
||
|
|
$assert($offset !== false, 'Missing GET-only administrator billing route: ' . $path);
|
||
|
|
$assert(substr_count($routes, $routeStart) === 1,
|
||
|
|
'Administrator billing route is registered more than once: ' . $path);
|
||
|
|
$routeSource = $offset === false ? '' : substr($routes, $offset, 240);
|
||
|
|
$assert(str_contains($routeSource, "'{$target}'"),
|
||
|
|
'Administrator billing route targets the wrong action: ' . $path);
|
||
|
|
}
|
||
|
|
$assert(str_contains($routes, '})->add(new \App\Middleware\CloudApi());'),
|
||
|
|
'Administrator billing routes lost the CloudApi authentication boundary.');
|
||
|
|
$assert(str_contains($middleware, '/api/v1/admin/billing')
|
||
|
|
&& str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'),
|
||
|
|
'Database-only billing reads must authenticate without creating an engine session.');
|
||
|
|
foreach (['cloud_invoice_admin_created', 'cloud_invoice_admin_status',
|
||
|
|
'cloud_invoice_admin_user', 'cloud_order_admin_created',
|
||
|
|
'cloud_order_admin_status',
|
||
|
|
'cloud_order_admin_user', 'cloud_invoice_payment_admin_status',
|
||
|
|
'cloud_invoice_payment_admin_created',
|
||
|
|
'cloud_invoice_payment_admin_provider',
|
||
|
|
'cloud_invoice_payment_admin_user'] as $indexName) {
|
||
|
|
$assert(str_contains($schema, $indexName),
|
||
|
|
'Missing billing list index: ' . $indexName);
|
||
|
|
}
|
||
|
|
|
||
|
|
$actor = $method($controller, 'actor');
|
||
|
|
$assert($actor !== ''
|
||
|
|
&& str_contains($actor, 'CloudAccess::actor(false)')
|
||
|
|
&& str_contains($actor, "['is_admin']")
|
||
|
|
&& str_contains($actor, '403'),
|
||
|
|
'Billing controller must independently require an authenticated administrator.');
|
||
|
|
foreach (['invoices', 'invoice', 'orders', 'payments'] as $action) {
|
||
|
|
$actionSource = $method($controller, $action);
|
||
|
|
$assert($actionSource !== '' && str_contains($actionSource, '$this->actor($request)'),
|
||
|
|
'Billing action does not enforce administrator access: ' . $action);
|
||
|
|
$assert(str_contains($actionSource, 'CloudAdminBillingService::' . $action . '('),
|
||
|
|
'Billing action does not delegate to its bounded read service: ' . $action);
|
||
|
|
$assert(str_contains($actionSource, '$this->json($response,'),
|
||
|
|
'Billing action bypasses the shared safe JSON response: ' . $action);
|
||
|
|
}
|
||
|
|
$json = $method($controller, 'json');
|
||
|
|
$assert(str_contains($json, 'withJson(')
|
||
|
|
&& str_contains($json, 'Cache-Control')
|
||
|
|
&& str_contains($json, 'private, no-store'),
|
||
|
|
'Billing responses must be JSON and private/non-cacheable.');
|
||
|
|
|
||
|
|
$commonFilters = $method($service, 'commonFilters');
|
||
|
|
$positiveInteger = $method($service, 'positiveInteger');
|
||
|
|
$assert(str_contains($service, 'private const DEFAULT_PER_PAGE = 30;')
|
||
|
|
&& str_contains($service, 'private const MAX_PER_PAGE = 100;')
|
||
|
|
&& str_contains($commonFilters,
|
||
|
|
"self::positiveInteger(\$input, 'page', 1)")
|
||
|
|
&& str_contains($commonFilters,
|
||
|
|
"self::positiveInteger(\$input, 'per_page', self::DEFAULT_PER_PAGE)")
|
||
|
|
&& str_contains($commonFilters, 'min(self::MAX_PER_PAGE, $perPage)')
|
||
|
|
&& str_contains($positiveInteger, 'return (int) $value;'),
|
||
|
|
'Billing pagination must default to 30 rows and clamp page size to 1..100.');
|
||
|
|
foreach (['invoices', 'orders', 'payments'] as $action) {
|
||
|
|
$assert(str_contains($method($controller, $action), 'getQueryParams()'),
|
||
|
|
'Billing list does not pass query parameters through the bounded service parser: '
|
||
|
|
. $action);
|
||
|
|
}
|
||
|
|
$assert(!str_contains($method($controller, 'invoice'), 'getQueryParams()'),
|
||
|
|
'Invoice detail must not accept meaningless list pagination.');
|
||
|
|
|
||
|
|
foreach (['invoices', 'orders', 'payments'] as $listMethod) {
|
||
|
|
$listSource = $method($service, $listMethod);
|
||
|
|
foreach (['items', 'pagination', 'summary', 'filters'] as $topLevelKey) {
|
||
|
|
$assert(str_contains($listSource, "'{$topLevelKey}' =>"),
|
||
|
|
"{$listMethod} response is missing {$topLevelKey}.");
|
||
|
|
}
|
||
|
|
$assert(str_contains($listSource, '->offset(')
|
||
|
|
&& str_contains($listSource, '->limit('),
|
||
|
|
$listMethod . ' must fetch only the requested database page.');
|
||
|
|
}
|
||
|
|
|
||
|
|
$detail = $method($service, 'invoice');
|
||
|
|
foreach (['invoice', 'order', 'job', 'instance', 'payment_attempts',
|
||
|
|
'payment_attempts_truncated'] as $detailKey) {
|
||
|
|
$assert(str_contains($detail, "'{$detailKey}' =>"),
|
||
|
|
'Invoice detail is missing the independently named ' . $detailKey . ' section.');
|
||
|
|
}
|
||
|
|
|
||
|
|
$invoiceRow = $method($service, 'invoiceRow');
|
||
|
|
$orderRow = $method($service, 'orderRow');
|
||
|
|
$paymentRow = $method($service, 'paymentRow');
|
||
|
|
$jobRow = $method($service, 'jobRow');
|
||
|
|
$instanceRow = $method($service, 'instanceRow');
|
||
|
|
$specification = $method($service, 'specification');
|
||
|
|
foreach (['financial_status', 'fulfillment_status', 'payment_method',
|
||
|
|
'user_name', 'user_email', 'plan_name', 'subject_name'] as $invoiceField) {
|
||
|
|
$assert(str_contains($invoiceRow, "'{$invoiceField}' =>"),
|
||
|
|
'Invoice read model is missing field: ' . $invoiceField);
|
||
|
|
}
|
||
|
|
$assert(str_contains($orderRow, "'financial_status' =>")
|
||
|
|
&& str_contains($orderRow, "'fulfillment_status' =>"),
|
||
|
|
'Orders must expose financial and fulfillment state as separate fields.');
|
||
|
|
$assert(str_contains($paymentRow, "'payment_status' =>")
|
||
|
|
&& str_contains($paymentRow, "'invoice_financial_status' =>"),
|
||
|
|
'Payments must expose attempt and invoice financial state separately.');
|
||
|
|
$assert(str_contains($invoiceRow, 'AdminDataMasker::account(')
|
||
|
|
&& str_contains($invoiceRow, 'AdminDataMasker::email(')
|
||
|
|
&& str_contains($orderRow, 'AdminDataMasker::account(')
|
||
|
|
&& str_contains($orderRow, 'AdminDataMasker::email(')
|
||
|
|
&& str_contains($paymentRow, 'AdminDataMasker::account(')
|
||
|
|
&& str_contains($paymentRow, 'AdminDataMasker::email('),
|
||
|
|
'Ordinary administrators must receive masked user names and email addresses.');
|
||
|
|
$assert(!str_contains($invoiceRow, "'status' =>")
|
||
|
|
&& !str_contains($orderRow, "'status' =>")
|
||
|
|
&& !str_contains($paymentRow, "'status' =>"),
|
||
|
|
'Primary billing records reintroduced an ambiguous status field.');
|
||
|
|
|
||
|
|
// Never serialize models wholesale: several source tables deliberately retain
|
||
|
|
// reconciliation secrets and encrypted provisioning material.
|
||
|
|
$assert(!str_contains($service, '->toArray()')
|
||
|
|
&& !str_contains($service, 'jsonSerialize('),
|
||
|
|
'Billing payloads must be explicit allowlists, not raw model serialization.');
|
||
|
|
$responseBuilders = implode("\n", [
|
||
|
|
$invoiceRow, $orderRow, $paymentRow, $jobRow, $instanceRow, $specification,
|
||
|
|
]);
|
||
|
|
foreach (['invoice_no', 'payment_reference', 'request_hash', 'spec_json',
|
||
|
|
'payload_cipher', 'idempotency_key', 'provider_order_no', 'operation_id',
|
||
|
|
'lease_token', 'result_json'] as $sensitiveField) {
|
||
|
|
$assert(!str_contains($responseBuilders, "'{$sensitiveField}' =>"),
|
||
|
|
'Administrator billing API serializes sensitive data: ' . $sensitiveField);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Every list may load a page first and then resolve its users, invoices,
|
||
|
|
// instances, orders and jobs in fixed-size batches. Database calls from a row
|
||
|
|
// loop would turn a 100-row page into an unbounded N+1 query sequence.
|
||
|
|
$batchLoads = substr_count($service, 'whereIn(')
|
||
|
|
+ substr_count($service, 'join(')
|
||
|
|
+ substr_count($service, 'leftJoin(');
|
||
|
|
$assert($batchLoads >= 4,
|
||
|
|
'Billing associations are not resolved through fixed-size batch queries.');
|
||
|
|
$paymentContext = $method($service, 'paymentContext');
|
||
|
|
$assert(str_contains($paymentContext, 'CloudInstance::whereIn(')
|
||
|
|
&& str_contains($paymentRow,
|
||
|
|
'self::financialStatus($invoice, $instance, true)'),
|
||
|
|
'Renewal payment rows must preload instance state instead of treating a missing argument as a deleted instance.');
|
||
|
|
$assert(str_contains($detail, "'instances' => \$context['instances']"),
|
||
|
|
'Invoice detail payment attempts must reuse the preloaded renewal instance context.');
|
||
|
|
$financialFilter = $method($service, 'applyInvoiceFinancialStatus');
|
||
|
|
$invoiceSummary = $method($service, 'invoiceSummary');
|
||
|
|
$invoiceFilters = $method($service, 'applyInvoiceFilters');
|
||
|
|
$orderFilters = $method($service, 'applyOrderFulfillmentStatus');
|
||
|
|
$orderSummary = $method($service, 'orderSummary');
|
||
|
|
$paymentSummary = $method($service, 'paymentSummary');
|
||
|
|
$assert(str_contains($financialFilter, 'whereOrphanOpenRenewal(')
|
||
|
|
&& str_contains($financialFilter, 'whereValidRenewalTarget(')
|
||
|
|
&& str_contains($invoiceSummary, '$liveRenewalTarget'),
|
||
|
|
'Invoice filters and outstanding totals must use the same orphan-renewal state as response rows.');
|
||
|
|
$assert(str_contains($invoiceFilters, "where('cloud_invoices.paid_via',")
|
||
|
|
&& !str_contains($invoiceFilters, "from('cloud_invoice_payments')"),
|
||
|
|
'Invoice payment-method filtering must match the settled method displayed by the list.');
|
||
|
|
$assert(str_contains($method($service, 'orders'), 'applyOrderFulfillmentStatus(')
|
||
|
|
&& str_contains($orderFilters, "where('cloud_jobs.status', \$status)")
|
||
|
|
&& str_contains($orderFilters, "where('cloud_orders.status', \$status)")
|
||
|
|
&& str_contains($orderFilters, 'whereNotExists('),
|
||
|
|
'Order filtering must prefer the engine job state and fall back only when no job exists.');
|
||
|
|
$assert(str_contains($orderSummary,
|
||
|
|
'COALESCE(cloud_jobs.status, cloud_orders.status)')
|
||
|
|
&& str_contains($orderSummary, "'cloud_jobs.user_id'")
|
||
|
|
&& str_contains($orderSummary, "'cloud_orders.user_id'")
|
||
|
|
&& str_contains($orderSummary, 'SUM(CASE WHEN')
|
||
|
|
&& !str_contains($orderSummary, '->count()')
|
||
|
|
&& !str_contains($orderSummary, '->sum('),
|
||
|
|
'Order summaries must aggregate job-first state in one bounded query.');
|
||
|
|
$assert(str_contains($paymentSummary, 'SUM(CASE WHEN')
|
||
|
|
&& !str_contains($paymentSummary, '->count()')
|
||
|
|
&& !str_contains($paymentSummary, '->sum('),
|
||
|
|
'Payment summaries must aggregate status counts and amounts in one query.');
|
||
|
|
$normalizeIdentifier = $method($service, 'normalizeIdentifier');
|
||
|
|
$assert(str_contains($normalizeIdentifier, '18446744073709551615')
|
||
|
|
&& str_contains($method($service, 'optionalIdentifier'),
|
||
|
|
'self::identifier(')
|
||
|
|
&& !str_contains($method($service, 'applyInvoiceSearch'), '(int) $q')
|
||
|
|
&& str_contains($invoiceRow, "'user_id' => (string)")
|
||
|
|
&& str_contains($orderRow, "'host_id' => (string)"),
|
||
|
|
'BIGINT identifiers must stay canonical decimal strings instead of overflowing PHP or JSON numbers.');
|
||
|
|
$assert(str_contains($invoiceFilters, "where('cloud_invoices.purpose', 'provision')")
|
||
|
|
&& str_contains($invoiceFilters,
|
||
|
|
"whereColumn('cloud_orders.user_id',")
|
||
|
|
&& str_contains($method($service, 'whereInvoiceFinancialStatus'),
|
||
|
|
"whereColumn('cloud_invoices.user_id', \$outerUserColumn)"),
|
||
|
|
'Billing filters must enforce the same ownership links used by serialization.');
|
||
|
|
$assert(str_contains($method($service, 'applyInvoiceSearch'), "from('shop')")
|
||
|
|
&& str_contains($method($service, 'applyOrderSearch'), "from('shop')"),
|
||
|
|
'Invoice and order keyword searches must honor the advertised plan-name lookup.');
|
||
|
|
$assert(str_contains($detail, 'self::DETAIL_PAYMENT_LIMIT + 1')
|
||
|
|
&& str_contains($client, 'payment_attempts_truncated')
|
||
|
|
&& str_contains($client, '仅显示最近 100 条'),
|
||
|
|
'Invoice detail must bound and disclose truncated payment-attempt history.');
|
||
|
|
$assert(str_contains($client, "['支付截止', formatDate(invoice.payment_deadline_at)]")
|
||
|
|
&& str_contains($client, 'resetSummary(false)')
|
||
|
|
&& str_contains($client, "setAttribute('aria-busy', String(busy))"),
|
||
|
|
'Billing detail deadlines and failed-list summary state must remain accurate.');
|
||
|
|
$queryInLoop = '/(?:::query|::where|::find|->where|->first|->get|->value|->count|->exists)\s*\(/';
|
||
|
|
foreach ($foreachBodies($service) as $loopBody) {
|
||
|
|
$assert(preg_match($queryInLoop, $loopBody) !== 1,
|
||
|
|
'Billing service performs a database query inside a row loop (N+1).');
|
||
|
|
}
|
||
|
|
foreach ([$invoiceRow, $orderRow, $paymentRow] as $rowBuilder) {
|
||
|
|
$assert(preg_match($queryInLoop, $rowBuilder) !== 1,
|
||
|
|
'Billing row serialization performs a database query instead of using batch context.');
|
||
|
|
}
|
||
|
|
|
||
|
|
$money = $method($service, 'money');
|
||
|
|
$assert(str_contains($money, '$whole = ltrim(')
|
||
|
|
&& str_contains($money, "if (\$whole === '')")
|
||
|
|
&& str_contains($money, "return \$whole . '.' . str_pad("),
|
||
|
|
'Billing money formatting may drop the decimal part through ternary precedence.');
|
||
|
|
|
||
|
|
echo "Administrator billing API routes, permissions, pagination, privacy and batch-query contracts passed.\n";
|