From bd6bf4f28cbf72c9ba01033b481db9dc1e68c4ce Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:13:26 +0200 Subject: [PATCH] feat(groups): grid-wide parcels and native Firestorm NV$ history (#274) Add real 7-day group ledger history with native Firestorm UDP accounting and sales packets, and grid-wide group-owned parcel queries from authoritative region storage. Authenticate group requests, require dual-scoped machine keys for finance, preserve membership and Accountable checks, document rollout, and verify remote region SQL fixtures and genuine signed NV$ credits over HTTP. CI green. --- NexVerse/Core/Security/NexApiKeyStore.cs | 3 + .../Discovery/NexDiscoveryViewerModule.cs | 72 +++++++ .../Economy/NexVerseMoneyModule.cs | 122 +++++++++++- NexVerse/Server/Api/NexGroupLandDirectory.cs | 138 ++++++++++++++ NexVerse/Server/Api/NexGroupsApi.cs | 142 ++++++++++++++ .../Server/Api/NexVerseWorldApiConnector.cs | 15 ++ OpenSim/Framework/GroupData.cs | 12 ++ OpenSim/Framework/IClientAPI.cs | 14 ++ .../ClientStack/Linden/UDP/LLClientView.cs | 50 ++++- bin/OpenSim.ini.example | 3 + bin/Robust.HG.ini.example | 2 + bin/config-include/GridCommon.ini | 1 + doc/NexVerse/FIRESTORM_GROUP_LAND_NVDOLLAR.md | 32 ++-- doc/NexVerse/NEXGROUPS_GRID_LAND_HISTORY.md | 84 +++++++++ tools/ci/NexGroupsHttpRegression/Program.cs | 177 +++++++++++++++++- 15 files changed, 843 insertions(+), 24 deletions(-) create mode 100644 NexVerse/Server/Api/NexGroupLandDirectory.cs create mode 100644 doc/NexVerse/NEXGROUPS_GRID_LAND_HISTORY.md diff --git a/NexVerse/Core/Security/NexApiKeyStore.cs b/NexVerse/Core/Security/NexApiKeyStore.cs index 3b18f0dc..a5ebaae2 100644 --- a/NexVerse/Core/Security/NexApiKeyStore.cs +++ b/NexVerse/Core/Security/NexApiKeyStore.cs @@ -101,6 +101,9 @@ namespace NexVerse.Core.Security NexScopes.EstatesManage, NexScopes.EconomyRead, NexScopes.EconomyTransfer, + // Viewer simulator backend may read group-owned land + // only via an explicitly granted groups:read machine key. + NexScopes.GroupsRead, NexScopes.ExperiencesScript, // Separate trusted simulator CAP transport. This is // deliberately NOT experiences:manage or admin:*. diff --git a/NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs b/NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs index e312f836..8ff0dbad 100644 --- a/NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs +++ b/NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs @@ -36,6 +36,8 @@ namespace NexVerse.RegionModules.Discovery private bool m_Enabled; private bool m_LegacyFirestormCompatibility; private string m_WorldApiBaseUrl = string.Empty; + // Backend-only group land credential; never exposed to viewers/CAPS. + private string m_GroupLandApiKey = string.Empty; private int m_RequestTimeoutMilliseconds = 3000; private HttpClient m_Http; @@ -61,6 +63,9 @@ namespace NexVerse.RegionModules.Discovery .Trim() .TrimEnd('/'); + m_GroupLandApiKey = section.GetString( + "GroupLandApiKey", string.Empty).Trim(); + m_LegacyFirestormCompatibility = section.GetBoolean( "LegacyFirestormCompatibility", @@ -253,6 +258,51 @@ namespace NexVerse.RegionModules.Discovery BillableArea = 0, SimName = string.Empty }); + // Prefer the authoritative grid-wide SQL directory, which + // includes other simulator processes. Only the trusted + // simulator may use the explicit groups:read machine key; + // the avatar's membership was checked above. + if (!string.IsNullOrEmpty(m_GroupLandApiKey)) + { + try + { + using JsonDocument remote = GetGroupLandJson(queryID); + if (!remote.RootElement.TryGetProperty( + "parcels", out JsonElement list) || + list.ValueKind != JsonValueKind.Array) + throw new InvalidOperationException( + "Group land response has no parcels list."); + + foreach (JsonElement parcel in list.EnumerateArray()) + { + rows.Add(new PlacesReplyData { + OwnerID = TryUuid(parcel, "owner_id", out UUID owner) + ? owner : UUID.Zero, + Name = String(parcel, "name"), + Desc = String(parcel, "description"), + ActualArea = Int32(parcel, "area"), + BillableArea = Int32(parcel, "area"), + GlobalX = UInt32(parcel, "global_x"), + GlobalY = UInt32(parcel, "global_y"), + GlobalZ = UInt32(parcel, "global_z"), + SimName = String(parcel, "region_name"), + SnapshotID = TryUuid(parcel, "snapshot_id", out UUID snapshot) + ? snapshot : UUID.Zero, + Price = Int32(parcel, "price"), + Dwell = 0 + }); + } + client.SendPlacesReply(queryID, transactionID, rows.ToArray()); + return; + } + catch (Exception e) + { + m_Log.WarnFormat( + "[NEX-DISCOVERY]: Grid-wide group land lookup failed for {0}; falling back to this simulator only: {1}", + queryID, e.Message); + } + } + foreach (Scene scene in scenes) { if (scene?.LandChannel == null) @@ -505,6 +555,28 @@ namespace NexVerse.RegionModules.Discovery } } + private JsonDocument GetGroupLandJson(UUID groupId) + { + using HttpRequestMessage request = new HttpRequestMessage( + HttpMethod.Get, + m_WorldApiBaseUrl + "/api/v1/groups/" + + Uri.EscapeDataString(groupId.ToString()) + "/land"); + request.Headers.TryAddWithoutValidation( + "X-NexVerse-Api-Key", m_GroupLandApiKey); + using HttpResponseMessage response = m_Http.Send(request); + response.EnsureSuccessStatusCode(); + return JsonDocument.Parse( + response.Content.ReadAsStringAsync() + .GetAwaiter().GetResult()); + } + + private static uint UInt32(JsonElement element, string name) + { + return element.TryGetProperty(name, out JsonElement value) && + value.ValueKind == JsonValueKind.Number && + value.TryGetUInt32(out uint result) ? result : 0; + } + private JsonDocument GetJson(string path) { using HttpRequestMessage request = diff --git a/NexVerse/RegionModules/Economy/NexVerseMoneyModule.cs b/NexVerse/RegionModules/Economy/NexVerseMoneyModule.cs index d8ca58c9..aed395b3 100644 --- a/NexVerse/RegionModules/Economy/NexVerseMoneyModule.cs +++ b/NexVerse/RegionModules/Economy/NexVerseMoneyModule.cs @@ -1290,10 +1290,23 @@ namespace NexVerse.RegionModules.Economy // details; unauthorized viewers get a harmless empty response. if (!CanReadGroupAccount(client, agentId, groupId)) m_Log.DebugFormat("[NEX-ECONOMY-VIEWER]: Denied group accounting details for {0}", groupId); - // There is currently no mapped billing-period breakdown in the - // legacy viewer protocol. Never fabricate transactions or tax. + if (!CanReadGroupAccount(client, agentId, groupId)) + { + client.SendGroupAccountingDetails(client, groupId, transactionId, + sessionId, 0); + return; + } + if (!TryGetGroupHistory(groupId, false, + out IReadOnlyList entries)) + { + client.SendAgentAlertMessage( + "Gruppen-NV$-Historie ist derzeit nicht erreichbar.", false); + client.SendGroupAccountingDetails(client, groupId, transactionId, + sessionId, 0); + return; + } client.SendGroupAccountingDetails(client, groupId, transactionId, - sessionId, 0); + sessionId, 0, entries); } private void HandleGroupAccountTransactionsRequest( @@ -1304,9 +1317,110 @@ namespace NexVerse.RegionModules.Economy client.AgentId != agentId) return; if (!CanReadGroupAccount(client, agentId, groupId)) + { m_Log.DebugFormat("[NEX-ECONOMY-VIEWER]: Denied group sales detail for {0}", groupId); + client.SendGroupTransactionsSummaryDetails(client, groupId, + transactionId, sessionId, 0); + return; + } + if (!TryGetGroupHistory(groupId, true, + out IReadOnlyList sales)) + { + client.SendAgentAlertMessage( + "Gruppen-NV$-Verkaeufe sind derzeit nicht erreichbar.", false); + client.SendGroupTransactionsSummaryDetails(client, groupId, + transactionId, sessionId, 0); + return; + } client.SendGroupTransactionsSummaryDetails(client, groupId, - transactionId, sessionId, 0); + transactionId, sessionId, 0, sales); + } + + // The simulator authenticates as a narrowly scoped backend and + // verifies the connected avatar's Accountable power first. The + // World API independently checks both groups:read and economy:read. + private bool TryGetGroupHistory(UUID groupId, bool salesOnly, + out IReadOnlyList entries) + { + entries = Array.Empty(); + try + { + using HttpRequestMessage request = CreateRequest( + HttpMethod.Get, "/api/v1/groups/" + + Uri.EscapeDataString(groupId.ToString()) + "/transactions"); + using HttpResponseMessage response = m_Http.Send(request); + if (!response.IsSuccessStatusCode) + { + m_Log.WarnFormat( + "[NEX-ECONOMY-VIEWER]: Group history HTTP {0} for {1}", + (int)response.StatusCode, groupId); + return false; + } + using JsonDocument data = JsonDocument.Parse( + response.Content.ReadAsStringAsync().GetAwaiter().GetResult()); + if (!data.RootElement.TryGetProperty( + "transactions", out JsonElement items) || + items.ValueKind != JsonValueKind.Array) + return false; + + List rows = + new List(); + foreach (JsonElement item in items.EnumerateArray()) + { + if (!item.TryGetProperty("amount", out JsonElement rawAmount) || + !rawAmount.TryGetInt64(out long signed) || + signed < int.MinValue || signed > int.MaxValue) + return false; + + string kind = item.TryGetProperty("kind", out JsonElement k) && + k.ValueKind == JsonValueKind.String ? + k.GetString() ?? string.Empty : string.Empty; + // The legacy Sales tab must never label ordinary + // transfers or refunds as a sale. + bool isSale = signed > 0 && + (kind.Contains("sale", StringComparison.OrdinalIgnoreCase) || + kind.Contains("commerce", StringComparison.OrdinalIgnoreCase) || + kind.Contains("purchase", StringComparison.OrdinalIgnoreCase)); + if (salesOnly && !isSale) + continue; + + string note = item.TryGetProperty("description", out JsonElement d) && + d.ValueKind == JsonValueKind.String ? + d.GetString() ?? string.Empty : string.Empty; + string reference = item.TryGetProperty("reference", out JsonElement r) && + r.ValueKind == JsonValueKind.String ? + r.GetString() ?? string.Empty : string.Empty; + string timestamp = item.TryGetProperty("occurred_at", out JsonElement t) && + t.ValueKind == JsonValueKind.String ? + t.GetString() ?? string.Empty : string.Empty; + if (DateTimeOffset.TryParse(timestamp, + out DateTimeOffset occurred)) + timestamp = occurred.UtcDateTime.ToString("yyyy-MM-dd HH:mm"); + + rows.Add(new GroupAccountHistoryEntry + { + Description = (string.IsNullOrWhiteSpace(note) ? kind : note), + Time = timestamp, + // The ledger has no authenticated buyer display + // name; never guess a resident or counterparty. + User = "NV$ Ledger", + Item = string.IsNullOrWhiteSpace(reference) ? kind : reference, + Amount = (int)signed, + Type = 0 + }); + if (rows.Count >= 200) + break; + } + entries = rows; + return true; + } + catch (Exception e) + { + m_Log.WarnFormat( + "[NEX-ECONOMY-VIEWER]: Group history lookup failed for {0}: {1}", + groupId, e.Message); + return false; + } } // Ledger API always uses the account UUID; it never trusts a viewer diff --git a/NexVerse/Server/Api/NexGroupLandDirectory.cs b/NexVerse/Server/Api/NexGroupLandDirectory.cs new file mode 100644 index 00000000..b5a99291 --- /dev/null +++ b/NexVerse/Server/Api/NexGroupLandDirectory.cs @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: MPL-2.0 +// Grid-wide group-owned land is authoritative in the shared region SQL store. +// This is deliberately read-only; no tables or migrations are created. +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Globalization; +using NexVerse.Core.Economy; +using OpenMetaverse; +using OpenSim.Services.Interfaces; +using GridRegion = OpenSim.Services.Interfaces.GridRegion; + +namespace NexVerse.Server.Api +{ + internal sealed class NexGroupLandDirectory + { + private readonly NexLedgerSqlRuntime m_Storage; + private readonly IGridService m_Grid; + + public NexGroupLandDirectory( + string storageProvider, + string connectionString, + IGridService grid) + { + m_Storage = NexLedgerSqlRuntime.Resolve( + storageProvider, connectionString); + m_Grid = grid ?? + throw new ArgumentNullException(nameof(grid)); + } + + public IReadOnlyList List(UUID groupId, int limit = 500) + { + if (groupId.IsZero()) + throw new ArgumentException("A valid group UUID is required.", nameof(groupId)); + if (limit < 1 || limit > 500) + throw new ArgumentOutOfRangeException(nameof(limit)); + + using DbConnection connection = m_Storage.CreateConnection(); + connection.Open(); + + using DbCommand command = connection.CreateCommand(); + command.CommandText = + "SELECT UUID, RegionUUID, OwnerUUID, Name, Description, " + + "Area, SalePrice, SnapshotUUID, UserLocationX, " + + "UserLocationY, UserLocationZ " + + "FROM land WHERE IsGroupOwned = 1 AND GroupUUID = @group " + + "ORDER BY RegionUUID, UUID LIMIT @max"; + DbParameter groupParam = command.CreateParameter(); + groupParam.ParameterName = "@group"; + groupParam.Value = groupId.ToString(); + command.Parameters.Add(groupParam); + DbParameter maxParam = command.CreateParameter(); + maxParam.ParameterName = "@max"; + maxParam.Value = limit; + command.Parameters.Add(maxParam); + + List parcels = new List(); + using DbDataReader reader = command.ExecuteReader(); + while (reader.Read()) + { + if (!UUID.TryParse(ReadString(reader, "RegionUUID"), out UUID regionId) || + regionId.IsZero() || + !UUID.TryParse(ReadString(reader, "UUID"), out UUID parcelId) || + parcelId.IsZero()) + continue; + + // Only include regions still registered in this grid. + GridRegion region = m_Grid.GetRegionByUUID(UUID.Zero, regionId); + if (region == null) + continue; + + UUID.TryParse(ReadString(reader, "OwnerUUID"), out UUID owner); + UUID.TryParse(ReadString(reader, "SnapshotUUID"), out UUID snapshot); + float x = ReadFloat(reader, "UserLocationX"); + float y = ReadFloat(reader, "UserLocationY"); + float z = ReadFloat(reader, "UserLocationZ"); + x = float.IsFinite(x) ? Math.Clamp(x, 0, Math.Max(0, region.RegionSizeX)) : 0; + y = float.IsFinite(y) ? Math.Clamp(y, 0, Math.Max(0, region.RegionSizeY)) : 0; + z = float.IsFinite(z) ? Math.Max(0, z) : 0; + + parcels.Add(new NexGroupLandEntry + { + ParcelId = parcelId, + RegionId = regionId, + OwnerId = owner, + SnapshotId = snapshot, + Name = ReadString(reader, "Name"), + Description = ReadString(reader, "Description"), + RegionName = region.RegionName, + Area = Math.Max(0, ReadInt(reader, "Area")), + SalePrice = Math.Max(0, ReadInt(reader, "SalePrice")), + GlobalX = checked((uint)Math.Max(0, region.RegionLocX) + (uint)x), + GlobalY = checked((uint)Math.Max(0, region.RegionLocY) + (uint)y), + GlobalZ = (uint)Math.Min(uint.MaxValue, z) + }); + } + return parcels; + } + + private static string ReadString(DbDataReader reader, string name) + { + object value = reader[name]; + return value == DBNull.Value || value == null ? + string.Empty : Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; + } + + private static float ReadFloat(DbDataReader reader, string name) + { + object value = reader[name]; + return value == DBNull.Value || value == null ? 0 : + Convert.ToSingle(value, CultureInfo.InvariantCulture); + } + + private static int ReadInt(DbDataReader reader, string name) + { + object value = reader[name]; + return value == DBNull.Value || value == null ? 0 : + Convert.ToInt32(value, CultureInfo.InvariantCulture); + } + } + + internal sealed class NexGroupLandEntry + { + public UUID ParcelId { get; set; } + public UUID RegionId { get; set; } + public UUID OwnerId { get; set; } + public UUID SnapshotId { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string RegionName { get; set; } = string.Empty; + public int Area { get; set; } + public int SalePrice { get; set; } + public uint GlobalX { get; set; } + public uint GlobalY { get; set; } + public uint GlobalZ { get; set; } + } +} diff --git a/NexVerse/Server/Api/NexGroupsApi.cs b/NexVerse/Server/Api/NexGroupsApi.cs index 155f5918..c8d91971 100644 --- a/NexVerse/Server/Api/NexGroupsApi.cs +++ b/NexVerse/Server/Api/NexGroupsApi.cs @@ -26,6 +26,7 @@ namespace NexVerse.Server.Api private readonly INexAuditSink m_Audit; private readonly GroupsService m_Groups; private readonly Func m_Economy; + private NexGroupLandDirectory m_LandDirectory; public NexGroupsApi( NexApiAuthenticator authenticator, @@ -39,6 +40,11 @@ namespace NexVerse.Server.Api m_Economy = economy ?? throw new ArgumentNullException(nameof(economy)); } + public void ConfigureLandDirectory(NexGroupLandDirectory directory) + { + m_LandDirectory = directory; + } + public void Handle( IOSHttpRequest request, IOSHttpResponse response) @@ -897,6 +903,142 @@ namespace NexVerse.Server.Api return; } + if (parts[1].Equals("transactions", StringComparison.OrdinalIgnoreCase) && + parts.Length == 2) + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.GroupsRead, + out authPrincipal, out authAccount)) + return; + + try + { + ExtendedGroupRecord group = RequireGroup(authPrincipal, request, groupId); + // Only the simulator backend can act on a prior viewer + // Accountable check. Require BOTH explicit machine scopes. + // Never permit resident bearer identity impersonation. + bool trustedViewer = authAccount == null && + authPrincipal.Subject.StartsWith( + "api-key:", StringComparison.OrdinalIgnoreCase) && + authPrincipal.HasScope(NexScopes.EconomyRead); + if (!trustedViewer && + !CanReadGroupAccounting(authPrincipal, authAccount, groupId)) + throw new UnauthorizedAccessException( + "Group transaction history requires membership and Accountable power."); + + NexEconomyService economy = m_Economy() ?? + throw new InvalidOperationException("NV$ economy is unavailable."); + + // Transaction history is read-only. Do NOT silently create + // wallet accounts or reveal other users' ledger postings. + if (economy.GetAccount(groupId.Guid) == null) + { + WriteJson(response, new + { + group_id = groupId.ToString(), + currency = NexLedgerCurrency.Code, + period_days = 7, + transactions = Array.Empty(), + correlation_id = Correlation(response) + }); + return; + } + + DateTimeOffset from = DateTimeOffset.UtcNow.AddDays(-7); + var history = economy.ListTransactions( + groupId.Guid, from, DateTimeOffset.UtcNow, 0, 200); + WriteJson(response, new + { + group_id = groupId.ToString(), + currency = NexLedgerCurrency.Code, + period_days = 7, + transactions = history.Select(t => new + { + transaction_id = t.TransactionId.ToString("D"), + occurred_at = t.OccurredAt, + kind = t.Kind, + reference = t.Reference, + amount = t.Postings + .Where(p => p.AccountId == groupId.Guid) + .Sum(p => p.Side == NexLedgerSide.Credit + ? p.AmountMinor : -p.AmountMinor), + description = t.Postings + .Where(p => p.AccountId == groupId.Guid) + .Select(p => p.Memo) + .FirstOrDefault() ?? string.Empty + }).ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts[1].Equals("land", StringComparison.OrdinalIgnoreCase) && + parts.Length == 2) + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.GroupsRead, + out authPrincipal, out authAccount)) + return; + + try + { + RequireGroup(authPrincipal, request, groupId); + // Real residents must have an actual group membership. + // Explicit groups:read machine credentials represent the + // trusted simulator's already-authorized viewer request. + bool machine = authAccount == null && + authPrincipal.Subject.StartsWith( + "api-key:", StringComparison.OrdinalIgnoreCase); + if (!authPrincipal.HasScope(NexScopes.AdminAll) && + !machine && + (authAccount == null || + m_Groups.GetAgentGroupMembership( + authAccount.PrincipalID.ToString(), + authAccount.PrincipalID.ToString(), groupId) == null)) + throw new UnauthorizedAccessException( + "Group-owned land requires group membership."); + + if (m_LandDirectory == null) + throw new InvalidOperationException( + "The grid-wide group land directory is not configured."); + + var parcels = m_LandDirectory.List(groupId); + WriteJson(response, new + { + group_id = groupId.ToString(), + total = parcels.Count, + parcels = parcels.Select(p => new + { + parcel_id = p.ParcelId.ToString(), + region_id = p.RegionId.ToString(), + owner_id = p.OwnerId.ToString(), + snapshot_id = p.SnapshotId.ToString(), + name = p.Name, + description = p.Description, + region_name = p.RegionName, + area = p.Area, + price = p.SalePrice, + global_x = p.GlobalX, + global_y = p.GlobalY, + global_z = p.GlobalZ + }).ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + if (parts[1].Equals("capabilities", StringComparison.OrdinalIgnoreCase) && parts.Length == 2) { diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index d8464535..eedb404a 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -756,6 +756,21 @@ namespace NexVerse.Server.Api ? NexEconomyConnector.Current.Economy : null); + // Group-owned land may be hosted on another simulator. + // Query the shared RegionStore database read-only and + // resolve region coordinates through the grid service. + if (nexGroupsConfig.GetBoolean("EnableGridWideLand", true) && + grid != null && + !string.IsNullOrWhiteSpace(databaseStorageProvider) && + !string.IsNullOrWhiteSpace(databaseConnectionString)) + { + nexGroupsApi.ConfigureLandDirectory( + new NexGroupLandDirectory( + databaseStorageProvider, + databaseConnectionString, + grid)); + } + server.AddSimpleStreamHandler( new SimpleStreamHandler( "/api/v1/groups", diff --git a/OpenSim/Framework/GroupData.cs b/OpenSim/Framework/GroupData.cs index 815946ca..ba622e61 100644 --- a/OpenSim/Framework/GroupData.cs +++ b/OpenSim/Framework/GroupData.cs @@ -30,6 +30,18 @@ using OpenMetaverse; namespace OpenSim.Framework { + // Signed NV$ group posting projected into the Firestorm 7-day UDP + // accounting/sales panes. Never include counterparty ledger postings. + public sealed class GroupAccountHistoryEntry + { + public string Description = string.Empty; + public string Time = string.Empty; + public string User = string.Empty; + public string Item = string.Empty; + public int Amount; + public int Type; + } + public class GroupRecord { public UUID GroupID; diff --git a/OpenSim/Framework/IClientAPI.cs b/OpenSim/Framework/IClientAPI.cs index 6be2d950..4544a610 100644 --- a/OpenSim/Framework/IClientAPI.cs +++ b/OpenSim/Framework/IClientAPI.cs @@ -1464,10 +1464,24 @@ namespace OpenSim.Framework void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages); void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt); + // Default compatibility keeps older test clients and legacy viewers + // operational; Linden UDP implements real history data blocks. + void SendGroupAccountingDetails(IClientAPI sender, UUID groupID, + UUID transactionID, UUID sessionID, int amt, + IReadOnlyList history) + { + SendGroupAccountingDetails(sender, groupID, transactionID, sessionID, amt); + } void SendGroupAccountingSummary(IClientAPI sender, UUID groupID, UUID requestID, uint moneyAmt, int totalTier, int usedTier); void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt); + void SendGroupTransactionsSummaryDetails(IClientAPI sender, UUID groupID, + UUID transactionID, UUID sessionID, int amt, + IReadOnlyList history) + { + SendGroupTransactionsSummaryDetails(sender, groupID, transactionID, sessionID, amt); + } void SendChangeUserRights(UUID agentID, UUID friendID, int rights); void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId); diff --git a/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs b/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs index 102343a6..101c50a4 100644 --- a/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs +++ b/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs @@ -1467,6 +1467,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) + { + SendGroupAccountingDetails(sender, groupID, transactionID, + sessionID, amt, null); + } + + public void SendGroupAccountingDetails(IClientAPI sender, UUID groupID, + UUID transactionID, UUID sessionID, int amt, + IReadOnlyList history) { GroupAccountDetailsReplyPacket GADRP = new(); @@ -1481,6 +1489,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP // No legacy billing-period breakdown yet. Return zero real // entries, never fabricate a transaction for the viewer. GADRP.HistoryData = Array.Empty(); + if (history != null && history.Count > 0) + { + int count = Math.Min(200, history.Count); + var blocks = new GroupAccountDetailsReplyPacket.HistoryDataBlock[count]; + for (int i = 0; i < count; i++) + { + GroupAccountHistoryEntry entry = history[i]; + blocks[i] = new GroupAccountDetailsReplyPacket.HistoryDataBlock + { + Description = Utils.StringToBytes(entry.Description ?? string.Empty), + Amount = entry.Amount + }; + } + GADRP.HistoryData = blocks; + } OutPacket(GADRP, ThrottleOutPacketType.Task); } @@ -1519,7 +1542,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { - // bad ! + SendGroupTransactionsSummaryDetails(sender, groupID, transactionID, + sessionID, amt, null); + } + + public void SendGroupTransactionsSummaryDetails(IClientAPI sender, + UUID groupID, UUID transactionID, UUID sessionID, int amt, + IReadOnlyList history) + { GroupAccountTransactionsReplyPacket GATRP = (GroupAccountTransactionsReplyPacket)PacketPool.Instance.GetPacket( PacketType.GroupAccountTransactionsReply); @@ -1535,6 +1565,24 @@ namespace OpenSim.Region.ClientStack.LindenUDP // The group sales protocol is independent of ledger postings; // until a proper breakdown exists, do not invent transaction data. GATRP.HistoryData = Array.Empty(); + if (history != null && history.Count > 0) + { + int count = Math.Min(200, history.Count); + var blocks = new GroupAccountTransactionsReplyPacket.HistoryDataBlock[count]; + for (int i = 0; i < count; i++) + { + GroupAccountHistoryEntry entry = history[i]; + blocks[i] = new GroupAccountTransactionsReplyPacket.HistoryDataBlock + { + Time = Utils.StringToBytes(entry.Time ?? string.Empty), + User = Utils.StringToBytes(entry.User ?? string.Empty), + Type = entry.Type, + Item = Utils.StringToBytes(entry.Item ?? string.Empty), + Amount = entry.Amount + }; + } + GATRP.HistoryData = blocks; + } OutPacket(GATRP, ThrottleOutPacketType.Task); } diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index f3abc98e..f62f0d6d 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -151,6 +151,9 @@ Enabled = true LegacyFirestormCompatibility = true WorldApiBaseUrl = "${Const|BaseURL}:${Const|PublicPort}" + ; Dedicated backend-only groups:read machine key, created in the World API. + ; Without it, the Firestorm group land tab sees local simulator regions only. + GroupLandApiKey = "${Environment|NEXVERSE_GROUP_LAND_API_KEY}" RequestTimeoutMilliseconds = 3000 [NexExperiencesViewer] diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 2ee4016b..4ac18b11 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -283,6 +283,8 @@ [NexGroups] ; OpenGenesisLINK NexGroups management/parity facade. Enabled = true + ; Read shared RegionStore land + GridService to locate remote group parcels. + EnableGridWideLand = true [NexExperiences] ; Persistent store: only one local Robust writer is supported. diff --git a/bin/config-include/GridCommon.ini b/bin/config-include/GridCommon.ini index ebf4e37d..db957448 100644 --- a/bin/config-include/GridCommon.ini +++ b/bin/config-include/GridCommon.ini @@ -7,6 +7,7 @@ ; disabled. The actual secret value remains outside version control. NEXVERSE_DB_PASSWORD = "" NEXVERSE_ECONOMY_API_KEY = "" + NEXVERSE_GROUP_LAND_API_KEY = "" NEXVERSE_EXPERIENCES_API_KEY = "" NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY = "" NEXVERSE_EXPERIENCES_VIEWER_MANAGE_API_KEY = "" diff --git a/doc/NexVerse/FIRESTORM_GROUP_LAND_NVDOLLAR.md b/doc/NexVerse/FIRESTORM_GROUP_LAND_NVDOLLAR.md index e97fea1f..8b9b6806 100644 --- a/doc/NexVerse/FIRESTORM_GROUP_LAND_NVDOLLAR.md +++ b/doc/NexVerse/FIRESTORM_GROUP_LAND_NVDOLLAR.md @@ -25,11 +25,11 @@ Live-Datenbankzustand. - Der Viewer schickt `PlacesQuery` mit `DFQ_GROUP_OWNED=0x100`, Gruppen-UUID im `QueryID` und eigener `TransactionID`. Der bisherige NexDiscoveryViewerModule bediente nur `DirPlacesQuery`, - nicht `PlacesQuery`. Jetzt liefert er eine erste - Gruppenland-Antwort für Parzellen auf **den in diesem - Simulatorprozess laufenden Regionen**. Die Daten werden aus den - echten `LandChannel.AllParcels()` geladen und die Gruppenmitgliedschaft - autoritativ geprüft. + nicht `PlacesQuery`. Mit konfiguriertem `GroupLandApiKey` wird + jetzt die gridweite Gruppenlandliste aus dem zentralen SQL-RegionStore + abgefragt. Ohne diesen Schlüssel bleibt die Abfrage auf lokale + Simulatorregionen beschränkt. Die Gruppenmitgliedschaft wird + vor der Anfrage geprüft. - Für Gruppen-NV$ existierten bereits `GroupAccountSummaryRequest`, `DetailsRequest`, `TransactionsRequest` im UDP-Layer. Das NexVerseMoneyModule antwortete nicht. Jetzt werden die Events @@ -40,11 +40,10 @@ Live-Datenbankzustand. dem Viewer übernehmen; zuvor nutzte der LLClientView-Sendeweg irrtümlich die Avatar-UUID. Deshalb konnte Firestorm eine Abrechnungsantwort nicht der geöffneten Registerkarte zuordnen. -- Leere Gruppenabrechnungsdetails/Verkäufe werden ohne erfundene - Ledger-Transaktionen als leere Ergebnisliste zurückgegeben. - Eine vollständige 7-Tage-Umsatzhistorie wird in dieser Iteration - **noch nicht** aus dem Ledger auf die Firestorm-Detailansicht - abgebildet. +- Seit PR #274 werden autorisierte NV$-Ledgerbuchungen der letzten + sieben Tage über `/api/v1/groups/{id}/transactions` gelesen und + auf Firestorm-Gruppenabrechnungs-/Verkaufspakete abgebildet. + Gegenkonten und erfundene Verkäufe werden nicht offengelegt. ## Nach Deployment prüfen @@ -57,12 +56,15 @@ Live-Datenbankzustand. Wenn nicht, Berechtigungsanzeige und zentrale `os_groups_membership`-Zeile sowie Viewer-Gruppen-Updates prüfen. Kein Rechtebypass per SQL einführen. -3. „Land und NV$“ erneut öffnen: bei Mitgliedschaft sollte der - Gruppenland-Reiter nicht mehr auf eine fehlende Paketantwort - warten. Für Land auf **anderen Simulatorprozessen** wird noch - eine zentrale oder delegierte Gruppenlandabfrage benötigt. +3. „Land und NV$“ erneut öffnen: bei Mitgliedschaft sollte die + zentrale Gruppenland-Abfrage Parzellen aus anderen Simulatorprozessen + ebenfalls anzeigen. Voraussetzung: gemeinsamer SQL-RegionStore, + `[NexGroups] EnableGridWideLand = true` und gültiger + `[NexDiscoveryViewer] GroupLandApiKey` mit `groups:read`. + Ohne Backend-Schlüssel gilt weiterhin die lokale Fallback-Liste. 4. Für Gruppen-NV$ benötigt der Simulator-API-Key - `economy:read`. Zum erstmaligen Anlegen fehlender + `economy:read` und für den Firestorm-Gruppenverlauf zusätzlich + `groups:read`. Zum erstmaligen Anlegen fehlender Gruppen-Wallets (ohne Startguthaben) zusätzlich `economy:transfer`. Das Geld-/Gruppenkonto darf nicht anhand eines ungeprüften Avatar-/Gruppennamens identifiziert diff --git a/doc/NexVerse/NEXGROUPS_GRID_LAND_HISTORY.md b/doc/NexVerse/NEXGROUPS_GRID_LAND_HISTORY.md new file mode 100644 index 00000000..89dcad23 --- /dev/null +++ b/doc/NexVerse/NEXGROUPS_GRID_LAND_HISTORY.md @@ -0,0 +1,84 @@ +# NexGroups – gridweite Landliste und NV$-Gruppenhistorie + +## Neue World-API-Endpunkte + +Beide Endpunkte benötigen eine gültige Authentifizierung und +`groups:read`. Der Dienst prüft für Bewohner die echte Gruppenmitgliedschaft. +Die Finanzhistorie verlangt zusätzlich `GroupPowers.Accountable`. + +``` +GET /api/v1/groups/{group_id}/land +GET /api/v1/groups/{group_id}/transactions +``` + +Die Landabfrage liest ausschließlich `IsGroupOwned=1` und +`GroupUUID={group_id}` aus dem gemeinsamen OpenSim-`land`-RegionStore. +Mit dem GridService werden die tatsächlichen Regionen, globalen +Koordinaten und Namen aufgelöst. Regionen, die nicht mehr im Grid +registriert sind, werden nicht angezeigt. Es sind keine neuen SQL-Tabellen +oder Produktionsmigrationen notwendig. + +Die Transaktionsliste liest die letzten sieben Tage aus dem echten +NV$-Ledger (maximal 200 Einträge). Pro Transaktion wird ausschließlich +die signierte Gruppenbuchung (positiv = Gutschrift, negativ = Belastung) +zurückgegeben; fremde Gegenkonto-Buchungen werden nicht preisgegeben. +Eine noch nicht angelegte Gruppenwallet liefert eine leere Historie, +ohne sie nur durch die Leseabfrage zu erzeugen. + +## Firestorm und Simulator konfigurieren + +ROBUST: `[NexGroups] Enabled = true`, `EnableGridWideLand = true`. +Die World API braucht Zugriff auf den gemeinsamen +`[DatabaseService]`-`RegionStore` und den `IGridService`. + +In der World API einen **dedizierten**, serverseitigen API-Key mit dem +expliziten Scope `groups:read` für die Simulator-Landverzeichnisse +erstellen. Nicht das Admin-Token und keinen Avatar-Token verwenden. +Dieser Schlüssel muss nur für den Simulator erreichbar sein. + +Im Simulator: + +```ini +[NexDiscoveryViewer] +Enabled = true +LegacyFirestormCompatibility = true +WorldApiBaseUrl = "https://world.stadt-nexverse.de" +GroupLandApiKey = "${Environment|NEXVERSE_GROUP_LAND_API_KEY}" +``` + +Das `NEXVERSE_GROUP_LAND_API_KEY`-Environment-Secret darf niemals in +CAPS-URLs, Avatar-Inventar, Viewer-Code oder Logs auftauchen. +Der Simulator prüft die Gruppenmitgliedschaft, bevor er diesen +serverseitigen Schlüssel zur World API sendet. + +Fehlt der Schlüssel oder ist das zentrale Verzeichnis nicht erreichbar, +bleibt die bisherige **lokale**, unvollständige Landliste verfügbar +und die Warnung erscheint im Simulatorlog. Für vollständige Gridabdeckung +muss eine gemeinsam genutzte RegionStore-Datenbank vorhanden sein. +Parzellen auf separaten, unabhängigen SQL-Instanzen sind nicht enthalten. + +## Firestorm-Gruppenabrechnung + +Die API liefert echte Finanzbuchungen der letzten sieben Tage unter +`/api/v1/groups/{id}/transactions`. Der Simulator prüft vor dem Abruf +die tatsächliche `GroupPowers.Accountable`-Berechtigung des verbundenen +Avatars und überträgt die Buchungszeilen anschließend in die nativen +`GroupAccountDetailsReply`- und `GroupAccountTransactionsReply`-Pakete. + +**Konfiguration:** Der Simulator-Key unter `[NexEconomyViewer] ApiKey` +muss für diese neue Funktion zusätzlich zu `economy:read` auch +`groups:read` enthalten. Die World API akzeptiert für den +Gruppenverlauf nur einen ausdrücklich doppelt berechtigten Maschinen-Key +oder einen tatsächlich berechtigten Bewohner-Token. Ohne die zusätzliche +Berechtigung bleibt der Kontostand funktionsfähig, der Verlauf kann jedoch +nicht geladen werden. + +Die Buchungsdaten sind Ledger-Daten. Gegenkonten und nicht verifizierte +Käufernamen werden nicht angezeigt. Der Firestorm-Verkaufsreiter filtert +echte positive `sale`-/`commerce`-/`purchase`-Buchungen, während die +Detailansicht sämtliche Gruppenbuchungen innerhalb der Periode enthält. +Negative, zu große oder nicht lesbare Buchungen werden nicht stillschweigend +als gültige Werte dargestellt. + +Das neue HTTP-Regressionstestpaket kontrolliert die Rechte- und +Landabfrage samt SQL-Daten einer Region auf einem anderen Simulator. diff --git a/tools/ci/NexGroupsHttpRegression/Program.cs b/tools/ci/NexGroupsHttpRegression/Program.cs index 591a80bf..2e5002b1 100644 --- a/tools/ci/NexGroupsHttpRegression/Program.cs +++ b/tools/ci/NexGroupsHttpRegression/Program.cs @@ -21,10 +21,14 @@ using OpenSim.Framework.Console; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Groups; using OpenSim.Services.Interfaces; +using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Services.UserAccountService; internal static class Program { + private static IGridService m_TestGrid; + private static string m_TestConnection; + private static void Check(bool ok, string what) { if (!ok) throw new InvalidOperationException("Groups HTTP integration: " + what); @@ -66,14 +70,28 @@ internal static class Program private static SimpleStreamMethod Route(GroupsService groups, UserAccountService users, HmacNexAccessTokenService tokens, - Func economy) + Func economy, INexApiKeyStore keys) { 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); + tokens, null, keys, 200); var api = Construct(groupsType, auth, null, groups, economy); + // A second simulator's group parcels are projected by the central + // directory. Configure it through the same optional production hook. + // Tests use an isolated SQL table and a fake grid registry. + if (m_TestGrid != null) + { + Type directoryType = assembly.GetType( + "NexVerse.Server.Api.NexGroupLandDirectory", true); + object directory = Construct(directoryType, + "OpenSim.Data.MySQL.dll", m_TestConnection, m_TestGrid); + groupsType.GetMethod("ConfigureLandDirectory", + BindingFlags.Public | BindingFlags.Instance)! + .Invoke(api, new[] { directory }); + } + MethodInfo handle = groupsType.GetMethod("Handle", BindingFlags.Instance | BindingFlags.Public); Check(handle != null, "NexGroupsApi.Handle missing"); @@ -155,10 +173,29 @@ internal static class Program var runtime = NexLedgerSqlRuntime.Resolve("OpenSim.Data.MySQL.dll", connection); NexLedgerSqlStore store = runtime.CreateStore(); - var economy = new NexEconomyService(new NexDoubleEntryLedger(store), store); + var ledger = new NexDoubleEntryLedger(store); + var economy = new NexEconomyService(ledger, store); NexEconomyService activeEconomy = economy; - var handler = Route(groups, users, tokens, () => activeEconomy); + // One remote group parcel in the same authoritative RegionStore. + // Its region is not hosted by this HTTP process. + UUID remoteRegion = UUID.Random(); + UUID parcel = UUID.Random(); + m_TestGrid = DispatchProxy.Create(); + ((GroupGridProxy)m_TestGrid).Region = new GridRegion + { + RegionID = remoteRegion, RegionName = "Remote CI Region", + RegionLocX = 256000, RegionLocY = 258560, + RegionSizeX = 256, RegionSizeY = 256 + }; + m_TestConnection = connection; + var keyStore = new PersistentNexApiKeyStore( + Path.Combine(scratch, "keys.json")); + var machineKey = keyStore.Create("Groups Viewer Service", + new[] { NexScopes.GroupsRead, NexScopes.EconomyRead }); + var groupsOnlyKey = keyStore.Create("Group Land Service", + new[] { NexScopes.GroupsRead }); + var handler = Route(groups, users, tokens, () => activeEconomy, keyStore); int port = FindPort(); server = new BaseHttpServer((uint)port) { ListenIPAddress = IPAddress.Loopback }; server.AddSimpleStreamHandler( @@ -178,6 +215,43 @@ internal static class Program false, UUID.Zero, 0, false, false, false, owner.PrincipalID, out reason); Check(!otherGroup.IsZero(), "second group creation failed: " + reason); + using (var landDb = NexLedgerSqlRuntime.Resolve( + "OpenSim.Data.MySQL.dll", connection).CreateConnection()) + { + landDb.Open(); + using var schema = landDb.CreateCommand(); + schema.CommandText = + "CREATE TABLE IF NOT EXISTS land (" + + "UUID varchar(255) PRIMARY KEY, RegionUUID varchar(255), " + + "OwnerUUID varchar(255), GroupUUID varchar(255), " + + "Name varchar(255), Description varchar(255), " + + "IsGroupOwned int, Area int, SalePrice int, " + + "SnapshotUUID varchar(255), UserLocationX float, " + + "UserLocationY float, UserLocationZ float)"; + schema.ExecuteNonQuery(); + using var insert = landDb.CreateCommand(); + insert.CommandText = + "INSERT INTO land (UUID, RegionUUID, OwnerUUID, GroupUUID, " + + "Name, Description, IsGroupOwned, Area, SalePrice, " + + "SnapshotUUID, UserLocationX, UserLocationY, UserLocationZ) " + + "VALUES (@parcel, @region, @owner, @group, " + + "'Remote parcel', 'Other simulator', 1, 512, 0, " + + "@snapshot, 12, 24, 30)"; + foreach ((string paramName, string value) in new[] { + ("@parcel", parcel.ToString()), + ("@region", remoteRegion.ToString()), + ("@owner", owner.PrincipalID.ToString()), + ("@group", group.ToString()), + ("@snapshot", UUID.Random().ToString()) }) + { + var param = insert.CreateParameter(); + param.ParameterName = paramName; + param.Value = value; + insert.Parameters.Add(param); + } + Check(insert.ExecuteNonQuery() == 1, + "failed seeding remote land fixture"); + } string accounting = "/api/v1/groups/" + group + "/accounting"; Check(groups.AddAgentToGroup(owner.PrincipalID.ToString(), @@ -200,6 +274,77 @@ internal static class Program await Verify(http, accounting + "?requester_id=" + owner.PrincipalID, strangerToken, HttpStatusCode.Forbidden, "error"); await Verify(http, accounting, ownerToken, HttpStatusCode.OK, "nvban"); + // Ensure the API returns real signed ledger postings, not a + // fabricated empty/history placeholder. + var system = new NexLedgerAccount( + Guid.NewGuid(), NexLedgerAccountClass.System, + NexLedgerSide.Debit, "system:groups-ci:" + + Guid.NewGuid().ToString("N"), "NexGroups CI System"); + Check(ledger.TryCreateAccount(system), "test system wallet create failed"); + economy.AdministrativeAdjustment(group.Guid, system.AccountId, + 73, owner.PrincipalID.ToString(), "Group history SQL proof"); + string historyUrl = "/api/v1/groups/" + group + "/transactions"; + using (var req = new HttpRequestMessage(HttpMethod.Get, historyUrl)) + { + req.Headers.Authorization = + new AuthenticationHeaderValue("Bearer", ownerToken); + using var resp = await http.SendAsync(req); + Check(resp.StatusCode == HttpStatusCode.OK, + "owner transaction read failed"); + using var result = JsonDocument.Parse( + await resp.Content.ReadAsStringAsync()); + var lines = result.RootElement.GetProperty("transactions"); + Check(lines.GetArrayLength() == 1 && + lines[0].GetProperty("amount").GetInt64() == 73, + "group transaction history omitted real credit or signed it incorrectly"); + } + using (var req = new HttpRequestMessage(HttpMethod.Get, historyUrl)) + { + req.Headers.TryAddWithoutValidation("X-NexVerse-Api-Key", machineKey.ApiKey); + using var resp = await http.SendAsync(req); + Check(resp.StatusCode == HttpStatusCode.OK, + "trusted dual-scoped simulator history request was denied"); + } + using (var req = new HttpRequestMessage(HttpMethod.Get, historyUrl)) + { + req.Headers.TryAddWithoutValidation("X-NexVerse-Api-Key", groupsOnlyKey.ApiKey); + using var resp = await http.SendAsync(req); + Check(resp.StatusCode == HttpStatusCode.Forbidden, + "groups:read key without economy:read gained finance history"); + } + string land = "/api/v1/groups/" + group + "/land"; + await Verify(http, land, ownerToken, HttpStatusCode.OK, "parcels"); + using (var req = new HttpRequestMessage(HttpMethod.Get, land)) + { + req.Headers.TryAddWithoutValidation("X-NexVerse-Api-Key", groupsOnlyKey.ApiKey); + using var resp = await http.SendAsync(req); + Check(resp.StatusCode == HttpStatusCode.OK, + "trusted group land machine key failed"); + } + await Verify(http, land, strangerToken, HttpStatusCode.Forbidden, "error"); + await Verify(http, land + "?requester_id=" + owner.PrincipalID, + strangerToken, HttpStatusCode.Forbidden, "error"); + await Verify(http, "/api/v1/groups/" + group + "/transactions", + ownerToken, HttpStatusCode.OK, "transactions"); + await Verify(http, "/api/v1/groups/" + group + "/transactions", + strangerToken, HttpStatusCode.Forbidden, "error"); + await Verify(http, "/api/v1/groups/" + group + "/transactions", + memberToken, HttpStatusCode.Forbidden, "error"); + using (var request = new HttpRequestMessage(HttpMethod.Get, land)) + { + request.Headers.Authorization = + new AuthenticationHeaderValue("Bearer", ownerToken); + using var response = await http.SendAsync(request); + using var result = JsonDocument.Parse( + await response.Content.ReadAsStringAsync()); + var items = result.RootElement.GetProperty("parcels"); + Check(items.GetArrayLength() == 1 && + items[0].GetProperty("parcel_id").GetString() == parcel.ToString() && + items[0].GetProperty("region_name").GetString() == "Remote CI Region" && + items[0].GetProperty("global_x").GetUInt32() == 256012u, + "grid-wide land omitted remote region or incorrect coordinates"); + } + UUID accountingRole = UUID.Random(); Check(groups.AddGroupRole(owner.PrincipalID.ToString(), group, @@ -264,6 +409,18 @@ internal static class Program "pending wallet fixture group cleanup failed: " + reason); } + using (var landDb = NexLedgerSqlRuntime.Resolve( + "OpenSim.Data.MySQL.dll", connection).CreateConnection()) + { + landDb.Open(); + using var clean = landDb.CreateCommand(); + clean.CommandText = "DELETE FROM land WHERE UUID = @id"; + var param = clean.CreateParameter(); + param.ParameterName = "@id"; + param.Value = parcel.ToString(); + clean.Parameters.Add(param); + clean.ExecuteNonQuery(); + } Check(groups.DeleteGroup(owner.PrincipalID.ToString(), group, out reason), "first fixture cleanup failed: " + reason); Check(groups.DeleteGroup(owner.PrincipalID.ToString(), otherGroup, out reason), @@ -277,3 +434,15 @@ internal static class Program } } } + +internal class GroupGridProxy : DispatchProxy +{ + public GridRegion Region { get; set; } + + protected override object Invoke(MethodInfo method, object[] args) + { + if (method.Name == "GetRegionByUUID") + return (UUID)args[1] == Region?.RegionID ? Region : null; + throw new NotSupportedException(method.Name); + } +}