Merge pull request #462 from opengenesislink/feature/sysapi-live-readmodel-20261120
feat(sys.api): live MariaDB JSON views for UserAccounts, GridUser, Presence, Regions + UUID names
This commit is contained in:
10 files changed
+634
-4
No files matched your search
@@ -974,6 +974,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 tools/ci/verify_sys_api_foundation.py
|
||||
python3 tools/ci/verify_sys_api_readmodel.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
|
||||
|
||||
@@ -45,7 +45,16 @@ public sealed class SysApiConnector : ServiceConnector
|
||||
if (accounts is null || authentication is null)
|
||||
throw new InvalidOperationException("SYS.API requires local ROBUST account and authentication services");
|
||||
var token = PortalSecretStore.OpenOrCreate(secretDirectory);
|
||||
var host = new SysApiHost(port, publicOrigin, accounts, authentication, token);
|
||||
ISysApiReadModel? readModel = null;
|
||||
try { readModel = new MySqlSysApiReadModel(config); }
|
||||
catch (Exception e)
|
||||
{
|
||||
// Core dashboard stays available if an installation uses
|
||||
// another DB provider or its read model is misconfigured.
|
||||
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);
|
||||
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);
|
||||
|
||||
@@ -25,6 +25,7 @@ public sealed class SysApiHost : IDisposable
|
||||
private readonly ConcurrentDictionary<string, Attempts> _attempts = new();
|
||||
private readonly IUserAccountService _accounts;
|
||||
private readonly IAuthenticationService _auth;
|
||||
private readonly ISysApiReadModel? _readModel;
|
||||
private readonly byte[] _portalToken;
|
||||
private readonly Uri? _publicOrigin;
|
||||
private readonly string _localAuthority;
|
||||
@@ -33,11 +34,12 @@ public sealed class SysApiHost : IDisposable
|
||||
private int _disposed;
|
||||
|
||||
public SysApiHost(int localPort, string publicOrigin, IUserAccountService accounts,
|
||||
IAuthenticationService auth, string portalToken)
|
||||
IAuthenticationService auth, string portalToken, ISysApiReadModel? readModel = 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;
|
||||
if (portalToken.Length != 128 || !portalToken.All(Uri.IsHexDigit))
|
||||
throw new ArgumentException("Invalid portal token", nameof(portalToken));
|
||||
_portalToken = Encoding.ASCII.GetBytes(portalToken);
|
||||
@@ -288,10 +290,80 @@ public sealed class SysApiHost : IDisposable
|
||||
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/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;
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using MySql.Data.MySqlClient;
|
||||
using Nini.Config;
|
||||
|
||||
namespace OpenGenesisLINK.SysApi;
|
||||
|
||||
/// <summary>
|
||||
/// Every call reads the live database. Only explicitly enumerated, non-secret
|
||||
/// columns can leave this backend. This is NOT a generic SQL/DB browser.
|
||||
/// </summary>
|
||||
public interface ISysApiReadModel
|
||||
{
|
||||
object List(string resource, int limit, int offset, string? search);
|
||||
object? Account(string uuid);
|
||||
object Resolve(string uuid);
|
||||
}
|
||||
|
||||
public sealed class MySqlSysApiReadModel : ISysApiReadModel
|
||||
{
|
||||
private const string Zero = "00000000-0000-0000-0000-000000000000";
|
||||
private readonly string _connectionString;
|
||||
|
||||
public MySqlSysApiReadModel(IConfigSource config)
|
||||
{
|
||||
string raw = config.Configs["DatabaseService"]?.GetString("ConnectionString", "") ?? "";
|
||||
raw = Regex.Replace(raw, @"\$\{Environment\|([A-Za-z_][A-Za-z_0-9]*)\}", m =>
|
||||
Environment.GetEnvironmentVariable(m.Groups[1].Value) ??
|
||||
throw new InvalidOperationException("SYS.API database environment not available"));
|
||||
if (string.IsNullOrWhiteSpace(raw) || raw.Contains("${", StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("SYS.API database configuration not resolved");
|
||||
// The production ROBUST deployment uses MariaDB. Other DB engines will
|
||||
// require provider-specific implementations, not arbitrary SQL fallback.
|
||||
var builder = new MySqlConnectionStringBuilder(raw)
|
||||
{
|
||||
ConnectionTimeout = 5,
|
||||
DefaultCommandTimeout = 12,
|
||||
MaximumPoolSize = 5,
|
||||
PersistSecurityInfo = false
|
||||
};
|
||||
_connectionString = builder.ConnectionString;
|
||||
}
|
||||
|
||||
private MySqlConnection Open()
|
||||
{
|
||||
var connection = new MySqlConnection(_connectionString);
|
||||
connection.Open();
|
||||
return connection;
|
||||
}
|
||||
|
||||
private static MySqlCommand Command(MySqlConnection connection, string sql,
|
||||
params (string Name, object Value)[] values)
|
||||
{
|
||||
var command = new MySqlCommand(sql, connection) { CommandTimeout = 12 };
|
||||
foreach (var (name, value) in values)
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
return command;
|
||||
}
|
||||
|
||||
private static string EscapeLike(string value) => value.Replace("!", "!!", StringComparison.Ordinal)
|
||||
.Replace("%", "!%", StringComparison.Ordinal).Replace("_", "!_", StringComparison.Ordinal);
|
||||
|
||||
private static string? UtcFromUnix(long seconds) => seconds is > 0 and < 253402300799
|
||||
? DateTimeOffset.FromUnixTimeSeconds(seconds).ToString("O", CultureInfo.InvariantCulture)
|
||||
: null;
|
||||
|
||||
private static string? UtcFromDb(object value) => value is DateTime time
|
||||
? DateTime.SpecifyKind(time, DateTimeKind.Utc).ToString("O", CultureInfo.InvariantCulture)
|
||||
: null;
|
||||
|
||||
private static string? Value(MySqlDataReader reader, string field) =>
|
||||
reader[field] is DBNull ? null : Convert.ToString(reader[field], CultureInfo.InvariantCulture);
|
||||
|
||||
private static long Number(MySqlDataReader reader, string field) =>
|
||||
long.TryParse(Value(reader, field), NumberStyles.Integer, CultureInfo.InvariantCulture, out long value)
|
||||
? value : 0;
|
||||
|
||||
private static string? Principal(string? userId)
|
||||
{
|
||||
if (userId is null) return null;
|
||||
string candidate = userId.Split(';', 2)[0];
|
||||
return Guid.TryParse(candidate, out var parsed) ? parsed.ToString("D") : null;
|
||||
}
|
||||
|
||||
private static string? ForeignName(string? userId)
|
||||
{
|
||||
if (userId is null) return null;
|
||||
var parts = userId.Split(';', 3);
|
||||
return parts.Length == 3 && parts[2].Length is > 0 and <= 128 &&
|
||||
!parts[2].Any(char.IsControl) ? parts[2].Trim() : null;
|
||||
}
|
||||
|
||||
private static string AvatarName(string? first, string? last) =>
|
||||
string.Join(" ", new[] { first, last }.Where(x => !string.IsNullOrWhiteSpace(x)));
|
||||
|
||||
private sealed record Label(string Name, string? DisplayName, string Source);
|
||||
|
||||
// Bounded name resolution prevents N+1 DB calls and labels both local
|
||||
// avatar UUIDs and foreign HG UUI identities where an unambiguous UUI exists.
|
||||
private static Dictionary<string, Label> Labels(MySqlConnection db, MySqlTransaction? tx, IEnumerable<string?> users)
|
||||
{
|
||||
var uuids = users.Select(Principal).Where(x => x is not null).Select(x => x!)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase).Take(200).ToArray();
|
||||
var labels = new Dictionary<string, Label>(StringComparer.OrdinalIgnoreCase);
|
||||
if (uuids.Length == 0) return labels;
|
||||
var sqlParams = uuids.Select((_, i) => "@u" + i).ToArray();
|
||||
var values = uuids.Select((id, i) => ("@u" + i, (object)id)).ToArray();
|
||||
using (var cmd = Command(db, "SELECT PrincipalID,FirstName,LastName,DisplayName FROM UserAccounts WHERE PrincipalID IN (" +
|
||||
string.Join(",", sqlParams) + ")", values))
|
||||
{ cmd.Transaction = tx;
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
string id = Value(reader, "PrincipalID")!;
|
||||
string name = AvatarName(Value(reader, "FirstName"), Value(reader, "LastName"));
|
||||
string? display = Value(reader, "DisplayName");
|
||||
labels[id] = new Label(name, string.IsNullOrWhiteSpace(display) ? name : display, "UserAccounts");
|
||||
}
|
||||
}
|
||||
|
||||
// Never guess a foreign name from an unrelated local account. If one
|
||||
// UUID has several HG names, leave it explicitly ambiguous.
|
||||
var foreign = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
using (var cmd = Command(db, "SELECT UserID FROM GridUser WHERE LEFT(UserID,36) IN (" +
|
||||
string.Join(",", sqlParams) + ") AND UserID LIKE '%;%' LIMIT 2000", values))
|
||||
{ cmd.Transaction = tx;
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
string? identity = Value(reader, "UserID");
|
||||
string? id = Principal(identity);
|
||||
string? name = ForeignName(identity);
|
||||
if (id is null || name is null || labels.ContainsKey(id)) continue;
|
||||
if (!foreign.TryGetValue(id, out var names)) foreign[id] = names = new(StringComparer.Ordinal);
|
||||
names.Add(name);
|
||||
}
|
||||
}
|
||||
foreach (var (id, names) in foreign)
|
||||
if (names.Count == 1) labels[id] = new Label(names.First(), names.First(), "HypergridUUI");
|
||||
return labels;
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> RegionNames(MySqlConnection db, MySqlTransaction? tx, IEnumerable<string?> regions)
|
||||
{
|
||||
var ids = regions.Where(x => Guid.TryParse(x, out _)).Select(x => x!)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase).Take(200).ToArray();
|
||||
var names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (ids.Length == 0) return names;
|
||||
var keys = ids.Select((_, i) => "@r" + i).ToArray();
|
||||
using var cmd = Command(db, "SELECT uuid, regionName FROM regions WHERE uuid IN (" +
|
||||
string.Join(",", keys) + ")", ids.Select((v, i) => ("@r" + i, (object)v)).ToArray());
|
||||
cmd.Transaction = tx;
|
||||
using var reader = cmd.ExecuteReader();
|
||||
while (reader.Read()) names[Value(reader, "uuid")!] = Value(reader, "regionName") ?? "";
|
||||
return names;
|
||||
}
|
||||
|
||||
public object List(string resource, int limit, int offset, string? search)
|
||||
{
|
||||
if (limit is < 1 or > 100 || offset is < 0 or > 1000000)
|
||||
throw new ArgumentOutOfRangeException(nameof(limit));
|
||||
if (search?.Length > 80) throw new ArgumentOutOfRangeException(nameof(search));
|
||||
string table = resource switch
|
||||
{
|
||||
"UserAccounts" => "UserAccounts",
|
||||
"GridUser" => "GridUser",
|
||||
"Presence" => "Presence",
|
||||
"Regions" => "regions",
|
||||
_ => throw new ArgumentException("Unknown resource", nameof(resource))
|
||||
};
|
||||
string? term = string.IsNullOrWhiteSpace(search) ? null : "%" + EscapeLike(search.Trim()) + "%";
|
||||
string searchColumn = resource switch
|
||||
{
|
||||
"UserAccounts" => "(FirstName LIKE @search ESCAPE '!' OR LastName LIKE @search ESCAPE '!' OR CONCAT(FirstName,' ',LastName) LIKE @search ESCAPE '!' OR PrincipalID LIKE @search ESCAPE '!')",
|
||||
"GridUser" => "UserID LIKE @search ESCAPE '!'",
|
||||
"Presence" => "UserID LIKE @search ESCAPE '!'",
|
||||
_ => "(regionName LIKE @search ESCAPE '!' OR uuid LIKE @search ESCAPE '!')"
|
||||
};
|
||||
string where = term is null ? "" : " WHERE " + searchColumn;
|
||||
string sql = resource switch
|
||||
{
|
||||
"UserAccounts" => "SELECT PrincipalID,FirstName,LastName,DisplayName,UserLevel,active,NexVerseState,Created FROM UserAccounts",
|
||||
"GridUser" => "SELECT UserID,Online,Login,Logout,LastRegionID FROM GridUser",
|
||||
"Presence" => "SELECT UserID,RegionID,LastSeen FROM Presence",
|
||||
_ => "SELECT uuid,regionName,owner_uuid,PrincipalID,locX,locY,sizeX,sizeY,last_seen FROM regions"
|
||||
};
|
||||
string order = resource switch
|
||||
{
|
||||
"UserAccounts" => "PrincipalID", "GridUser" => "UserID", "Presence" => "UserID", _ => "uuid"
|
||||
};
|
||||
using var db = Open();
|
||||
using (var init = Command(db, "SET TRANSACTION READ ONLY")) init.ExecuteNonQuery();
|
||||
using var tx = db.BeginTransaction(IsolationLevel.RepeatableRead);
|
||||
int total;
|
||||
using (var cmd = Command(db, "SELECT COUNT(*) FROM " + table + where,
|
||||
term is null ? Array.Empty<(string, object)>() : new[] { ("@search", (object)term) }))
|
||||
{
|
||||
cmd.Transaction = tx;
|
||||
total = Convert.ToInt32(cmd.ExecuteScalar(), CultureInfo.InvariantCulture);
|
||||
}
|
||||
var values = new List<(string Name, object Value)> { ("@limit", limit), ("@offset", offset) };
|
||||
if (term is not null) values.Add(("@search", term));
|
||||
var rows = new List<Dictionary<string, object?>>();
|
||||
using (var cmd = Command(db, sql + where + " ORDER BY " + order + " LIMIT @limit OFFSET @offset", values.ToArray()))
|
||||
{
|
||||
cmd.Transaction = tx;
|
||||
using var reader = cmd.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
var row = new Dictionary<string, object?>();
|
||||
switch (resource)
|
||||
{
|
||||
case "UserAccounts":
|
||||
string name = AvatarName(Value(reader, "FirstName"), Value(reader, "LastName"));
|
||||
row["uuid"] = Value(reader, "PrincipalID");
|
||||
row["avatarName"] = name;
|
||||
row["displayName"] = string.IsNullOrWhiteSpace(Value(reader, "DisplayName"))
|
||||
? name : Value(reader, "DisplayName");
|
||||
row["userLevel"] = Number(reader, "UserLevel");
|
||||
row["active"] = Number(reader, "active") != 0;
|
||||
row["accountState"] = Value(reader, "NexVerseState");
|
||||
row["createdAtUtc"] = UtcFromUnix(Number(reader, "Created"));
|
||||
break;
|
||||
case "GridUser":
|
||||
row["userId"] = Value(reader, "UserID");
|
||||
row["uuid"] = Principal(Value(reader, "UserID"));
|
||||
row["reportedOnline"] = string.Equals(Value(reader, "Online"), "true", StringComparison.OrdinalIgnoreCase);
|
||||
row["loginAtUtc"] = UtcFromUnix(Number(reader, "Login"));
|
||||
row["logoutAtUtc"] = UtcFromUnix(Number(reader, "Logout"));
|
||||
row["lastRegionUuid"] = Value(reader, "LastRegionID");
|
||||
break;
|
||||
case "Presence":
|
||||
row["uuid"] = Principal(Value(reader, "UserID"));
|
||||
row["regionUuid"] = Value(reader, "RegionID");
|
||||
row["lastSeenUtc"] = UtcFromDb(reader["LastSeen"]);
|
||||
row["regionReported"] = !string.Equals(Value(reader, "RegionID"), Zero, StringComparison.OrdinalIgnoreCase);
|
||||
break;
|
||||
default:
|
||||
row["uuid"] = Value(reader, "uuid");
|
||||
row["regionName"] = Value(reader, "regionName");
|
||||
row["ownerUuid"] = Value(reader, "owner_uuid");
|
||||
row["principalUuid"] = Value(reader, "PrincipalID");
|
||||
row["gridX"] = Number(reader, "locX");
|
||||
row["gridY"] = Number(reader, "locY");
|
||||
row["sizeX"] = Number(reader, "sizeX");
|
||||
row["sizeY"] = Number(reader, "sizeY");
|
||||
row["lastSeenUtc"] = UtcFromUnix(Number(reader, "last_seen"));
|
||||
break;
|
||||
}
|
||||
rows.Add(row);
|
||||
}
|
||||
}
|
||||
// The consistent read transaction covers account / HG-label lookups.
|
||||
var userIds = rows.SelectMany(x => new[] { x.GetValueOrDefault("uuid")?.ToString(),
|
||||
x.GetValueOrDefault("ownerUuid")?.ToString(), x.GetValueOrDefault("principalUuid")?.ToString() });
|
||||
var labels = Labels(db, tx, userIds);
|
||||
var regions = RegionNames(db, tx, rows.SelectMany(x => new[] { x.GetValueOrDefault("regionUuid")?.ToString(),
|
||||
x.GetValueOrDefault("lastRegionUuid")?.ToString() }));
|
||||
foreach (var row in rows)
|
||||
{
|
||||
string? uuid = row.GetValueOrDefault("uuid")?.ToString();
|
||||
if (resource is "GridUser" or "Presence")
|
||||
{
|
||||
Label? name = uuid is not null && labels.TryGetValue(uuid, out var found) ? found : null;
|
||||
row["avatarName"] = name?.Name ?? ForeignName(row.GetValueOrDefault("userId")?.ToString());
|
||||
row["nameSource"] = name?.Source ?? (row["avatarName"] is not null ? "HypergridUUI" : "Unknown");
|
||||
string field = resource == "GridUser" ? "lastRegionUuid" : "regionUuid";
|
||||
string? id = row.GetValueOrDefault(field)?.ToString();
|
||||
row[resource == "GridUser" ? "lastRegionName" : "regionName"] =
|
||||
id is not null && regions.TryGetValue(id, out var rn) ? rn : null;
|
||||
}
|
||||
if (resource == "Regions")
|
||||
{
|
||||
string? owner = row["ownerUuid"]?.ToString();
|
||||
row["ownerAvatarName"] = owner is not null && labels.TryGetValue(owner, out var who)
|
||||
? who.Name : null;
|
||||
string? principal = row["principalUuid"]?.ToString();
|
||||
row["principalAvatarName"] = principal is not null && labels.TryGetValue(principal, out var p)
|
||||
? p.Name : null;
|
||||
}
|
||||
}
|
||||
tx.Commit();
|
||||
return new { resource, generatedAtUtc = DateTimeOffset.UtcNow, pagination = new
|
||||
{ offset, limit, total, hasMore = (long)offset + rows.Count < total }, items = rows };
|
||||
}
|
||||
|
||||
public object? Account(string uuid)
|
||||
{
|
||||
if (!Guid.TryParse(uuid, out var parsed)) throw new ArgumentException("Invalid UUID", nameof(uuid));
|
||||
using var db = Open();
|
||||
using var cmd = Command(db,
|
||||
"SELECT PrincipalID,FirstName,LastName,DisplayName,UserLevel,active,NexVerseState,Created FROM UserAccounts WHERE PrincipalID=@uuid LIMIT 1",
|
||||
("@uuid", parsed.ToString("D")));
|
||||
using var r = cmd.ExecuteReader();
|
||||
if (!r.Read()) return null;
|
||||
string name = AvatarName(Value(r, "FirstName"), Value(r, "LastName"));
|
||||
return new { uuid = Value(r, "PrincipalID"), avatarName = name,
|
||||
displayName = string.IsNullOrWhiteSpace(Value(r, "DisplayName")) ? name : Value(r, "DisplayName"),
|
||||
userLevel = Number(r, "UserLevel"), active = Number(r, "active") != 0,
|
||||
accountState = Value(r, "NexVerseState"), createdAtUtc = UtcFromUnix(Number(r, "Created")) };
|
||||
}
|
||||
|
||||
public object Resolve(string uuid)
|
||||
{
|
||||
if (!Guid.TryParse(uuid, out var parsed)) throw new ArgumentException("Invalid UUID", nameof(uuid));
|
||||
string id = parsed.ToString("D");
|
||||
using var db = Open();
|
||||
var names = Labels(db, null, new[] { id });
|
||||
return new { uuid = id, found = names.TryGetValue(id, out var label),
|
||||
avatarName = label?.Name, displayName = label?.DisplayName,
|
||||
source = label?.Source ?? "Unknown", resolvedAtUtc = DateTimeOffset.UtcNow };
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
<Reference Include="OpenMetaverseTypes"><HintPath>../../bin/OpenMetaverseTypes.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Nini"><HintPath>../../bin/Nini.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="log4net"><HintPath>../../bin/log4net.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="MySql.Data"><HintPath>../../bin/MySql.Data.dll</HintPath><Private>false</Private></Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="www/index.html"/>
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# SYS.API v1 – geschützte Live-Datenbankansichten
|
||||
|
||||
SYS.API ruft die Daten **bei jedem GET frisch aus der ROBUST-MariaDB ab**. Es gibt keine zweite Datenbank und keinen periodischen Sync, der veralten könnte. Eine Listenanfrage hat eine konsistente, schreibgeschützte SQL-Transaktion für den Seitenausschnitt und die Namensauflösung. Die Datenbankansichten sind ein expliziter Feld-Whitelist-Vertrag; **keine generische Tabellen-/SQL-Abfrage-API**.
|
||||
|
||||
## Authentifizierung
|
||||
|
||||
**Alle folgenden Endpunkte sind geschützt**: Entweder ein gültiger `Authorization: Bearer <OGL_SYSAPI_PORTAL_TOKEN>` vom Stadtportal-Backend (niemals im Browser oder Client-JS ablegen) oder eine gültige `ogl_sysapi`-Webadministratorsitzung mit aktuell überprüftem `UserLevel >= 200`. Ohne Berechtigung stets HTTP 401. JSON-Antworten mit `Cache-Control: no-store, private`, ohne CORS-Freigabe. Das unveränderte öffentliche `/v1/health` liefert keine Nutzerdaten.
|
||||
|
||||
Die bisherigen Endpunkte `/api/v1/portal/ping`, `/api/v1/portal/capabilities` und `/api/admin/overview` bleiben kompatibel. `GET /api/v1/portal/capabilities` führt die neuen URLs auf. Schreibmethoden sind nicht implementiert; POST an diese Datenrouten liefert nach Authentifizierung 405.
|
||||
|
||||
## Endpunkte
|
||||
|
||||
| HTTP-Methode / Pfad | Daten / Status |
|
||||
| --- | --- |
|
||||
| `GET /api/v1/UserAccounts/lists?limit=50&offset=0&search=Vorname` | Aktuelle lokale Avatar-Konten: `uuid`, `avatarName`, `displayName`, `userLevel`, `active`, `accountState`, `createdAtUtc`. |
|
||||
| `GET /UserAccounts/lists` | Identischer, geschützter Alias für die gewünschte Kurz-URL. |
|
||||
| `GET /api/v1/UserAccounts/{uuid}` | Ein Avatar-Konto; 404, wenn UUID nicht existiert. |
|
||||
| `GET /api/v1/UUID/resolve?uuid={uuid}` | `uuid`, `avatarName`, `displayName`, `source` und `found`; lokale Namen aus UserAccounts, fremde aus HG-UUI, wenn eindeutig. |
|
||||
| `GET /api/v1/GridUser/lists?limit=50&offset=0&search=...` | GridUser-Identität mit `uuid`, `userId`, `avatarName`, `reportedOnline`, `loginAtUtc`, `logoutAtUtc`, `lastRegionUuid`, `lastRegionName`. |
|
||||
| `GET /api/v1/Presence/lists?limit=50&offset=0&search=...` | Presence mit `uuid`, `avatarName`, `regionUuid`, `regionName`, `lastSeenUtc`, `regionReported`. |
|
||||
| `GET /api/v1/Regions/lists?limit=50&offset=0&search=...` | Region mit `uuid`, `regionName`, `ownerUuid`, `ownerAvatarName`, `principalUuid`, `principalAvatarName`, `gridX/Y`, `sizeX/Y`, `lastSeenUtc`. |
|
||||
|
||||
Für `GridUser`, `Presence` und `Regions` sind die Kurzformen `/GridUser/lists`, `/Presence/lists`, `/Regions/lists` ebenfalls authentifizierte Aliasse. Jeder API-Abruf nutzt ausschließlich GET.
|
||||
|
||||
Abfrageparameter: `limit` standardmäßig 50, Bereich **1–100**; `offset` standardmäßig 0, Bereich **0–1.000.000**; optional `search` maximal 80 Zeichen. Alle Suchausdrücke sind parameterisiert und die LIKE-Sonderzeichen werden wörtlich behandelt. Die Antwort enthält `resource`, `generatedAtUtc`, `pagination` (`limit`, `offset`, `total`, `hasMore`) und `items`. Listen werden stabil nach Primärschlüssel sortiert; bei parallel laufenden Änderungen können sich Seiten zwischen zwei Aufrufen natürlich verschieben.
|
||||
|
||||
**Namensauflösung:** UUIDs lokaler Avatare werden über `UserAccounts.PrincipalID` mit Vor- und Nachnamen verknüpft. Hypergrid-UUIs enthalten häufig selbst einen Namen (`uuid;homeUri;name`); der wird verwendet, sofern er zuordenbar ist. Bei mehrdeutiger oder unbekannter Identität wird `nameSource=Unknown` bzw. ein nicht auflösbarer Name ausgewiesen: **niemals Namen erraten**. Fehlende Regionnamen werden als `null` geliefert, statt eine falsche Region anzuzeigen.
|
||||
|
||||
**Wichtig zu Online-Status:** `reportedOnline` ist ausschließlich der aktuelle Wert der **GridUser-Tabelle**. `Presence.regionReported=true` bedeutet nur eine gesetzte Region-ID. Beides ist **kein verifizierter Root-Agent-Anwesenheitsnachweis**. Siehe die unabhängige laufende Hypergrid-Presence-Beobachtung #461.
|
||||
|
||||
## Beispielantwort (anonymisierte Musterdaten)
|
||||
|
||||
```json
|
||||
{
|
||||
"resource": "UserAccounts",
|
||||
"generatedAtUtc": "2026-11-20T12:00:00Z",
|
||||
"pagination": { "limit": 2, "offset": 0, "total": 30, "hasMore": true },
|
||||
"items": [
|
||||
{
|
||||
"uuid": "00000000-0000-0000-0000-000000000001",
|
||||
"avatarName": "Beispiel Avatar",
|
||||
"displayName": "Beispiel Avatar",
|
||||
"userLevel": 0,
|
||||
"active": true,
|
||||
"accountState": "active",
|
||||
"createdAtUtc": "2026-01-01T00:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Datenschutz und Bereitstellung
|
||||
|
||||
Ausgelassen werden insbesondere **E-Mail-Adressen, Passwort-/Authentifizierungsdaten, SessionIDs, SecureSessionIDs, ServiceURLs, Region-Recv-/Send-/Asset-Keys, API-Tokens, interne Server-URIs und -IPs**. Es gibt keinen Rohdatenbank-Endpunkt. Fehler liefern nur einen neutralen JSON-Fehlertext. Anfrageprotokolle dürfen Tokens, UUIDs oder Nutzernamen nicht dauerhaft veröffentlichen.
|
||||
|
||||
Der initiale Implementierungsprovider ist **MariaDB/MySQL** (wie der aktuelle Stadt-NexVerse-ROBUST). Für SQLite/PostgreSQL muss eine eigene `ISysApiReadModel`-Implementierung ergänzt werden; falls der Provider nicht initialisiert werden kann, antworten nur die neuen Datenendpunkte mit **503**, während das bisherige Dashboard und die World API weiterhin verfügbar bleiben.
|
||||
|
||||
Die neue DLL wird **nicht automatisch produktiv geladen**, nur weil der Code nach `main` gelangt: Für eine Installation im bestehenden ROBUST ist ein gesicherter, geplanter Neustart erforderlich. Während der laufenden sieben Tage Hypergrid-Presence-Überwachung (#461) keinen unkoordinierten Neustart auslösen.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
python3 tools/ci/verify_sys_api_foundation.py
|
||||
python3 tools/ci/verify_sys_api_readmodel.py
|
||||
dotnet build addons/SysApi/sys.api.csproj -c Release
|
||||
dotnet run --project tools/ci/SysApiSmoke/SysApiSmoke.csproj -c Release
|
||||
```
|
||||
|
||||
Zusätzlich: `SysApiReadModelIntegration` nur in einer **autorisierten Staging-/Operatorumgebung** mit vorhandener MariaDB-Konfiguration und geschützter DB-Umgebung ausführen. Der Test liest nur Daten, schreibt keine Namen oder UUIDs ins Testlog.
|
||||
@@ -0,0 +1,72 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Nini.Config;
|
||||
using OpenGenesisLINK.SysApi;
|
||||
|
||||
// Read-only staging validation against the operator-provided existing MariaDB.
|
||||
// DO NOT print raw rows, UUIDs, names, URLs, or connection strings.
|
||||
string robust = File.ReadAllText("/opt/robust/bin/Robust.HG.ini");
|
||||
Match m = Regex.Match(robust, @"(?m)^\s*ConnectionString\s*=\s*""?([^""\r\n]+)");
|
||||
if (!m.Success) throw new Exception("Database configuration unavailable");
|
||||
var config = new IniConfigSource();
|
||||
config.Configs.Add("DatabaseService").Set("ConnectionString", m.Groups[1].Value);
|
||||
var data = new MySqlSysApiReadModel(config);
|
||||
static void Check(bool yes, string message) { if (!yes) throw new Exception(message); }
|
||||
foreach (string resource in new[] { "UserAccounts", "GridUser", "Presence", "Regions" })
|
||||
{
|
||||
using JsonDocument result = JsonDocument.Parse(JsonSerializer.Serialize(data.List(resource, 7, 0, null)));
|
||||
var root = result.RootElement;
|
||||
int total = root.GetProperty("pagination").GetProperty("total").GetInt32();
|
||||
var items = root.GetProperty("items");
|
||||
Check(total > 0 && items.GetArrayLength() > 0 && items.GetArrayLength() <= 7, "Live listing failure " + resource);
|
||||
Check(root.GetProperty("pagination").GetProperty("limit").GetInt32() == 7, "Pagination wrong");
|
||||
string json = root.GetRawText();
|
||||
foreach (string secret in new[] { "Email", "ServiceURLs", "password", "regionSecret", "SessionID", "Token" })
|
||||
Check(!json.Contains('"' + secret + '"', StringComparison.OrdinalIgnoreCase), "Sensitive field in " + resource);
|
||||
foreach (var item in items.EnumerateArray())
|
||||
{
|
||||
Check(item.TryGetProperty("uuid", out _), "UUID missing in " + resource);
|
||||
if (resource is "UserAccounts" or "GridUser" or "Presence")
|
||||
Check(item.TryGetProperty("avatarName", out _), "Avatar-name field missing in " + resource);
|
||||
if (resource == "Regions") Check(item.TryGetProperty("ownerAvatarName", out _), "Owner label missing");
|
||||
}
|
||||
Console.WriteLine($"PASS {resource}: live rows={total}, page-size={items.GetArrayLength()}, no secret fields");
|
||||
}
|
||||
using (JsonDocument list = JsonDocument.Parse(JsonSerializer.Serialize(data.List("UserAccounts", 1, 0, null))))
|
||||
{
|
||||
string uuid = list.RootElement.GetProperty("items")[0].GetProperty("uuid").GetString()!;
|
||||
Check(data.Account(uuid) is not null, "Single account cannot resolve");
|
||||
using JsonDocument resolved = JsonDocument.Parse(JsonSerializer.Serialize(data.Resolve(uuid)));
|
||||
Check(resolved.RootElement.GetProperty("found").GetBoolean(), "UUID not resolved");
|
||||
Check(resolved.RootElement.GetProperty("avatarName").GetString() is { Length: > 0 }, "Resolved name absent");
|
||||
}
|
||||
Console.WriteLine("PASS UUID→avatar display name, live MariaDB, protected column allowlist");
|
||||
|
||||
foreach (string dataset in new[] { "GridUser", "Presence", "Regions" })
|
||||
{
|
||||
using JsonDocument list = JsonDocument.Parse(JsonSerializer.Serialize(data.List(dataset, 100, 0, null)));
|
||||
var items = list.RootElement.GetProperty("items");
|
||||
int labeled = 0;
|
||||
int unresolved = 0;
|
||||
foreach (var item in items.EnumerateArray())
|
||||
{
|
||||
string field = dataset == "Regions" ? "ownerAvatarName" : "avatarName";
|
||||
if (!item.TryGetProperty(field, out var name) || name.ValueKind == JsonValueKind.Null ||
|
||||
string.IsNullOrWhiteSpace(name.GetString())) unresolved++;
|
||||
else labeled++;
|
||||
}
|
||||
Console.WriteLine($"NAME_RESOLUTION_SAMPLE {dataset}: labeled={labeled}, unknown={unresolved}");
|
||||
}
|
||||
|
||||
using (JsonDocument injection = JsonDocument.Parse(JsonSerializer.Serialize(data.List("UserAccounts", 10, 0, "' OR 1=1 --"))))
|
||||
Check(injection.RootElement.GetProperty("pagination").GetProperty("total").GetInt32() == 0,
|
||||
"SQL metacharacters affected account search");
|
||||
using (JsonDocument escapedWildcard = JsonDocument.Parse(JsonSerializer.Serialize(data.List("UserAccounts", 10, 0, "%"))))
|
||||
Check(escapedWildcard.RootElement.GetProperty("pagination").GetProperty("total").GetInt32() == 0,
|
||||
"LIKE wildcard escaped incorrectly");
|
||||
using (JsonDocument laterPage = JsonDocument.Parse(JsonSerializer.Serialize(data.List("UserAccounts", 10, 1000000, null))))
|
||||
Check(laterPage.RootElement.GetProperty("items").GetArrayLength() == 0,
|
||||
"Pagination offset not enforced");
|
||||
Check(data.Account("00000000-0000-0000-0000-000000000000") is null, "Unexpected UUID.Zero account");
|
||||
Console.WriteLine("PASS SQL injection/LIKE search, empty high-offset page and UUID miss");
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../addons/SysApi/sys.api.csproj"/>
|
||||
<Reference Include="Nini"><HintPath>../../../bin/Nini.dll</HintPath><Private>true</Private></Reference>
|
||||
<Reference Include="MySql.Data"><HintPath>../../../bin/MySql.Data.dll</HintPath><Private>true</Private></Reference>
|
||||
<Reference Include="System.Security.Permissions"><HintPath>../../../bin/System.Security.Permissions.dll</HintPath><Private>true</Private></Reference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -33,7 +33,7 @@ int port = ((IPEndPoint)free.LocalEndpoint).Port;
|
||||
free.Stop();
|
||||
using var host = new SysApiHost(port, "https://sysapi.example.test:8850",
|
||||
DispatchProxy.Create<IUserAccountService, AccountProxy>(),
|
||||
DispatchProxy.Create<IAuthenticationService, AuthenticationProxy>(), first);
|
||||
DispatchProxy.Create<IAuthenticationService, AuthenticationProxy>(), first, new FakeSysApiReadModel());
|
||||
host.Start();
|
||||
try
|
||||
{
|
||||
@@ -61,11 +61,49 @@ try
|
||||
Expect(health.StatusCode, HttpStatusCode.OK, "health");
|
||||
using var anonymous = await client.GetAsync("/api/admin/overview");
|
||||
Expect(anonymous.StatusCode, HttpStatusCode.Unauthorized, "dashboard 401");
|
||||
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 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");
|
||||
@@ -86,9 +124,13 @@ 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 (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 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");
|
||||
@@ -131,3 +173,17 @@ public class AuthenticationProxy : DispatchProxy
|
||||
_ => 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 Resolve(string uuid) =>
|
||||
new { uuid, found = true, avatarName = "Test Operator", source = "UserAccounts" };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Security contract for the SYS.API allowlisted read-only database views."""
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[2]
|
||||
read=lambda p:(root/p).read_text(encoding='utf-8')
|
||||
host=read('addons/SysApi/SysApiHost.cs')
|
||||
backend=read('addons/SysApi/SysApiReadModel.cs')
|
||||
connector=read('addons/SysApi/SysApiConnector.cs')
|
||||
for path in ('/UserAccounts/lists','/GridUser/lists','/Presence/lists','/Regions/lists','/UUID/resolve'):
|
||||
assert path in host,path
|
||||
for marker in ('if (!HasPortalToken(req) && !TryAdmin(req, out _))',
|
||||
'Authorization required','Read-only endpoint','Invalid pagination or search',
|
||||
'if (_readModel is null)','Database read temporarily unavailable'):
|
||||
assert marker in host,marker
|
||||
for marker in ('SET TRANSACTION READ ONLY','MySqlConnection', 'PrincipalID',
|
||||
'nameSource', 'ownerAvatarName', 'avatarName', 'LIMIT @limit OFFSET @offset',
|
||||
'command.Parameters.AddWithValue','"@search"', 'EscapeLike'):
|
||||
assert marker in backend,marker
|
||||
assert 'SELECT *' not in backend
|
||||
assert 'DROP TABLE' not in backend
|
||||
assert 'DELETE FROM' not in backend
|
||||
assert 'UPDATE UserAccounts' not in backend
|
||||
assert 'Email,ServiceURLs' not in backend
|
||||
assert 'MySqlSysApiReadModel(config)' in connector
|
||||
assert 'SYS_API_LIVE_READMODEL.md' not in host
|
||||
print('SYS.API live read-only JSON, URL routes, whitelist, pagination and authorization: PASS')
|
||||
Reference in new issue
Block a user