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.
virt/web/tests/LegalDocumentServiceTest.php

207 lines
11 KiB
PHTML

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudError;
use App\Services\LegalDocumentService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$reject = static function (callable $call, int $status) use ($assert): void {
try {
$call();
} catch (CloudError $exception) {
$assert($exception->httpStatus === $status, 'Unexpected rejection status: ' . $exception->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('legal_documents', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('slug', 32);
$table->string('locale', 10);
$table->string('title', 120);
$table->longText('draft_html');
$table->date('effective_date');
$table->unsignedInteger('draft_version')->default(0);
$table->unsignedBigInteger('published_revision_id')->nullable();
$table->unsignedBigInteger('updated_by')->default(0);
$table->dateTime('created_at');
$table->dateTime('updated_at');
$table->unique(['slug', 'locale']);
});
$schema->create('legal_document_revisions', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('document_id');
$table->unsignedInteger('version');
$table->string('title', 120);
$table->longText('content_html');
$table->date('effective_date');
$table->dateTime('published_at');
$table->unsignedBigInteger('published_by');
$table->unique(['document_id', 'version']);
});
$schema->create('ui_copy_locales', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('locale', 32)->unique();
$table->string('display_name', 128);
$table->boolean('enabled')->default(false);
$table->boolean('source_claim')->nullable()->unique();
});
$connection->table('ui_copy_locales')->insert([
['locale' => 'zh-CN', 'display_name' => '简体中文',
'enabled' => 1, 'source_claim' => 1],
['locale' => 'en', 'display_name' => 'English',
'enabled' => 1, 'source_claim' => null],
['locale' => 'ja', 'display_name' => '日本語',
'enabled' => 1, 'source_claim' => null],
['locale' => 'fr', 'display_name' => 'Français',
'enabled' => 0, 'source_claim' => null],
]);
$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];
$initial = LegalDocumentService::editorState($admin, 'terms', 'zh-CN');
$assert($initial['draft_version'] === 0 && $initial['published'] === null
&& str_contains($initial['content_html'], '接受与适用范围'), 'New editor did not expose safe default copy.');
$fallback = LegalDocumentService::published('terms', 'zh-CN', '测试云');
$assert($fallback['fallback'] === true && $fallback['version'] === 1
&& str_contains($fallback['content_html'], '测试云') && count($fallback['outline']) >= 5,
'Public fallback or site-name substitution is incorrect.');
$englishFallback = LegalDocumentService::published('terms', 'en', '测试云');
$assert($englishFallback['fallback'] === true
&& str_contains($englishFallback['content_html'], '接受与适用范围')
&& $englishFallback['title'] === '服务条款',
'An unpublished target locale did not use the Chinese safety baseline.');
$japaneseState = LegalDocumentService::editorState($admin, 'privacy', 'ja');
$assert(($japaneseState['locales']['ja'] ?? null) === '日本語'
&& !array_key_exists('fr', $japaneseState['locales'])
&& $japaneseState['locale_label'] === '日本語',
'Legal authoring did not use the enabled dynamic locale directory.');
$japaneseFallback = LegalDocumentService::published('privacy', 'ja', '测试云');
$assert($japaneseFallback['fallback'] === true
&& $japaneseFallback['locale'] === 'ja'
&& str_contains($japaneseFallback['content_html'], '我们收集的信息'),
'A dynamic legal locale did not safely fall back to Chinese content.');
$unregisteredPublicFallback = LegalDocumentService::published(
'terms',
'de-DE',
'测试云'
);
$assert($unregisteredPublicFallback['fallback'] === true
&& $unregisteredPublicFallback['locale'] === 'de-DE'
&& str_contains($unregisteredPublicFallback['content_html'], '接受与适用范围'),
'Public legal fallback incorrectly depended on the authoring locale table.');
$japanesePublished = LegalDocumentService::publish($super, 'privacy', [
'locale' => 'ja',
'title' => 'プライバシーポリシー',
'effective_date' => '2026-11-08',
'draft_version' => '0',
'content_html' => '<h2>収集する情報</h2><p>{{site_name}} の方針です。</p>',
]);
$assert($japanesePublished['published']['version'] === 1
&& LegalDocumentService::published('privacy', 'ja', 'テスト')['fallback'] === false,
'A dynamic legal locale could not be published and read.');
$serviceSource = file_get_contents(dirname(__DIR__) . '/app/Services/LegalDocumentService.php');
$assert(is_string($serviceSource)
&& !str_contains($serviceSource, 'Acceptance and scope')
&& !str_contains($serviceSource, 'Information we collect'),
'Legal target-language translations remain embedded in source.');
$draft = LegalDocumentService::saveDraft($super, 'terms', [
'locale' => 'zh-CN',
'title' => '平台服务条款',
'effective_date' => '2026-11-01',
'draft_version' => '0',
'content_html' => '<h2 onclick="alert(1)">范围</h2><p>使用 {{site_name}}。</p>'
. '<script>alert(1)</script><a href="javascript:alert(1)">危险链接</a>'
. '<img src=x onerror=alert(1)><blockquote style="color:red">说明</blockquote>',
]);
$assert($draft['draft_version'] === 1 && !str_contains($draft['content_html'], '<script')
&& !str_contains($draft['content_html'], 'onclick') && !str_contains($draft['content_html'], 'href=')
&& !str_contains($draft['content_html'], '<img') && !str_contains($draft['content_html'], 'style='),
'Draft sanitizer retained executable markup or attributes.');
$stillFallback = LegalDocumentService::published('terms', 'zh-CN', '测试云');
$assert($stillFallback['fallback'] === true && !str_contains($stillFallback['content_html'], '危险链接'),
'An unpublished draft leaked to the public page.');
$publishedState = LegalDocumentService::publish($super, 'terms', [
'locale' => 'zh-CN',
'title' => '平台服务条款',
'effective_date' => '2026-11-01',
'draft_version' => '1',
'content_html' => '<h2>适用范围</h2><p>{{site_name}} 为你提供云服务。</p><h3>账户</h3><p>请保护凭据。</p>',
]);
$assert($publishedState['draft_version'] === 2 && $publishedState['published']['version'] === 1
&& count($publishedState['history']) === 1, 'First publication did not create an immutable revision.');
$published = LegalDocumentService::published('terms', 'zh-CN', '<站点>');
$assert($published['fallback'] === false && $published['version'] === 1
&& str_contains($published['content_html'], '&lt;站点&gt;')
&& str_contains($published['content_html'], 'id="legal-section-1"')
&& count($published['outline']) === 2, 'Published DTO is unsafe or missing its outline.');
$firstRevision = $connection->table('legal_document_revisions')->where('version', 1)->first();
$secondState = LegalDocumentService::publish($super, 'terms', [
'locale' => 'zh-CN',
'title' => '平台服务条款(更新)',
'effective_date' => '2026-12-01',
'draft_version' => '2',
'content_html' => '<h2>更新范围</h2><p>第二版正文。</p>',
]);
$assert($secondState['draft_version'] === 3 && $secondState['published']['version'] === 2
&& count($secondState['history']) === 2, 'Second publication overwrote or omitted revision history.');
$unchangedFirst = $connection->table('legal_document_revisions')->where('version', 1)->first();
$assert($firstRevision->content_html === $unchangedFirst->content_html,
'Publishing a new version mutated an older revision.');
$reject(static fn () => LegalDocumentService::saveDraft($super, 'terms', [
'locale' => 'zh-CN', 'title' => '冲突', 'effective_date' => '2026-12-01',
'draft_version' => '2', 'content_html' => '<p>陈旧版本。</p>',
]), 409);
$reject(static fn () => LegalDocumentService::saveDraft($admin, 'terms', [
'locale' => 'zh-CN', 'title' => '无权限', 'effective_date' => '2026-12-01',
'draft_version' => '3', 'content_html' => '<p>无权限。</p>',
]), 403);
$reject(static fn () => LegalDocumentService::editorState($customer, 'terms', 'zh-CN'), 403);
$reject(static fn () => LegalDocumentService::editorState([], 'terms', 'zh-CN'), 401);
$reject(static fn () => LegalDocumentService::preview($admin, 'wrong', [], '站点'), 400);
$reject(static fn () => LegalDocumentService::preview($admin, 'terms', [
'locale' => 'fr', 'title' => 'Title', 'effective_date' => '2026-12-01', 'content_html' => '<p>Body</p>',
], '站点'), 400);
$reject(static fn () => LegalDocumentService::preview($admin, 'terms', [
'locale' => 'en', 'title' => 'Title', 'effective_date' => '2026-02-30', 'content_html' => '<p>Body</p>',
], '站点'), 400);
$reject(static fn () => LegalDocumentService::preview($admin, 'terms', [
'locale' => 'en', 'title' => 'Title', 'effective_date' => '2026-12-01', 'content_html' => ' ',
], '站点'), 400);
$documentId = (int) $connection->table('legal_documents')->where('slug', 'terms')->where('locale', 'zh-CN')->value('id');
$revisionId = (int) $connection->table('legal_documents')->where('id', $documentId)->value('published_revision_id');
$connection->table('legal_document_revisions')->where('id', $revisionId)->update([
'content_html' => '<h2 onmouseover="x">数据库异常内容</h2><script>alert(1)</script><p>仍可显示。</p>',
]);
$sanitizedRead = LegalDocumentService::published('terms', 'zh-CN', '站点');
$assert(!str_contains($sanitizedRead['content_html'], '<script')
&& !str_contains($sanitizedRead['content_html'], 'onmouseover')
&& str_contains($sanitizedRead['content_html'], '仍可显示'),
'Public reads trusted unsafe database HTML.');
$assert(!$schema->hasColumn('legal_documents', 'domain') && !$schema->hasColumn('legal_documents', 'host'),
'Legal content was accidentally scoped per domain.');
echo "Legal document service tests passed.\n";