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/app/Services/UserDataDeletionService.php

372 lines
16 KiB
PHP

<?php
namespace App\Services;
use App\Models\EmailLog;
use App\Models\TicketAttachment;
use App\Services\TicketAttachmentService;
use App\Models\User;
class UserDataDeletionService
{
private const USER_REFERENCES = [
['checkout_apply', 'userid'], ['code', 'userid'],
['login_ip', 'userid'], ['payback', 'userid'], ['payback', 'ref_by'],
['paylist', 'userid'], ['ss_invite_code', 'user_id'], ['ticket', 'userid'],
['user_survey_responses', 'user_id'],
['cloud_ssh_keys', 'user_id'], ['cloud_sessions', 'user_id'],
// Delete cloud history from dependants to parents after the active VM,
// order and payment guards above have proved the account is safe to
// remove. cloud_jobs may contain encrypted provisioning credentials.
['cloud_jobs', 'user_id'], ['cloud_instance_snapshots', 'user_id'],
['cloud_instance_firewalls', 'user_id'],
['cloud_backup_period_entitlements', 'user_id'],
['cloud_service_periods', 'user_id'],
['cloud_renewals', 'user_id'], ['cloud_invoice_payments', 'user_id'],
['cloud_invoices', 'user_id'], ['cloud_orders', 'user_id'],
['cloud_instances', 'user_id'],
];
private const EMAIL_REFERENCES = [
['checkout_apply', 'email'], ['email_verify', 'email'], ['ss_password_reset', 'email'],
];
private $schemaCache = [];
public function deleteUsers(array $userIds, $cleanupCaches = true)
{
$requested = $this->normalizeIds($userIds);
if ($requested === []) {
return $this->emptyResult();
}
$connection = (new User())->getConnection();
$result = $connection->transaction(function () use ($connection, $requested) {
// Row locks and a second non-admin condition protect concurrent promotion.
$users = User::whereIn('id', $requested)->where('is_admin', 0)->lockForUpdate()->get();
if ($users->isEmpty()) {
return $this->emptyResult($requested);
}
$ids = [];
$emails = [];
foreach ($users as $user) {
$ids[] = (int) $user->id;
$emails[] = strtolower(trim((string) $user->email));
}
// Account deletion must never orphan a VM or an in-flight purchase.
if ($connection->getSchemaBuilder()->hasTable('cloud_instances')
&& $connection->table('cloud_instances')->whereIn('user_id', $ids)
->where('status', '!=', 'deleted')->exists()) {
throw new \RuntimeException('用户仍有云服务器,请先删除或转交实例后再删除账户');
}
if ($connection->getSchemaBuilder()->hasTable('cloud_orders')
&& $connection->table('cloud_orders')->whereIn('user_id', $ids)
->whereIn('status', ['awaiting_payment', 'queued'])
->exists()) {
throw new \RuntimeException('用户仍有开通中的订单,请先处理订单后再删除账户');
}
$this->assertNoCloudTaskFence($connection, $ids);
foreach ([
['cloud_invoice_payments', ['creating', 'pending', 'creation_unknown']],
['yipay_orders', ['creating', 'pending', 'creation_unknown']],
['paytaro_orders', ['creating', 'pending', 'creation_unknown']],
['usdt_payment_orders', ['pending', 'expired']],
] as [$table, $statuses]) {
if ($this->hasColumns($connection, $table, ['user_id', 'status'])
&& $connection->table($table)->whereIn('user_id', $ids)
->whereIn('status', $statuses)->exists()) {
throw new \RuntimeException(
'用户仍有支付安全栅栏,请先完成网关或链上状态处理');
}
}
foreach ($users as $user) {
LoginSessionRevocationService::revokeUser($user);
}
$emails = array_values(array_unique(array_filter($emails, 'strlen')));
if ($this->hasColumns($connection, 'cloud_invoices', ['id', 'user_id'])) {
$invoiceIds = $connection->table('cloud_invoices')
->whereIn('user_id', $ids)->pluck('id')->all();
$deletedMailRows = $this->deleteWhereIn(
$connection, 'cloud_mail_outbox', 'invoice_id', $invoiceIds);
} else {
$deletedMailRows = 0;
}
// The log database has its own transaction; this is not distributed atomicity.
// Log unavailability aborts deletion before the default database is changed.
$logRows = $this->deleteLogRecords($ids, $emails);
// cloud_jobs.user_id is the audited actor. A super administrator
// may therefore own the job row while its instance/snapshot still
// belongs to the tenant being deleted. Remove those resource-bound
// jobs before their parent rows so encrypted owner/VM payloads do
// not survive as orphaned administrator audit records.
$resourceJobRows = $this->deleteCloudResourceJobs($connection, $ids);
$rows = $deletedMailRows + $resourceJobRows
+ $this->deleteRelatedRecords($connection, $ids, $emails);
$deleted = (int) User::whereIn('id', $ids)->where('is_admin', 0)->delete();
if ($deleted !== count($ids)) {
throw new \RuntimeException('用户状态发生变化,删除已取消');
}
return [
'deleted' => $deleted, 'deleted_user_ids' => $ids,
'skipped_user_ids' => array_values(array_diff($requested, $ids)),
'default_rows_deleted' => $rows, 'log_rows_deleted' => $logRows, 'cache_error' => false,
];
}, 3);
if ($result['deleted'] > 0 && $cleanupCaches) {
$result['cache_error'] = !$this->cleanupCaches($result['deleted_user_ids']);
}
return $result;
}
/**
* Lock every task that can still own work or an unresolved side effect.
* The cloud_jobs -> user foreign key serializes new owner-scoped inserts
* with the locked user rows above; resource-owned administrator jobs are
* included explicitly through instance and snapshot identifiers.
*/
private function assertNoCloudTaskFence($connection, array $userIds): void
{
if (!$this->hasColumns($connection, 'cloud_jobs', [
'id', 'user_id', 'instance_id', 'snapshot_id', 'phase',
'outcome', 'effect_resolution',
])) {
return;
}
$instanceIds = $this->pluckByUsers(
$connection, 'cloud_instances', 'user_id', $userIds, 'id'
);
$snapshotIds = $this->pluckByUsers(
$connection, 'cloud_instance_snapshots', 'user_id', $userIds, 'id'
);
$jobs = $connection->table('cloud_jobs')
->where(function ($owner) use ($userIds, $instanceIds,
$snapshotIds): void {
$owner->whereIn('user_id', $userIds);
if ($instanceIds !== []) {
$owner->orWhereIn('instance_id', $instanceIds);
}
if ($snapshotIds !== []) {
$owner->orWhereIn('snapshot_id', $snapshotIds);
}
})
->where(function ($unsafe): void {
$unsafe->where('phase', '<>', 'terminal')
->orWhere(function ($unknown): void {
$unknown->where('phase', 'terminal')
->where('outcome', 'failed')
->where('effect_resolution', 'unknown');
});
})
->orderBy('id')->lockForUpdate()->get(['id']);
if (!$jobs->isEmpty()) {
throw new \RuntimeException(
'用户仍有执行中任务或资源安全栅栏,请先完成任务侧安全处理'
);
}
}
private function deleteRelatedRecords($connection, array $ids, array $emails)
{
$deleted = 0;
foreach ([
['yipay_orders', [['yipay_refunds', 'order_no'], ['yipay_callback_events', 'order_no']]],
['paytaro_orders', [['paytaro_callback_events', 'order_no']]],
['usdt_payment_orders', [['usdt_chain_transactions', 'order_no']]],
] as [$table, $references]) {
$orders = $this->pluckByUsers($connection, $table, 'user_id', $ids, 'order_no');
foreach ($references as [$dependentTable, $column]) {
$deleted += $this->deleteWhereIn($connection, $dependentTable, $column, $orders);
}
$deleted += $this->deleteWhereIn($connection, $table, 'user_id', $ids);
}
if ($this->hasColumns($connection, 'user', ['ref_by'])) {
$connection->table('user')->whereIn('ref_by', $ids)->update(['ref_by' => 0]);
}
if ($this->hasColumns($connection, 'ticket', ['id', 'userid', 'rootid'])) {
$roots = $connection->table('ticket')->whereIn('userid', $ids)->where('rootid', 0)->pluck('id')->all();
if ($roots !== [] && $this->hasColumns($connection, 'ticket_attachments', ['id', 'ticket_id'])) {
foreach (TicketAttachment::whereIn('ticket_id', $roots)->get() as $attachment) {
TicketAttachmentService::remove($attachment);
}
}
$deleted += $this->deleteWhereIn($connection, 'ticket', 'rootid', $roots);
}
$deleted += $this->deleteWhereIn($connection, 'ticket_attachments', 'user_id', $ids);
// Firewall rules and immutable versions have no direct user_id. Resolve
// them through both the policy and instance while those parent rows
// still exist, then delete children before USER_REFERENCES removes the
// policy and instance audit rows.
$firewallInstanceIds = array_values(array_unique(array_merge(
$this->pluckByUsers($connection, 'cloud_instances', 'user_id',
$ids, 'id'),
$this->pluckByUsers($connection, 'cloud_instance_firewalls',
'user_id', $ids, 'instance_id')
)));
$firewallVersionIds = $this->pluckByUsers(
$connection, 'cloud_instance_firewall_versions', 'instance_id',
$firewallInstanceIds, 'id'
);
$deleted += $this->deleteWhereIn($connection,
'cloud_instance_firewall_rules', 'version_id', $firewallVersionIds);
$deleted += $this->deleteWhereIn($connection,
'cloud_instance_firewall_versions', 'instance_id',
$firewallInstanceIds);
foreach (self::USER_REFERENCES as [$table, $column]) {
$deleted += $this->deleteWhereIn($connection, $table, $column, $ids);
}
foreach (self::EMAIL_REFERENCES as [$table, $column]) {
$deleted += $this->deleteWhereIn($connection, $table, $column, $emails);
}
// Manual email blacklist configuration is deliberately never changed.
return $deleted;
}
private function deleteCloudResourceJobs($connection, array $userIds): int
{
if (!$this->hasColumns($connection, 'cloud_jobs', ['id'])) {
return 0;
}
$instanceIds = $this->pluckByUsers(
$connection, 'cloud_instances', 'user_id', $userIds, 'id'
);
$snapshotIds = $this->pluckByUsers(
$connection, 'cloud_instance_snapshots', 'user_id', $userIds, 'id'
);
$hasInstance = $instanceIds !== []
&& $this->hasColumns($connection, 'cloud_jobs', ['instance_id']);
$hasSnapshot = $snapshotIds !== []
&& $this->hasColumns($connection, 'cloud_jobs', ['snapshot_id']);
if (!$hasInstance && !$hasSnapshot) {
return 0;
}
return (int) $connection->table('cloud_jobs')
->where(function ($query) use ($hasInstance, $instanceIds,
$hasSnapshot, $snapshotIds): void {
if ($hasInstance) {
$query->whereIn('instance_id', $instanceIds);
}
if ($hasSnapshot) {
$method = $hasInstance ? 'orWhereIn' : 'whereIn';
$query->{$method}('snapshot_id', $snapshotIds);
}
})->delete();
}
private function deleteLogRecords(array $ids, array $emails)
{
if (Config::get('enable_log', 'false') !== 'true') {
return 0;
}
$connection = (new EmailLog())->getConnection();
return $connection->transaction(function () use ($connection, $ids, $emails) {
$deleted = 0;
foreach (['site_visit_events', 'site_security_events'] as $table) {
$deleted += $this->deleteWhereIn($connection, $table, 'user_id', $ids);
}
$deleted += $this->deleteWhereIn($connection, 'user_email_log', 'email', $emails);
return $deleted;
}, 3);
}
private function pluckByUsers($connection, $table, $column, array $ids, $valueColumn)
{
if ($ids === [] || !$this->hasColumns($connection, $table, [$column, $valueColumn])) {
return [];
}
return $connection->table($table)->whereIn($column, $ids)->pluck($valueColumn)->all();
}
private function deleteWhereIn($connection, $table, $column, array $values)
{
if ($values === [] || !$this->hasColumns($connection, $table, [$column])) {
return 0;
}
return (int) $connection->table($table)->whereIn($column, $values)->delete();
}
private function hasColumns($connection, $table, array $columns)
{
$key = $connection->getName() . ':' . $table;
if (!array_key_exists($key, $this->schemaCache)) {
$this->schemaCache[$key] = $connection->getSchemaBuilder()->hasTable($table);
}
if (!$this->schemaCache[$key]) {
return false;
}
foreach ($columns as $column) {
$columnKey = $key . ':' . $column;
if (!array_key_exists($columnKey, $this->schemaCache)) {
$this->schemaCache[$columnKey] = $connection->getSchemaBuilder()->hasColumn($table, $column);
}
if (!$this->schemaCache[$columnKey]) {
return false;
}
}
return true;
}
private function cleanupCaches(array $ids)
{
$wanted = array_fill_keys($ids, true);
try {
$redis = new RedisClient();
$keys = [];
foreach ([
['trusted_login_device:*', '/^trusted_login_device:(\d+):/'],
['login_email_code_fail:*', '/^login_email_code_fail:(\d+):/'],
['login_ga_code_fail:*', '/^login_ga_code_fail:(\d+):/'],
] as [$pattern, $expression]) {
foreach ($this->scanKeys($redis->getClient(), $pattern) as $key) {
if (preg_match($expression, $key, $match) === 1 && isset($wanted[(int) $match[1]])) {
$keys[] = $key;
}
}
}
$redis->deleteMultiple(array_unique($keys));
return true;
} catch (\Throwable $exception) {
error_log('Deleted account cache cleanup failed: ' . get_class($exception));
return false;
}
}
private function scanKeys($client, $pattern)
{
$cursor = '0';
$keys = [];
do {
$result = $client->executeRaw(['SCAN', $cursor, 'MATCH', $pattern, 'COUNT', '500']);
if (!is_array($result) || count($result) !== 2) {
throw new \RuntimeException('Invalid Redis SCAN response');
}
$cursor = (string) $result[0];
foreach (is_array($result[1]) ? $result[1] : [] as $key) {
$keys[] = (string) $key;
}
} while ($cursor !== '0');
return array_unique($keys);
}
private function normalizeIds(array $ids)
{
$result = [];
foreach ($ids as $id) {
$value = is_int($id) || is_string($id) ? filter_var($id, FILTER_VALIDATE_INT) : false;
if ($value !== false && $value > 0) {
$result[$value] = $value;
}
}
return array_values($result);
}
private function emptyResult(array $requested = [])
{
return [
'deleted' => 0, 'deleted_user_ids' => [], 'skipped_user_ids' => $requested,
'default_rows_deleted' => 0, 'log_rows_deleted' => 0, 'cache_error' => false,
];
}
}