From 5c708eb335ecc70b453fbaf667e3bd21e60da800 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 2 Nov 2026 02:08:31 +0800 Subject: [PATCH] feat(ticket): enforce support usage policy --- .../Services/Ticket/TicketThreadService.php | 35 +++- web/app/Services/Ticket/TicketUsagePolicy.php | 95 +++++++++++ web/tests/TicketIdempotencyTest.php | 4 + web/tests/TicketReplyTransactionTest.php | 4 + web/tests/TicketUsagePolicyTest.php | 158 ++++++++++++++++++ 5 files changed, 292 insertions(+), 4 deletions(-) create mode 100644 web/app/Services/Ticket/TicketUsagePolicy.php create mode 100644 web/tests/TicketUsagePolicyTest.php diff --git a/web/app/Services/Ticket/TicketThreadService.php b/web/app/Services/Ticket/TicketThreadService.php index bfed8208..64ca5bc5 100644 --- a/web/app/Services/Ticket/TicketThreadService.php +++ b/web/app/Services/Ticket/TicketThreadService.php @@ -26,13 +26,15 @@ final class TicketThreadService ? $command->type : 'technical'; $priority = in_array($command->priority, ['high', 'medium', 'low'], true) ? $command->priority : 'medium'; + $fingerprints = TicketAttachmentService::fingerprints($command->request); + $attachmentBytes = $this->fingerprintBytes($fingerprints); $requestHash = $this->requestHash('open', [ 'title' => $title, 'content' => $content, 'type' => $type, 'priority' => $priority, 'instance_id' => $command->instanceId, - ], $command->request, $command->requestKey); + ], $fingerprints, $command->requestKey); $connection = (new Ticket())->getConnection(); $createdPaths = []; @@ -44,6 +46,7 @@ final class TicketThreadService $type, $priority, $requestHash, + $attachmentBytes, &$createdPaths ): TicketWriteResult { [$intent, $replay] = $this->claimIntent( @@ -56,6 +59,12 @@ final class TicketThreadService if ($replay !== null) { return $replay; } + (new TicketUsagePolicy())->assertOpen( + $command->actorId, + $title, + $content, + $attachmentBytes + ); $instanceId = $this->ownedInstanceId($command->actorId, $command->instanceId); $ticket = new Ticket(); $ticket->title = $title; @@ -93,11 +102,13 @@ final class TicketThreadService } $content = $this->cleanRequired($command->content, '请填写回复内容'); $event = $command->actorIsAdmin ? '管理员回复工单' : '用户回复工单'; + $fingerprints = TicketAttachmentService::fingerprints($command->request); + $attachmentBytes = $this->fingerprintBytes($fingerprints); $requestHash = $this->requestHash('reply', [ 'ticket_id' => $command->ticketId, 'content' => $content, 'status' => $command->status, - ], $command->request, $command->requestKey); + ], $fingerprints, $command->requestKey); $connection = (new Ticket())->getConnection(); $createdPaths = []; try { @@ -106,6 +117,7 @@ final class TicketThreadService $content, $event, $requestHash, + $attachmentBytes, &$createdPaths ): ?TicketWriteResult { [$intent, $replay] = $this->claimIntent( @@ -118,6 +130,12 @@ final class TicketThreadService if ($replay !== null) { return $replay; } + (new TicketUsagePolicy())->assertReply( + $command->actorId, + $content, + $attachmentBytes, + $command->actorIsAdmin + ); $query = Ticket::where('id', $command->ticketId)->where('rootid', 0); if ($command->ownerId !== null) { $query->where('userid', $command->ownerId); @@ -165,7 +183,7 @@ final class TicketThreadService private function requestHash( string $operation, array $payload, - mixed $request, + array $fingerprints, string $requestKey ): string { if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $requestKey) !== 1) { @@ -174,7 +192,7 @@ final class TicketThreadService $encoded = json_encode([ 'operation' => $operation, 'payload' => $payload, - 'attachments' => TicketAttachmentService::fingerprints($request), + 'attachments' => $fingerprints, ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if (!is_string($encoded)) { throw new \RuntimeException('工单请求摘要生成失败'); @@ -182,6 +200,15 @@ final class TicketThreadService return hash('sha256', $encoded); } + private function fingerprintBytes(array $fingerprints): int + { + $bytes = 0; + foreach ($fingerprints as $fingerprint) { + $bytes += (int) ($fingerprint['bytes'] ?? 0); + } + return $bytes; + } + /** * @return array{TicketWriteRequest, TicketWriteResult|null} */ diff --git a/web/app/Services/Ticket/TicketUsagePolicy.php b/web/app/Services/Ticket/TicketUsagePolicy.php new file mode 100644 index 00000000..4a787daa --- /dev/null +++ b/web/app/Services/Ticket/TicketUsagePolicy.php @@ -0,0 +1,95 @@ +assertFieldLengths($title, $content); + $this->lockUser($userId); + if (Ticket::where('userid', $userId)->where('rootid', 0)->where('status', 1)->count() + >= self::MAX_OPEN_TICKETS) { + throw new \InvalidArgumentException('最多同时保留 5 个处理中工单,请先等待处理或关闭旧工单'); + } + if (Ticket::where('userid', $userId)->where('rootid', 0) + ->where('datetime', '>=', time() - self::CREATE_RATE_WINDOW)->count() + >= self::CREATE_RATE_COUNT) { + throw new \InvalidArgumentException('工单提交过于频繁,请一小时后再试'); + } + $this->assertAttachmentQuota($userId, $newAttachmentBytes); + } + + public function assertReply( + int $userId, + string $content, + int $newAttachmentBytes, + bool $actorIsAdmin + ): void { + $this->assertFieldLengths('', $content); + if ($actorIsAdmin) { + return; + } + $this->lockUser($userId); + if (Ticket::where('userid', $userId)->where('rootid', '<>', 0) + ->where('datetime', '>=', time() - self::REPLY_RATE_WINDOW)->count() + >= self::REPLY_RATE_COUNT) { + throw new \InvalidArgumentException('工单回复过于频繁,请稍后再试'); + } + $this->assertAttachmentQuota($userId, $newAttachmentBytes); + } + + private function assertFieldLengths(string $title, string $content): void + { + if ($title !== '' && mb_strlen($title) > self::MAX_TITLE_CHARS) { + throw new \InvalidArgumentException('工单标题不能超过 120 个字符'); + } + if (mb_strlen($content) > self::MAX_CONTENT_CHARS) { + throw new \InvalidArgumentException('工单内容不能超过 10000 个字符'); + } + } + + private function lockUser(int $userId): void + { + $connection = (new Ticket())->getConnection(); + $connection->table('ticket_user_guards')->insertOrIgnore([ + 'user_id' => $userId, + 'updated_at' => time(), + ]); + $guard = $connection->table('ticket_user_guards') + ->where('user_id', $userId)->lockForUpdate()->first(); + if ($guard === null) { + throw new \RuntimeException('工单用户策略锁获取失败'); + } + $connection->table('ticket_user_guards')->where('user_id', $userId) + ->update(['updated_at' => time()]); + } + + private function assertAttachmentQuota(int $userId, int $newBytes): void + { + if ($newBytes <= 0) { + return; + } + $used = (int) TicketAttachment::where('user_id', $userId)->sum('bytes'); + if ($used + $newBytes > self::MAX_USER_ATTACHMENT_BYTES) { + throw new \InvalidArgumentException('工单附件总容量不能超过 100 MiB,请联系管理员清理旧工单附件'); + } + } +} diff --git a/web/tests/TicketIdempotencyTest.php b/web/tests/TicketIdempotencyTest.php index 03ce49aa..d8f54786 100644 --- a/web/tests/TicketIdempotencyTest.php +++ b/web/tests/TicketIdempotencyTest.php @@ -63,6 +63,10 @@ $schema->create('ticket_write_requests', static function (Blueprint $table): voi $table->integer('created_at'); $table->unique(['actor_user_id', 'request_key']); }); +$schema->create('ticket_user_guards', static function (Blueprint $table): void { + $table->integer('user_id')->primary(); + $table->integer('updated_at'); +}); $schema->create('cloud_instances', static function (Blueprint $table): void { $table->increments('id'); $table->integer('user_id'); diff --git a/web/tests/TicketReplyTransactionTest.php b/web/tests/TicketReplyTransactionTest.php index aa65c424..cef2593b 100644 --- a/web/tests/TicketReplyTransactionTest.php +++ b/web/tests/TicketReplyTransactionTest.php @@ -68,6 +68,10 @@ $schema->create('ticket_write_requests', static function (Blueprint $table): voi $table->integer('created_at'); $table->unique(['actor_user_id', 'request_key']); }); +$schema->create('ticket_user_guards', static function (Blueprint $table): void { + $table->integer('user_id')->primary(); + $table->integer('updated_at'); +}); $schema->create('cloud_instances', static function (Blueprint $table): void { $table->increments('id'); $table->integer('user_id'); diff --git a/web/tests/TicketUsagePolicyTest.php b/web/tests/TicketUsagePolicyTest.php new file mode 100644 index 00000000..f3d3f0b6 --- /dev/null +++ b/web/tests/TicketUsagePolicyTest.php @@ -0,0 +1,158 @@ +addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->getConnection('default')->getSchemaBuilder(); +$schema->create('ticket', static function (Blueprint $table): void { + $table->increments('id'); $table->text('title'); $table->text('content'); + $table->integer('rootid'); $table->integer('userid'); $table->integer('datetime'); + $table->integer('status'); $table->string('ticket_type'); $table->string('priority'); + $table->integer('instance_id')->nullable(); +}); +$schema->create('ticket_attachments', static function (Blueprint $table): void { + $table->increments('id'); $table->integer('ticket_id'); $table->integer('message_id'); + $table->integer('user_id'); $table->string('storage_key'); $table->string('original_name'); + $table->string('mime_type'); $table->integer('bytes'); $table->string('sha256'); + $table->integer('created_at'); +}); +$schema->create('ticket_write_requests', static function (Blueprint $table): void { + $table->increments('id'); $table->integer('actor_user_id'); $table->string('request_key'); + $table->string('request_hash'); $table->string('operation'); + $table->integer('ticket_id')->nullable(); $table->integer('message_id')->nullable(); + $table->integer('created_at'); $table->unique(['actor_user_id', 'request_key']); +}); +$schema->create('ticket_user_guards', static function (Blueprint $table): void { + $table->integer('user_id')->primary(); $table->integer('updated_at'); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); $table->integer('user_id'); $table->string('status'); +}); + +$now = time(); +for ($id = 1; $id <= 5; $id += 1) { + Capsule::table('ticket')->insert([ + 'id' => $id, 'title' => 'Open ' . $id, 'content' => 'x', 'rootid' => 0, + 'userid' => 7, 'datetime' => $now - $id, 'status' => 1, + 'ticket_type' => 'technical', 'priority' => 'medium', 'instance_id' => null, + ]); +} +$service = new TicketThreadService(); +try { + $service->open(new OpenTicketCommand( + 7, 'Sixth open ticket', 'Must fail', 'technical', 'medium', null, + $emptyRequest(), 'policy-open-limit-1' + )); + throw new RuntimeException('The sixth open ticket unexpectedly succeeded.'); +} catch (InvalidArgumentException $exception) { + $assert(str_contains($exception->getMessage(), '处理中工单'), + 'Open-ticket limit returned an unclear error.'); +} +$assert(Capsule::table('ticket')->count() === 5 + && Capsule::table('ticket_write_requests')->count() === 0, + 'A rejected policy write left a ticket or idempotency intent behind.'); + +Capsule::table('ticket')->where('userid', 7)->update(['status' => 0]); +try { + $service->open(new OpenTicketCommand( + 7, 'Rate limited', 'Must fail', 'technical', 'medium', null, + $emptyRequest(), 'policy-rate-limit-1' + )); + throw new RuntimeException('The create rate limit was not enforced.'); +} catch (InvalidArgumentException $exception) { + $assert(str_contains($exception->getMessage(), '提交过于频繁'), + 'Create rate limit returned an unclear error.'); +} + +try { + $service->open(new OpenTicketCommand( + 8, str_repeat('题', 121), 'Must fail', 'technical', 'medium', null, + $emptyRequest(), 'policy-title-limit-1' + )); + throw new RuntimeException('An overlong title unexpectedly succeeded.'); +} catch (InvalidArgumentException $exception) { + $assert(str_contains($exception->getMessage(), '120'), 'Title length error omitted its limit.'); +} + +// Administrators remain exempt from user reply rate and account attachment +// quota. Field and per-request file safety limits still apply. +Capsule::table('ticket')->insert([ + 'id' => 20, 'title' => 'Root', 'content' => 'x', 'rootid' => 0, 'userid' => 8, + 'datetime' => $now - 5000, 'status' => 1, 'ticket_type' => 'technical', + 'priority' => 'medium', 'instance_id' => null, +]); +for ($id = 21; $id <= 50; $id += 1) { + Capsule::table('ticket')->insert([ + 'id' => $id, 'title' => 'Root', 'content' => 'admin', 'rootid' => 20, + 'userid' => 9, 'datetime' => $now - 10, 'status' => 1, + 'ticket_type' => 'technical', 'priority' => 'medium', 'instance_id' => null, + ]); +} +$adminReply = $service->reply(new ReplyTicketCommand( + 20, 9, 'Allowed administrator reply', 1, $emptyRequest(), null, true, + 'policy-admin-reply-1' +)); +$assert($adminReply !== null && $adminReply->wasCreated, + 'Administrator reply was incorrectly blocked by user rate policy.'); + +$png = base64_decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk' + . 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=', + true +); +$uploadPath = tempnam(sys_get_temp_dir(), 'ticket-policy-upload-'); +if ($uploadPath === false || file_put_contents($uploadPath, $png) === false) { + throw new RuntimeException('Could not create quota upload fixture.'); +} +$uploadRequest = new class($uploadPath) { + public function __construct(private string $path) {} + public function getUploadedFiles(): array + { + return ['attachments' => [[ + 'name' => 'proof.png', 'tmp_name' => $this->path, + 'error' => UPLOAD_ERR_OK, 'size' => filesize($this->path), + 'type' => 'image/png', + ]]]; + } +}; +Capsule::table('ticket_attachments')->insert([ + 'ticket_id' => 999, 'message_id' => 999, 'user_id' => 11, + 'storage_key' => 'existing.png', 'original_name' => 'existing.png', + 'mime_type' => 'image/png', 'bytes' => 100 * 1024 * 1024, + 'sha256' => str_repeat('a', 64), 'created_at' => $now, +]); +try { + $service->open(new OpenTicketCommand( + 11, 'Quota', 'Must fail', 'technical', 'medium', null, + $uploadRequest, 'policy-quota-limit-1' + )); + throw new RuntimeException('Attachment account quota was not enforced.'); +} catch (InvalidArgumentException $exception) { + $assert(str_contains($exception->getMessage(), '100 MiB'), + 'Attachment quota returned an unclear error.'); +} +$assert(Capsule::table('ticket')->where('userid', 11)->count() === 0 + && Capsule::table('ticket_write_requests')->where('actor_user_id', 11)->count() === 0, + 'An attachment-quota rejection left durable write state behind.'); +@unlink($uploadPath); + +echo "Ticket usage policy checks passed.\n";