using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Infrastructure.Correlation; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ClassNotify.Server.Services; /// /// 设备技术诊断包服务实现 (P2.5 RC1-3 Support Bundle Phase 1, Phase 2, Phase 3) /// 严格满足 RBAC、客户端幂等性、单 Active 互斥、事务与审计一致性、安全下载与生命周期管理 /// public class SupportBundleService : ISupportBundleService { private static readonly ConcurrentDictionary _creationLocks = new(); private readonly ClassNotifyDbContext _db; private readonly ICorrelationContext _correlationContext; private readonly ISupportBundleDispatchNotifier _dispatchNotifier; private readonly IOptions _options; private readonly ILogger _logger; public SupportBundleService( ClassNotifyDbContext db, ICorrelationContext correlationContext, ISupportBundleDispatchNotifier dispatchNotifier, IOptions options, ILogger logger) { _db = db; _correlationContext = correlationContext; _dispatchNotifier = dispatchNotifier; _options = options; _logger = logger; } public async Task CreateSupportBundleAsync( string deviceId, CreateSupportBundleRequest request, string actorUserId, string actorRole, string? actorTenantId, string actorIp, bool simulateAuditFailure, CancellationToken ct) { if (string.IsNullOrWhiteSpace(deviceId)) { return SupportBundleCreationResult.BadRequest("DeviceId 不可为空。"); } if (request == null) { request = new CreateSupportBundleRequest(); } if (string.IsNullOrWhiteSpace(request.ClientRequestId)) { request.ClientRequestId = Guid.NewGuid().ToString("N"); } var lockKey = $"{actorUserId}:{request.ClientRequestId}"; var gate = _creationLocks.GetOrAdd(lockKey, _ => new SemaphoreSlim(1, 1)); await gate.WaitAsync(ct); try { // 1. Load Device var device = await _db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId, ct); if (device == null) { return SupportBundleCreationResult.NotFound($"设备 '{deviceId}' 不存在。"); } // 2. Authorize // SuperAdmin: 全局允许 // SchoolAdmin: 严格限定同校 JWT TenantId == Device.TenantId // Teacher / 其它: 403 if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, device.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin {User} (Tenant={UserTenant}) attempted to request support bundle for device {DeviceId} (Tenant={DeviceTenant}). 403 Forbidden.", actorUserId, actorTenantId, device.Id, device.TenantId); return SupportBundleCreationResult.Forbidden("跨租户技术诊断包请求被拒绝。"); } } else if (actorRole != "SuperAdmin") { _logger.LogWarning("User {User} with role {Role} attempted to request support bundle. 403 Forbidden.", actorUserId, actorRole); return SupportBundleCreationResult.Forbidden("仅允许系统管理员或学校管理员发起技术诊断包请求。"); } // 3. Idempotency Check: Same ClientRequestId by same user returns existing bundle var existing = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.RequestedByUserId == actorUserId && sb.ClientRequestId == request.ClientRequestId, ct); if (existing != null) { _logger.LogInformation("Idempotent hit for support bundle ClientRequestId={ClientRequestId}, returning existing BundleId={BundleId}", request.ClientRequestId, existing.Id); return SupportBundleCreationResult.Accepted(new SupportBundleCreatedDto { SupportBundleId = existing.Id, DeviceId = existing.DeviceId, Status = existing.Status, CreatedAtUtc = existing.CreatedAtUtc, DeadlineAtUtc = existing.DeadlineAtUtc, CorrelationId = existing.CorrelationId }); } // 4. Active Bundle Check: 同一设备同一时间只允许一个正在生成的 Support Bundle (PendingDispatch 或 Collecting) var existingActive = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.DeviceId == device.Id && (sb.Status == SupportBundleStatuses.PendingDispatch || sb.Status == SupportBundleStatuses.Collecting), ct); if (existingActive != null) { _logger.LogWarning("Device {DeviceId} already has active support bundle {ActiveBundleId} in state {State}. 409 Conflict.", device.Id, existingActive.Id, existingActive.Status); return SupportBundleCreationResult.Conflict( SupportBundleErrorCodes.SupportBundleAlreadyRunning, existingActive.Id, $"设备 '{device.Id}' 当前已有正在收集中的技术诊断包 ({existingActive.Id})。"); } // 5. Begin Transaction: DeviceSupportBundle + SUPPORT_BUNDLE_REQUESTED Audit 原子落库 var now = DateTimeOffset.UtcNow; var bundleId = $"sb_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var correlationId = !string.IsNullOrWhiteSpace(_correlationContext.CorrelationId) ? _correlationContext.CorrelationId : $"sb_corr_{Guid.NewGuid():N}"[..20]; var bundle = new DeviceSupportBundle { Id = bundleId, ClientRequestId = request.ClientRequestId, TenantId = device.TenantId, DeviceId = device.Id, CorrelationId = correlationId, RequestedByUserId = actorUserId, Status = SupportBundleStatuses.PendingDispatch, CreatedAtUtc = now, UpdatedAtUtc = now, DeadlineAtUtc = now.AddMinutes(2), // 固定第一版 CreatedAtUtc + 2 minutes NextDispatchAttemptAtUtc = now, DispatchAttemptCount = 0, StoragePath = null, SizeBytes = null, Sha256 = null, ExpiresAtUtc = null, ErrorCode = null }; var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUserId, ActorRole = actorRole, Action = "SUPPORT_BUNDLE_REQUESTED", TargetType = "DeviceSupportBundle", TargetId = bundle.Id, Details = JsonSerializer.Serialize(new { supportBundleId = bundle.Id, tenantId = bundle.TenantId, deviceId = bundle.DeviceId }), IpAddress = actorIp }; await using var tx = await _db.Database.BeginTransactionAsync(ct); try { _db.DeviceSupportBundles.Add(bundle); if (simulateAuditFailure) { throw new InvalidOperationException("Simulated audit failure for testing atomic transaction rollback"); } _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); await tx.CommitAsync(ct); } catch (DbUpdateException dbEx) { _logger.LogWarning(dbEx, "DbUpdateException during support bundle creation. Checking for concurrent collision."); // 检查幂等性冲突 (ClientRequestId + RequestedByUserId) var collisionExisting = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.RequestedByUserId == actorUserId && sb.ClientRequestId == request.ClientRequestId, ct); if (collisionExisting != null) { return SupportBundleCreationResult.Accepted(new SupportBundleCreatedDto { SupportBundleId = collisionExisting.Id, DeviceId = collisionExisting.DeviceId, Status = collisionExisting.Status, CreatedAtUtc = collisionExisting.CreatedAtUtc, DeadlineAtUtc = collisionExisting.DeadlineAtUtc, CorrelationId = collisionExisting.CorrelationId }); } // 检查单 Active 唯一约束冲突 (UX_DeviceSupportBundles_Device_Active) var collisionActive = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.DeviceId == device.Id && (sb.Status == SupportBundleStatuses.PendingDispatch || sb.Status == SupportBundleStatuses.Collecting), ct); if (collisionActive != null) { return SupportBundleCreationResult.Conflict( SupportBundleErrorCodes.SupportBundleAlreadyRunning, collisionActive.Id, $"设备 '{device.Id}' 当前已有正在收集中的技术诊断包 ({collisionActive.Id})。"); } throw; } catch (Exception ex) { _logger.LogError(ex, "Transaction failed while creating support bundle {BundleId}. Rolled back.", bundle.Id); throw; } _logger.LogInformation("Support bundle requested successfully: BundleId={BundleId}, DeviceId={DeviceId}, TenantId={TenantId}, CorrelationId={CorrelationId}", bundle.Id, bundle.DeviceId, bundle.TenantId, bundle.CorrelationId); // 6. Post-commit: 唤醒后台调度 Worker _dispatchNotifier.Notify(); return SupportBundleCreationResult.Accepted(new SupportBundleCreatedDto { SupportBundleId = bundle.Id, DeviceId = bundle.DeviceId, Status = bundle.Status, CreatedAtUtc = bundle.CreatedAtUtc, DeadlineAtUtc = bundle.DeadlineAtUtc, CorrelationId = bundle.CorrelationId }); } finally { gate.Release(); } } public async Task GetSupportBundleAsync(string bundleId, string actorRole, string? actorTenantId, CancellationToken ct) { var bundle = await _db.DeviceSupportBundles.AsNoTracking().FirstOrDefaultAsync(b => b.Id == bundleId, ct); if (bundle == null) return null; if (actorRole == "SchoolAdmin" && !string.Equals(actorTenantId, bundle.TenantId, StringComparison.OrdinalIgnoreCase)) { return null; // 租户越界静默拦截或 404 } return new SupportBundleDetailDto { SupportBundleId = bundle.Id, DeviceId = bundle.DeviceId, TenantId = bundle.TenantId, CorrelationId = bundle.CorrelationId, RequestedByUserId = bundle.RequestedByUserId, Status = bundle.Status, CreatedAtUtc = bundle.CreatedAtUtc, UpdatedAtUtc = bundle.UpdatedAtUtc, DeadlineAtUtc = bundle.DeadlineAtUtc, DispatchedAtUtc = bundle.DispatchedAtUtc, CompletedAtUtc = bundle.CompletedAtUtc, ExpiresAtUtc = bundle.ExpiresAtUtc, DispatchAttemptCount = bundle.DispatchAttemptCount, StoragePath = bundle.StoragePath, SizeBytes = bundle.SizeBytes, Sha256 = bundle.Sha256, ErrorCode = bundle.ErrorCode }; } public async Task> GetSupportBundleStatusAsync( string bundleId, string actorRole, string? actorTenantId, CancellationToken ct) { var bundle = await _db.DeviceSupportBundles.AsNoTracking().FirstOrDefaultAsync(b => b.Id == bundleId, ct); if (bundle == null) { return SupportBundleQueryResult.NotFound($"Support bundle '{bundleId}' not found."); } if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, bundle.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin (Tenant={UserTenant}) attempted cross-tenant status query for bundle {BundleId} (Tenant={BundleTenant}). 403 Forbidden.", actorTenantId, bundle.Id, bundle.TenantId); return SupportBundleQueryResult.Forbidden("跨租户技术诊断包查询被拒绝。"); } } else if (actorRole != "SuperAdmin") { return SupportBundleQueryResult.Forbidden("仅允许系统管理员或学校管理员查询技术诊断包。"); } var now = DateTimeOffset.UtcNow; bool isDownloadAvailable = bundle.Status == SupportBundleStatuses.Available && bundle.ExpiresAtUtc.HasValue && bundle.ExpiresAtUtc.Value > now; var dto = new SupportBundleStatusDto { SupportBundleId = bundle.Id, DeviceId = bundle.DeviceId, TenantId = bundle.TenantId, Status = bundle.Status, CreatedAtUtc = bundle.CreatedAtUtc, CompletedAtUtc = bundle.CompletedAtUtc, ExpiresAtUtc = bundle.ExpiresAtUtc, SizeBytes = bundle.SizeBytes, Sha256 = bundle.Sha256, DownloadAvailable = isDownloadAvailable, ErrorCode = bundle.ErrorCode }; return SupportBundleQueryResult.Ok(dto); } public async Task>> GetDeviceSupportBundlesAsync( string deviceId, int take, string actorRole, string? actorTenantId, CancellationToken ct) { var device = await _db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId, ct); if (device == null) { return SupportBundleQueryResult>.NotFound($"Device '{deviceId}' not found."); } if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, device.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin (Tenant={UserTenant}) attempted cross-tenant device bundles query for device {DeviceId} (Tenant={DeviceTenant}). 403 Forbidden.", actorTenantId, device.Id, device.TenantId); return SupportBundleQueryResult>.Forbidden("跨租户设备诊断包列表查询被拒绝。"); } } else if (actorRole != "SuperAdmin") { return SupportBundleQueryResult>.Forbidden("仅允许系统管理员或学校管理员查询技术诊断包。"); } var clampedTake = Math.Clamp(take <= 0 ? 5 : take, 1, 20); var now = DateTimeOffset.UtcNow; var bundles = await _db.DeviceSupportBundles .AsNoTracking() .Where(b => b.DeviceId == deviceId) .OrderByDescending(b => b.CreatedAtUtc) .Take(clampedTake) .Select(b => new SupportBundleStatusDto { SupportBundleId = b.Id, DeviceId = b.DeviceId, TenantId = b.TenantId, Status = b.Status, CreatedAtUtc = b.CreatedAtUtc, CompletedAtUtc = b.CompletedAtUtc, ExpiresAtUtc = b.ExpiresAtUtc, SizeBytes = b.SizeBytes, Sha256 = b.Sha256, DownloadAvailable = b.Status == SupportBundleStatuses.Available && b.ExpiresAtUtc.HasValue && b.ExpiresAtUtc.Value > now, ErrorCode = b.ErrorCode }) .ToListAsync(ct); return SupportBundleQueryResult>.Ok(bundles); } public async Task PrepareDownloadAsync( string bundleId, string actorRole, string? actorTenantId, string actorUser, string actorIp, CancellationToken ct) { // 1. 加载诊断包记录 var bundle = await _db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == bundleId, ct); if (bundle == null) { return SupportBundleDownloadResult.NotFound($"Support bundle '{bundleId}' not found."); } // 2. 权限校验 if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, bundle.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin {User} (Tenant={UserTenant}) attempted cross-tenant download for bundle {BundleId} (Tenant={BundleTenant}). 403 Forbidden.", actorUser, actorTenantId, bundle.Id, bundle.TenantId); return SupportBundleDownloadResult.Forbidden("跨校技术诊断包下载被拒绝。"); } } else if (actorRole != "SuperAdmin") { return SupportBundleDownloadResult.Forbidden("仅允许系统管理员或学校管理员下载技术诊断包。"); } // 3. 状态与有效期检查 if (bundle.Status == SupportBundleStatuses.PendingDispatch || bundle.Status == SupportBundleStatuses.Collecting) { return SupportBundleDownloadResult.Conflict(SupportBundleErrorCodes.BundleNotReady, $"Support bundle is currently in state '{bundle.Status}' and not ready for download."); } if (bundle.Status == SupportBundleStatuses.Failed) { return SupportBundleDownloadResult.Conflict(SupportBundleErrorCodes.BundleFailed, "Support bundle collection failed and cannot be downloaded."); } if (bundle.Status == SupportBundleStatuses.TimedOut || bundle.Status == SupportBundleStatuses.Expired) { return SupportBundleDownloadResult.Gone(SupportBundleErrorCodes.BundleExpired, $"Support bundle is in terminal state '{bundle.Status}' and cannot be downloaded."); } var now = DateTimeOffset.UtcNow; if (bundle.ExpiresAtUtc.HasValue && bundle.ExpiresAtUtc.Value <= now) { return SupportBundleDownloadResult.Gone(SupportBundleErrorCodes.BundleExpired, "Support bundle has expired (retention period exceeded)."); } if (bundle.Status != SupportBundleStatuses.Available) { return SupportBundleDownloadResult.Conflict(SupportBundleErrorCodes.BundleNotReady, $"Support bundle is in state '{bundle.Status}' and cannot be downloaded."); } if (string.IsNullOrWhiteSpace(bundle.StoragePath)) { return SupportBundleDownloadResult.ServerError(SupportBundleErrorCodes.SupportBundleFileMissing, "Support bundle record has no StoragePath."); } // 4. Storage Root Confinement (Strict Relative Path & Path Traversal Protection) var root = _options.Value.GetEffectiveStorageRoot(); string candidatePath; try { candidatePath = SupportBundlePathResolver.ResolveBundlePath(root, bundle.StoragePath); } catch (InvalidStoragePathException ex) { _logger.LogWarning("CRITICAL: Storage path validation failed for bundle {BundleId}: {Message} (StoragePath='{Path}')", bundle.Id, ex.Message, bundle.StoragePath); return SupportBundleDownloadResult.BadRequest(SupportBundleErrorCodes.InvalidStoragePath, "Invalid storage path detected."); } catch (Exception ex) { _logger.LogWarning(ex, "Unexpected error resolving StoragePath '{StoragePath}' for bundle {BundleId}", bundle.StoragePath, bundle.Id); return SupportBundleDownloadResult.BadRequest(SupportBundleErrorCodes.InvalidStoragePath, "Invalid storage path detected."); } // 5. Physical File Existence Check if (!File.Exists(candidatePath)) { _logger.LogError("Support bundle file missing from disk! BundleId={BundleId}, Path={StoragePath}, ExpectedSha256={Sha256}", bundle.Id, bundle.StoragePath, bundle.Sha256); return SupportBundleDownloadResult.ServerError(SupportBundleErrorCodes.SupportBundleFileMissing, "Support bundle file missing from storage."); } // 6. Audit Logging: 仅当成功授权并准备提供下载时写入 SUPPORT_BUNDLE_DOWNLOADED var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "SUPPORT_BUNDLE_DOWNLOADED", TargetType = "DeviceSupportBundle", TargetId = bundle.Id, Details = JsonSerializer.Serialize(new { supportBundleId = bundle.Id, tenantId = bundle.TenantId, deviceId = bundle.DeviceId, sizeBytes = bundle.SizeBytes, sha256 = bundle.Sha256 }), IpAddress = actorIp }; _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); var downloadFileName = $"classnotify-support-{bundle.DeviceId}-{bundle.CreatedAtUtc:yyyyMMdd-HHmm}.zip"; return SupportBundleDownloadResult.Success(candidatePath, downloadFileName); } }