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.
286 lines
18 KiB
PHP
286 lines
18 KiB
PHP
<?php
|
|
|
|
namespace App\Services {
|
|
final class Auth
|
|
{
|
|
public static $user = null;
|
|
public static function getUser() { return self::$user; }
|
|
}
|
|
final class AdminPermission
|
|
{
|
|
public static bool $superAdmin = false;
|
|
public static function isSuperAdmin(): bool { return self::$superAdmin; }
|
|
}
|
|
}
|
|
|
|
namespace App\Services\Cloud {
|
|
final class CloudSessionService
|
|
{
|
|
public static int $calls = 0;
|
|
public static function current($user): string
|
|
{
|
|
self::$calls++;
|
|
throw new \RuntimeException('Announcement requested a console session');
|
|
}
|
|
}
|
|
final class CloudAgentSettingsService
|
|
{
|
|
public static int $calls = 0;
|
|
public function __construct()
|
|
{
|
|
self::$calls++;
|
|
throw new \RuntimeException('Announcement contacted a host Agent');
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace {
|
|
require dirname(__DIR__) . '/vendor/autoload.php';
|
|
|
|
use App\Controllers\Admin\AnnController;
|
|
use App\Controllers\AnnouncementController;
|
|
use App\Models\Ann;
|
|
use App\Models\User;
|
|
use App\Services\AdminCsrf;
|
|
use App\Services\AdminPermission;
|
|
use App\Services\AnnouncementSchema;
|
|
use App\Services\AnnouncementService as Announcements;
|
|
use App\Services\Auth;
|
|
use App\Services\Cloud\CloudError;
|
|
use App\Services\Cloud\CloudAgentSettingsService;
|
|
use App\Services\Cloud\CloudSessionService;
|
|
use Illuminate\Database\Capsule\Manager as Capsule;
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
use Slim\Http\Environment;
|
|
use Slim\Http\Request;
|
|
use Slim\Http\Response;
|
|
|
|
$System_Config = ['cookie_secure' => 'false'];
|
|
$assert = static function (bool $ok, string $message): void {
|
|
if (!$ok) throw new RuntimeException($message);
|
|
};
|
|
$reject = static function (callable $call, int $status) use ($assert): void {
|
|
try { $call(); } catch (CloudError $error) {
|
|
$assert($error->httpStatus === $status, 'Unexpected rejection status: ' . $error->httpStatus);
|
|
return;
|
|
}
|
|
throw new RuntimeException('Expected rejection was accepted.');
|
|
};
|
|
$capsule = new Capsule();
|
|
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
|
$capsule->setAsGlobal();
|
|
$capsule->bootEloquent();
|
|
$connection = $capsule->getConnection();
|
|
$schema = $connection->getSchemaBuilder();
|
|
$schema->create('announcement', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->dateTime('date');
|
|
$table->longText('content'); $table->longText('markdown');
|
|
});
|
|
// This rollout intentionally supports empty legacy tables only. Existing
|
|
// records must stop it before the very first DDL statement, not be converted.
|
|
$connection->table('announcement')->insert(['id' => 1, 'date' => '2020-01-02 03:04:05',
|
|
'content' => '<p>do not delete this record</p>', 'markdown' => '**archive**']);
|
|
$originalColumns = $schema->getColumnListing('announcement');
|
|
$originalData = $connection->table('announcement')->get()->toJson();
|
|
$connection->enableQueryLog(); $connection->flushQueryLog();
|
|
try {
|
|
AnnouncementSchema::upgrade($connection);
|
|
throw new LogicException('Nonempty legacy schema was silently changed.');
|
|
} catch (RuntimeException $error) {
|
|
$assert(str_contains($error->getMessage(), '旧公告表仍有数据'), 'Unsafe legacy migration had no clear error.');
|
|
}
|
|
foreach ($connection->getQueryLog() as $query) {
|
|
$assert(!preg_match('/^(?:alter|create|drop|update|delete|insert)\b/i', $query['query']),
|
|
'Legacy data guard ran after a schema/data mutation.');
|
|
}
|
|
$assert($schema->getColumnListing('announcement') === $originalColumns
|
|
&& $connection->table('announcement')->get()->toJson() === $originalData, 'Rejected migration changed legacy structure/data.');
|
|
// Remove only the test fixture, then exercise an interrupted empty migration.
|
|
$connection->table('announcement')->where('id', 1)->delete();
|
|
$schema->table('announcement', static function (Blueprint $table): void { $table->string('title', 120)->default(''); });
|
|
AnnouncementSchema::upgrade($connection);
|
|
$assert($schema->hasIndex('announcement', 'announcement_published')
|
|
&& !$schema->hasColumn('announcement', 'content') && !$schema->hasColumn('announcement', 'markdown')
|
|
&& !$schema->hasColumn('announcement', 'date') && $connection->table('announcement')->count() === 0,
|
|
'Empty legacy migration left rich-text fields or created content.');
|
|
AnnouncementSchema::upgrade($connection);
|
|
for ($id = 1; $id <= 205; $id++) {
|
|
$connection->table('announcement')->insert(['id' => $id, 'title' => '通知 ' . $id,
|
|
'body' => $id === 1 ? "第一段\n\n第二段 链接文字" : '纯文本通知 ' . $id,
|
|
'type' => 'notice', 'status' => 'published', 'published_at' => '2020-01-02 03:04:05',
|
|
'updated_at' => '2020-01-02 03:04:05']);
|
|
}
|
|
$snapshot = static fn (): string => $connection->table('announcement')->orderBy('id')->get()->toJson();
|
|
$migrated = $snapshot();
|
|
AnnouncementSchema::upgrade($connection);
|
|
$assert($snapshot() === $migrated, 'Repeated migration was not idempotent.');
|
|
|
|
$customer = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false];
|
|
$admin = ['user_id' => 2, 'is_admin' => true, 'is_super_admin' => false, 'can_manage' => false];
|
|
$super = ['user_id' => 3, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true];
|
|
$page = Announcements::page($admin);
|
|
$assert($page['pagination']['total'] === 205 && count($page['items']) === 20
|
|
&& $page['filters']['status'] === 'all', 'Admin pagination lost historical announcements.');
|
|
$seen = [];
|
|
for ($pageNo = 1; $pageNo <= 21; $pageNo++) {
|
|
$published = Announcements::published($customer, ['page' => $pageNo]);
|
|
foreach ($published['items'] as $item) {
|
|
$assert($item['status'] === 'published' && is_string($item['id'])
|
|
&& !array_key_exists('content', $item) && !array_key_exists('markdown', $item), 'Public DTO exposed archives or unpublished records.');
|
|
$seen[] = $item['id'];
|
|
}
|
|
}
|
|
$assert(count(array_unique($seen)) === 205 && in_array('1', $seen, true), 'Public pagination clipped old records at two months or 200 rows.');
|
|
$lastPage = Announcements::published($customer, ['page' => 999]);
|
|
$assert($lastPage['pagination']['page'] === 21 && count($lastPage['items']) === 5,
|
|
'User out-of-range page was not clamped to the final page.');
|
|
$lastAdminPage = Announcements::page($admin, ['page' => 999]);
|
|
$assert($lastAdminPage['pagination']['page'] === 11 && $lastAdminPage['filters']['page'] === 11
|
|
&& count($lastAdminPage['items']) === 5, 'Admin filters and pagination disagree after clamping.');
|
|
$assert(Announcements::page($admin, ['q' => '链接文字'])['pagination']['total'] === 1, 'Plain-text search failed.');
|
|
|
|
$input = ['title' => '维护通知 🛠', 'type' => 'maintenance', 'body' => "第一行\r\n第二行 <script>只是文本</script>", 'status' => 'published'];
|
|
$new = Announcements::save($super, $input);
|
|
$assert($new['type_label'] === '维护' && $new['status'] === 'published' && $new['published_at'] !== null
|
|
&& $new['body'] === "第一行\n第二行 <script>只是文本</script>", 'New announcement was not stored as literal plain text.');
|
|
$stored = $connection->table('announcement')->where('id', $new['id'])->first();
|
|
$assert(!property_exists($stored, 'content') && !property_exists($stored, 'markdown'), 'New schema retained legacy rich-text fields.');
|
|
$connection->table('announcement')->where('id', $new['id'])->update(['published_at' => '2021-01-01 00:00:00']);
|
|
$withdrawn = Announcements::setStatus($super, $new['id'], ['status' => 'withdrawn']);
|
|
$assert($withdrawn['status'] === 'withdrawn' && $withdrawn['published_at'] === '2021-01-01 00:00:00'
|
|
&& Announcements::published($customer)['pagination']['total'] === 205, 'Withdraw did not hide the announcement or destroyed publication history.');
|
|
// The old edit form still says published; only an explicit status action may republish.
|
|
$staleEdit = Announcements::save($super, array_replace($input, ['title' => '陈旧表单更新']), $new['id']);
|
|
$assert($staleEdit['status'] === 'withdrawn' && $staleEdit['published_at'] === '2021-01-01 00:00:00',
|
|
'A stale edit form republished a concurrently withdrawn announcement.');
|
|
$republished = Announcements::setStatus($super, $new['id'], ['status' => 'published']);
|
|
$assert($republished['status'] === 'published' && $republished['published_at'] > '2021-01-01 00:00:00',
|
|
'Explicit republish did not record a real publication time.');
|
|
$connection->table('announcement')->where('id', $new['id'])->update(['updated_at' => '2021-02-03 00:00:00']);
|
|
$same = Announcements::setStatus($super, $new['id'], ['status' => 'published']);
|
|
$assert($same['updated_at'] === '2021-02-03 00:00:00', 'Idempotent status request forged an update event.');
|
|
Announcements::save($super, array_replace($input, ['title' => '50%_! literal', 'type' => 'incident', 'status' => 'withdrawn']));
|
|
$assert(Announcements::page($admin, ['q' => '%_!'])['pagination']['total'] === 1
|
|
&& Announcements::page($admin, ['q' => "' OR 1=1 --"])['pagination']['total'] === 0
|
|
&& Announcements::page($admin, ['type' => 'incident', 'status' => 'withdrawn'])['pagination']['total'] === 1,
|
|
'Filters did not bind literal keywords, type and status safely.');
|
|
$saved = $snapshot();
|
|
AnnouncementSchema::upgrade($connection);
|
|
$assert($snapshot() === $saved, 'Repeated upgrade changed published or withdrawn records.');
|
|
|
|
foreach (['title', 'body', 'type', 'status'] as $key) {
|
|
$reject(static fn () => Announcements::save($super, array_replace($input, [$key => ['bad']])), 400);
|
|
}
|
|
foreach ([['title' => ''], ['body' => ' '], ['title' => str_repeat('字', 121)], ['body' => str_repeat('字', 20001)],
|
|
['title' => "multi\nline"], ['body' => "nul\0byte"], ['type' => 'html'], ['status' => 'deleted']] as $invalid) {
|
|
$reject(static fn () => Announcements::save($super, array_replace($input, $invalid)), 400);
|
|
}
|
|
$withoutStatus = $input; unset($withoutStatus['status']);
|
|
$reject(static fn () => Announcements::save($super, $withoutStatus), 400);
|
|
foreach (['page', 'per_page', 'q', 'type', 'status'] as $key) {
|
|
$reject(static fn () => Announcements::page($admin, [$key => ['bad']]), 400);
|
|
}
|
|
foreach ([['page' => 0], ['page' => '1.1'], ['per_page' => 500], ['q' => str_repeat('a', 81)],
|
|
['type' => 'wrong'], ['status' => 'deleted']] as $invalid) {
|
|
$reject(static fn () => Announcements::page($admin, $invalid), 400);
|
|
}
|
|
$reject(static fn () => Announcements::published($customer, ['per_page' => 100]), 400);
|
|
$reject(static fn () => Announcements::published([], []), 401);
|
|
$reject(static fn () => Announcements::page($customer), 403);
|
|
$reject(static fn () => Announcements::save($admin, $input), 403);
|
|
$reject(static fn () => Announcements::setStatus($admin, '1', ['status' => 'withdrawn']), 403);
|
|
$reject(static fn () => Announcements::detail($admin, '0'), 400);
|
|
$reject(static fn () => Announcements::detail($admin, '999999'), 404);
|
|
$reject(static fn () => Announcements::save($super, $input, '999999'), 404);
|
|
$reject(static fn () => Announcements::setStatus($super, '999999', ['status' => 'withdrawn']), 404);
|
|
$assert(!method_exists(AnnController::class, 'delete') && !method_exists(AnnController::class, 'ajax'), 'Legacy rich-text deletion/list endpoints remain.');
|
|
|
|
$connection->enableQueryLog();
|
|
$counts = [];
|
|
foreach ([20, 100] as $size) {
|
|
$connection->flushQueryLog();
|
|
Announcements::page($admin, ['per_page' => $size]);
|
|
$log = $connection->getQueryLog(); $counts[] = count($log);
|
|
foreach ($log as $query) {
|
|
$sql = strtolower($query['query']);
|
|
$assert(str_starts_with($sql, 'select ') && !str_contains($sql, 'content')
|
|
&& !str_contains($sql, 'markdown'), 'Read path performs DDL/writes or reads archived rich text.');
|
|
}
|
|
}
|
|
$assert($counts === [2, 2], 'Announcement pagination has per-row queries.');
|
|
$beforeReads = $snapshot();
|
|
$login = static function (bool $isAdmin, bool $isSuper = false, bool $enabled = true): void {
|
|
$user = new User(); $user->id = $isSuper ? 3 : ($isAdmin ? 2 : 1);
|
|
$user->enable = $enabled ? 1 : 0; $user->is_admin = $isAdmin; $user->isLogin = true;
|
|
Auth::$user = $user; AdminPermission::$superAdmin = $isSuper;
|
|
};
|
|
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
|
|
require dirname(__DIR__) . '/config/routes_cloud.php';
|
|
$request = static function (string $method, string $path, ?array $body = null, array $query = []): Request {
|
|
$request = Request::createFromEnvironment(Environment::mock(['REQUEST_METHOD' => $method, 'REQUEST_URI' => $path]));
|
|
return $request->withQueryParams($query)->withParsedBody($body);
|
|
};
|
|
$login(false);
|
|
$response = $app->process($request('GET', '/api/v1/announcements'), new Response());
|
|
$public = json_decode((string) $response->getBody(), true);
|
|
$assert($response->getStatusCode() === 200 && $response->getHeaderLine('Cache-Control') === 'private, no-store'
|
|
&& count($public['items']) === 10 && $public['pagination']['total'] === 206, 'Registered user API contract failed.');
|
|
$response = $app->process($request('GET', '/api/v1/announcements', null, ['page' => ['bad']]), new Response());
|
|
$assert($response->getStatusCode() === 400, 'User API did not reject array parameters.');
|
|
$login(false, false, false);
|
|
$response = $app->process($request('GET', '/api/v1/announcements'), new Response());
|
|
$assert($response->getStatusCode() === 401 && str_contains($response->getHeaderLine('Cache-Control'), 'no-store'),
|
|
'Disabled user reached the notice feed.');
|
|
Auth::$user = null;
|
|
$response = $app->process($request('GET', '/api/v1/announcements'), new Response());
|
|
$assert($response->getStatusCode() === 401, 'Anonymous user reached the notice feed.');
|
|
$login(false);
|
|
$response = (new AnnouncementController())->index($request('GET', '/api/v1/announcements'), new Response());
|
|
$assert($response->getStatusCode() === 200 && $snapshot() === $beforeReads, 'Direct API fallback wrote business state.');
|
|
|
|
$controller = (new ReflectionClass(AnnController::class))->newInstanceWithoutConstructor();
|
|
foreach (['anonymous' => 401, 'disabled' => 401, 'customer' => 403] as $identity => $status) {
|
|
$login($identity !== 'customer', true, $identity !== 'disabled');
|
|
if ($identity === 'anonymous') Auth::$user = null;
|
|
$response = $controller->index($request('GET', '/admin/announcement'), new Response(), []);
|
|
$assert($response->getStatusCode() === $status && (string) $response->getBody() === ''
|
|
&& $response->getHeaderLine('Cache-Control') === 'private, no-store', 'Unauthorized SSR rendered an admin shell.');
|
|
}
|
|
$login(true);
|
|
foreach (['create', 'edit'] as $method) {
|
|
$response = $controller->$method($request('GET', '/admin/announcement/1/edit'), new Response(), ['id' => '1']);
|
|
$assert($response->getStatusCode() === 403, 'Read-only administrator gained an edit form.');
|
|
}
|
|
$response = $controller->add($request('POST', '/admin/announcement', $input), new Response(), []);
|
|
$assert($response->getStatusCode() === 403 && json_decode((string) $response->getBody(), true)['ret'] === 0,
|
|
'Controller accepted a read-only administrator write.');
|
|
$login(true, true);
|
|
$response = $controller->add($request('POST', '/admin/announcement', array_replace($input, ['title' => 'Controller created'])), new Response(), []);
|
|
$created = json_decode((string) $response->getBody(), true);
|
|
$assert($response->getStatusCode() === 200 && $created['ret'] === 1
|
|
&& $created['announcement']['title'] === 'Controller created'
|
|
&& $response->getHeaderLine('Cache-Control') === 'private, no-store', 'Admin JSON create contract failed.');
|
|
$response = $controller->update($request('PUT', '/admin/announcement/999999', $input), new Response(), ['id' => '999999']);
|
|
$assert($response->getStatusCode() === 404 && json_decode((string) $response->getBody(), true)['ret'] === 0,
|
|
'Missing update did not return JSON 404.');
|
|
$response = $controller->add($request('POST', '/admin/announcement'), new Response(), []);
|
|
$assert($response->getStatusCode() === 400, 'Malformed request body did not return 400.');
|
|
|
|
// Exercise the existing CSRF and super-admin middleware around the actual status handler.
|
|
$protected = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
|
|
$protected->post('/admin/announcement/{id}/status', [$controller, 'status'])->add(new \App\Middleware\SuperAdmin());
|
|
$path = '/admin/announcement/' . $created['announcement']['id'] . '/status';
|
|
$response = $protected->process($request('POST', $path, ['status' => 'withdrawn']), new Response());
|
|
$assert($response->getStatusCode() === 419, 'Status changes bypassed existing CSRF protection: '
|
|
. $response->getStatusCode() . ' ' . (string) $response->getBody());
|
|
$token = AdminCsrf::token();
|
|
$response = $protected->process($request('POST', $path, ['status' => 'withdrawn'])
|
|
->withHeader(AdminCsrf::HEADER_NAME, $token), new Response());
|
|
$assert($response->getStatusCode() === 200
|
|
&& json_decode((string) $response->getBody(), true)['announcement']['status'] === 'withdrawn',
|
|
'Valid CSRF-protected status request failed.');
|
|
$assert(CloudAgentSettingsService::$calls === 0 && CloudSessionService::$calls === 0,
|
|
'Announcements acquired Agent or console-session state.');
|
|
echo "Announcement guarded/idempotent empty-schema migration, plain text, clamped pagination, stale edits, publication, API/auth/CSRF and read-only queries passed.\n";
|
|
}
|