Files
opengenesislinkserver/addons/SysApi/SysApiHost.cs
T
OpenGenesis (EULA) e81076f33c feat(g1): global SYS.API alerts over signed NexBus to all simulator regions
Adds a CSRF-protected admin-only alert command with severity presets and 5-second rate limit; signs a NexBus event and fans out via native IDialogModule.SendGeneralAlert across all hosted regions, including EventSim when configured. Default remains opt-in. NexVerse CI, .NET10 full build, SYS.API HTTP/HMAC tests and security contracts passed. Cross-platform builds/ROBUST boot passed; release-artifact upload remains blocked by GitHub storage quota. No production deployment.
2026-11-22 21:53:26 +01:00

485 lines
23 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: MPL-2.0
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenGenesisLINK.SysApi;
public sealed class SysApiHost : IDisposable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SysApiHost));
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private readonly record struct AdminSession(UUID Avatar, string Name, string Csrf, DateTimeOffset Expires);
private sealed record LoginInput(string Username, string Password);
private sealed record AlertInput(string Command);
private sealed class Attempts { public int Count; public DateTimeOffset Until = DateTimeOffset.UtcNow.AddMinutes(5); }
private readonly HttpListener _http = new();
private readonly CancellationTokenSource _stop = new();
private readonly ConcurrentDictionary<string, AdminSession> _sessions = new();
private readonly ConcurrentDictionary<string, Attempts> _attempts = new();
private readonly IUserAccountService _accounts;
private readonly IAuthenticationService _auth;
private readonly ISysApiReadModel? _readModel;
private readonly ISysApiAlertPublisher? _alertPublisher;
private readonly SemaphoreSlim _alertGate = new(1, 1);
private DateTimeOffset _lastAlertAt = DateTimeOffset.MinValue;
private readonly byte[] _portalToken;
private readonly Uri? _publicOrigin;
private readonly string _localAuthority;
private readonly DateTimeOffset _startup = DateTimeOffset.UtcNow;
private Task? _listenerTask;
private int _disposed;
public SysApiHost(int localPort, string publicOrigin, IUserAccountService accounts,
IAuthenticationService auth, string portalToken, ISysApiReadModel? readModel = null,
ISysApiAlertPublisher? alertPublisher = null)
{
if (localPort is < 1025 or > 65535) throw new ArgumentOutOfRangeException(nameof(localPort));
_accounts = accounts ?? throw new ArgumentNullException(nameof(accounts));
_auth = auth ?? throw new ArgumentNullException(nameof(auth));
_readModel = readModel;
_alertPublisher = alertPublisher;
if (portalToken.Length != 128 || !portalToken.All(Uri.IsHexDigit))
throw new ArgumentException("Invalid portal token", nameof(portalToken));
_portalToken = Encoding.ASCII.GetBytes(portalToken);
_localAuthority = "127.0.0.1:" + localPort;
if (publicOrigin.Length != 0)
{
if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out var address) ||
address.Scheme != Uri.UriSchemeHttps || address.AbsolutePath != "/" ||
address.UserInfo.Length != 0 || address.Query.Length != 0 || address.Fragment.Length != 0)
throw new ArgumentException("PublicOrigin must be an HTTPS origin without path or query");
_publicOrigin = address;
}
// Public port 8850 is reserved for HTTPS termination via an ACME-provisioned proxy.
// Never bind the internal module directly to the public interface.
_http.Prefixes.Add($"http://127.0.0.1:{localPort}/");
}
public void Start()
{
_http.Start();
_listenerTask = Task.Run(ServeAsync);
}
private async Task ServeAsync()
{
while (!_stop.IsCancellationRequested)
{
HttpListenerContext request;
try { request = await _http.GetContextAsync(); }
catch (Exception e) when (e is HttpListenerException or ObjectDisposedException) { break; }
_ = Task.Run(() => HandleAsync(request));
}
}
private static string RandomSecret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
private static void SecurityHeaders(HttpListenerResponse r)
{
r.Headers["X-Content-Type-Options"] = "nosniff";
r.Headers["Referrer-Policy"] = "no-referrer";
r.Headers["X-Frame-Options"] = "DENY";
r.Headers["Cache-Control"] = "no-store, private";
r.Headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self' data:; " +
"script-src 'self'; style-src 'self'; connect-src 'self'; form-action 'self'; " +
"frame-ancestors 'none'; base-uri 'none'; object-src 'none'";
}
private bool IsTrustedProxy(HttpListenerRequest req) =>
_publicOrigin is not null &&
IPAddress.IsLoopback(req.RemoteEndPoint?.Address ?? IPAddress.None) &&
string.Equals(req.Headers["Host"], _localAuthority, StringComparison.OrdinalIgnoreCase) &&
string.Equals(req.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase) &&
string.Equals(req.Headers["X-Forwarded-Host"], _publicOrigin.Authority, StringComparison.OrdinalIgnoreCase);
private bool SameOrigin(HttpListenerRequest req)
{
string origin = req.Headers["Origin"] ?? "";
string fetchSite = req.Headers["Sec-Fetch-Site"] ?? "";
if (fetchSite.Length > 0 && fetchSite is not ("same-origin" or "none")) return false;
if (origin.Length == 0) return true;
if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? parsed)) return false;
bool direct = parsed.Scheme == "http" &&
string.Equals(parsed.Authority, _localAuthority, StringComparison.OrdinalIgnoreCase);
bool proxy = IsTrustedProxy(req) && string.Equals(
parsed.GetLeftPart(UriPartial.Authority),
_publicOrigin!.GetLeftPart(UriPartial.Authority),
StringComparison.OrdinalIgnoreCase);
return direct || proxy;
}
private bool HasPortalToken(HttpListenerRequest req)
{
string header = req.Headers["Authorization"] ?? "";
if (!header.StartsWith("Bearer ", StringComparison.Ordinal) || header.Length != 135)
return false;
return CryptographicOperations.FixedTimeEquals(
Encoding.ASCII.GetBytes(header[7..]), _portalToken);
}
private bool TryAdmin(HttpListenerRequest req, out AdminSession s)
{
s = default;
string? sid = req.Cookies["ogl_sysapi"]?.Value;
if (sid is null || !_sessions.TryGetValue(sid, out var candidate)) return false;
if (candidate.Expires < DateTimeOffset.UtcNow) { _sessions.TryRemove(sid, out _); return false; }
try
{
var account = _accounts.GetUserAccount(UUID.Zero, candidate.Avatar);
if (account is null || account.UserLevel < 200 || !account.LoginAllowed)
{
_sessions.TryRemove(sid, out _);
return false;
}
}
catch (Exception ex) { Log.Warn("[SYS.API] Session authorization unavailable", ex); return false; }
s = candidate;
return true;
}
private static async Task<T?> ReadInput<T>(HttpListenerRequest req) where T : class
{
if (req.ContentLength64 > 16384 ||
!(req.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) ?? false))
return null;
using var ms = new MemoryStream();
byte[] buffer = new byte[4096];
int n;
while ((n = await req.InputStream.ReadAsync(buffer)) > 0)
{
if (ms.Length + n > 16384) return null;
ms.Write(buffer.AsSpan(0, n));
}
try { return JsonSerializer.Deserialize<T>(ms.ToArray(), Json); }
catch (JsonException) { return null; }
}
private static async Task ReplyAsync(HttpListenerResponse r, int status, object data)
{
r.StatusCode = status;
r.ContentType = "application/json; charset=utf-8";
byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(data, Json);
r.ContentLength64 = bytes.Length;
await r.OutputStream.WriteAsync(bytes);
}
private static async Task AssetAsync(HttpListenerResponse r, string suffix, string mime)
{
var asm = typeof(SysApiHost).Assembly;
string? name = asm.GetManifestResourceNames().FirstOrDefault(x =>
x.EndsWith(".www." + suffix, StringComparison.Ordinal));
if (name is null) { r.StatusCode = 404; return; }
using var content = asm.GetManifestResourceStream(name);
if (content is null) { r.StatusCode = 404; return; }
r.ContentType = mime;
r.ContentLength64 = content.Length;
await content.CopyToAsync(r.OutputStream);
}
private async Task LoginAsync(HttpListenerContext context)
{
var req = context.Request;
var data = await ReadInput<LoginInput>(req);
if (data is null || string.IsNullOrWhiteSpace(data.Username) ||
string.IsNullOrWhiteSpace(data.Password) || data.Username.Length > 128 || data.Password.Length > 1024)
{
await ReplyAsync(context.Response, 400, new { error = "Invalid login request" });
return;
}
string key = data.Username.Trim().ToLowerInvariant();
Attempts throttle = _attempts.GetOrAdd(key, _ => new Attempts());
lock (throttle)
{
if (DateTimeOffset.UtcNow > throttle.Until)
{
throttle.Count = 0;
throttle.Until = DateTimeOffset.UtcNow.AddMinutes(5);
}
if (++throttle.Count > 8)
{
context.Response.StatusCode = 429;
return;
}
}
string[] parts = data.Username.Replace('.', ' ')
.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length != 2)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
try
{
var account = _accounts.GetUserAccount(UUID.Zero, parts[0], parts[1]);
if (account is null || !account.LoginAllowed)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
string hashed = Util.Md5Hash(data.Password);
string loginToken = _auth.Authenticate(account.PrincipalID, hashed, 30);
if (!UUID.TryParse(loginToken, out var session) || session == UUID.Zero)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
try { _auth.Release(account.PrincipalID, loginToken); }
catch (Exception e) { Log.Warn("[SYS.API] Failed to release one-time auth session", e); }
if (account.UserLevel < 200)
{
await ReplyAsync(context.Response, 403, new { error = "Access Denied – Keine Berechtigung" });
return;
}
lock (throttle) throttle.Count = 0;
string sid = RandomSecret();
AdminSession s = new(account.PrincipalID, account.Name, RandomSecret(),
DateTimeOffset.UtcNow.AddHours(1));
_sessions[sid] = s;
bool secure = context.Request.IsSecureConnection || IsTrustedProxy(context.Request);
context.Response.AppendHeader("Set-Cookie", $"ogl_sysapi={sid}; Path=/; " +
"HttpOnly; SameSite=Strict; Max-Age=3600" + (secure ? "; Secure" : ""));
await ReplyAsync(context.Response, 200, new { name = s.Name, csrf = s.Csrf, minLevel = 200 });
Log.Info("[SYS.API] Web administrator authenticated (UserLevel>=200).");
}
catch (Exception e)
{
Log.Error("[SYS.API] Login validation unavailable", e);
await ReplyAsync(context.Response, 503, new { error = "Authentifizierungsdienst nicht erreichbar" });
}
}
private async Task HandleAsync(HttpListenerContext context)
{
try
{
var req = context.Request;
var response = context.Response;
SecurityHeaders(response);
string path = req.Url?.AbsolutePath ?? "";
bool isGet = req.HttpMethod == "GET";
if (isGet && path is "/" or "/index.html")
{
await AssetAsync(response, "index.html", "text/html; charset=utf-8");
return;
}
if (isGet && path == "/app.js") { await AssetAsync(response, "app.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/style.css") { await AssetAsync(response, "style.css", "text/css; charset=utf-8"); return; }
if (isGet && path == "/ogl-mascot.webp") { await AssetAsync(response, "ogl-mascot.webp", "image/webp"); return; }
if (isGet && path == "/v1/health")
{
await ReplyAsync(response, 200, new { status = "online", module = "sys.api",
port = 8850, version = 1 }); return;
}
if (req.HttpMethod == "POST" && path == "/api/session/login")
{
if (!SameOrigin(req))
{
await ReplyAsync(response, 403, new { error = "Origin rejected" }); return;
}
await LoginAsync(context); return;
}
if (isGet && path is "/api/v1/portal/ping" or "/api/v1/portal/capabilities")
{
if (!HasPortalToken(req))
{
await ReplyAsync(response, 401, new { error = "Invalid portal credential" }); return;
}
await ReplyAsync(response, 200, path.EndsWith("ping")
? new { ok = true, service = "sys.api", apiVersion = "v1" }
: (object)new { apiVersion = "v1", authentication = "single-machine-token", endpoints = new[]
{ "/api/v1/portal/ping", "/api/v1/portal/capabilities",
"/api/v1/UserAccounts/lists", "/api/v1/UserAccounts/{uuid}",
"/api/v1/GridUser/lists", "/api/v1/Presence/lists",
"/api/v1/Regions/lists", "/api/v1/UUID/resolve?uuid={uuid}" },
legacyWorldApiUnchanged = true });
return;
}
// Live SQL read-model: strictly allowlisted, read-only, paginated,
// accessible only to a valid backend token OR a revalidated admin.
// The legacy /UserAccounts/lists spelling is an authenticated alias.
string apiPath = path.StartsWith("/api/v1/", StringComparison.Ordinal)
? path[7..] : path;
bool listRoute = apiPath is "/UserAccounts/lists" or "/GridUser/lists" or
"/Presence/lists" or "/Regions/lists";
bool resolveRoute = apiPath == "/UUID/resolve";
bool accountRoute = apiPath.StartsWith("/UserAccounts/", StringComparison.Ordinal) &&
apiPath != "/UserAccounts/lists";
if (listRoute || resolveRoute || accountRoute)
{
if (!HasPortalToken(req) && !TryAdmin(req, out _))
{
await ReplyAsync(response, 401, new { error = "Authorization required" }); return;
}
if (!isGet)
{
await ReplyAsync(response, 405, new { error = "Read-only endpoint" }); return;
}
if (_readModel is null)
{
await ReplyAsync(response, 503, new { error = "Read model unavailable" }); return;
}
try
{
if (listRoute)
{
var query = System.Web.HttpUtility.ParseQueryString(req.Url?.Query ?? "");
if (!int.TryParse(query["limit"] ?? "50", out int limit) ||
!int.TryParse(query["offset"] ?? "0", out int offset) ||
limit is < 1 or > 100 || offset is < 0 or > 1000000 ||
(query["search"]?.Length ?? 0) > 80)
{
await ReplyAsync(response, 400, new { error = "Invalid pagination or search" }); return;
}
string table = apiPath.Split('/', StringSplitOptions.RemoveEmptyEntries)[0];
await ReplyAsync(response, 200, _readModel.List(table, limit, offset, query["search"]));
return;
}
if (resolveRoute)
{
string? uuid = System.Web.HttpUtility.ParseQueryString(req.Url?.Query ?? "")["uuid"];
if (!Guid.TryParse(uuid, out _))
{
await ReplyAsync(response, 400, new { error = "UUID must be valid" }); return;
}
await ReplyAsync(response, 200, _readModel.Resolve(uuid!)); return;
}
string id = apiPath["/UserAccounts/".Length..];
if (!Guid.TryParse(id, out _))
{
await ReplyAsync(response, 400, new { error = "UUID must be valid" }); return;
}
object? account = _readModel.Account(id);
await ReplyAsync(response, account is null ? 404 : 200,
account ?? new { error = "Account not found" });
return;
}
catch (Exception e)
{
// Never expose SQL/configuration/secrets in JSON or logs.
Log.WarnFormat("[SYS.API] Live database read unavailable ({0})", e.GetType().Name);
await ReplyAsync(response, 503, new { error = "Database read temporarily unavailable" });
return;
}
}
if (!TryAdmin(req, out AdminSession admin))
{
await ReplyAsync(response, 401, new { error = "Access Denied – Keine Berechtigung" }); return;
}
if (!isGet && (!SameOrigin(req) ||
!string.Equals(req.Headers["X-OGL-CSRF"], admin.Csrf, StringComparison.Ordinal)))
{
await ReplyAsync(response, 403, new { error = "CSRF protection denied" }); return;
}
if (path == "/api/admin/alerts")
{
if (req.HttpMethod != "POST")
{
await ReplyAsync(response, 405, new { error = "POST required" }); return;
}
if (_alertPublisher is null)
{
await ReplyAsync(response, 503, new { error = "Global alerts require an enabled NexBus relay" }); return;
}
AlertInput? input = await ReadInput<AlertInput>(req);
if (input is null || !SysApiAlertCommand.TryParse(input.Command, out string alertMessage))
{
await ReplyAsync(response, 400,
new { error = "Only alert <message> is supported (1–500 characters, one line)" });
return;
}
await _alertGate.WaitAsync(_stop.Token);
try
{
if (DateTimeOffset.UtcNow - _lastAlertAt < TimeSpan.FromSeconds(5))
{
await ReplyAsync(response, 429, new { error = "Bitte mindestens fünf Sekunden zwischen Alerts warten" });
return;
}
Guid eventId;
try { eventId = await _alertPublisher.PublishAsync(alertMessage, admin.Avatar, _stop.Token); }
catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException or
OperationCanceledException or JsonException)
{
Log.WarnFormat("[SYS.API ALERT] Central NexBus rejected alert ({0})", ex.GetType().Name);
await ReplyAsync(response, 503, new { error = "NexBus alert distribution unavailable" });
return;
}
_lastAlertAt = DateTimeOffset.UtcNow;
// Audit only the event ID and administrator; do not log private message text.
Log.InfoFormat("[SYS.API ALERT] Queued global alert {0} by {1}", eventId, admin.Avatar);
await ReplyAsync(response, 202, new
{
queued = true, eventId, command = "alert",
status = "NexBus accepted; delivery to individual regions is asynchronous"
});
}
finally { _alertGate.Release(); }
return;
}
if (isGet && path == "/api/session")
{
await ReplyAsync(response, 200, new { user = admin.Name,
csrf = admin.Csrf, minLevel = 200 }); return;
}
if (req.HttpMethod == "POST" && path == "/api/session/logout")
{
string? sid = req.Cookies["ogl_sysapi"]?.Value;
if (sid != null) _sessions.TryRemove(sid, out _);
response.AppendHeader("Set-Cookie",
"ogl_sysapi=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0");
await ReplyAsync(response, 200, new { ok = true }); return;
}
if (isGet && path == "/api/admin/overview")
{
await ReplyAsync(response, 200, new
{
service = "OpenGenesisLINK System API",
generation = "GEN 1",
api = "v1",
status = "operational",
port = 8850,
internalPort = new Uri(_http.Prefixes.First()).Port,
tlsConfigured = _publicOrigin is not null,
uptimeSeconds = (long)(DateTimeOffset.UtcNow - _startup).TotalSeconds,
portalTokenPresent = true,
session = admin.Name,
minAdminLevel = 200,
oldWorldApiUnchanged = true,
alertsAvailable = _alertPublisher is not null,
endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities", "/api/admin/alerts" }
});
return;
}
await ReplyAsync(response, 404, new { error = "Not found" });
}
catch (Exception e)
{
Log.Error("[SYS.API] Request failed", e);
try { await ReplyAsync(context.Response, 500, new { error = "Internal error" }); }
catch { }
}
finally { try { context.Response.Close(); } catch { } }
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_stop.Cancel();
_http.Stop();
_http.Close();
_sessions.Clear();
_alertPublisher?.Dispose();
_alertGate.Dispose();
_stop.Dispose();
}
}