using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using eMCPy; using eMCPy.Mcp; using eMCPy.Update; public static class UpdateTests { sealed class FakeHttp : HttpMessageHandler { public readonly Dictionary> Routes = new Dictionary>(); public readonly List Requests = new List(); protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { Requests.Add(request); return Task.FromResult(Routes.TryGetValue(request.RequestUri.AbsoluteUri, out var r) ? r() : new HttpResponseMessage(HttpStatusCode.NotFound)); } } public static void Run() { int assertions = 0; void Check(bool ok, string msg) { if (!ok) throw new Exception(msg); assertions++; } // ---- JSON-RPC id behält den Typ ---- Check(McpToolRegistry.IdValue(JsonDocument.Parse("1").RootElement) is long l && l == 1, "Numeric id stays number"); Check(McpToolRegistry.IdValue(JsonDocument.Parse("\"abc\"").RootElement) as string == "abc", "String id stays string"); Check(McpToolRegistry.IdValue(JsonDocument.Parse("1.5").RootElement) is decimal, "Fractional id stays number"); Check(McpToolRegistry.IdValue(JsonDocument.Parse("null").RootElement) == null, "Null id"); var reg = new McpToolRegistry(null, null); var resp = (Dictionary)reg.HandleRequest("{\"jsonrpc\":\"2.0\",\"id\":42,\"method\":\"ping\"}"); Check(resp["id"] is long id42 && id42 == 42, "Response carries plain numeric id (not JsonElement)"); // ---- Selbst-Update ---- var root = Path.Combine(Path.GetTempPath(), "emcpy-update-" + Guid.NewGuid()); var plugins = Path.Combine(root, "plugins"); var state = Path.Combine(root, "data", "emcpy"); Directory.CreateDirectory(plugins); try { var target = Path.Combine(plugins, "eMCPy.dll"); var newDll = File.ReadAllBytes(typeof(Plugin).Assembly.Location); // echte eMCPy-Assembly 1.5.0 string Sha(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant(); const string feedUrl = "https://git.example/michael/eMCPy/raw/branch/main/releases/latest.json"; const string dllUrl = "https://git.example/michael/eMCPy/raw/branch/main/releases/1.5.0/eMCPy.dll"; var cfg = new PluginConfiguration { UpdateFeedUrl = feedUrl, UpdateToken = "gitea-secret-token" }; var http = new FakeHttp(); int restarts = 0; void Reset() { File.WriteAllText(target, "OLD"); if (Directory.Exists(state)) Directory.Delete(state, true); http.Requests.Clear(); http.Routes.Clear(); restarts = 0; } HttpResponseMessage Json(object o) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(o), Encoding.UTF8, "application/json") }; HttpResponseMessage Bytes(byte[] b) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(b) }; void Feed(string version, string url, string sha, string minServer = null) => http.Routes[feedUrl] = () => Json(new { version, url, sha256 = sha, minServerVersion = minServer, notes = "Test" }); SelfUpdater Updater(string running = "1.4.1") => new SelfUpdater(http, () => cfg, target, Version.Parse(running), new Version(4, 9, 5, 0), state, () => restarts++); UpdateStatus Go(string running = "1.4.1") => Updater(running).Run(CancellationToken.None); bool Untouched() => File.ReadAllText(target) == "OLD" && !File.Exists(target + ".download") && restarts == 0; Reset(); cfg.EnableAutoUpdate = false; Check(Go().State == "disabled" && http.Requests.Count == 0, "Disabled makes no requests"); cfg.EnableAutoUpdate = true; foreach (var bad in new[] { "http://git.example/latest.json", "ftp://x/latest.json", "https://user:pw@git.example/latest.json", "kein url" }) { Reset(); cfg.UpdateFeedUrl = bad; Check(Go().State == "not_configured" && http.Requests.Count == 0, "Rejected feed URL: " + bad); } Check(SelfUpdater.ValidateFeedUrl("http://192.168.1.2:3000/x/latest.json") != null, "HTTP to LAN IP allowed"); cfg.UpdateFeedUrl = feedUrl; Reset(); var missing = Go(); Check(missing.State == "auth_required_or_not_found", "404 explained as token/file problem"); Check(http.Requests[0].Headers.Authorization?.Scheme == "token" && http.Requests[0].Headers.Authorization?.Parameter == "gitea-secret-token", "Gitea token header sent to feed host"); Check(!File.ReadAllText(Path.Combine(state, SelfUpdater.StatusFileName)).Contains("gitea-secret-token"), "Token never stored in status"); Reset(); http.Routes[feedUrl] = () => new HttpResponseMessage(HttpStatusCode.Found) { Headers = { Location = new Uri("https://evil.example/") } }; Check(Go().State == "error" && http.Requests.Count == 1, "Redirect not followed"); Reset(); http.Routes[feedUrl] = () => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("") }; Check(Go().State == "invalid_feed", "Non-JSON feed rejected"); Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); Check(Go("1.5.0").State == "up_to_date" && http.Requests.Count == 1, "Same version: no download"); Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); Check(Go("1.6.0").State == "up_to_date" && Untouched(), "Never downgrade"); Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll), "9.0.0.0"); Check(Go().State == "server_too_old" && Untouched(), "Server version requirement"); Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", "abc"); Check(Go().State == "invalid_feed", "Invalid sha in feed"); Reset(); cfg.AutoInstallUpdates = false; Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); var notify = Go(); Check(notify.State == "update_available" && notify.AvailableVersion == "1.5.0" && Untouched() && http.Requests.Count == 1, "Notify-only mode does not download"); cfg.AutoInstallUpdates = true; Reset(); Feed("1.5.0", "https://evil.example/eMCPy.dll", Sha(newDll)); Check(Go().State == "invalid_feed" && http.Requests.Count == 1 && Untouched(), "DLL from other host refused, token not sent there"); Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); http.Routes[dllUrl] = () => Bytes(Encoding.UTF8.GetBytes("tampered")); Check(Go().State == "checksum_mismatch" && Untouched(), "Checksum mismatch leaves plugin untouched"); var junk = Encoding.UTF8.GetBytes("not an assembly at all"); Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(junk)); http.Routes[dllUrl] = () => Bytes(junk); Check(Go().State == "invalid_assembly" && Untouched(), "Non-assembly refused even with matching sha"); Reset(); Feed("1.6.0", "1.5.0/eMCPy.dll", Sha(newDll)); http.Routes[dllUrl] = () => Bytes(newDll); Check(Go().State == "invalid_assembly" && Untouched(), "Assembly version must match feed version"); Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); http.Routes[dllUrl] = () => Bytes(newDll); var installed = Go(); Check(installed.State == "installed_restart_pending" && installed.InstalledVersion == "1.5.0", "Update installed"); Check(File.ReadAllBytes(target).SequenceEqual(newDll) && !File.Exists(target + ".download"), "Plugin DLL replaced atomically"); Check(restarts == 1, "Pending restart reported once"); Check(File.ReadAllText(Path.Combine(state, "backup", "eMCPy-1.4.1.dll")) == "OLD", "Previous DLL backed up outside plugins folder"); Check(Directory.GetFiles(plugins).Length == 1, "No extra DLLs in plugins folder"); int before = http.Requests.Count; var again = Go(); Check(again.State == "installed_restart_pending" && http.Requests.Count == before && restarts == 1, "No re-download while restart pending"); File.WriteAllText(target, "OLD"); // Admin hat manuell zurückgerollt Check(Go().State == "installed_restart_pending" && http.Requests.Count > before, "Manual rollback detected, update re-applied"); Check(SelfUpdater.ReadStatus(state).State == "installed_restart_pending", "Status persisted for emby_plugins"); for (int i = 0; i < 5; i++) { File.WriteAllText(target, "OLD"); if (File.Exists(Path.Combine(state, SelfUpdater.StatusFileName))) File.Delete(Path.Combine(state, SelfUpdater.StatusFileName)); Go("1.4." + (10 + i)); } Check(Directory.GetFiles(Path.Combine(state, "backup")).Length <= 3, "At most 3 backups kept"); Console.WriteLine($"PASS update: {assertions} assertions."); } finally { if (Directory.Exists(root)) Directory.Delete(root, true); } } }