Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion BepInEx/BepInExConsentPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace MLVScan.BepInEx
{
[BepInPlugin("com.bars.mlvscan.consent", "MLVScan Consent", PlatformConstants.PlatformVersion)]
public class BepInExConsentPlugin : BaseUnityPlugin

Check warning on line 15 in BepInEx/BepInExConsentPlugin.cs

View workflow job for this annotation

GitHub Actions / build

Class BepInExConsentPlugin has BepInPlugin attribute but does not inherit from BaseUnityPlugin

Check warning on line 15 in BepInEx/BepInExConsentPlugin.cs

View workflow job for this annotation

GitHub Actions / build

Class BepInExConsentPlugin has BepInPlugin attribute but does not inherit from BaseUnityPlugin
{
private BepInExConfigManager _configManager;
private ReportUploadService _reportUploadService;
Expand Down Expand Up @@ -97,7 +97,7 @@
? 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.");
Expand Down
2 changes: 1 addition & 1 deletion BepInEx/BepInExIl2CppConsentPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
namespace MLVScan.BepInEx
{
[BepInPlugin("com.bars.mlvscan.consent.il2cpp", "MLVScan Consent IL2CPP", PlatformConstants.PlatformVersion)]
public class BepInExIl2CppConsentPlugin : BasePlugin

Check warning on line 14 in BepInEx/BepInExIl2CppConsentPlugin.cs

View workflow job for this annotation

GitHub Actions / build

Class BepInExIl2CppConsentPlugin has BepInPlugin attribute but does not inherit from BaseUnityPlugin

Check warning on line 14 in BepInEx/BepInExIl2CppConsentPlugin.cs

View workflow job for this annotation

GitHub Actions / build

Class BepInExIl2CppConsentPlugin has BepInPlugin attribute but does not inherit from BaseUnityPlugin
{
private static ConsentPopupState _state;

Expand Down Expand Up @@ -139,7 +139,7 @@
? Path.GetFileName(_pendingUploadPath)
: _pendingUploadName;

var bytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath);
var bytes = ReportUploadService.ReadPrivateSampleBytes(_pendingUploadPath, _reportUploadService.RecordPreparationFailure);
var metadata = new SubmissionMetadata
{
LoaderType = "BepInEx6IL2CPP",
Expand Down
2 changes: 1 addition & 1 deletion BepInEx/BepInExReportGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
4 changes: 2 additions & 2 deletions MelonLoader/MelonLoaderPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ private void GenerateDetailedReports(List<DisabledPluginInfo> 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();
Expand Down Expand Up @@ -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<ScanFinding>());
metadata.OriginalVerdict = _pendingUploadVerdictKind;
metadata.OriginalScanStatus = _pendingUploadScanStatus;
Expand Down
25 changes: 24 additions & 1 deletion Services/Diagnostics/PostHogScanTelemetry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ public static async Task<bool> 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);
}
Expand Down Expand Up @@ -129,6 +132,26 @@ public static async Task<bool> 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;

/// <summary>One terminal outcome per upload operation; no sample identity or response text.</summary>
public static async Task<bool> 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<string, object> {
["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<bool> SendEnvelopeAsync(HttpClient client, MLVScanConfig config,
string eventName, string distinctId, Dictionary<string, object> properties, CancellationToken cancellationToken)
{
Expand Down Expand Up @@ -167,7 +190,7 @@ private static async Task<bool> 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<AnalysisCompletenessReasonDto>()
},
Expand Down
91 changes: 75 additions & 16 deletions Services/ReportUploadService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,53 @@ public ReportUploadService(IConfigManager configManager, Action<string> logInfo,
}

/// <summary>Reads an optional upload within its transport budget, independently of local scanning.</summary>
public static byte[] ReadPrivateSampleBytes(string path)
public static byte[] ReadPrivateSampleBytes(string path, Action<string> 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); }
});
}

/// <summary>
Expand All @@ -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 ?? "<unknown>"}");
return;
}

if (string.IsNullOrWhiteSpace(apiBaseUrl))
{
RecordOutcome("skipped", "not_configured", 0);
_logWarn("ReportUploadService: API base URL not configured");
return;
}
Expand Down Expand Up @@ -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 ?? "<unknown>"}");
return;
}

if (assemblyBytes.Length > SmallFileLimitBytes)
{
RecordOutcome("skipped", "size_limit", 0);
_logWarn("Private review skipped: file exceeds 64 MiB. It remains local.");
return;
}
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -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)
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -214,6 +261,7 @@ await PostHogScanTelemetry.SendReviewReceiptAsync(analyticsClient, _configManage
}
finally
{
RecordOutcome(outcome, reason, attempts);
if (HashUtility.IsValidHash(assemblyHash))
{
lock (InFlightUploadsLock)
Expand Down Expand Up @@ -259,8 +307,7 @@ private async Task<string> 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
{
Expand All @@ -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.
Expand Down
Loading