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.
This commit is contained in:
1 parent
07e34055db
commit
e81076f33c
15 files changed
+504
-6
No files matched your search
@@ -977,6 +977,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
python3 tools/ci/verify_sys_api_foundation.py
|
||||
python3 tools/ci/verify_sys_api_readmodel.py
|
||||
python3 tools/ci/verify_sysapi_global_alert.py
|
||||
bash -n tools/ops/sys-api-tls-install.sh
|
||||
dotnet build addons/SysApi/sys.api.csproj --configuration Release --no-restore
|
||||
dotnet run --project tools/ci/SysApiSmoke/SysApiSmoke.csproj --configuration Release
|
||||
|
||||
@@ -93,6 +93,7 @@ namespace NexVerse.RegionModules.NodeAgent
|
||||
private IDisposable m_MoveRegionSubscription;
|
||||
private IDisposable m_RegionLifecycleSubscription;
|
||||
private IDisposable m_NodeControlSubscription;
|
||||
private IDisposable m_AdminAlertSubscription;
|
||||
private IDisposable m_NodeUpdateSubscription;
|
||||
private IDisposable m_NodeLiveUpdateSubscription;
|
||||
private bool m_LiveUpdaterEnabled;
|
||||
@@ -348,6 +349,7 @@ namespace NexVerse.RegionModules.NodeAgent
|
||||
"region.control.lifecycle.requested",
|
||||
HandleRegionLifecycleCommand);
|
||||
m_NodeControlSubscription = m_Bus.Subscribe("node.control.requested", HandleNodeControlCommand);
|
||||
m_AdminAlertSubscription = m_Bus.Subscribe("admin.alert.requested", HandleAdminAlert);
|
||||
m_NodeUpdateSubscription = m_Bus.Subscribe("node.update.stage.requested", HandleStageUpdateCommand);
|
||||
m_NodeLiveUpdateSubscription = m_Bus.Subscribe("node.update.live.requested", HandleLiveUpdateCommand);
|
||||
m_OarControlSubscription = m_Bus.Subscribe("archive.oar.requested", HandleOarCommand);
|
||||
@@ -408,6 +410,47 @@ namespace NexVerse.RegionModules.NodeAgent
|
||||
NodeData()));
|
||||
}
|
||||
|
||||
// The NexBus event is authenticated and deduplicated by the existing
|
||||
// signed transport. One shared NodeAgent fans it out to every Scene in
|
||||
// this simulator process, including multi-region processes.
|
||||
private void HandleAdminAlert(NexEvent alert)
|
||||
{
|
||||
if (!m_Enabled || Volatile.Read(ref m_Stopping) != 0 ||
|
||||
alert == null || alert.Data == null ||
|
||||
!string.Equals(alert.Source, "opengenesislink.sysapi", StringComparison.Ordinal) ||
|
||||
!alert.Data.TryGetValue("command", out string command) ||
|
||||
command != "alert" ||
|
||||
!alert.Data.TryGetValue("administrator", out string operatorId) ||
|
||||
!UUID.TryParse(operatorId, out UUID administrator) || administrator == UUID.Zero ||
|
||||
!alert.Data.TryGetValue("message", out string message) ||
|
||||
string.IsNullOrWhiteSpace(message) || message.Length > 500 ||
|
||||
message.Any(ch => char.IsControl(ch) || ch is '\u2028' or '\u2029'))
|
||||
return;
|
||||
TimeSpan age = DateTimeOffset.UtcNow - alert.Timestamp;
|
||||
if (age < TimeSpan.FromSeconds(-5) || age > TimeSpan.FromSeconds(30))
|
||||
return;
|
||||
|
||||
int notifiedRegions = 0;
|
||||
foreach (Scene scene in m_Scenes.Values)
|
||||
{
|
||||
try
|
||||
{
|
||||
IDialogModule dialog = scene.RequestModuleInterface<IDialogModule>();
|
||||
if (dialog == null) continue;
|
||||
// Same viewer notification as the native console "alert".
|
||||
dialog.SendGeneralAlert(message);
|
||||
++notifiedRegions;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_Log.WarnFormat("[NEX-ALERT] Region {0} failed for event {1} ({2})",
|
||||
scene.RegionInfo.RegionID, alert.EventId, e.GetType().Name);
|
||||
}
|
||||
}
|
||||
m_Log.InfoFormat("[NEX-ALERT] Event {0} from Sys.API broadcast to {1} local regions on node {2}",
|
||||
alert.EventId, notifiedRegions, m_NodeId);
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (!m_Enabled || Interlocked.Exchange(ref m_Stopping, 1) != 0)
|
||||
@@ -432,6 +475,8 @@ namespace NexVerse.RegionModules.NodeAgent
|
||||
m_RegionLifecycleSubscription = null;
|
||||
m_NodeControlSubscription?.Dispose();
|
||||
m_NodeControlSubscription = null;
|
||||
m_AdminAlertSubscription?.Dispose();
|
||||
m_AdminAlertSubscription = null;
|
||||
m_NodeUpdateSubscription?.Dispose();
|
||||
m_NodeUpdateSubscription = null;
|
||||
m_NodeLiveUpdateSubscription?.Dispose();
|
||||
|
||||
@@ -54,7 +54,32 @@ public sealed class SysApiConnector : ServiceConnector
|
||||
Log.WarnFormat("[SYS.API] Database read model unavailable ({0}); JSON data endpoints disabled.",
|
||||
e.GetType().Name);
|
||||
}
|
||||
var host = new SysApiHost(port, publicOrigin, accounts, authentication, token, readModel);
|
||||
// Global alerts use the pre-existing HMAC-signed NexBus. Do not
|
||||
// expose arbitrary console execution or write to any simulator INI.
|
||||
ISysApiAlertPublisher? alertPublisher = null;
|
||||
if (cfg.GetBoolean("AlertsEnabled", false))
|
||||
{
|
||||
try
|
||||
{
|
||||
var bus = config.Configs["NexBus"];
|
||||
if (bus?.GetBoolean("Enabled", false) != true ||
|
||||
string.IsNullOrWhiteSpace(bus.GetString("Peers", "")))
|
||||
throw new InvalidOperationException("Distributed NexBus with simulator peers is required");
|
||||
int robustPort = config.Configs["Const"]?.GetInt("PublicPort", 0) ?? 0;
|
||||
alertPublisher = new NexBusSysApiAlertPublisher(
|
||||
robustPort,
|
||||
bus.GetString("InboundPath", "/internal/nexbus/v1/events"),
|
||||
bus.GetString("SharedKey", ""));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A missing transport must not disable the administrative API.
|
||||
Log.WarnFormat("[SYS.API ALERT] Disabled: NexBus relay unavailable ({0})",
|
||||
ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
var host = new SysApiHost(port, publicOrigin, accounts, authentication, token,
|
||||
readModel, alertPublisher);
|
||||
host.Start();
|
||||
_host = host;
|
||||
Log.InfoFormat("[SYS.API] Foundation active on loopback 127.0.0.1:{0}; public TLS proxy port 8850 requires ACME certificate.", port);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
// Explicit "alert <message>" command only; never execute arbitrary console text.
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using NexVerse.Core.Messaging;
|
||||
using OpenMetaverse;
|
||||
|
||||
namespace OpenGenesisLINK.SysApi;
|
||||
|
||||
public interface ISysApiAlertPublisher : IDisposable
|
||||
{
|
||||
Task<Guid> PublishAsync(string message, UUID administrator, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public static class SysApiAlertCommand
|
||||
{
|
||||
public static bool TryParse(string? command, out string message)
|
||||
{
|
||||
message = "";
|
||||
if (command is null || command.Length > 512 ||
|
||||
!command.StartsWith("alert ", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
string value = command[6..].Trim();
|
||||
if (value.Length is < 1 or > 500)
|
||||
return false;
|
||||
foreach (char ch in value)
|
||||
{
|
||||
// Viewer alerts are single-line messages; avoid injected console commands.
|
||||
if (char.IsControl(ch) || ch is '\u2028' or '\u2029')
|
||||
return false;
|
||||
}
|
||||
message = value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Submits one HMAC-authenticated NexBus event to the *local* ROBUST listener.
|
||||
/// NexBus then forwards the same event ID to each configured simulator peer.
|
||||
/// HTTP 202 means queued by ROBUST, not verified delivered to every viewer.
|
||||
/// </summary>
|
||||
public sealed class NexBusSysApiAlertPublisher : ISysApiAlertPublisher
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly Uri _localEndpoint;
|
||||
private readonly string _sharedKey;
|
||||
|
||||
public NexBusSysApiAlertPublisher(int localRobustPort, string inboundPath, string sharedKey)
|
||||
{
|
||||
if (localRobustPort is < 1 or > 65535)
|
||||
throw new ArgumentOutOfRangeException(nameof(localRobustPort));
|
||||
if (inboundPath != "/internal/nexbus/v1/events")
|
||||
throw new ArgumentException("Untrusted NexBus inbound path", nameof(inboundPath));
|
||||
NexBusProtocol.ValidateSharedKey(sharedKey);
|
||||
_sharedKey = sharedKey;
|
||||
_localEndpoint = new Uri("http://127.0.0.1:" + localRobustPort + inboundPath);
|
||||
_client = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
UseProxy = false
|
||||
}) { Timeout = TimeSpan.FromSeconds(5) };
|
||||
}
|
||||
|
||||
public async Task<Guid> PublishAsync(
|
||||
string message, UUID administrator, CancellationToken cancellationToken)
|
||||
{
|
||||
if (administrator == UUID.Zero || message.Length is < 1 or > 500)
|
||||
throw new ArgumentException("Invalid alert or administrator");
|
||||
var outgoing = new NexEvent("admin.alert.requested", "opengenesislink.sysapi",
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["command"] = "alert",
|
||||
["message"] = message,
|
||||
["administrator"] = administrator.ToString()
|
||||
});
|
||||
byte[] payload = NexBusProtocol.Serialize(outgoing);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, _localEndpoint);
|
||||
request.Headers.TryAddWithoutValidation("X-NexBus-Node", "SysApi");
|
||||
request.Headers.TryAddWithoutValidation("X-NexBus-Signature",
|
||||
"sha256=" + NexBusProtocol.Sign(payload, _sharedKey));
|
||||
request.Content = new ByteArrayContent(payload);
|
||||
request.Content.Headers.ContentType =
|
||||
new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
|
||||
using HttpResponseMessage response =
|
||||
await _client.SendAsync(request, cancellationToken);
|
||||
if (response.StatusCode != HttpStatusCode.Accepted)
|
||||
throw new InvalidOperationException("NexBus did not accept the alert");
|
||||
|
||||
using JsonDocument receipt =
|
||||
JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
|
||||
if (!receipt.RootElement.TryGetProperty("accepted", out JsonElement accepted) ||
|
||||
accepted.ValueKind != JsonValueKind.True)
|
||||
throw new InvalidOperationException("NexBus rejected the alert");
|
||||
return outgoing.EventId;
|
||||
}
|
||||
|
||||
public void Dispose() => _client.Dispose();
|
||||
}
|
||||
@@ -17,6 +17,7 @@ public sealed class SysApiHost : IDisposable
|
||||
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();
|
||||
@@ -26,6 +27,9 @@ public sealed class SysApiHost : IDisposable
|
||||
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;
|
||||
@@ -34,12 +38,14 @@ public sealed class SysApiHost : IDisposable
|
||||
private int _disposed;
|
||||
|
||||
public SysApiHost(int localPort, string publicOrigin, IUserAccountService accounts,
|
||||
IAuthenticationService auth, string portalToken, ISysApiReadModel? readModel = null)
|
||||
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);
|
||||
@@ -373,6 +379,52 @@ public sealed class SysApiHost : IDisposable
|
||||
{
|
||||
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,
|
||||
@@ -402,7 +454,8 @@ public sealed class SysApiHost : IDisposable
|
||||
session = admin.Name,
|
||||
minAdminLevel = 200,
|
||||
oldWorldApiUnchanged = true,
|
||||
endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities" }
|
||||
alertsAvailable = _alertPublisher is not null,
|
||||
endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities", "/api/admin/alerts" }
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -424,6 +477,8 @@ public sealed class SysApiHost : IDisposable
|
||||
_http.Stop();
|
||||
_http.Close();
|
||||
_sessions.Clear();
|
||||
_alertPublisher?.Dispose();
|
||||
_alertGate.Dispose();
|
||||
_stop.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../NexVerse/Core/NexVerse.Core.csproj"/>
|
||||
<ProjectReference Include="../../OpenSim/Server/Handlers/OpenSim.Server.Handlers.csproj"/>
|
||||
<ProjectReference Include="../../OpenSim/Server/Base/OpenSim.Server.Base.csproj"/>
|
||||
<ProjectReference Include="../../OpenSim/Framework/OpenSim.Framework.csproj"/>
|
||||
|
||||
@@ -13,6 +13,8 @@ const view=async()=>{
|
||||
const d=await json("/api/admin/overview");
|
||||
$("admin-label").textContent=d.session+" · LEVEL 200+";
|
||||
$("uptime").textContent=int(Math.max(0,Math.floor(d.uptimeSeconds/60)))+"m";
|
||||
$("alert-send").disabled=!d.alertsAvailable;
|
||||
$("alert-status").textContent=d.alertsAvailable?"Alert-Versand bereit (ROBUST/NexBus)":"Nicht eingerichtet: [SysApi] AlertsEnabled und ein signierter NexBus mit Simulator-Peers sind erforderlich.";
|
||||
const info=$("diag");info.replaceChildren();
|
||||
for(const [label,value,good] of [
|
||||
["System API:",d.status,true],["Eigenständige DLL:","sys.api.dll",true],
|
||||
@@ -34,6 +36,30 @@ $("signin").addEventListener("submit",async e=>{
|
||||
catch(err){modal(err.message.includes("Access Denied")?"Access Denied":"Anmeldung fehlgeschlagen",err.message.includes("Access Denied")?"Keine Berechtigung. Für diese Verwaltung ist UserLevel 200 oder höher erforderlich.":err.message)}
|
||||
finally{submit.disabled=false;}
|
||||
});
|
||||
const renderAlertPreview=()=>{
|
||||
const kind=$("alert-level").value,body=$("alert-message").value.trim();
|
||||
$("alert-preview").textContent="alert "+kind+": "+(body||"…");
|
||||
};
|
||||
$("alert-level").addEventListener("change",renderAlertPreview);
|
||||
$("alert-message").addEventListener("input",renderAlertPreview);
|
||||
$("alert-form").addEventListener("submit",async event=>{
|
||||
event.preventDefault();
|
||||
const msg=$("alert-message").value.trim(),kind=$("alert-level").value;
|
||||
const result=$("alert-result"),button=$("alert-send");
|
||||
if(!msg || msg.length>450 || /[\r\n\u2028\u2029]/u.test(msg)){
|
||||
result.textContent="Bitte eine einzeilige Nachricht mit höchstens 450 Zeichen eingeben.";return;
|
||||
}
|
||||
const command="alert "+kind+": "+msg;
|
||||
if(!window.confirm("Diesen Alert wirklich an alle verbundenen Regionen senden?\n\n"+command))return;
|
||||
button.disabled=true;result.textContent="Alert wird an NexBus übertragen …";
|
||||
try{
|
||||
const receipt=await json("/api/admin/alerts",{method:"POST",
|
||||
headers:{"Content-Type":"application/json"},body:JSON.stringify({command})});
|
||||
result.textContent="Alert an NexBus übergeben (ID "+receipt.eventId+"). Die Zustellung an die einzelnen Simulatoren erfolgt asynchron.";
|
||||
}catch(error){result.textContent="Versand nicht bestätigt: "+error.message}
|
||||
finally{button.disabled=false;}
|
||||
});
|
||||
renderAlertPreview();
|
||||
$("signout").onclick=async()=>{try{await json("/api/session/logout",{method:"POST"})}catch{}csrf="";$("dashboard").hidden=true;$("login-shell").hidden=false};
|
||||
$("refresh").onclick=()=>view().catch(e=>modal("Systemfehler",e.message));
|
||||
document.querySelectorAll("nav a").forEach(a=>a.addEventListener("click",()=>document.querySelectorAll("nav a").forEach(v=>v.classList.toggle("selected",v===a))));
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
<div id="dashboard" hidden>
|
||||
<aside class="sidebar hologram"><div class="side-head"><span class="ogl-emblem">O<span>G</span>L</span><div><b>System Core</b><small>SYS.API // GEN 1</small></div></div>
|
||||
<div class="side-line">NAVIGATION</div>
|
||||
<nav><a href="#overview" class="selected">⌁ <span>Command Center</span></a><a href="#endpoints">▤ <span>API Endpunkte</span></a><a href="#security">⬡ <span>Security & Portal</span></a><a href="#future">▧ <span>Module (Coming Soon)</span></a></nav>
|
||||
<nav><a href="#overview" class="selected">⌁ <span>Command Center</span></a><a href="#alerts">⚑ <span>Grid Alerts</span></a><a href="#endpoints">▤ <span>API Endpunkte</span></a><a href="#security">⬡ <span>Security & Portal</span></a><a href="#future">▧ <span>Module (Coming Soon)</span></a></nav>
|
||||
<div class="sidebar-bottom"><img src="/ogl-mascot.webp" alt="" class="mini-mascot"><span class="live-indicator"><i></i> OGL CORE CONNECTED</span><small>LEGACY WORLD API REMAINS ACTIVE</small></div></aside>
|
||||
<main class="main"><header class="dash-header"><div><div class="eyebrow">OPENGENESISLINK / SYSTEM COMMAND</div><h2>System <span>Dashboard</span></h2></div><div class="righthead"><span id="admin-label" class="admin-label">ADMINISTRATOR</span><button id="signout" class="ghost-button">Abmelden ↗</button></div></header>
|
||||
<section id="overview" class="dash-section">
|
||||
@@ -49,6 +49,23 @@
|
||||
<div class="two-cols"><section class="module-card hologram"><div class="panel-title"><span>◈</span><h3>Architektur</h3></div><div class="node-path"><div><b>STADTPORTAL</b><small>SERVER-TO-SERVER</small></div><span>⟷</span><div><b>SYS.API</b><small>PORT 8850 / TLS</small></div><span>║</span><div><b>ROBUST</b><small>ALTE API BLEIBT</small></div></div></section>
|
||||
<section class="module-card hologram"><div class="panel-title"><span>⬡</span><h3>Systemdiagnose</h3></div><div id="diag" class="diagnostic">Lade aktuelle Werte...</div></section></div>
|
||||
</section>
|
||||
<section id="alerts" class="dash-section"><div class="section-title"><h3>Globale Grid Alerts</h3><p>Den nativen Simulator-Konsolenbefehl <code>alert <message></code> zentral ausführen. Alle über NexBus verbundenen Simulatoren erhalten dieselbe Meldung für ihre Regionen.</p></div>
|
||||
<div class="module-card hologram alert-panel">
|
||||
<div class="security-pill">⬡ NUR ADMINISTRATOREN (USERLEVEL 200+) · SIGNIERTER NEXBUS</div>
|
||||
<p id="alert-status" role="status">Verbindung zum Alert-Dienst wird geprüft …</p>
|
||||
<form id="alert-form">
|
||||
<label for="alert-level">Meldungstyp</label>
|
||||
<select id="alert-level"><option value="WARNUNG">WARNUNG</option><option value="INFO" selected>INFO</option><option value="HINWEIS">HINWEIS</option><option value="SYSTEM">SYSTEM</option></select>
|
||||
<label for="alert-message">Nachricht an alle verbundenen Regionen</label>
|
||||
<textarea id="alert-message" required maxlength="450" rows="4" placeholder="Geplante Wartung um 22:00 Uhr."></textarea>
|
||||
<p class="alert-preview-label">Konsolenbefehl (Vorschau)</p>
|
||||
<code id="alert-preview" class="alert-preview">alert INFO: …</code>
|
||||
<p class="alert-disclaimer">Die Übergabe an NexBus erfolgt sofort. Die Zustellung an einzelne Regionen geschieht asynchron; offline Simulatoren werden nicht erreicht.</p>
|
||||
<button type="submit" class="big-button" id="alert-send" disabled>ALERT AN DAS GESAMTE GRID SENDEN</button>
|
||||
<p id="alert-result" role="status" aria-live="polite"></p>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
<section id="endpoints" class="dash-section"><div class="section-title"><h3>API v1 Endpoints</h3><p>Grundgerüst. Weitere Funktionen folgen als eigene Module.</p></div><div class="module-card hologram" id="endpoint-list"></div></section>
|
||||
<section id="security" class="dash-section"><div class="section-title"><h3>Security & Portal</h3><p>Die Kommunikation mit dem Stadtportal erfolgt über einen einzigen geschützten Machine-Token.</p></div><div class="module-card hologram"><div class="security-pill">⬡ TOKEN GENERATED SERVER-SIDE</div><p>Der Portal-Token wird beim ersten Start unter <code>/etc/oglwebinterface/.env</code> gespeichert (0600). Er wird nicht im Browser angezeigt. Die Weitergabe an das Portal erfolgt ausschließlich über einen abgesicherten Backend-Kanal.</p><p>Für Administratoren gilt UserLevel 200+. Jeder API-Aufruf mit Avatar-Sitzung wird erneut berechtigt.</p></div></section>
|
||||
<section id="future" class="dash-section"><div class="section-title"><h3>API Modules</h3><p>Bereit für deine nächsten Funktionsvorgaben.</p></div><div class="module-card hologram"><div class="module-pending">+ Neue API-Module werden hier integriert, ohne die bestehende World API abzuschalten.</div></div></section>
|
||||
|
||||
@@ -1 +1,13 @@
|
||||
:root{color-scheme:dark;--cyan:#29e5ff;--blue:#138fff;--violet:#8c5bff;--ink:#050915;--panel:#101b31d9;--edge:#42a7df36;--pale:#b3cbe0}*{box-sizing:border-box}html{scroll-behavior:smooth}body{font:14px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:#eaf7ff;background:radial-gradient(ellipse at 80% 20%,#11345f 0%,transparent 50%),#050916;margin:0;min-height:100vh;overflow-x:hidden}button,input{font:inherit}a{color:inherit;text-decoration:none}button{cursor:pointer}#stars,.background-grid{position:fixed;inset:0;pointer-events:none;z-index:-2}#stars{height:100vh;width:100vw}.background-grid{z-index:-1;background-image:linear-gradient(90deg,#36adff0a 1px,transparent 1px),linear-gradient(#36adff0a 1px,transparent 1px);background-size:75px 75px;mask-image:linear-gradient(to bottom,transparent,#fff 30%,#fff 75%,transparent);transform:perspective(700px) rotateX(50deg) scale(1.6);transform-origin:center 70%;animation:gridflow 28s linear infinite}.light{position:fixed;width:400px;height:400px;border-radius:50%;filter:blur(100px);z-index:-1;pointer-events:none;opacity:.24}.halo-one{background:#007bff;left:-220px;bottom:-180px;animation:float 13s ease-in-out infinite alternate}.halo-two{background:#7e3ded;right:-220px;top:5%;animation:float 16s ease-in-out infinite alternate-reverse}@keyframes gridflow{to{background-position:0 300px}}@keyframes float{to{transform:translate(150px,-90px)}}@keyframes drift{to{transform:translateY(-12px)}}@keyframes glow{50%{filter:drop-shadow(0 0 24px #24bcff88)}}@keyframes orbit{to{transform:rotate(360deg)}}@keyframes shine{to{background-position:200% 0}}[hidden]{display:none!important}.hologram{background:linear-gradient(140deg,#172c4ad1,#101829e9 70%);border:1px solid var(--edge);backdrop-filter:blur(24px);box-shadow:0 16px 70px #0006,0 0 45px #0f69c211;border-radius:22px}.eyebrow{font-size:11px;font-weight:800;letter-spacing:.23em;color:#7fe6ff}.pulsedot,.status-chip i,.live-indicator i{display:inline-block;width:8px;height:8px;background:#3bf7bf;border-radius:50%;box-shadow:0 0 16px #41eeab;animation:glow 2s infinite}.topbrand{display:flex;align-items:center;gap:17px;font-size:15px;font-weight:800;letter-spacing:.13em}.topbrand small{display:block;color:#65cde9;letter-spacing:.21em;font-size:9px;margin-top:4px}.ogl-emblem{display:inline-grid;place-items:center;width:67px;height:67px;border:1px solid #51d6ff77;border-radius:19px;background:linear-gradient(145deg,#224c9a,#15264a);box-shadow:0 0 29px #1685eb5c,inset 0 0 25px #1b96df33;font-size:26px;font-weight:1000;letter-spacing:-.14em;padding-right:.15em}.ogl-emblem span{color:var(--cyan)}.login-layout{min-height:calc(100vh - 55px);max-width:1500px;margin:auto;padding:45px clamp(25px,5vw,85px) 25px;display:grid;grid-template-columns:1.13fr .87fr;gap:clamp(25px,6vw,100px);align-items:center}.identity-area{align-self:stretch;display:flex;flex-direction:column;justify-content:space-between}.mascot-halo{height:clamp(265px,36vw,490px);position:relative;display:grid;place-items:center;margin:0 0 4px}.mascot{height:100%;max-width:100%;object-fit:contain;z-index:1;animation:drift 5s ease-in-out infinite alternate,glow 4s ease-in-out infinite}.orbit{border:1px solid #30bdff45;position:absolute;border-radius:50%;width:min(76%,450px);aspect-ratio:1;box-shadow:0 0 20px #1689cf28;transform:rotateX(65deg);animation:orbit 36s linear infinite}.orbit-two{width:min(93%,540px);transform:rotateX(30deg) rotateZ(20deg);border-color:#6e7aff4c;animation-duration:54s;animation-direction:reverse}.intro{padding-bottom:10px}.intro h1{font-size:clamp(36px,4vw,68px);line-height:1.07;letter-spacing:-.055em;margin:15px 0}.intro h1 span{display:block;background:linear-gradient(110deg,#6ee7ff 10%,#088cff 50%,#b37cff 100%);background-size:220% auto;color:transparent;background-clip:text;animation:shine 7s ease-in-out infinite}.intro p{font-size:16px;color:var(--pale);max-width:570px}.feature-tags{display:flex;flex-wrap:wrap;gap:10px;margin-top:22px}.feature-tags span{font-size:9px;letter-spacing:.13em;color:#73cdeb;border:1px solid #3d729f7d;border-radius:7px;padding:8px 10px;background:#12345355}.login-card{position:relative;padding:clamp(28px,3.5vw,54px);max-width:550px;width:100%;margin:auto;overflow:hidden}.edge-line{position:absolute;top:0;left:16%;width:65%;height:2px;background:linear-gradient(90deg,transparent,var(--cyan),transparent);box-shadow:0 0 26px var(--cyan)}.card-top{display:flex;align-items:center;gap:12px;white-space:nowrap}.small-icon{display:grid;place-items:center;border:1px solid #39a5de66;background:#142a48;width:36px;height:36px;border-radius:11px;color:#70dcff}.status-chip{margin-left:auto;color:#75edc3;font-size:10px;letter-spacing:.07em}.status-chip i{width:6px;height:6px;margin-right:4px}.login-card h2{font-size:32px;letter-spacing:-.035em;margin:35px 0 8px}.login-card p,.module-card p{color:#adc2d8;line-height:1.8}.login-card label{display:block;margin:25px 0 10px;font-size:10px;font-weight:800;color:#98c7e5;Line truncated
|
||||
:root{color-scheme:dark;--cyan:#29e5ff;--blue:#138fff;--violet:#8c5bff;--ink:#050915;--panel:#101b31d9;--edge:#42a7df36;--pale:#b3cbe0}*{box-sizing:border-box}html{scroll-behavior:smooth}body{font:14px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:#eaf7ff;background:radial-gradient(ellipse at 80% 20%,#11345f 0%,transparent 50%),#050916;margin:0;min-height:100vh;overflow-x:hidden}button,input{font:inherit}a{color:inherit;text-decoration:none}button{cursor:pointer}#stars,.background-grid{position:fixed;inset:0;pointer-events:none;z-index:-2}#stars{height:100vh;width:100vw}.background-grid{z-index:-1;background-image:linear-gradient(90deg,#36adff0a 1px,transparent 1px),linear-gradient(#36adff0a 1px,transparent 1px);background-size:75px 75px;mask-image:linear-gradient(to bottom,transparent,#fff 30%,#fff 75%,transparent);transform:perspective(700px) rotateX(50deg) scale(1.6);transform-origin:center 70%;animation:gridflow 28s linear infinite}.light{position:fixed;width:400px;height:400px;border-radius:50%;filter:blur(100px);z-index:-1;pointer-events:none;opacity:.24}.halo-one{background:#007bff;left:-220px;bottom:-180px;animation:float 13s ease-in-out infinite alternate}.halo-two{background:#7e3ded;right:-220px;top:5%;animation:float 16s ease-in-out infinite alternate-reverse}@keyframes gridflow{to{background-position:0 300px}}@keyframes float{to{transform:translate(150px,-90px)}}@keyframes drift{to{transform:translateY(-12px)}}@keyframes glow{50%{filter:drop-shadow(0 0 24px #24bcff88)}}@keyframes orbit{to{transform:rotate(360deg)}}@keyframes shine{to{background-position:200% 0}}[hidden]{display:none!important}.hologram{background:linear-gradient(140deg,#172c4ad1,#101829e9 70%);border:1px solid var(--edge);backdrop-filter:blur(24px);box-shadow:0 16px 70px #0006,0 0 45px #0f69c211;border-radius:22px}.eyebrow{font-size:11px;font-weight:800;letter-spacing:.23em;color:#7fe6ff}.pulsedot,.status-chip i,.live-indicator i{display:inline-block;width:8px;height:8px;background:#3bf7bf;border-radius:50%;box-shadow:0 0 16px #41eeab;animation:glow 2s infinite}.topbrand{display:flex;align-items:center;gap:17px;font-size:15px;font-weight:800;letter-spacing:.13em}.topbrand small{display:block;color:#65cde9;letter-spacing:.21em;font-size:9px;margin-top:4px}.ogl-emblem{display:inline-grid;place-items:center;width:67px;height:67px;border:1px solid #51d6ff77;border-radius:19px;background:linear-gradient(145deg,#224c9a,#15264a);box-shadow:0 0 29px #1685eb5c,inset 0 0 25px #1b96df33;font-size:26px;font-weight:1000;letter-spacing:-.14em;padding-right:.15em}.ogl-emblem span{color:var(--cyan)}.login-layout{min-height:calc(100vh - 55px);max-width:1500px;margin:auto;padding:45px clamp(25px,5vw,85px) 25px;display:grid;grid-template-columns:1.13fr .87fr;gap:clamp(25px,6vw,100px);align-items:center}.identity-area{align-self:stretch;display:flex;flex-direction:column;justify-content:space-between}.mascot-halo{height:clamp(265px,36vw,490px);position:relative;display:grid;place-items:center;margin:0 0 4px}.mascot{height:100%;max-width:100%;object-fit:contain;z-index:1;animation:drift 5s ease-in-out infinite alternate,glow 4s ease-in-out infinite}.orbit{border:1px solid #30bdff45;position:absolute;border-radius:50%;width:min(76%,450px);aspect-ratio:1;box-shadow:0 0 20px #1689cf28;transform:rotateX(65deg);animation:orbit 36s linear infinite}.orbit-two{width:min(93%,540px);transform:rotateX(30deg) rotateZ(20deg);border-color:#6e7aff4c;animation-duration:54s;animation-direction:reverse}.intro{padding-bottom:10px}.intro h1{font-size:clamp(36px,4vw,68px);line-height:1.07;letter-spacing:-.055em;margin:15px 0}.intro h1 span{display:block;background:linear-gradient(110deg,#6ee7ff 10%,#088cff 50%,#b37cff 100%);background-size:220% auto;color:transparent;background-clip:text;animation:shine 7s ease-in-out infinite}.intro p{font-size:16px;color:var(--pale);max-width:570px}.feature-tags{display:flex;flex-wrap:wrap;gap:10px;margin-top:22px}.feature-tags span{font-size:9px;letter-spacing:.13em;color:#73cdeb;border:1px solid #3d729f7d;border-radius:7px;padding:8px 10px;background:#12345355}.login-card{position:relative;padding:clamp(28px,3.5vw,54px);max-width:550px;width:100%;margin:auto;overflow:hidden}.edge-line{position:absolute;top:0;left:16%;width:65%;height:2px;background:linear-gradient(90deg,transparent,var(--cyan),transparent);box-shadow:0 0 26px var(--cyan)}.card-top{display:flex;align-items:center;gap:12px;white-space:nowrap}.small-icon{display:grid;place-items:center;border:1px solid #39a5de66;background:#142a48;width:36px;height:36px;border-radius:11px;color:#70dcff}.status-chip{margin-left:auto;color:#75edc3;font-size:10px;letter-spacing:.07em}.status-chip i{width:6px;height:6px;margin-right:4px}.login-card h2{font-size:32px;letter-spacing:-.035em;margin:35px 0 8px}.login-card p,.module-card p{color:#adc2d8;line-height:1.8}.login-card label{display:block;margin:25px 0 10px;font-size:10px;font-weight:800;color:#98c7e5;Line truncated
|
||||
/* Global alert command center: accessible form on desktop and mobile. */
|
||||
.alert-panel{padding:28px;max-width:950px}
|
||||
.alert-panel form{display:grid;gap:12px;margin-top:17px}
|
||||
.alert-panel label{font-weight:700;color:#b1e5fa}
|
||||
.alert-panel select,.alert-panel textarea{width:100%;padding:13px 14px;background:#09192c;color:#f0f9ff;border:1px solid #4389aa;border-radius:10px;font:inherit}
|
||||
.alert-panel textarea{resize:vertical;min-height:110px}
|
||||
.alert-preview-label{font-size:12px;letter-spacing:.06em;color:#9fc8df;margin:0}
|
||||
.alert-preview{display:block;overflow-wrap:anywhere;white-space:pre-wrap;background:#071421;border:1px solid #235b7e;border-radius:10px;padding:14px;color:#75e4ff}
|
||||
.alert-disclaimer{font-size:12px;color:#a9c2d9}
|
||||
#alert-result,#alert-status{overflow-wrap:anywhere;color:#8bd5f5}
|
||||
#alert-send:disabled{opacity:.55;cursor:not-allowed}
|
||||
@media(max-width:640px){.alert-panel{padding:18px}.alert-panel select,.alert-panel textarea{font-size:16px}}
|
||||
@@ -1191,6 +1191,10 @@
|
||||
; be exposed exclusively by an HTTPS proxy with a valid ACME certificate.
|
||||
[SysApi]
|
||||
Enabled = false
|
||||
; Optional broadcast of the native 'alert' command over signed NexBus.
|
||||
; Requires active signed NexBus service with SharedKey and simulator Peers.
|
||||
; Enable only after ROBUST + simulator nodes have been updated and tested.
|
||||
AlertsEnabled = false
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = ""
|
||||
|
||||
@@ -1196,6 +1196,10 @@
|
||||
; be exposed exclusively by an HTTPS proxy with a valid ACME certificate.
|
||||
[SysApi]
|
||||
Enabled = false
|
||||
; Optional broadcast of the native 'alert' command over signed NexBus.
|
||||
; Requires active signed NexBus service with SharedKey and simulator Peers.
|
||||
; Enable only after ROBUST + simulator nodes have been updated and tested.
|
||||
AlertsEnabled = false
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = ""
|
||||
|
||||
@@ -881,6 +881,10 @@
|
||||
; be exposed exclusively by an HTTPS proxy with a valid ACME certificate.
|
||||
[SysApi]
|
||||
Enabled = false
|
||||
; Optional broadcast of the native 'alert' command over signed NexBus.
|
||||
; Requires active signed NexBus service with SharedKey and simulator Peers.
|
||||
; Enable only after ROBUST + simulator nodes have been updated and tested.
|
||||
AlertsEnabled = false
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = ""
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# SYS.API – Globale Grid-Alerts (Generation 1)
|
||||
|
||||
## Bedienung
|
||||
|
||||
Im Webinterface erscheint der neue Bereich **Globale Grid Alerts**. Der Administrator wählt den Meldungstyp INFO, WARNUNG, HINWEIS oder SYSTEM, schreibt die Nachricht, sieht den vollständigen Konsolenbefehl in der Vorschau und bestätigt den Versand.
|
||||
|
||||
Beispiele:
|
||||
|
||||
alert WARNUNG: Serverwartung in 10 Minuten.
|
||||
alert INFO: Die Wartung ist abgeschlossen.
|
||||
alert HINWEIS: Heute findet eine Veranstaltung statt.
|
||||
|
||||
Die Schnittstelle verarbeitet ausschließlich den bestehenden Befehl alert mit maximal 500 einzeiligen Zeichen. Es gibt **keine** allgemeine Remote-Konsole. Die Präfixe WARNUNG und INFO sind nur Text und werden dem Viewer unverändert angezeigt.
|
||||
|
||||
## Verteilung an alle Regionen
|
||||
|
||||
1. SYS.API prüft die bestehende Avatar-Admin-Sitzung (UserLevel mindestens 200), den CSRF-Header und Same-Origin. Der reine Stadtportal-Maschinen-Token berechtigt ausdrücklich NICHT zu Alerts.
|
||||
2. SYS.API sendet ein HMAC-signiertes NexBus-Ereignis admin.alert.requested an den lokalen ROBUST-NexBus-Endpunkt auf 127.0.0.1 (Port aus der vorhandenen ROBUST-Konfiguration). Es wird der bereits vorhandene NexBus-Key verwendet.
|
||||
3. Der bestehende NexBus transportiert diese Nachricht an alle registrierten Simulator-Peers. Der NexVerseNodeAgentModule jedes Simulator-Prozesses verarbeitet die Nachricht einmal und ruft in jeder von diesem Prozess betriebenen Region IDialogModule.SendGeneralAlert auf. Das entspricht exakt der Funktion des nativen Konsolenbefehls alert.
|
||||
4. Bei korrekt eingerichteten Peers kann die Nachricht somit die 42 Hauptregionen und die separate EventSim (NexTopia) erreichen.
|
||||
|
||||
**202 Accepted** besagt lediglich, dass ROBUST das Ereignis zum Weiterleiten angenommen hat, nicht, dass alle Clients es bereits erhalten haben. Offline-Simulatoren erhalten keine spätere Zustellung. Die NodeAgent-Logs enthalten Ereignis-ID und Anzahl angesprochener Regionen; Nachrichtentext und Geheimnisse werden nicht geloggt.
|
||||
|
||||
## Aktivierung und Sicherheit
|
||||
|
||||
Die Funktion ist standardmäßig **deaktiviert**, um einen unbeabsichtigten Versand durch das reine Software-Update auszuschließen.
|
||||
|
||||
In der *aktiven* ROBUST-Konfiguration unter [SysApi] muss nach erfolgreichem Test AlertsEnabled = true gesetzt werden. Vorausgesetzt ist [NexBus] Enabled = true mit mindestens 32 Byte geheimem SharedKey und Peers mit den Adressen **aller** Simulator-Prozesse. Die Simulatoren brauchen [NexVerseNodeAgent] Enabled = true mit identischem NexBus-Key, korrektem PeerUrl zu ROBUST und einem funktionsfähigen Inbound-Endpunkt.
|
||||
|
||||
ROBUST und sämtliche Simulatoren benötigen vor Aktivierung den neuen GitHub-Stand. Zuerst isoliert testen. Key-Material ausschließlich über geschützte Prozessumgebung bereitstellen, nicht in Git. Bei Netzen außerhalb von Loopback TLS oder eine abgesicherte private Verbindung verwenden.
|
||||
|
||||
Keine Änderungen an Stadtportal, Produktionsregionen oder AssetService. Keine neuen Rollen-/Scope-Rechte; maßgeblich bleibt die vorhandene UserLevel-200-Adminprüfung.
|
||||
|
||||
Der Aufruf über den Browser lautet POST /api/admin/alerts mit einem JSON-Objekt, dessen Feld command den vollständigen Befehl enthält. Beispielinhalt: {"command":"alert INFO: Willkommen in Stadt NexVerse!"}. Browser-Session und X-OGL-CSRF sind Pflicht.
|
||||
|
||||
Es gilt maximal ein Versand alle fünf Sekunden. HTTP 400 bedeutet ungültiger Befehl; 401 fehlende/entzogene Adminberechtigung; 403 fehlender CSRF-Header oder fremde Origin; 429 Ratenlimit; 503 fehlende NexBus-Verbindung.
|
||||
|
||||
## Testplan
|
||||
|
||||
1. Python-Vertragstest: tools/ci/verify_sysapi_global_alert.py.
|
||||
2. C#-Smoke-Test: tools/ci/SysApiSmoke/SysApiSmoke.csproj.
|
||||
3. Vollständiger .NET-10-Build und bestehende NexBus-Regressionen.
|
||||
4. Realer Test: ein Alert aus der Sys.API, je ein Avatar in einer Hauptregion und in NexTopia; pro Avatar nur eine Viewer-Meldung. NodeAgent-Log je Prozess auf Event-ID und Regionszahl (42 und 1) prüfen.
|
||||
@@ -9,6 +9,7 @@ using System.Text.Json;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Services.Interfaces;
|
||||
using OpenGenesisLINK.SysApi;
|
||||
using NexVerse.Core.Messaging;
|
||||
using OpenSim.Framework;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
@@ -27,13 +28,58 @@ if (!OperatingSystem.IsWindows() &&
|
||||
(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<Guid> 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();
|
||||
using var host = new SysApiHost(port, "https://sysapi.example.test:8850",
|
||||
DispatchProxy.Create<IUserAccountService, AccountProxy>(),
|
||||
DispatchProxy.Create<IAuthenticationService, AuthenticationProxy>(), first, new FakeSysApiReadModel());
|
||||
DispatchProxy.Create<IAuthenticationService, AuthenticationProxy>(),
|
||||
first, new FakeSysApiReadModel(), alertSink);
|
||||
host.Start();
|
||||
try
|
||||
{
|
||||
@@ -61,6 +107,18 @@ try
|
||||
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" })
|
||||
@@ -124,11 +182,37 @@ try
|
||||
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);
|
||||
async Task<HttpResponseMessage> 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");
|
||||
@@ -187,3 +271,17 @@ public sealed class FakeSysApiReadModel : ISysApiReadModel
|
||||
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<Guid> 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() { }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""SYS.API alert command + signed NexBus global fan-out integration contract."""
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
read = lambda relative: (root / relative).read_text(encoding="utf-8")
|
||||
|
||||
host = read("addons/SysApi/SysApiHost.cs")
|
||||
connector = read("addons/SysApi/SysApiConnector.cs")
|
||||
publisher = read("addons/SysApi/SysApiGlobalAlert.cs")
|
||||
node = read("NexVerse/RegionModules/NodeAgent/NexVerseNodeAgentModule.cs")
|
||||
page = read("addons/SysApi/www/index.html")
|
||||
javascript = read("addons/SysApi/www/app.js")
|
||||
tests = read("tools/ci/SysApiSmoke/Program.cs")
|
||||
|
||||
# Browser action is not an arbitrary remote command interpreter.
|
||||
for term in ('path == "/api/admin/alerts"', 'req.HttpMethod != "POST"',
|
||||
"TryAdmin(req, out AdminSession admin)", '"X-OGL-CSRF"',
|
||||
"SysApiAlertCommand.TryParse", "_alertGate.WaitAsync",
|
||||
"TimeSpan.FromSeconds(5)", "_alertPublisher.PublishAsync",
|
||||
"await ReplyAsync(response, 202", "alertsAvailable"):
|
||||
assert term in host, term
|
||||
assert "RunCommand(" not in publisher
|
||||
assert 'StartsWith("alert "' in publisher
|
||||
assert 'value.Length is < 1 or > 500' in publisher
|
||||
|
||||
# Sys.API signs an event for the *existing* ROBUST NexBus on local loopback.
|
||||
for term in ("NexBusProtocol.Sign", "NexBusProtocol.Serialize",
|
||||
'"http://127.0.0.1:"', 'UseProxy = false', 'AllowAutoRedirect = false',
|
||||
'"admin.alert.requested"', '"opengenesislink.sysapi"'):
|
||||
assert term in publisher, term
|
||||
for term in ('GetBoolean("AlertsEnabled", false)', 'GetBoolean("Enabled", false)',
|
||||
'GetString("SharedKey", "")', 'GetString("Peers", "")'):
|
||||
assert term in connector, term
|
||||
|
||||
# A shared NodeAgent handles the event once, then alerts every hosted scene.
|
||||
for term in ('m_Bus.Subscribe("admin.alert.requested", HandleAdminAlert)',
|
||||
"m_AdminAlertSubscription?.Dispose();", "m_Scenes.Values",
|
||||
"scene.RequestModuleInterface<IDialogModule>()",
|
||||
"dialog.SendGeneralAlert(message)", '"opengenesislink.sysapi"',
|
||||
"TimeSpan.FromSeconds(30)"):
|
||||
assert term in node, term
|
||||
|
||||
# UI deliberately uses textContent, confirmation and CSRF-enabled same-origin API.
|
||||
for term in ('id="alert-form"', 'id="alert-level"', 'id="alert-message"',
|
||||
'id="alert-preview"', 'id="alert-send"'):
|
||||
assert term in page, term
|
||||
for term in ('renderAlertPreview', 'window.confirm(', '"/api/admin/alerts"',
|
||||
'textContent', 'JSON.stringify({command})'):
|
||||
assert term in javascript, term
|
||||
assert "innerHTML" not in javascript
|
||||
|
||||
for ini in ("bin/Robust.HG.ini", "bin/Robust.HG.ini.example",
|
||||
"bin/Robust.ini.example"):
|
||||
assert "AlertsEnabled = false" in read(ini), ini
|
||||
|
||||
for term in ('"anonymous alert blocked"', '"alert CSRF required"',
|
||||
'"arbitrary console command forbidden"', '"multiline alert forbidden"',
|
||||
'"global alert rate limit"', '"revoked admin cannot alert"'):
|
||||
assert term in tests, term
|
||||
|
||||
print("PASS: global SYS.API alert command is protected, NexBus-signed and region-wide")
|
||||
Reference in new issue
Block a user