// SPDX-License-Identifier: MPL-2.0 using System.Net; using Nini.Config; using System.Net.Http; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.Json; using OpenMetaverse; using OpenSim.Services.Interfaces; using OpenGenesisLINK.SysApi; using NexVerse.Core.Messaging; using NexVerse.Core.Economy; using OpenSim.Framework; using System.Security.Cryptography; // Invalid opt-in settings must not crash ROBUST or disable the legacy World API. var unavailable = new IniConfigSource(); unavailable.Configs.Add("SysApi").Set("Enabled", "true"); new SysApiConnector(unavailable, null!, "SysApi"); var dir = Path.Combine(Path.GetTempPath(), "ogl-sysapi-smoke-" + Guid.NewGuid().ToString("N")); string first = PortalSecretStore.OpenOrCreate(dir); string second = PortalSecretStore.OpenOrCreate(dir); if (first != second || first.Length != 128 || File.ReadAllText(Path.Combine(dir, ".env")).Contains("CorrectSecret")) throw new Exception("Token store not stable or secure"); if (!OperatingSystem.IsWindows() && (File.GetUnixFileMode(Path.Combine(dir, ".env")) & (UnixFileMode.GroupRead | UnixFileMode.OtherRead)) != 0) throw new Exception("Secret permissions not private"); // Real signed transport contract: SYS.API must publish only to the ROBUST // loopback NexBus endpoint and preserve HMAC, event ID and exact message. using (var reserve = new TcpListener(IPAddress.Loopback, 0)) { reserve.Start(); int nexBusPort = ((IPEndPoint)reserve.LocalEndpoint).Port; reserve.Stop(); using var receiver = new HttpListener(); receiver.Prefixes.Add($"http://127.0.0.1:{nexBusPort}/"); receiver.Start(); string relayKey = new string('K', 64); Task inbound = Task.Run(async () => { HttpListenerContext ctx = await receiver.GetContextAsync().WaitAsync(TimeSpan.FromSeconds(6)); if (ctx.Request.Url?.AbsolutePath != "/internal/nexbus/v1/events" || ctx.Request.HttpMethod != "POST") throw new Exception("Alert used wrong NexBus endpoint"); using var bytes = new MemoryStream(); await ctx.Request.InputStream.CopyToAsync(bytes); if (!NexBusProtocol.Verify(bytes.ToArray(), relayKey, ctx.Request.Headers["X-NexBus-Signature"])) throw new Exception("Unsigned or invalid alert relay"); NexEvent packet = NexBusProtocol.Deserialize(bytes.ToArray()); if (packet.Name != "admin.alert.requested" || packet.Source != "opengenesislink.sysapi" || packet.Data["message"] != "INFO: Testnachricht" || packet.Data["command"] != "alert") throw new Exception("Alert event fields incorrect"); ctx.Response.StatusCode = 202; byte[] acknowledgement = Encoding.UTF8.GetBytes("{\"accepted\":true}"); ctx.Response.ContentType = "application/json"; ctx.Response.ContentLength64 = acknowledgement.Length; await ctx.Response.OutputStream.WriteAsync(acknowledgement); ctx.Response.Close(); return packet.EventId; }); using var relay = new NexBusSysApiAlertPublisher( nexBusPort, "/internal/nexbus/v1/events", relayKey); Guid expected = await relay.PublishAsync("INFO: Testnachricht", UUID.Random(), CancellationToken.None); Guid actual = await inbound.WaitAsync(TimeSpan.FromSeconds(6)); if (expected != actual) throw new Exception("Alert event ID changed during relay"); Console.WriteLine("PASS: SYS.API signed NexBus loopback alert transport and payload"); } using var free = new TcpListener(IPAddress.Loopback, 0); free.Start(); int port = ((IPEndPoint)free.LocalEndpoint).Port; free.Stop(); var alertSink = new TestAlertPublisher(); // In-memory test ledger only; absolutely no production NV$ or SQL connections. var fakeMoneyStore = new InMemoryNexLedgerStore(); var fakeEconomy = new NexEconomyService( new NexDoubleEntryLedger(fakeMoneyStore), fakeMoneyStore); var moneyBridge = new SysApiNvMoney( DispatchProxy.Create(), adminEnabled:true, portalEnabled:true, maxNv:10000, portalToken:new string('C', 64), getEconomy:()=>fakeEconomy); if (SysApiNvMoney.NvPerEuro != 100 || SysApiNvMoney.EuroCentsToNv(100) != 100 || SysApiNvMoney.EuroCentsToNv(150) != 150) throw new Exception("100 NV$ per EUR fixed-point conversion regression"); using var host = new SysApiHost(port, "https://sysapi.example.test:8850", DispatchProxy.Create(), DispatchProxy.Create(), first, new FakeSysApiReadModel(), accessPolicy: new FakeSysApiAccessPolicyStore(), policyReadToken: new string('A',64), alertPublisher: alertSink, nvMoney: moneyBridge); host.Start(); try { using var client = new HttpClient(new HttpClientHandler { UseCookies = true }) { BaseAddress = new Uri($"http://127.0.0.1:{port}/"), Timeout = TimeSpan.FromSeconds(8) }; static void Expect(HttpStatusCode actual, HttpStatusCode desired, string test) { if (actual != desired) throw new Exception($"{test}: expected {desired}, got {actual}"); } using (var anonymousMoney = await client.GetAsync("/api/admin/money/status")) Expect(anonymousMoney.StatusCode,HttpStatusCode.Unauthorized,"money status auth"); using (var anonymousPortal = await client.PostAsync("/api/v1/portal/money/payouts", new StringContent("{}", Encoding.UTF8, "application/json"))) Expect(anonymousPortal.StatusCode,HttpStatusCode.Unauthorized,"portal money token required"); using(var moneyJs=await client.GetAsync("/money.js")) { Expect(moneyJs.StatusCode,HttpStatusCode.OK,"embedded money JavaScript"); string script=await moneyJs.Content.ReadAsStringAsync(); if(!script.Contains("/api/admin/money/payouts") || !script.Contains("crypto.randomUUID()") ||script.Contains("innerHTML")) throw new Exception("Money UI does not use secure payout request contract"); } using var index = await client.GetAsync("/"); Expect(index.StatusCode, HttpStatusCode.OK, "Index"); if (!(await index.Content.ReadAsStringAsync()).Contains("Control the")) throw new Exception("Interactive command center absent"); if (!index.Headers.Contains("Content-Security-Policy")) throw new Exception("Missing restrictive CSP"); foreach (string asset in new[] {"/style.css","/app.js","/ogl-mascot.webp"}) { using var file = await client.GetAsync(asset); Expect(file.StatusCode, HttpStatusCode.OK, "asset "+asset); if (asset.EndsWith(".webp") && (await file.Content.ReadAsByteArrayAsync()).Length < 60000) throw new Exception("Official OGL mascot asset not embedded"); } using var health = await client.GetAsync("/v1/health"); Expect(health.StatusCode, HttpStatusCode.OK, "health"); using var anonymous = await client.GetAsync("/api/admin/overview"); Expect(anonymous.StatusCode, HttpStatusCode.Unauthorized, "dashboard 401"); using (var anonymousAlert = await client.PostAsync("/api/admin/alerts", new StringContent("{\"command\":\"alert INFO: public\"}", Encoding.UTF8, "application/json"))) Expect(anonymousAlert.StatusCode, HttpStatusCode.Unauthorized, "anonymous alert blocked"); if (!SysApiAlertCommand.TryParse("alert WARNUNG: Test", out string parsed) || parsed != "WARNUNG: Test" || !SysApiAlertCommand.TryParse("ALERT INFO: Test", out parsed) || parsed != "INFO: Test" || SysApiAlertCommand.TryParse("alert", out _) || SysApiAlertCommand.TryParse("restart", out _) || SysApiAlertCommand.TryParse("alert Test\nshutdown", out _) || SysApiAlertCommand.TryParse("alert " + new string('x', 501), out _)) throw new Exception("Alert command parser must allow alerts only"); foreach (string protectedUrl in new [] { "/api/v1/UserAccounts/lists", "/UserAccounts/lists", "/api/v1/GridUser/lists", "/api/v1/Presence/lists", "/api/v1/Regions/lists", "/api/v1/UUID/resolve?uuid=00000000-0000-0000-0000-000000000001" }) { using var blocked = await client.GetAsync(protectedUrl); Expect(blocked.StatusCode, HttpStatusCode.Unauthorized, "unauthorized read model " + protectedUrl); } using (var anonymousPolicy = await client.GetAsync("/api/v1/policies/active")) Expect(anonymousPolicy.StatusCode, HttpStatusCode.Unauthorized, "anonymous policy blocked"); using (var policyRequest = new HttpRequestMessage(HttpMethod.Get, "/api/v1/policies/active")) { policyRequest.Headers.Authorization = new("Bearer", new string('A',64)); using var active = await client.SendAsync(policyRequest); Expect(active.StatusCode, HttpStatusCode.OK, "signed policy reader"); using var payload = JsonDocument.Parse(await active.Content.ReadAsStringAsync()); var rules = payload.RootElement.GetProperty("citizenRules"); if (rules.GetProperty("version").GetString() != "1.0" || rules.GetProperty("url").GetString() != "https://stadt-nexverse.de/service/tos") throw new Exception("Lost authoritative citizen-rules policy endpoint"); Console.WriteLine("PASS: SYS.API full citizen-rules/denylist policy authority preserved"); } using var noToken = await client.GetAsync("/api/v1/portal/ping"); Expect(noToken.StatusCode, HttpStatusCode.Unauthorized, "portal no token"); client.DefaultRequestHeaders.Authorization = new("Bearer", first); using var yesToken = await client.GetAsync("/api/v1/portal/ping"); Expect(yesToken.StatusCode, HttpStatusCode.OK, "portal token"); foreach (string resource in new[] { "UserAccounts", "GridUser", "Presence", "Regions" }) { using var listing = await client.GetAsync($"/api/v1/{resource}/lists?limit=5&offset=0"); Expect(listing.StatusCode, HttpStatusCode.OK, resource + " listing"); string json = await listing.Content.ReadAsStringAsync(); if (!json.Contains("Test Operator") || json.Contains("Email") || json.Contains("password") || !json.Contains("pagination")) throw new Exception("Unsafe or incomplete " + resource + " listing"); } using (var account = await client.GetAsync("/api/v1/UserAccounts/00000000-0000-0000-0000-000000000001")) Expect(account.StatusCode, HttpStatusCode.OK, "single account"); using (var resolver = await client.GetAsync("/api/v1/UUID/resolve?uuid=00000000-0000-0000-0000-000000000001")) Expect(resolver.StatusCode, HttpStatusCode.OK, "resolve UUID"); using (var alias = await client.GetAsync("/UserAccounts/lists")) Expect(alias.StatusCode, HttpStatusCode.OK, "requested legacy alias"); using (var search = await client.GetAsync("/api/v1/UserAccounts/lists?limit=200")) Expect(search.StatusCode, HttpStatusCode.BadRequest, "pagination capped"); using (var search = await client.GetAsync("/api/v1/UserAccounts/lists?offset=-10")) Expect(search.StatusCode, HttpStatusCode.BadRequest, "negative offset"); using (var badUuid = await client.GetAsync("/api/v1/UUID/resolve?uuid=not-uuid")) Expect(badUuid.StatusCode, HttpStatusCode.BadRequest, "invalid UUID"); using (var post = await client.PostAsync("/api/v1/UserAccounts/lists",new StringContent("{}"))) Expect(post.StatusCode, HttpStatusCode.MethodNotAllowed, "read only POST denied"); using (var firstPage = await client.GetAsync("/api/v1/UserAccounts/lists")) { string before = await firstPage.Content.ReadAsStringAsync(); FakeSysApiReadModel.Revision++; using var secondPage = await client.GetAsync("/api/v1/UserAccounts/lists"); string after = await secondPage.Content.ReadAsStringAsync(); if (before == after) throw new Exception("Read model response was cached after source changed"); } Console.WriteLine("PASS: SYS.API protected paginated live JSON UserAccounts/GridUser/Presence/Regions and UUID resolver"); client.DefaultRequestHeaders.Authorization = new("Bearer", new string('a',128)); using var badToken = await client.GetAsync("/api/v1/portal/ping"); Expect(badToken.StatusCode, HttpStatusCode.Unauthorized, "portal wrong token"); client.DefaultRequestHeaders.Authorization = null; async Task LoginAsync(string pw) { return await client.PostAsync("/api/session/login", new StringContent(JsonSerializer.Serialize(new { username="Test Operator",password=pw }), Encoding.UTF8, "application/json")); } using var bad = await LoginAsync("bad-password"); Expect(bad.StatusCode, HttpStatusCode.Unauthorized, "wrong password"); AccountProxy.Level = 199; using var denied = await LoginAsync("CorrectSecret"); Expect(denied.StatusCode, HttpStatusCode.Forbidden, "user level below 200"); AccountProxy.Level = 200; using var allowed = await LoginAsync("CorrectSecret"); Expect(allowed.StatusCode, HttpStatusCode.OK, "user level 200"); using var admin = await client.GetAsync("/api/admin/overview"); Expect(admin.StatusCode, HttpStatusCode.OK, "authorized dashboard"); using JsonDocument loginResponse = JsonDocument.Parse(await allowed.Content.ReadAsStringAsync()); string csrf = loginResponse.RootElement.GetProperty("csrf").GetString()!; using (var withoutCsrf = await client.PostAsync("/api/admin/alerts", new StringContent("{\"command\":\"alert WARNUNG: Test\"}", Encoding.UTF8, "application/json"))) Expect(withoutCsrf.StatusCode, HttpStatusCode.Forbidden, "alert CSRF required"); client.DefaultRequestHeaders.Add("X-OGL-CSRF", csrf); // Real ledger bookkeeping and replay/reconciliation tests on a volatile // IN-MEMORY store. No production user, SQL row, payment or funds changed. using (var moneyStatus = await client.GetAsync("/api/admin/money/status")) { Expect(moneyStatus.StatusCode,HttpStatusCode.OK,"money status admin"); if (!(await moneyStatus.Content.ReadAsStringAsync()).Contains("100")) throw new Exception("Invalid fixed rate in money status"); } Guid payoutRequestId = Guid.NewGuid(); var moneyPayload = new { avatarId = AccountProxy.Principal.ToString(), amountNv = 125, description = "Automated test payout", requestId = payoutRequestId.ToString("D"), source = "admin-manual" }; async Task SendMoney(object body) => await client.PostAsync("/api/admin/money/payouts", new StringContent(JsonSerializer.Serialize(body),Encoding.UTF8,"application/json")); using (var firstPayout = await SendMoney(moneyPayload)) Expect(firstPayout.StatusCode,HttpStatusCode.Created,"first money credit"); if (fakeEconomy.GetBalance(AccountProxy.Principal.Guid) != 125) throw new Exception("Incorrect ledger balance after first admin payout"); using (var duplicatePayout = await SendMoney(moneyPayload)) Expect(duplicatePayout.StatusCode,HttpStatusCode.OK,"duplicate money idempotency"); if (fakeEconomy.GetBalance(AccountProxy.Principal.Guid) != 125) throw new Exception("Duplicate payout credited more than once"); using (var alteredPayout = await SendMoney(new { avatarId=AccountProxy.Principal.ToString(),amountNv=126, description="Automated test payout",requestId=payoutRequestId.ToString("D"), source="admin-manual" })) Expect(alteredPayout.StatusCode,HttpStatusCode.Conflict,"replay with altered payout rejected"); using (var fakeProviderPayment = await SendMoney(new { avatarId=AccountProxy.Principal.ToString(),amountNv=100, description="pretend stripe payment",requestId=Guid.NewGuid().ToString("D"), source="stripe" })) Expect(fakeProviderPayment.StatusCode,HttpStatusCode.BadRequest, "unverified Stripe payment must never mint NV$"); using (var amountTooLarge = await SendMoney(new { avatarId=AccountProxy.Principal.ToString(),amountNv=10001, description="too large amount",requestId=Guid.NewGuid().ToString("D"), source="admin-manual" })) Expect(amountTooLarge.StatusCode,HttpStatusCode.BadRequest,"limit enforced"); using (var portalWithoutProxy = new HttpRequestMessage( HttpMethod.Post,"/api/v1/portal/money/payouts")) { portalWithoutProxy.Headers.Authorization=new("Bearer",new string('C',64)); portalWithoutProxy.Content=new StringContent(JsonSerializer.Serialize(new { avatarId=AccountProxy.Principal.ToString(),amountNv=50, description="Portal test grant",requestId=Guid.NewGuid().ToString("D"), source="portal-manual"}),Encoding.UTF8,"application/json"); using var rejection=await client.SendAsync(portalWithoutProxy); Expect(rejection.StatusCode,HttpStatusCode.Unauthorized, "portal token must never bypass trusted TLS proxy"); } if(fakeEconomy.GetBalance(AccountProxy.Principal.Guid)!=125) throw new Exception("Unauthorized portal call changed NV$ balance"); // Valid backend credential is distinct from the general read-only portal token. // It may authorize an explicit manual grant, but not a claimed provider settlement. Guid portalRequestId=Guid.NewGuid(); async Task PortalMoney(string source,long amount,Guid reqId) { var msg=new HttpRequestMessage(HttpMethod.Post,"/api/v1/portal/money/payouts"); msg.Headers.Authorization=new("Bearer",new string('C',64)); msg.Headers.TryAddWithoutValidation("X-Forwarded-Proto","https"); msg.Headers.TryAddWithoutValidation("X-Forwarded-Host","sysapi.example.test:8850"); msg.Content=new StringContent(JsonSerializer.Serialize(new{ avatarId=AccountProxy.Principal.ToString(),amountNv=amount, description="Portal test grant",requestId=reqId.ToString("D"), source=source }),Encoding.UTF8,"application/json"); using(msg) return await client.SendAsync(msg); } using(var settled=await PortalMoney("portal-manual",50,portalRequestId)) Expect(settled.StatusCode,HttpStatusCode.Created,"authenticated portal grant"); using(var repeated=await PortalMoney("portal-manual",50,portalRequestId)) Expect(repeated.StatusCode,HttpStatusCode.OK,"portal at most one grant"); using(var alteredPortal=await PortalMoney("portal-manual",75,portalRequestId)) Expect(alteredPortal.StatusCode,HttpStatusCode.Conflict,"portal replay mismatch rejected"); using(var unverified=await PortalMoney("paypal",50,Guid.NewGuid())) Expect(unverified.StatusCode,HttpStatusCode.BadRequest,"claimed Paypal settlement never accepted"); if(fakeEconomy.GetBalance(AccountProxy.Principal.Guid)!=175) throw new Exception("Portal payments failed double-entry or idempotency"); Console.WriteLine("PASS: SYS.API portal token isolation, TLS proxy gate, in-memory ledger credits and payment-provider denial"); Console.WriteLine("PASS: SYS.API NV$ exact 100:1 rate, admin ledger credit, idempotency, mismatch rejection, portal auth and fake-payment denial"); async Task PostAlert(string command) => await client.PostAsync("/api/admin/alerts", new StringContent(JsonSerializer.Serialize(new { command }), Encoding.UTF8, "application/json")); using (var invalidAlert = await PostAlert("restart now")) Expect(invalidAlert.StatusCode, HttpStatusCode.BadRequest, "arbitrary console command forbidden"); using (var multilineAlert = await PostAlert("alert INFO: Hello\nshutdown")) Expect(multilineAlert.StatusCode, HttpStatusCode.BadRequest, "multiline alert forbidden"); using (var notice = await PostAlert("alert WARNUNG: Testbenachrichtigung")) { Expect(notice.StatusCode, HttpStatusCode.Accepted, "alert queued by signed relay"); if (!(await notice.Content.ReadAsStringAsync()).Contains("\"eventId\"")) throw new Exception("No alert event ID in receipt"); } if (alertSink.Calls != 1 || alertSink.LastMessage != "WARNUNG: Testbenachrichtigung") throw new Exception("Alert not passed correctly to signed bus"); using (var repeat = await PostAlert("alert INFO: again")) Expect(repeat.StatusCode, (HttpStatusCode)429, "global alert rate limit"); Console.WriteLine("PASS: sys.api global alert authentication, CSRF, parser, rate limit and dispatch"); using (var authenticatedList = await client.GetAsync("/api/v1/UserAccounts/lists")) Expect(authenticatedList.StatusCode, HttpStatusCode.OK, "authorized admin read model"); AccountProxy.Level = 0; using var revoked = await client.GetAsync("/api/admin/overview"); Expect(revoked.StatusCode, HttpStatusCode.Unauthorized, "revoked permission"); using (var afterRevocation = await PostAlert("alert INFO: prohibited")) Expect(afterRevocation.StatusCode, HttpStatusCode.Unauthorized, "revoked admin cannot alert"); using (var revokedList = await client.GetAsync("/api/v1/UserAccounts/lists")) Expect(revokedList.StatusCode, HttpStatusCode.Unauthorized, "revoked read model"); var forged = new HttpRequestMessage(HttpMethod.Post,"/api/session/login"); forged.Headers.TryAddWithoutValidation("Origin","https://attacker.example"); forged.Content = new StringContent("{}",Encoding.UTF8,"application/json"); using var forgedResult = await client.SendAsync(forged); Expect(forgedResult.StatusCode, HttpStatusCode.Forbidden, "cross-origin"); var foreignHost = new HttpRequestMessage(HttpMethod.Get,"/"); foreignHost.Headers.Host="attacker.example"; using var foreign = await client.SendAsync(foreignHost); Expect(foreign.StatusCode, HttpStatusCode.NotFound, "host binding"); Console.WriteLine("PASS: sys.api avatar UserLevel 200 gate, revoked session, OAuth-free portal token, official mascot, CSP and origin security"); } finally { Directory.Delete(dir,recursive:true); } public class AccountProxy : DispatchProxy { public static int Level = 199; public static UUID Principal = UUID.Random(); protected override object? Invoke(MethodInfo? method, object?[]? args) { if (method?.Name == "GetUserAccount") return new UserAccount(UUID.Zero, Principal, "Test", "Operator", "") { UserLevel = Level }; throw new NotImplementedException(method?.Name); } } public class AuthenticationProxy : DispatchProxy { protected override object? Invoke(MethodInfo? method, object?[]? args) => method?.Name switch { "Authenticate" when (string)args![1]! == Util.Md5Hash("CorrectSecret") => UUID.Random().ToString(), "Authenticate" => "", "Release" => true, _ => throw new NotImplementedException(method?.Name) }; } public sealed class FakeSysApiReadModel : ISysApiReadModel { public static int Revision = 1; public object List(string resource, int limit, int offset, string? search) => new { resource, generatedAtUtc = DateTimeOffset.UtcNow, pagination = new { limit, offset, total = 1, hasMore = false }, items = new [] { new { uuid = "00000000-0000-0000-0000-000000000001", avatarName = "Test Operator", displayName = "Test Operator", revision = Revision } } }; public object? Account(string uuid) => new { uuid, avatarName = "Test Operator", displayName = "Test Operator" }; public object? AdminProfile(string uuid) => new { uuid, avatarName = "Test Operator" }; public object Resolve(string uuid) => new { uuid, found = true, avatarName = "Test Operator", source = "UserAccounts" }; } public sealed class TestAlertPublisher : ISysApiAlertPublisher { public int Calls; public string LastMessage = ""; public Task PublishAsync(string message, UUID administrator, CancellationToken cancellationToken) { if (administrator == UUID.Zero) throw new Exception("Missing admin UUID"); LastMessage = message; Interlocked.Increment(ref Calls); return Task.FromResult(Guid.NewGuid()); } public void Dispose() { } } public sealed class FakeSysApiAccessPolicyStore : ISysApiAccessPolicyStore { public object Active() => new { viewers = new string[0], grids = new string[0], citizenRules = new { version = "1.0", url = "https://stadt-nexverse.de/service/tos" } }; public object CitizenRules() => new { version = "1.0", url = "https://stadt-nexverse.de/service/tos", sha256 = new string('a',64) }; public object ListViewers() => new { items = new string[0] }; public object ListGrids() => new { items = new string[0] }; public void PublishCitizenRules(string version,string url,string sha256,string actor) => throw new NotSupportedException(); public void SetViewer(string name,string reason,string actor) => throw new NotSupportedException(); public void RemoveViewer(string name,string actor) => throw new NotSupportedException(); public void SetGrid(string address,string reason,string actor) => throw new NotSupportedException(); public void RemoveGrid(string address,string actor) => throw new NotSupportedException(); }