using System.Collections.Concurrent; using System.Security.Claims; using System.Security.Cryptography; using System.Threading; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; public class VisualReceiptService : IVisualReceiptService { private static readonly ConcurrentDictionary _receiptLocks = new(); private readonly IServiceScopeFactory _scopeFactory; private readonly ISecurityService _securityService; private readonly IConfiguration _configuration; private readonly ILogger _logger; private readonly string _storageBasePath; public VisualReceiptService( IServiceScopeFactory scopeFactory, ISecurityService securityService, IConfiguration configuration, ILogger logger) { _scopeFactory = scopeFactory; _securityService = securityService; _configuration = configuration; _logger = logger; // Path resolution: config > /var/lib/classnotify/visual-receipts (if linux directory exists or creatable) > AppContext.BaseDirectory var configuredPath = _configuration.GetValue("VisualReceipt:StoragePath"); if (!string.IsNullOrWhiteSpace(configuredPath)) { _storageBasePath = configuredPath; } else if (OperatingSystem.IsLinux()) { _storageBasePath = "/var/lib/classnotify/visual-receipts"; } else { _storageBasePath = Path.Combine(AppContext.BaseDirectory, "visual_receipts"); } try { Directory.CreateDirectory(_storageBasePath); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to create visual receipts storage directory at {Path}, falling back to temp directory.", _storageBasePath); _storageBasePath = Path.Combine(Path.GetTempPath(), "classnotify_visual_receipts"); Directory.CreateDirectory(_storageBasePath); } } public async Task SaveVisualReceiptAsync( string notificationId, string deviceId, string deviceToken, byte[] jpegBytes) { if (string.IsNullOrWhiteSpace(notificationId) || string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken)) { return new VisualReceiptUploadResult(false, "缺少必要参数或凭据", 400); } // 1. Payload size check (Max 512 KiB) if (jpegBytes == null || jpegBytes.Length == 0) { return new VisualReceiptUploadResult(false, "图片数据为空", 400); } if (jpegBytes.Length > 524288) { return new VisualReceiptUploadResult(false, "图片文件超过 512 KiB 大小限制", 413); } // 2. JPEG magic bytes check: Starts with 0xFF 0xD8, Ends with 0xFF 0xD9 if (jpegBytes.Length < 4 || jpegBytes[0] != 0xFF || jpegBytes[1] != 0xD8 || jpegBytes[^2] != 0xFF || jpegBytes[^1] != 0xD9) { return new VisualReceiptUploadResult(false, "上传内容不是合法的 JPEG 格式图像", 415); } // 3. Authenticate device token var device = await _securityService.ValidateDeviceAsync(deviceId, deviceToken); if (device == null || !device.IsActive) { return new VisualReceiptUploadResult(false, "设备凭据无效或设备已被禁用", 401); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // 4. Validate Notification and NotificationReceipt attribution var notification = await db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == notificationId); if (notification == null) { return new VisualReceiptUploadResult(false, "目标通知不存在", 404); } // Defense in depth: Check tenant and class isolation if (notification.TenantId != device.TenantId || notification.ClassroomId != device.ClassroomId) { _logger.LogWarning("Cross-tenant/class visual receipt upload spoofing attempt: Device {DevId} ({DevTenant}/{DevClass}) vs Notif {NotifId} ({NotifTenant}/{NotifClass})", deviceId, device.TenantId, device.ClassroomId, notificationId, notification.TenantId, notification.ClassroomId); return new VisualReceiptUploadResult(false, "设备归属与通知目标班级不匹配", 403); } var receipt = await db.NotificationReceipts.FirstOrDefaultAsync(r => r.NotificationId == notificationId && r.DeviceId == deviceId); if (receipt == null) { return new VisualReceiptUploadResult(false, "该设备未被分配此通知回执记录", 403); } // 5. Concurrency & Idempotency: First Successful Receipt Wins with Per-Receipt Mutex var receiptLock = _receiptLocks.GetOrAdd(receipt.Id, _ => new SemaphoreSlim(1, 1)); await receiptLock.WaitAsync(); try { // Fresh check from database inside mutex var currentReceipt = await db.NotificationReceipts.FirstOrDefaultAsync(r => r.Id == receipt.Id); if (currentReceipt == null) { return new VisualReceiptUploadResult(false, "回执记录不存在", 404); } if (currentReceipt.VisualReceiptState == "Available") { _logger.LogInformation("Visual receipt already available for Notification {NotifId} / Device {DevId} (Receipt {ReceiptId}). First-wins idempotent success returned.", notificationId, deviceId, receipt.Id); return new VisualReceiptUploadResult(true, "视觉回执已存在", 200, currentReceipt.Id, currentReceipt.VisualReceiptCapturedAt, currentReceipt.VisualReceiptExpiresAt); } // 6. Compute SHA256 hash string sha256Hex; using (var sha = SHA256.Create()) { var hashBytes = sha.ComputeHash(jpegBytes); sha256Hex = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); } // 7. Atomic file writing with unique temporary file and overwrite: false var now = DateTimeOffset.UtcNow; var dateFolder = now.ToString("yyyyMMdd"); var targetDir = Path.Combine(_storageBasePath, dateFolder); Directory.CreateDirectory(targetDir); var relativePath = $"{dateFolder}/{currentReceipt.Id}.jpg"; var finalFilePath = Path.Combine(_storageBasePath, dateFolder, $"{currentReceipt.Id}.jpg"); var tempFilePath = Path.Combine(_storageBasePath, dateFolder, $"{currentReceipt.Id}_{Guid.NewGuid():N}.tmp"); try { await File.WriteAllBytesAsync(tempFilePath, jpegBytes); File.Move(tempFilePath, finalFilePath, overwrite: false); } catch (IOException ex) when (File.Exists(finalFilePath)) { // File already placed by a winning race; clean up temp and return idempotent success _logger.LogInformation(ex, "Final visual receipt file already exists at {Path}. Cleaned temp and returning first-wins idempotent.", finalFilePath); try { if (File.Exists(tempFilePath)) File.Delete(tempFilePath); } catch { } return new VisualReceiptUploadResult(true, "视觉回执已存在", 200, currentReceipt.Id, currentReceipt.VisualReceiptCapturedAt ?? now, currentReceipt.VisualReceiptExpiresAt ?? now.AddHours(24)); } catch (Exception ex) { _logger.LogError(ex, "Failed to write visual receipt file to {Path}", finalFilePath); try { if (File.Exists(tempFilePath)) File.Delete(tempFilePath); } catch { } return new VisualReceiptUploadResult(false, "服务端写入视觉回执文件失败", 500); } // 8. Update database record with 24-hour retention var expiresAt = now.AddHours(24); currentReceipt.VisualReceiptState = "Available"; currentReceipt.VisualReceiptPath = relativePath; currentReceipt.VisualReceiptCapturedAt = now; currentReceipt.VisualReceiptExpiresAt = expiresAt; currentReceipt.VisualReceiptSizeBytes = jpegBytes.Length; currentReceipt.VisualReceiptSha256 = sha256Hex; currentReceipt.UpdatedAt = now; try { await db.SaveChangesAsync(); _logger.LogInformation("Visual receipt successfully saved for Notification {NotifId} / Device {DevId} (Size: {Size} bytes, SHA256: {Sha256}, Expires: {ExpiresAt})", notificationId, deviceId, jpegBytes.Length, sha256Hex, expiresAt); return new VisualReceiptUploadResult(true, "视觉回执上传成功", 200, currentReceipt.Id, now, expiresAt); } catch (Exception ex) { _logger.LogError(ex, "Database update failed after saving visual receipt file. Compensating by removing file {Path}", finalFilePath); try { if (File.Exists(finalFilePath)) File.Delete(finalFilePath); } catch { } return new VisualReceiptUploadResult(false, "更新回执数据库状态失败", 500); } } finally { receiptLock.Release(); } } public async Task GetVisualReceiptFileAsync(string notificationId, string deviceId, ClaimsPrincipal user) { if (user.Identity?.IsAuthenticated != true) { return new VisualReceiptFileResult(false, null, 401, "未登录或登录凭据无效"); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var notification = await db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == notificationId); if (notification == null) { return new VisualReceiptFileResult(false, null, 404, "通知记录不存在"); } // Permission check var userRole = user.FindFirst(ClaimTypes.Role)?.Value ?? "Teacher"; var userTenant = user.FindFirst("tenant_id")?.Value; var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (userRole != "SuperAdmin") { if (string.IsNullOrEmpty(userTenant) || userTenant != notification.TenantId) { return new VisualReceiptFileResult(false, null, 403, "无权查看非本校通知记录的视觉回执"); } if (userRole == "Teacher") { // Teacher can view notifications sent by themselves or targeting their classroom bool isSender = !string.IsNullOrEmpty(userId) && notification.SenderUserId == userId; if (!isSender) { // Allow teacher within same school to view class notification history // (Consistent with existing NotificationController.GetNotifications policy) } } } var receipt = await db.NotificationReceipts.AsNoTracking() .FirstOrDefaultAsync(r => r.NotificationId == notificationId && r.DeviceId == deviceId); if (receipt == null || receipt.VisualReceiptState == "None") { return new VisualReceiptFileResult(false, null, 404, "该设备无视觉回执记录"); } var now = DateTimeOffset.UtcNow; if (receipt.VisualReceiptState == "Expired" || (receipt.VisualReceiptExpiresAt.HasValue && receipt.VisualReceiptExpiresAt.Value <= now)) { return new VisualReceiptFileResult(false, null, 410, "该视觉回执已按 24 小时隐私保存策略自动销毁"); } if (string.IsNullOrEmpty(receipt.VisualReceiptPath)) { return new VisualReceiptFileResult(false, null, 404, "视觉回执文件路径为空"); } // Prevent path traversal var safeRelativePath = receipt.VisualReceiptPath.Replace('\\', '/').TrimStart('/'); if (safeRelativePath.Contains("..")) { return new VisualReceiptFileResult(false, null, 400, "非法文件路径"); } var fullPath = Path.Combine(_storageBasePath, safeRelativePath); if (!File.Exists(fullPath)) { _logger.LogWarning("Visual receipt file missing on disk: {Path}", fullPath); return new VisualReceiptFileResult(false, null, 404, "视觉回执图像文件已被物理删除"); } return new VisualReceiptFileResult(true, fullPath, 200); } public async Task CleanupExpiredVisualReceiptsAsync(CancellationToken ct = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; var expiredReceipts = await db.NotificationReceipts .Where(r => r.VisualReceiptState == "Available" && r.VisualReceiptExpiresAt <= now) .Take(200) .ToListAsync(ct); if (expiredReceipts.Count == 0) return 0; int cleanedCount = 0; foreach (var r in expiredReceipts) { if (!string.IsNullOrEmpty(r.VisualReceiptPath)) { var safeRelativePath = r.VisualReceiptPath.Replace('\\', '/').TrimStart('/'); var fullPath = Path.Combine(_storageBasePath, safeRelativePath); try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to delete expired visual receipt file at {Path}. Retaining Available state in database for retry in next cleanup cycle.", fullPath); continue; // Retain Available state and Path in database! Next worker cycle will retry. } } r.VisualReceiptPath = null; r.VisualReceiptState = "Expired"; r.UpdatedAt = now; cleanedCount++; } if (cleanedCount > 0) { await db.SaveChangesAsync(ct); _logger.LogInformation("Cleaned up {Count} expired visual receipts per 24-hour privacy retention policy.", cleanedCount); } return cleanedCount; } }