fix: restrict browser origins, honor ListenAddress, tighten JSON-RPC handling (1.4.2)
- OriginPolicy: only localhost, private/loopback IP origins, ServerUrl origin and the new AllowedOrigins setting may call the MCP port from a browser; others get 403 (blocks cross-site reads and DNS rebinding). No more reflected origin with Allow-Credentials. - ListenAddress is now used for the HttpListener prefix; warn when the server listens on all interfaces without an API key. - JSON-RPC: implement ping, never answer notifications, acknowledge client responses, negotiate protocolVersion, return 405 for GET /mcp and 404 for paths other than /mcp. - Tests for origin policy, listen prefix and protocol handling. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
37eb8b8a4e
commit
5b3dbc2d04
10 files changed
+256
-30
No files matched your search
@@ -70,6 +70,12 @@ Das Plugin startet im `IServerEntryPoint.Run()` einen eigenen **HTTP-Listener**
|
||||
|
||||
**Authentifizierung:** Der MCP-Port ist nur für das lokale Netz gedacht; optionaler statischer API-Key im Plugin-Config (Header `X-Api-Key` oder `Authorization: Bearer ***`).
|
||||
|
||||
**Browser-Zugriff (ab 1.4.2):** Requests mit `Origin`-Header werden nur von localhost, privaten/Loopback-IPs, dem Origin der `ServerUrl` und den unter *Erlaubte Origins* eingetragenen Adressen angenommen; alle anderen erhalten 403. Damit können fremde Webseiten (auch per DNS-Rebinding) den MCP-Port nicht mehr auslesen. Clients ohne Browser (AI-Agenten, curl, PHP) senden keinen Origin und sind nicht betroffen. Läuft das Dashboard über eine Domain, diese unter *Erlaubte Origins* eintragen.
|
||||
|
||||
**Listen-Adresse (ab 1.4.2):** Wird tatsächlich verwendet. `0.0.0.0`/leer = alle Interfaces, sonst Bindung an die angegebene IP/den Hostnamen; Clients müssen dann genau diese Adresse ansprechen. Ohne API-Key auf allen Interfaces schreibt das Plugin eine Warnung ins Log.
|
||||
|
||||
**Protokoll (ab 1.4.2):** `ping`, Notifications ohne Antwort (202), Aushandlung der Protokollversion (2025-06-18, 2025-03-26, 2024-11-05), `GET /mcp` → 405.
|
||||
|
||||
### Newtonsoft-Falle (make-or-break)
|
||||
|
||||
Emby's `IJsonSerializer` ist **Newtonsoft**. `DeserializeFromString(body, typeof(Dictionary<string,object>))` deserialisiert verschachtelte Objekte (wie `params`) in **`JObject`**, nicht in `Dictionary<string,object>` – der Cast liefert still `null`. **Lösung:** Eingehende JSON-RPC-Requests mit `System.Text.Json` parsen (`JsonDocument.Parse`), Felder über `JsonElement`/`TryGetProperty` lesen. Emby's `IJsonSerializer.SerializeToString` wird für bestehende Antworten beibehalten. Der Inhalt der neuen Inventarantwort wird mit `System.Text.Json` serialisiert, damit fehlende Werte ausdrücklich als `null` erhalten bleiben.
|
||||
|
||||
@@ -53,7 +53,8 @@
|
||||
<label class="inputLabel inputLabelUnfocused" for="listenAddress">Listen-Adresse</label>
|
||||
<input is="emby-input" type="text" id="listenAddress" />
|
||||
<div class="fieldDescription">
|
||||
<code>0.0.0.0</code> = alle Interfaces (empfohlen für Docker), <code>127.0.0.1</code> = nur lokal.
|
||||
<code>0.0.0.0</code> = alle Interfaces (empfohlen für Docker), <code>127.0.0.1</code> = nur lokal, oder eine konkrete IP.
|
||||
Bei konkreter Adresse müssen Clients genau diese Adresse verwenden (Host-Header).
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -85,6 +86,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="inputContainer" style="margin-top: 1em;">
|
||||
<label class="inputLabel" for="allowedOrigins">Erlaubte Origins (optional)</label>
|
||||
<input is="emby-input" type="text" id="allowedOrigins" placeholder="https://emby.domain.de" />
|
||||
<div class="fieldDescription">
|
||||
Browser-Seiten, die den MCP-Port aufrufen dürfen (kommagetrennt). LAN-IPs, <code>localhost</code> und die Server-URL sind immer erlaubt.
|
||||
Nur nötig, wenn das Dashboard über eine Domain läuft. AI-Agenten ohne Browser sind nicht betroffen.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="emcpy-status pending" id="serverStatus">
|
||||
Status wird geladen …
|
||||
</div>
|
||||
|
||||
@@ -84,6 +84,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) {
|
||||
view.querySelector('#apiKey').value = config.ApiKey || '';
|
||||
view.querySelector('#mcpUrl').value = config.McpUrl || '';
|
||||
view.querySelector('#serverUrl').value = config.ServerUrl || '';
|
||||
view.querySelector('#allowedOrigins').value = config.AllowedOrigins || '';
|
||||
this.checkServerStatus(view, config);
|
||||
loading.hide();
|
||||
}).catch(() => {
|
||||
@@ -112,6 +113,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) {
|
||||
config.ApiKey = view.querySelector('#apiKey').value.trim();
|
||||
config.McpUrl = view.querySelector('#mcpUrl').value.trim();
|
||||
config.ServerUrl = view.querySelector('#serverUrl').value.trim();
|
||||
config.AllowedOrigins = view.querySelector('#allowedOrigins').value.trim();
|
||||
|
||||
updatePluginConfiguration(config).then(result => {
|
||||
loading.hide();
|
||||
|
||||
@@ -32,8 +32,6 @@ namespace eMCPy.Mcp
|
||||
_listenAddress = string.IsNullOrEmpty(listenAddress) ? "0.0.0.0" : listenAddress;
|
||||
_apiKey = apiKey ?? string.Empty;
|
||||
_listener = new HttpListener();
|
||||
// "*" bindet an alle Interfaces (Linux: ohne Root-Problem)
|
||||
_listener.Prefixes.Add($"http://*:{_port}/");
|
||||
_tools = new McpToolRegistry(_logger, _json);
|
||||
}
|
||||
|
||||
@@ -41,8 +39,14 @@ namespace eMCPy.Mcp
|
||||
{
|
||||
try
|
||||
{
|
||||
// "*" bindet an alle Interfaces (Linux: ohne Root-Problem); sonst nur an die konfigurierte Adresse.
|
||||
// Hinweis: Bei konkreter Adresse muss der Host-Header der Clients zu dieser Adresse passen.
|
||||
var prefix = OriginPolicy.ListenerPrefix(_listenAddress, _port);
|
||||
_listener.Prefixes.Add(prefix);
|
||||
_listener.Start();
|
||||
_logger.Info("[eMCPy] MCP-Server lauscht auf http://{0}:{1}/mcp", _listenAddress, _port);
|
||||
_logger.Info("[eMCPy] MCP-Server lauscht auf {0}mcp", prefix);
|
||||
if (OriginPolicy.IsWildcard(prefix) && string.IsNullOrEmpty(_apiKey))
|
||||
_logger.Warn("[eMCPy] MCP-Server ist ohne API-Key auf allen Interfaces erreichbar. API-Key setzen oder Listen-Adresse einschränken.");
|
||||
Task.Run(() => ListenAsync(_cts.Token));
|
||||
return $"Lauscht auf {_listenAddress}:{_port}";
|
||||
}
|
||||
@@ -87,9 +91,21 @@ namespace eMCPy.Mcp
|
||||
var resp = ctx.Response;
|
||||
resp.ContentType = "application/json";
|
||||
|
||||
// Browser-Requests nur von erlaubten Origins (Dashboard per LAN-IP, ServerUrl, AllowedOrigins).
|
||||
// Fremde Webseiten (inkl. DNS-Rebinding) werden abgewiesen, bevor ein Tool läuft.
|
||||
var origin = req.Headers["Origin"];
|
||||
var cfg = Plugin.Instance?.Configuration;
|
||||
if (!OriginPolicy.IsAllowed(origin, cfg?.ServerUrl, cfg?.AllowedOrigins))
|
||||
{
|
||||
_logger.Warn("[eMCPy] Request von nicht erlaubtem Origin abgewiesen: {0}", origin);
|
||||
resp.StatusCode = 403;
|
||||
await WriteJsonAsync(resp, new { error = "Origin nicht erlaubt. Im Plugin unter 'Erlaubte Origins' eintragen." });
|
||||
return;
|
||||
}
|
||||
|
||||
// CORS: Dashboard (:8096) ruft den MCP-Port (:8097) cross-origin auf.
|
||||
// Ohne diese Header blockt der Browser den Request.
|
||||
ApplyCors(resp, req);
|
||||
ApplyCors(resp, origin);
|
||||
|
||||
// CORS-Preflight (Browser schickt OPTIONS vor POST)
|
||||
if (req.HttpMethod == "OPTIONS")
|
||||
@@ -99,13 +115,21 @@ namespace eMCPy.Mcp
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.HttpMethod != "POST" ||
|
||||
!req.Url.AbsolutePath.StartsWith("/mcp", StringComparison.OrdinalIgnoreCase))
|
||||
var path = req.Url.AbsolutePath.TrimEnd('/');
|
||||
if (!path.Equals("/mcp", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
resp.StatusCode = 404;
|
||||
await WriteJsonAsync(resp, new { error = "Nicht gefunden. Nutze POST /mcp" });
|
||||
return;
|
||||
}
|
||||
if (req.HttpMethod != "POST")
|
||||
{
|
||||
// Kein SSE-Stream angeboten → laut Streamable-HTTP-Transport 405.
|
||||
resp.StatusCode = 405;
|
||||
resp.AddHeader("Allow", "POST, OPTIONS");
|
||||
await WriteJsonAsync(resp, new { error = "Methode nicht erlaubt. Nutze POST /mcp" });
|
||||
return;
|
||||
}
|
||||
|
||||
// API-Key-Check (Header "X-Api-Key" oder "Authorization: Bearer <key>")
|
||||
if (!string.IsNullOrEmpty(_apiKey))
|
||||
@@ -155,24 +179,16 @@ namespace eMCPy.Mcp
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Setzt CORS-Header, damit das Emby-Dashboard (Browser) den MCP-Port
|
||||
/// cross-origin aufrufen kann. Origin wird zurückgespiegelt (LAN-Plugin,
|
||||
/// kein öffentlicher Service).
|
||||
/// Setzt CORS-Header für bereits geprüfte Origins (siehe OriginPolicy).
|
||||
/// Keine Credentials: der API-Key wird als Header gesendet, nicht als Cookie.
|
||||
/// </summary>
|
||||
private void ApplyCors(HttpListenerResponse resp, HttpListenerRequest req)
|
||||
private void ApplyCors(HttpListenerResponse resp, string origin)
|
||||
{
|
||||
var origin = req.Headers["Origin"];
|
||||
if (!string.IsNullOrEmpty(origin))
|
||||
{
|
||||
resp.AddHeader("Access-Control-Allow-Origin", origin);
|
||||
resp.AddHeader("Access-Control-Allow-Credentials", "true");
|
||||
}
|
||||
else
|
||||
{
|
||||
resp.AddHeader("Access-Control-Allow-Origin", "*");
|
||||
}
|
||||
if (string.IsNullOrEmpty(origin)) return;
|
||||
resp.AddHeader("Access-Control-Allow-Origin", origin);
|
||||
resp.AddHeader("Vary", "Origin");
|
||||
resp.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
||||
resp.AddHeader("Access-Control-Allow-Headers", "Content-Type, X-Api-Key, Authorization");
|
||||
resp.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Api-Key, Authorization, Mcp-Protocol-Version, Mcp-Session-Id");
|
||||
resp.AddHeader("Access-Control-Max-Age", "86400");
|
||||
}
|
||||
|
||||
|
||||
@@ -55,23 +55,35 @@ namespace eMCPy.Mcp
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
return RpcError(default, -32700, "Parse error: Request ist kein JSON-Objekt");
|
||||
|
||||
var id = root.TryGetProperty("id", out var idEl) ? idEl.Clone() : default;
|
||||
var hasId = root.TryGetProperty("id", out var idEl);
|
||||
var id = hasId ? idEl.Clone() : default;
|
||||
var method = root.TryGetProperty("method", out var mEl) && mEl.ValueKind == JsonValueKind.String
|
||||
? mEl.GetString() : null;
|
||||
var hasParams = root.TryGetProperty("params", out var pEl) && pEl.ValueKind == JsonValueKind.Object;
|
||||
|
||||
if (method == null)
|
||||
{
|
||||
// Antwort des Clients auf eine Server-Anfrage (result/error) → nur quittieren.
|
||||
if (!hasId || root.TryGetProperty("result", out _) || root.TryGetProperty("error", out _)) return null;
|
||||
return RpcError(id, -32600, "Invalid Request: method fehlt");
|
||||
}
|
||||
|
||||
// JSON-RPC-Notifications (ohne id) werden nie beantwortet,
|
||||
// z. B. notifications/initialized, notifications/cancelled.
|
||||
if (!hasId) return null;
|
||||
|
||||
switch (method)
|
||||
{
|
||||
case "initialize":
|
||||
return RpcResult(id, new
|
||||
{
|
||||
protocolVersion = "2024-11-05",
|
||||
protocolVersion = NegotiateProtocolVersion(hasParams ? pEl : default),
|
||||
serverInfo = new { name = "eMCPy", version = GetVersion() },
|
||||
capabilities = new { tools = new { listChanged = false } }
|
||||
});
|
||||
|
||||
case "notifications/initialized":
|
||||
return null; // Notification → keine Antwort
|
||||
case "ping":
|
||||
return RpcResult(id, new { });
|
||||
|
||||
case "tools/list":
|
||||
return RpcResult(id, new { tools = GetToolDefinitions() });
|
||||
@@ -84,6 +96,17 @@ namespace eMCPy.Mcp
|
||||
}
|
||||
}
|
||||
|
||||
// Neueste zuerst. Unterstützte Version des Clients wird übernommen, sonst die neueste angeboten.
|
||||
public static readonly string[] SupportedProtocolVersions = { "2025-06-18", "2025-03-26", "2024-11-05" };
|
||||
|
||||
private static string NegotiateProtocolVersion(JsonElement p)
|
||||
{
|
||||
var requested = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("protocolVersion", out var v)
|
||||
&& v.ValueKind == JsonValueKind.String ? v.GetString() : null;
|
||||
return requested != null && Array.IndexOf(SupportedProtocolVersions, requested) >= 0
|
||||
? requested : SupportedProtocolVersions[0];
|
||||
}
|
||||
|
||||
private object HandleToolCall(JsonElement id, JsonElement p)
|
||||
{
|
||||
var name = p.ValueKind == JsonValueKind.Object && p.TryGetProperty("name", out var nEl)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace eMCPy.Mcp
|
||||
{
|
||||
/// <summary>
|
||||
/// Entscheidet, welche Browser-Origins den MCP-Port aufrufen dürfen.
|
||||
/// Clients ohne Origin-Header (AI-Agenten, curl, PHP) sind nicht betroffen.
|
||||
/// Erlaubt sind: localhost / private oder Loopback-IP-Literale (Dashboard per LAN-IP),
|
||||
/// der Origin der konfigurierten ServerUrl sowie ausdrücklich eingetragene AllowedOrigins.
|
||||
/// Öffentliche Domains (auch per DNS-Rebinding) werden abgewiesen.
|
||||
/// </summary>
|
||||
public static class OriginPolicy
|
||||
{
|
||||
public static bool IsAllowed(string origin, string serverUrl, string allowedOrigins)
|
||||
{
|
||||
if (string.IsNullOrEmpty(origin)) return true; // kein Browser-Request
|
||||
if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri) ||
|
||||
(uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
|
||||
return false;
|
||||
|
||||
var normalized = Normalize(uri);
|
||||
if (Configured(serverUrl, allowedOrigins).Contains(normalized, StringComparer.OrdinalIgnoreCase)) return true;
|
||||
|
||||
var host = uri.Host.Trim('[', ']');
|
||||
if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return IPAddress.TryParse(host, out var ip) && IsPrivateOrLoopback(ip);
|
||||
}
|
||||
|
||||
static IEnumerable<string> Configured(string serverUrl, string allowedOrigins)
|
||||
{
|
||||
var entries = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(serverUrl)) entries.Add(serverUrl);
|
||||
if (!string.IsNullOrWhiteSpace(allowedOrigins))
|
||||
entries.AddRange(allowedOrigins.Split(new[] { ',', ';', ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries));
|
||||
foreach (var entry in entries)
|
||||
if (Uri.TryCreate(entry.Trim(), UriKind.Absolute, out var u)) yield return Normalize(u);
|
||||
}
|
||||
|
||||
static string Normalize(Uri uri) => uri.GetLeftPart(UriPartial.Authority).TrimEnd('/');
|
||||
|
||||
public static bool IsPrivateOrLoopback(IPAddress ip)
|
||||
{
|
||||
if (IPAddress.IsLoopback(ip)) return true;
|
||||
if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4();
|
||||
if (ip.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
var b = ip.GetAddressBytes();
|
||||
return b[0] == 10 ||
|
||||
(b[0] == 172 && b[1] >= 16 && b[1] <= 31) ||
|
||||
(b[0] == 192 && b[1] == 168) ||
|
||||
(b[0] == 169 && b[1] == 254);
|
||||
}
|
||||
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
var b = ip.GetAddressBytes();
|
||||
return ip.IsIPv6LinkLocal || (b[0] & 0xFE) == 0xFC; // fc00::/7 (ULA)
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Baut das HttpListener-Prefix aus der konfigurierten Listen-Adresse.
|
||||
/// Leer, 0.0.0.0, ::, * und + bedeuten alle Interfaces.
|
||||
/// </summary>
|
||||
public static string ListenerPrefix(string listenAddress, int port)
|
||||
{
|
||||
var address = (listenAddress ?? string.Empty).Trim();
|
||||
if (address.Length == 0 || address == "0.0.0.0" || address == "::" || address == "*" || address == "+")
|
||||
return $"http://*:{port}/";
|
||||
var bare = address.Trim('[', ']');
|
||||
if (IPAddress.TryParse(bare, out var ip) && ip.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
return $"http://[{bare}]:{port}/";
|
||||
if (Uri.CheckHostName(bare) == UriHostNameType.Unknown)
|
||||
throw new ArgumentException("Ungültige Listen-Adresse: " + address);
|
||||
return $"http://{bare}:{port}/";
|
||||
}
|
||||
|
||||
public static bool IsWildcard(string prefix) => prefix.StartsWith("http://*:", StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -23,5 +23,12 @@ namespace eMCPy
|
||||
/// z. B. http://192.168.1.2:8096. Leer = automatische Erkennung.
|
||||
/// </summary>
|
||||
public string ServerUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Zusätzliche Browser-Origins (kommagetrennt), die den MCP-Port aufrufen dürfen,
|
||||
/// z. B. https://emby.domain.de, wenn das Dashboard über eine Domain läuft.
|
||||
/// LAN-IPs/localhost und der Origin der ServerUrl sind immer erlaubt.
|
||||
/// </summary>
|
||||
public string AllowedOrigins { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<AssemblyName>eMCPy</AssemblyName>
|
||||
<RootNamespace>eMCPy</RootNamespace>
|
||||
<Version>1.4.1</Version>
|
||||
<AssemblyVersion>1.4.1</AssemblyVersion>
|
||||
<FileVersion>1.4.1</FileVersion>
|
||||
<Version>1.4.2</Version>
|
||||
<AssemblyVersion>1.4.2</AssemblyVersion>
|
||||
<FileVersion>1.4.2</FileVersion>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<NoWarn>CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -132,8 +132,9 @@ foreach(var t in tools.EnumerateArray()) if(t.GetProperty("inputSchema").GetProp
|
||||
rows.Clear();
|
||||
var emptySeries=Run(new {seriesId="100"});
|
||||
Check(emptySeries.GetProperty("total").GetInt32()==0 && emptySeries.GetProperty("returned").GetInt32()==0 && !emptySeries.GetProperty("hasMore").GetBoolean(), "Empty series");
|
||||
Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.4.1", "Release version");
|
||||
Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.4.2", "Release version");
|
||||
AdvancedTests.Run();
|
||||
ProtocolTests.Run();
|
||||
InventoryReplay.Run();
|
||||
Console.WriteLine($"PASS: {passed} assertions; 35 episodes in 5 pages, no per-episode detail lookup.");
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using eMCPy.Mcp;
|
||||
|
||||
public static class ProtocolTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
int assertions = 0;
|
||||
void Check(bool ok, string msg) { if (!ok) throw new Exception(msg); assertions++; }
|
||||
void Throws(Action f, string msg) { bool t = false; try { f(); } catch (ArgumentException) { t = true; } Check(t, msg); }
|
||||
|
||||
// ---- Origin-Policy ----
|
||||
Check(OriginPolicy.IsAllowed(null, null, null), "Kein Origin (Agent/curl) erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("", null, null), "Leerer Origin erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("http://192.168.1.2:8096", null, null), "Dashboard per LAN-IP");
|
||||
Check(OriginPolicy.IsAllowed("http://10.0.0.5:8096", null, null), "10/8 erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("http://172.20.1.1:8096", null, null), "172.16/12 erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("http://localhost:8096", null, null), "localhost erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("http://127.0.0.1:8096", null, null), "Loopback erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("http://[::1]:8096", null, null), "IPv6-Loopback erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("http://[fd00::12]:8096", null, null), "IPv6-ULA erlaubt");
|
||||
Check(!OriginPolicy.IsAllowed("https://evil.example", null, null), "Fremde Domain abgewiesen");
|
||||
Check(!OriginPolicy.IsAllowed("http://evil.example:8097", null, null), "DNS-Rebinding-Domain abgewiesen");
|
||||
Check(!OriginPolicy.IsAllowed("http://8.8.8.8", null, null), "Öffentliche IP abgewiesen");
|
||||
Check(!OriginPolicy.IsAllowed("http://172.32.0.1", null, null), "172.32 ist nicht privat");
|
||||
Check(!OriginPolicy.IsAllowed("null", null, null), "Origin 'null' (Sandbox/Datei) abgewiesen");
|
||||
Check(!OriginPolicy.IsAllowed("file://x", null, null), "file-Schema abgewiesen");
|
||||
Check(!OriginPolicy.IsAllowed("http://192.168.1.2.evil.example", null, null), "IP-ähnliche Domain abgewiesen");
|
||||
Check(OriginPolicy.IsAllowed("https://emby.domain.de", "https://emby.domain.de/emby/", null), "ServerUrl-Origin erlaubt");
|
||||
Check(OriginPolicy.IsAllowed("https://emby.domain.de", null, "https://a.de, https://EMBY.domain.de/"), "AllowedOrigins erlaubt");
|
||||
Check(!OriginPolicy.IsAllowed("https://emby.domain.de:8443", null, "https://emby.domain.de"), "Port muss passen");
|
||||
Check(!OriginPolicy.IsAllowed("http://emby.domain.de", null, "https://emby.domain.de"), "Schema muss passen");
|
||||
|
||||
// ---- Listen-Prefix ----
|
||||
Check(OriginPolicy.ListenerPrefix("", 8097) == "http://*:8097/", "Leer = alle");
|
||||
Check(OriginPolicy.ListenerPrefix("0.0.0.0", 8097) == "http://*:8097/", "0.0.0.0 = alle");
|
||||
Check(OriginPolicy.ListenerPrefix("::", 8097) == "http://*:8097/", ":: = alle");
|
||||
Check(OriginPolicy.ListenerPrefix("127.0.0.1", 8097) == "http://127.0.0.1:8097/", "Loopback-Bindung");
|
||||
Check(OriginPolicy.ListenerPrefix(" 192.168.1.2 ", 9000) == "http://192.168.1.2:9000/", "Konkrete IP");
|
||||
Check(OriginPolicy.ListenerPrefix("::1", 8097) == "http://[::1]:8097/", "IPv6 in Klammern");
|
||||
Check(OriginPolicy.ListenerPrefix("emby.local", 8097) == "http://emby.local:8097/", "Hostname");
|
||||
Throws(() => OriginPolicy.ListenerPrefix("bad host/x", 8097), "Ungültige Adresse abgewiesen");
|
||||
|
||||
// ---- JSON-RPC / MCP ----
|
||||
var registry = new McpToolRegistry(null, null);
|
||||
JsonElement Call(string body) => JsonSerializer.SerializeToElement(registry.HandleRequest(body));
|
||||
|
||||
var ping = Call("{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"ping\"}");
|
||||
Check(ping.GetProperty("id").GetInt32() == 7 && ping.GetProperty("result").ValueKind == JsonValueKind.Object, "ping liefert leeres Ergebnis");
|
||||
|
||||
Check(registry.HandleRequest("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}") == null, "initialized ohne Antwort");
|
||||
Check(registry.HandleRequest("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":1}}") == null, "cancelled ohne Antwort");
|
||||
Check(registry.HandleRequest("{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\"}") == null, "Jede Notification ohne Antwort");
|
||||
Check(registry.HandleRequest("{\"jsonrpc\":\"2.0\",\"id\":3,\"result\":{}}") == null, "Client-Antwort wird nur quittiert");
|
||||
|
||||
var noMethod = Call("{\"jsonrpc\":\"2.0\",\"id\":4}");
|
||||
Check(noMethod.GetProperty("error").GetProperty("code").GetInt32() == -32600, "Fehlende method = Invalid Request");
|
||||
|
||||
var unknown = Call("{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"resources/list\"}");
|
||||
Check(unknown.GetProperty("error").GetProperty("code").GetInt32() == -32601, "Unbekannte Methode");
|
||||
|
||||
string Version(string requested)
|
||||
{
|
||||
var p = requested == null ? "{}" : "{\"protocolVersion\":\"" + requested + "\"}";
|
||||
return Call("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":" + p + "}")
|
||||
.GetProperty("result").GetProperty("protocolVersion").GetString();
|
||||
}
|
||||
Check(Version("2024-11-05") == "2024-11-05", "Alte Version wird übernommen");
|
||||
Check(Version("2025-03-26") == "2025-03-26", "2025-03-26 wird übernommen");
|
||||
Check(Version("2025-06-18") == "2025-06-18", "2025-06-18 wird übernommen");
|
||||
Check(Version("2099-01-01") == McpToolRegistry.SupportedProtocolVersions[0], "Unbekannt → neueste");
|
||||
Check(Version(null) == McpToolRegistry.SupportedProtocolVersions[0], "Ohne Angabe → neueste");
|
||||
|
||||
Console.WriteLine($"PASS protocol: {assertions} assertions.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user