From 06967fef5376ae785c44051f5613cb8a32a08dc1 Mon Sep 17 00:00:00 2001 From: ifBars Date: Mon, 16 Nov 2026 16:08:54 -0800 Subject: [PATCH] Report bounded private upload outcomes and incomplete scan diagnostics --- BepInEx/BepInExConsentPlugin.cs | 2 +- BepInEx/BepInExIl2CppConsentPlugin.cs | 2 +- BepInEx/BepInExReportGenerator.cs | 2 +- MelonLoader/MelonLoaderPlugin.cs | 4 +- Services/Diagnostics/PostHogScanTelemetry.cs | 25 +++++- Services/ReportUploadService.cs | 91 ++++++++++++++++---- 6 files changed, 104 insertions(+), 22 deletions(-) diff --git a/BepInEx/BepInExConsentPlugin.cs b/BepInEx/BepInExConsentPlugin.cs index a6ac4a9..0d6a766 100644 --- a/BepInEx/BepInExConsentPlugin.cs +++ b/BepInEx/BepInExConsentPlugin.cs @@ -97,7 +97,7 @@ private void TryUploadPendingFile() ? Path.GetFileName(_pendingUploadPath) : _pendingUploadName; - var bytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath); + var bytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath, _reportUploadService.RecordPreparationFailure); var metadata = BuildSubmissionMetadata(modName); _reportUploadService.UploadReportNonBlocking(bytes, modName, metadata, apiBaseUrl); Logger.LogInfo("MLVScan report upload enabled and initial mod upload queued."); diff --git a/BepInEx/BepInExIl2CppConsentPlugin.cs b/BepInEx/BepInExIl2CppConsentPlugin.cs index 9a265aa..2bdd722 100644 --- a/BepInEx/BepInExIl2CppConsentPlugin.cs +++ b/BepInEx/BepInExIl2CppConsentPlugin.cs @@ -139,7 +139,7 @@ private void TryUploadPendingFile() ? Path.GetFileName(_pendingUploadPath) : _pendingUploadName; - var bytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath); + var bytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath, _reportUploadService.RecordPreparationFailure); var metadata = new SubmissionMetadata { LoaderType = "BepInEx6IL2CPP", diff --git a/BepInEx/BepInExReportGenerator.cs b/BepInEx/BepInExReportGenerator.cs index ba716e5..d378654 100644 --- a/BepInEx/BepInExReportGenerator.cs +++ b/BepInEx/BepInExReportGenerator.cs @@ -363,7 +363,7 @@ private void GenerateFileReport( : (scanResult?.FilePath ?? string.Empty); if (File.Exists(accessiblePath)) { - var assemblyBytes = ReportUploadService.ReadPrivateSampleBytes(accessiblePath); + var assemblyBytes = ReportUploadService.ReadPrivateSampleBytes(accessiblePath, _reportUploadService.RecordPreparationFailure); var metadata = BuildSubmissionMetadata(pluginName, findings); metadata.OriginalVerdict = scanResult?.ThreatVerdict?.Kind.ToString(); metadata.OriginalScanStatus = scanResult?.ScanStatus?.Kind.ToString(); diff --git a/MelonLoader/MelonLoaderPlugin.cs b/MelonLoader/MelonLoaderPlugin.cs index 1b88d93..bd9e9ff 100644 --- a/MelonLoader/MelonLoaderPlugin.cs +++ b/MelonLoader/MelonLoaderPlugin.cs @@ -440,7 +440,7 @@ private void GenerateDetailedReports(List disabledMods, Dict var apiBaseUrl = _configManager.GetReportUploadApiBaseUrl(); if (!string.IsNullOrWhiteSpace(apiBaseUrl) && File.Exists(accessiblePath)) { - var assemblyBytes = ReportUploadService.ReadPrivateSampleBytes(accessiblePath); + var assemblyBytes = ReportUploadService.ReadPrivateSampleBytes(accessiblePath, _reportUploadService.RecordPreparationFailure); var metadata = BuildSubmissionMetadata(modName, actualFindings); metadata.OriginalVerdict = threatVerdict.Kind.ToString(); metadata.OriginalScanStatus = scanStatus.Kind.ToString(); @@ -528,7 +528,7 @@ private void HandleUploadConsentDecision(bool approved, bool shareFiles) var apiBaseUrl = _configManager.GetReportUploadApiBaseUrl(); if (!string.IsNullOrWhiteSpace(apiBaseUrl)) { - var assemblyBytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath); + var assemblyBytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath, _reportUploadService.RecordPreparationFailure); var metadata = BuildSubmissionMetadata(_pendingUploadModName, _pendingUploadFindings ?? new List()); metadata.OriginalVerdict = _pendingUploadVerdictKind; metadata.OriginalScanStatus = _pendingUploadScanStatus; diff --git a/Services/Diagnostics/PostHogScanTelemetry.cs b/Services/Diagnostics/PostHogScanTelemetry.cs index 5c91110..be3c87b 100644 --- a/Services/Diagnostics/PostHogScanTelemetry.cs +++ b/Services/Diagnostics/PostHogScanTelemetry.cs @@ -95,6 +95,9 @@ public static async Task SendAsync(HttpClient client, MLVScanConfig config properties["$ip"] = "0.0.0.0"; properties["consumer"] = "loader"; properties["environment"] = config.TelemetryEnvironment; + properties["review_candidate_count"] = new[] { "suspicious_count", "known_threat_count", "manual_review_required_count" } + .Sum(key => properties.TryGetValue(key, out var count) ? (int)count : 0); + properties["file_sharing_enabled"] = SharingConsentPolicy.CanUploadFiles(config); return await SendEnvelopeAsync(client, config, "mlvscan_scan_run_completed", "scan-run:" + Guid.NewGuid().ToString("N"), properties, cancellationToken).ConfigureAwait(false); } @@ -129,6 +132,26 @@ public static async Task SendReviewReceiptAsync(HttpClient client, MLVScan public static bool IsValidReviewId(string value) => value != null && value.Length == 36 && Guid.TryParseExact(value, "D", out _) && value[14] == '4' && "89abAB".IndexOf(value[19]) >= 0; + /// One terminal outcome per upload operation; no sample identity or response text. + public static async Task SendUploadOutcomeAsync(HttpClient client, MLVScanConfig config, + string outcome, string reason, int attempts) + { + if (!IsConfigured(config) || !new[] { "accepted", "failed", "skipped" }.Contains(outcome) || + !new[] { "none", "invalid_receipt", "size_limit", "empty_file", "duplicate", "in_flight", "not_configured", + "consent_revoked", "read_error", "not_found", "rejected", "rate_limited", "server_error", "network_error", "timeout", "preparation_error" }.Contains(reason)) + return false; + var properties = new Dictionary { + ["telemetry_schema_version"] = 1, ["consumer"] = "loader", ["environment"] = config.TelemetryEnvironment, + ["core_version"] = MLVScanVersions.CoreVersion, ["plugin_version"] = PlatformConstants.PlatformVersion, + ["loader"] = PlatformConstants.PlatformName, ["upload_outcome"] = outcome, ["upload_reason"] = reason, + ["upload_operation_count"] = 1, ["upload_attempt_count"] = Math.Max(0, Math.Min(3, attempts)), + ["$process_person_profile"] = false, ["$geoip_disable"] = true, ["$ip"] = "0.0.0.0" + }; + try { return await SendEnvelopeAsync(client, config, "mlvscan_private_review_upload_outcome", + "upload-outcome:" + Guid.NewGuid().ToString("N"), properties, default).ConfigureAwait(false); } + catch (Exception) { return false; } + } + private static async Task SendEnvelopeAsync(HttpClient client, MLVScanConfig config, string eventName, string distinctId, Dictionary properties, CancellationToken cancellationToken) { @@ -167,7 +190,7 @@ private static async Task SendEnvelopeAsync(HttpClient client, MLVScanConf ? result.Findings .Where(f => AnalysisCompletenessEvaluator.IsIncompleteFinding(f) || f.RuleId == PluginScannerBase.OversizedAssemblyRuleId) - .Select(f => new AnalysisCompletenessReasonDto { ReasonId = "scanner-incomplete", RuleId = f.RuleId }) + .Select(f => new AnalysisCompletenessReasonDto { ReasonId = "scanner-incomplete", RuleId = f.RuleId, Summary = f.Description }) .ToList() : new List() }, diff --git a/Services/ReportUploadService.cs b/Services/ReportUploadService.cs index 24374d7..c23f5a9 100644 --- a/Services/ReportUploadService.cs +++ b/Services/ReportUploadService.cs @@ -46,20 +46,53 @@ public ReportUploadService(IConfigManager configManager, Action logInfo, } /// Reads an optional upload within its transport budget, independently of local scanning. - public static byte[] ReadPrivateSampleBytes(string path) + public static byte[] ReadPrivateSampleBytes(string path, Action onSkipped = null) { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); - if (stream.Length > SmallFileLimitBytes) - throw new IOException("Private review skipped: file exceeds 64 MiB. Local scanning is not size limited."); - var bytes = new byte[checked((int)stream.Length)]; - var offset = 0; - while (offset < bytes.Length) + var sizeLimitExceeded = false; + try { - var count = stream.Read(bytes, offset, bytes.Length - offset); - if (count == 0) throw new EndOfStreamException("Sample changed while preparing private review."); - offset += count; + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + if (stream.Length > SmallFileLimitBytes) + { + sizeLimitExceeded = true; + try { onSkipped?.Invoke("size_limit"); } catch (Exception) { } + throw new IOException("Private review skipped: file exceeds 64 MiB. Local scanning is not size limited."); + } + var bytes = new byte[checked((int)stream.Length)]; + var offset = 0; + while (offset < bytes.Length) + { + var count = stream.Read(bytes, offset, bytes.Length - offset); + if (count == 0) throw new EndOfStreamException("Sample changed while preparing private review."); + offset += count; + } + return bytes; + } + catch (Exception error) when (error is IOException || error is UnauthorizedAccessException) + { + if (!sizeLimitExceeded) + try { onSkipped?.Invoke("read_error"); } catch (Exception) { } + throw; } - return bytes; + } + + private int _outcomePending; + public void RecordPreparationFailure(string reason) => RecordOutcome("skipped", reason, 0); + + private void RecordOutcome(string outcome, string reason, int attempts) + { + if (!SharingConsentPolicy.CanSendAnalytics(_configManager?.Config) || + Interlocked.CompareExchange(ref _outcomePending, 1, 0) != 0) return; + _ = Task.Run(async () => + { + try + { + using var client = _createHttpClient(); + await PostHogScanTelemetry.SendUploadOutcomeAsync(client, _configManager?.Config, outcome, reason, attempts).ConfigureAwait(false); + } + catch (Exception) { } + finally { Interlocked.Exchange(ref _outcomePending, 0); } + }); } /// @@ -71,12 +104,14 @@ public void UploadReportNonBlocking(byte[] assemblyBytes, string filename, Submi if (!SharingConsentPolicy.CanUploadFiles(_configManager?.Config)) return; if (assemblyBytes == null || assemblyBytes.Length == 0) { + RecordOutcome("skipped", "empty_file", 0); _logWarn($"ReportUploadService: No assembly bytes to upload for {filename ?? ""}"); return; } if (string.IsNullOrWhiteSpace(apiBaseUrl)) { + RecordOutcome("skipped", "not_configured", 0); _logWarn("ReportUploadService: API base URL not configured"); return; } @@ -105,12 +140,14 @@ public async Task UploadReportAsync(byte[] assemblyBytes, string filename, Submi if (!SharingConsentPolicy.CanUploadFiles(_configManager?.Config)) return; if (assemblyBytes == null || assemblyBytes.Length == 0) { + RecordOutcome("skipped", "empty_file", 0); _logWarn($"ReportUploadService: No assembly bytes to upload for {filename ?? ""}"); return; } if (assemblyBytes.Length > SmallFileLimitBytes) { + RecordOutcome("skipped", "size_limit", 0); _logWarn("Private review skipped: file exceeds 64 MiB. It remains local."); return; } @@ -119,6 +156,7 @@ public async Task UploadReportAsync(byte[] assemblyBytes, string filename, Submi { if (_configManager?.IsReportHashUploaded(assemblyHash) == true) { + RecordOutcome("skipped", "duplicate", 0); _logInfo($"ReportUploadService: Skipping duplicate upload for {filename} ({assemblyHash})"); return; } @@ -127,6 +165,7 @@ public async Task UploadReportAsync(byte[] assemblyBytes, string filename, Submi { if (InFlightUploads.Contains(assemblyHash)) { + RecordOutcome("skipped", "in_flight", 0); _logInfo($"ReportUploadService: Upload already queued for {filename} ({assemblyHash})"); return; } @@ -135,9 +174,12 @@ public async Task UploadReportAsync(byte[] assemblyBytes, string filename, Submi } } + var outcome = "failed"; + var reason = "preparation_error"; + var attempts = 0; try { - if (string.IsNullOrWhiteSpace(apiBaseUrl)) return; + if (string.IsNullOrWhiteSpace(apiBaseUrl)) { outcome = "skipped"; reason = "not_configured"; return; } var baseUrl = apiBaseUrl.TrimEnd('/'); _logInfo("ReportUploadService: Submitting a file for private review."); if (metadata?.OriginalFindings != null) @@ -171,14 +213,19 @@ public async Task UploadReportAsync(byte[] assemblyBytes, string filename, Submi { try { - if (!SharingConsentPolicy.CanUploadFiles(_configManager?.Config)) return; + if (!SharingConsentPolicy.CanUploadFiles(_configManager?.Config)) { outcome = "skipped"; reason = "consent_revoked"; return; } + attempts++; receipt = await UploadViaPostFilesAsync(assemblyBytes, filename, metadata, baseUrl); + outcome = "accepted"; + reason = receipt == null ? "invalid_receipt" : "none"; break; } catch (Exception ex) { + reason = ex is PrivateUploadException uploadError ? uploadError.Reason + : ex is OperationCanceledException ? "timeout" : "network_error"; _logWarn($"ReportUploadService: Attempt {attempt + 1} failed: {ex.Message}"); - if (attempt == MaxRetries) + if (attempt == MaxRetries || ex is PrivateUploadException permanent && !permanent.Retryable) { throw; } @@ -214,6 +261,7 @@ await PostHogScanTelemetry.SendReviewReceiptAsync(analyticsClient, _configManage } finally { + RecordOutcome(outcome, reason, attempts); if (HashUtility.IsValidHash(assemblyHash)) { lock (InFlightUploadsLock) @@ -259,8 +307,7 @@ private async Task UploadViaPostFilesAsync(byte[] assemblyBytes, string if (!response.IsSuccessStatusCode) { - var body = await response.Content.ReadAsStringAsync(); - throw new IOException($"Private review returned {(int)response.StatusCode}: {body}"); + throw new PrivateUploadException((int)response.StatusCode); } try { @@ -282,6 +329,18 @@ private sealed class PrivateReviewReceipt [DataMember(Name = "visibility")] public string Visibility { get; set; } } + private sealed class PrivateUploadException : IOException + { + public string Reason { get; } + public bool Retryable { get; } + public PrivateUploadException(int status) : base($"Private review returned {status}.") + { + Reason = status == 404 ? "not_found" : status == 413 ? "size_limit" : status == 429 ? "rate_limited" + : status >= 500 ? "server_error" : "rejected"; + Retryable = status >= 500; + } + } + private static HttpClient CreateDefaultHttpClient() { // Enable TLS 1.2 on older runtimes (Unity/Mono); otherwise "TLS Support not available" occurs.