test(groups): signed JWT HTTP authorization with SQL and wallet recovery (#273)

Add production-handler real HTTP integration tests with native HMAC bearer authentication, MariaDB groups membership and invitation IDOR guards, role revocation, NV$ wallet state and pending provisioning recovery. All CI jobs pass.
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-22 18:20:27 +02:00
1 parent bcb528ac5c
commit e8cc586323
4 files changed
+353

No files matched your search

+6
View File
@@ -1329,3 +1329,9 @@ jobs:
chmod +x runprebuild.sh
./runprebuild.sh
dotnet run --configuration Release --project tools/ci/NexGroupsSqlAuthorizationRegression/NexGroupsSqlAuthorizationRegression.csproj
- name: Run signed bearer HTTP NexGroups authorization regression
shell: bash
env:
NEX_GROUPS_MARIADB: "Data Source=127.0.0.1;Port=33306;Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;"
run: dotnet run --configuration Release --project tools/ci/NexGroupsHttpRegression/NexGroupsHttpRegression.csproj
@@ -0,0 +1,43 @@
# NexGroups HTTP bearer/JWT + MariaDB regression
This is a **runtime, real-TCP HTTP integration test**. It instantiates the
production `NexGroupsApi` handler, `NexApiAuthenticator`, `GroupsService`,
`UserAccountService`, `NexEconomyService` and the SQL-backed NVD ledger.
It uses OpenSim's `BaseHttpServer` to process actual `HttpClient`
requests on an isolated loopback port, with HMAC-signed bearer tokens.
```bash
# Requires an isolated MariaDB test database, generated OpenSim projects
# and the private CI-only connection string.
NEX_GROUPS_MARIADB='Data Source=127.0.0.1;Port=33306;Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;' \
dotnet run --configuration Release --project tools/ci/NexGroupsHttpRegression/NexGroupsHttpRegression.csproj
```
## Scenarios
- Unauthenticated and tampered JWTs return 401.
- Insufficient JWT scopes, strangers and non-accountant members receive 403.
- Spoofed `requester_id` does not impersonate a group accountant.
- Group founder and assigned accountants get 200 from the accounting route,
with real NV$ balance and NVBAN.
- Revoking Accountable reverts access to 403 immediately.
- Invitations are readable by their legitimate recipient and group owner
but not by other residents.
- A known invite UUID cannot be read or deleted by a stranger, including
via `requester_id` impersonation.
- Cross-group URL/invite mismatch returns 404.
- When the Economy delegate is temporarily unavailable, a committed group
creation reports `201 Created` and `wallet_status=pending`;
subsequent accounting is successfully provisioned after recovery.
- Created groups are deleted after successful test completion.
## Security boundaries
The test issues **nonproduction bearer tokens** for freshly created local
CI users; the issuer, signing key and database are dedicated to the test
run and never used by a production ROBUST instance. The listener binds only
to loopback. It does not need full ROBUST bootstrap to exercise the actual
HTTP transport and handler/authenticator code.
This test does not verify TLS termination or proxy identity trust, and does
not run against the production grid. Those remain separate deployment checks.
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Security.Permissions" Version="8.0.0" />
<Reference Include="Nini"><HintPath>../../../bin/Nini.dll</HintPath><Private>True</Private></Reference>
<Reference Include="OpenMetaverse"><HintPath>../../../bin/OpenMetaverse.dll</HintPath><Private>True</Private></Reference>
<Reference Include="OpenMetaverseTypes"><HintPath>../../../bin/OpenMetaverseTypes.dll</HintPath><Private>True</Private></Reference>
<Reference Include="log4net"><HintPath>../../../bin/log4net.dll</HintPath><Private>True</Private></Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../NexVerse/Core/NexVerse.Core.csproj" />
<ProjectReference Include="../../../NexVerse/Server/Api/NexVerse.Server.Api.csproj" />
<ProjectReference Include="../../../OpenSim/Addons/Groups/OpenSim.Addons.Groups.csproj" />
<ProjectReference Include="../../../OpenSim/Framework/OpenSim.Framework.csproj" />
<ProjectReference Include="../../../OpenSim/Framework/Console/OpenSim.Framework.Console.csproj" />
<ProjectReference Include="../../../OpenSim/Framework/Servers/HttpServer/OpenSim.Framework.Servers.HttpServer.csproj" />
<ProjectReference Include="../../../OpenSim/Services/UserAccountService/OpenSim.Services.UserAccountService.csproj" />
<ProjectReference Include="../../../OpenSim/Data/MySQL/OpenSim.Data.MySQL.csproj" />
</ItemGroup>
</Project>
+279
View File
@@ -0,0 +1,279 @@
// SPDX-License-Identifier: MPL-2.0
// Real TCP/HTTP, signed resident JWTs, MariaDB Groups V2 and NV$ ledger.
// Run ONLY against the isolated GitHub Actions test database.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.Json;
using Nini.Config;
using NexVerse.Core.Economy;
using NexVerse.Core.Security;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Groups;
using OpenSim.Services.Interfaces;
using OpenSim.Services.UserAccountService;
internal static class Program
{
private static void Check(bool ok, string what)
{
if (!ok) throw new InvalidOperationException("Groups HTTP integration: " + what);
}
private static int FindPort()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
private static UserAccount Seed(UserAccountService users, string name)
{
var account = new UserAccount(UUID.Zero, UUID.Random(), name, "Resident",
name.ToLowerInvariant() + "@nexgroups-ci.invalid")
{
Active = true,
LocalToGrid = true,
UserLevel = 0,
NexVerseState = "active",
NexVerseRoles = "resident",
NexVerseStateChanged = 7
};
Check(users.StoreUserAccount(account), "unable to persist resident " + name);
var stored = users.GetUserAccount(UUID.Zero, account.PrincipalID);
Check(stored != null && stored.NexVerseStateChanged == account.NexVerseStateChanged,
"resident identity/security stamp did not persist");
return stored;
}
private static object Construct(Type type, params object[] args)
{
object result = Activator.CreateInstance(type,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, args, null);
return result ?? throw new InvalidOperationException("Could not construct " + type.Name);
}
private static SimpleStreamMethod Route(GroupsService groups,
UserAccountService users, HmacNexAccessTokenService tokens,
Func<NexEconomyService> economy)
{
Assembly assembly = Assembly.Load("NexVerse.Server.Api");
Type authType = assembly.GetType("NexVerse.Server.Api.NexApiAuthenticator", true);
Type groupsType = assembly.GetType("NexVerse.Server.Api.NexGroupsApi", true);
var auth = Construct(authType, users, new NexAuthorizationService(),
tokens, null, null, 200);
var api = Construct(groupsType, auth, null, groups, economy);
MethodInfo handle = groupsType.GetMethod("Handle",
BindingFlags.Instance | BindingFlags.Public);
Check(handle != null, "NexGroupsApi.Handle missing");
return (SimpleStreamMethod)Delegate.CreateDelegate(
typeof(SimpleStreamMethod), api, handle);
}
private static async System.Threading.Tasks.Task Verify(
HttpClient client, string path, string token,
HttpStatusCode expected, string jsonProperty = null,
HttpMethod method = null, string body = null)
{
using var req = new HttpRequestMessage(method ?? HttpMethod.Get, path);
if (token != null)
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body != null)
req.Content = new StringContent(body, Encoding.UTF8, "application/json");
using var res = await client.SendAsync(req);
string response = await res.Content.ReadAsStringAsync();
Check(res.StatusCode == expected,
(method ?? HttpMethod.Get) + " " + path +
" expected " + (int)expected + ", got " + (int)res.StatusCode +
"; body=" + response);
if (jsonProperty != null)
{
using var json = JsonDocument.Parse(response);
Check(json.RootElement.TryGetProperty(jsonProperty, out _),
"JSON property '" + jsonProperty + "' missing from " + path);
}
}
private static async System.Threading.Tasks.Task Main()
{
string connection = Environment.GetEnvironmentVariable("NEX_GROUPS_MARIADB");
Check(!string.IsNullOrWhiteSpace(connection),
"isolated NEX_GROUPS_MARIADB connection is required");
MainConsole.Instance = new MockConsole();
var config = new IniConfigSource();
var db = config.AddConfig("DatabaseService");
string mysql = Path.GetFullPath(Path.Combine("bin", "OpenSim.Data.MySQL.dll"));
Check(File.Exists(mysql), "MySQL provider missing");
db.Set("StorageProvider", mysql);
db.Set("ConnectionString", connection);
var userCfg = config.AddConfig("UserAccountService");
userCfg.Set("CreateDefaultAvatarEntries", false);
var groupsCfg = config.AddConfig("Groups");
string scratch = Path.Combine(Path.GetTempPath(), "nexgroups-http-" +
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(scratch);
groupsCfg.Set("Realm", "os_groups");
groupsCfg.Set("NexModerationStorePath", Path.Combine(scratch, "moderation.json"));
var grid = config.AddConfig("GridUserService");
grid.Set("StorageProvider", mysql);
grid.Set("ConnectionString", connection);
grid.Set("Realm", "GridUser");
BaseHttpServer server = null;
try
{
var users = new UserAccountService(config);
var groups = new GroupsService(config, "Groups");
UserAccount owner = Seed(users, "Owner" + Guid.NewGuid().ToString("N").Substring(0, 9));
UserAccount member = Seed(users, "Member" + Guid.NewGuid().ToString("N").Substring(0, 9));
UserAccount stranger = Seed(users, "Stranger" + Guid.NewGuid().ToString("N").Substring(0, 9));
UserAccount invitee = Seed(users, "Invitee" + Guid.NewGuid().ToString("N").Substring(0, 9));
string key = new string('H', 64);
var tokens = new HmacNexAccessTokenService(
"http://127.0.0.1:19981", "nexgroups-http-ci", key, 600);
string Jwt(UserAccount account, params string[] scopes) =>
tokens.Issue(account.PrincipalID.ToString(), scopes,
account.NexVerseStateChanged);
string ownerToken = Jwt(owner, NexScopes.GroupsRead, NexScopes.GroupsManage);
string memberToken = Jwt(member, NexScopes.GroupsRead, NexScopes.GroupsManage);
string strangerToken = Jwt(stranger, NexScopes.GroupsRead, NexScopes.GroupsManage);
string inviteeReadToken = Jwt(invitee, NexScopes.GroupsRead);
string inviteeToken = Jwt(invitee, NexScopes.GroupsRead, NexScopes.GroupsManage);
string narrowToken = Jwt(stranger, NexScopes.UsersRead);
var runtime = NexLedgerSqlRuntime.Resolve("OpenSim.Data.MySQL.dll", connection);
NexLedgerSqlStore store = runtime.CreateStore();
var economy = new NexEconomyService(new NexDoubleEntryLedger(store), store);
NexEconomyService activeEconomy = economy;
var handler = Route(groups, users, tokens, () => activeEconomy);
int port = FindPort();
server = new BaseHttpServer((uint)port) { ListenIPAddress = IPAddress.Loopback };
server.AddSimpleStreamHandler(
new SimpleStreamHandler("/api/v1/groups", handler, "Groups HTTP CI"), true);
server.Start();
using var http = new HttpClient { BaseAddress =
new Uri("http://127.0.0.1:" + port + "/"),
Timeout = TimeSpan.FromSeconds(12) };
UUID group = groups.CreateGroup(owner.PrincipalID.ToString(),
"HTTP-CI-" + Guid.NewGuid().ToString("N"), "HTTP fixture",
false, UUID.Zero, 0, false, false, false,
owner.PrincipalID, out string reason);
Check(!group.IsZero(), "fixture group creation failed: " + reason);
UUID otherGroup = groups.CreateGroup(owner.PrincipalID.ToString(),
"HTTP-CI-OTHER-" + Guid.NewGuid().ToString("N"), "URL mismatch",
false, UUID.Zero, 0, false, false, false,
owner.PrincipalID, out reason);
Check(!otherGroup.IsZero(), "second group creation failed: " + reason);
string accounting = "/api/v1/groups/" + group + "/accounting";
Check(groups.AddAgentToGroup(owner.PrincipalID.ToString(),
member.PrincipalID.ToString(), group, UUID.Zero, "", out reason),
"could not join member: " + reason);
Check(groups.UpdateGroupRole(owner.PrincipalID.ToString(), group,
UUID.Zero, "Everyone", "Without financial access", "Member",
(ulong)GroupPowers.JoinChat),
"could not drop Accountable from Everyone");
await Verify(http, accounting, null, HttpStatusCode.Unauthorized, "error");
await Verify(http, accounting, "invalid.jwt.token",
HttpStatusCode.Unauthorized, "error");
await Verify(http, accounting, narrowToken,
HttpStatusCode.Forbidden, "error");
await Verify(http, accounting, strangerToken,
HttpStatusCode.Forbidden, "error");
await Verify(http, accounting, memberToken,
HttpStatusCode.Forbidden, "error");
await Verify(http, accounting + "?requester_id=" + owner.PrincipalID,
strangerToken, HttpStatusCode.Forbidden, "error");
await Verify(http, accounting, ownerToken, HttpStatusCode.OK, "nvban");
UUID accountingRole = UUID.Random();
Check(groups.AddGroupRole(owner.PrincipalID.ToString(), group,
accountingRole, "Accountants", "Finance", "Accountant",
(ulong)GroupPowers.Accountable, out reason),
"accountant role creation failed: " + reason);
Check(groups.AddAgentToGroupRole(owner.PrincipalID.ToString(),
member.PrincipalID.ToString(), group, accountingRole),
"accountant assignment failed");
await Verify(http, accounting, memberToken, HttpStatusCode.OK, "balance");
Check(groups.RemoveAgentFromGroupRole(owner.PrincipalID.ToString(),
member.PrincipalID.ToString(), group, accountingRole),
"accountant role revocation failed");
await Verify(http, accounting, memberToken, HttpStatusCode.Forbidden, "error");
UUID invite = UUID.Random();
Check(groups.AddAgentToGroupInvite(owner.PrincipalID.ToString(),
invite, group, UUID.Zero, invitee.PrincipalID.ToString()),
"cannot seed invitation");
string invitation = "/api/v1/groups/" + group + "/invites/" + invite;
await Verify(http, invitation, inviteeToken, HttpStatusCode.OK, "invite");
await Verify(http, invitation, ownerToken, HttpStatusCode.OK, "invite");
await Verify(http, invitation, strangerToken, HttpStatusCode.NotFound, "error");
await Verify(http, invitation + "?requester_id=" + invitee.PrincipalID,
strangerToken, HttpStatusCode.NotFound, "error");
await Verify(http, "/api/v1/groups/" + otherGroup + "/invites/" + invite,
inviteeToken, HttpStatusCode.NotFound, "error");
await Verify(http, invitation, strangerToken, HttpStatusCode.NotFound,
"error", HttpMethod.Delete);
await Verify(http, invitation, inviteeToken, HttpStatusCode.OK,
"invite");
await Verify(http, invitation, inviteeReadToken, HttpStatusCode.Forbidden,
"error", HttpMethod.Delete);
await Verify(http, invitation, inviteeToken, HttpStatusCode.OK,
"deleted", HttpMethod.Delete);
await Verify(http, invitation, inviteeToken, HttpStatusCode.NotFound, "error");
// Persisted group creation succeeds even during an economy outage:
// the API must return 201/pending rather than misleading 500.
activeEconomy = null;
string name = "HTTP-CREATE-" + Guid.NewGuid().ToString("N");
using (var req = new HttpRequestMessage(HttpMethod.Post, "/api/v1/groups"))
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ownerToken);
req.Content = new StringContent(
JsonSerializer.Serialize(new { name, charter = "temporary economy outage" }),
Encoding.UTF8, "application/json");
using var response = await http.SendAsync(req);
string body = await response.Content.ReadAsStringAsync();
Check(response.StatusCode == HttpStatusCode.Created,
"group creation during outage returned " + body);
using var json = JsonDocument.Parse(body);
Check(json.RootElement.GetProperty("wallet_status").GetString() == "pending",
"outage did not report wallet_status=pending");
UUID created = new UUID(json.RootElement.GetProperty("group_id").GetString());
Check(groups.GetGroupRecord(owner.PrincipalID.ToString(), created) != null,
"group with pending wallet was not persisted");
activeEconomy = economy;
await Verify(http, "/api/v1/groups/" + created + "/accounting",
ownerToken, HttpStatusCode.OK, "nvban");
Check(groups.DeleteGroup(owner.PrincipalID.ToString(), created, out reason),
"pending wallet fixture group cleanup failed: " + reason);
}
Check(groups.DeleteGroup(owner.PrincipalID.ToString(), group, out reason),
"first fixture cleanup failed: " + reason);
Check(groups.DeleteGroup(owner.PrincipalID.ToString(), otherGroup, out reason),
"second fixture cleanup failed: " + reason);
Console.WriteLine("NexGroups signed bearer HTTP / real MariaDB / NV$ ledger: OK");
}
finally
{
server?.Stop(true);
try { Directory.Delete(scratch, true); } catch (IOException) {}
}
}
}