diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index 9479e668..d73a5ecc 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -653,11 +653,9 @@ jobs: dotnet run --configuration Release --project tools/ci/NexNpcDirectoryRegression/NexNpcDirectoryRegression.csproj python3 tools/ci/verify_npc_owner_bridge_r617.py - - name: Regression-test NPC direct IM archive opt-in, owner privacy and retention (R619) + - name: Verify NPC IM archive privacy and MariaDB-only wiring (R620) shell: bash - run: | - dotnet run --configuration Release --project tools/ci/NexNpcChatStoreRegression/NexNpcChatStoreRegression.csproj - python3 tools/ci/verify_npc_chat_r619.py + run: python3 tools/ci/verify_npc_chat_r619.py - name: Regression-test OGL FastMap deferred startup queue shell: bash @@ -1563,6 +1561,12 @@ jobs: NEX_PORTAL_IM_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;" run: dotnet run --configuration Release --project tools/ci/NexPortalImMariaDbRegression/NexPortalImMariaDbRegression.csproj + - name: Run real MariaDB NPC owner direct-IM archive regression (R620) + shell: bash + env: + NEX_NPC_CHAT_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;" + run: dotnet run --configuration Release --project tools/ci/NexNpcChatStoreRegression/NexNpcChatStoreRegression.csproj + - name: Run real MariaDB NexGroups authorization and invitation regression shell: bash env: diff --git a/NexVerse/Server/Api/NexNpcChatStore.cs b/NexVerse/Server/Api/NexNpcChatStore.cs index 816abcb4..7337245a 100644 --- a/NexVerse/Server/Api/NexNpcChatStore.cs +++ b/NexVerse/Server/Api/NexNpcChatStore.cs @@ -1,212 +1,193 @@ // SPDX-License-Identifier: MPL-2.0 -// R619: owner-consented direct NPC IM archive; not a general chat logger. +// R620: NPC direct-IM opt-in archive in the EXISTING OpenGenesisLINK MariaDB. +// Dedicated tables only; no local SQLite files and no citizen IM table reuse. using System; using System.Collections.Generic; -using System.IO; -using Mono.Data.Sqlite; +using System.Data; +using System.Data.Common; +using System.Text; +using MySql.Data.MySqlClient; namespace NexVerse.Server.Api { internal sealed class NexNpcChatStore { - private readonly object m_Guard = new object(); - private readonly string m_Connection; + private readonly Func m_Connect; private readonly int m_RetentionDays; private const int MaxPerOwner = 10000; - internal NexNpcChatStore(string path, int retentionDays) + internal NexNpcChatStore(string provider, string connectionString, int retentionDays) { - if (string.IsNullOrWhiteSpace(path)) - throw new ArgumentException("A dedicated NPC chat database is required.", nameof(path)); - string full = Path.GetFullPath(path); - Directory.CreateDirectory(Path.GetDirectoryName(full)); - m_Connection = "Data Source=" + full + ";Version=3;Pooling=False;"; + if (string.IsNullOrWhiteSpace(provider) || + (provider.IndexOf("MySQL", StringComparison.OrdinalIgnoreCase) < 0 && + provider.IndexOf("MariaDB", StringComparison.OrdinalIgnoreCase) < 0)) + throw new NotSupportedException("NPC IM archive requires existing MariaDB/MySQL grid storage."); + if (string.IsNullOrWhiteSpace(connectionString)) + throw new ArgumentException("Grid [DatabaseService] MariaDB connection is required."); + m_Connect = () => new MySqlConnection(connectionString); m_RetentionDays = Math.Clamp(retentionDays, 1, 90); - lock (m_Guard) - { - using var db = Open(); - Exec(db, @"CREATE TABLE IF NOT EXISTS npc_chat_consent ( - owner TEXT PRIMARY KEY NOT NULL, enabled INTEGER NOT NULL, - updated_at INTEGER NOT NULL)"); - Exec(db, @"CREATE TABLE IF NOT EXISTS npc_chat_messages ( - seq INTEGER PRIMARY KEY AUTOINCREMENT, - event_id TEXT NOT NULL, - owner TEXT NOT NULL, - npc_id TEXT NOT NULL, - sender TEXT NOT NULL CHECK(sender IN ('npc','owner')), - text TEXT NOT NULL, - accepted_at INTEGER NOT NULL, - UNIQUE(owner,event_id))"); - if (!OperatingSystem.IsWindows()) - File.SetUnixFileMode(full, UnixFileMode.UserRead | UnixFileMode.UserWrite); - Exec(db, "CREATE INDEX IF NOT EXISTS ix_npc_chat_owner_npc_seq ON npc_chat_messages(owner,npc_id,seq)"); - Exec(db, "CREATE INDEX IF NOT EXISTS ix_npc_chat_ttl ON npc_chat_messages(accepted_at)"); - } + + using DbConnection db = Open(); + Exec(db, null, @"CREATE TABLE IF NOT EXISTS npc_chat_consent ( + owner CHAR(36) NOT NULL PRIMARY KEY, + enabled TINYINT(1) NOT NULL DEFAULT 0, + updated_at BIGINT NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); + Exec(db, null, @"CREATE TABLE IF NOT EXISTS npc_chat_messages ( + seq BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + event_id CHAR(36) NOT NULL, + owner CHAR(36) NOT NULL, + npc_id CHAR(36) NOT NULL, + sender VARCHAR(8) NOT NULL, + body TEXT NOT NULL, + accepted_at BIGINT NOT NULL, + UNIQUE KEY uq_npc_chat_owner_event (owner,event_id), + KEY ix_npc_chat_owner_npc_seq (owner,npc_id,seq), + KEY ix_npc_chat_ttl (accepted_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); } - private SqliteConnection Open() + private DbConnection Open() { - var db = new SqliteConnection(m_Connection); + DbConnection db = m_Connect(); db.Open(); return db; } - private static void Exec(SqliteConnection db, string sql) + private static string Id(Guid id) => id.ToString("D"); + private static DbCommand Command(DbConnection db, DbTransaction tx, string sql, + params (string Name, object Value)[] parameters) { - using var cmd = db.CreateCommand(); - cmd.CommandText = sql; - cmd.ExecuteNonQuery(); + DbCommand command = db.CreateCommand(); + command.Transaction = tx; + command.CommandText = sql; + foreach ((string name, object value) in parameters) + { + DbParameter p = command.CreateParameter(); + p.ParameterName = name; + p.Value = value ?? DBNull.Value; + command.Parameters.Add(p); + } + return command; } - private static void Param(SqliteCommand cmd, string key, object value) + private static int Exec(DbConnection db, DbTransaction tx, string sql, + params (string Name, object Value)[] parameters) { - cmd.Parameters.AddWithValue(key, value); + using DbCommand command = Command(db, tx, sql, parameters); + return command.ExecuteNonQuery(); } - private void Purge(SqliteConnection db, SqliteTransaction tx = null) + private void Purge(DbConnection db, DbTransaction tx = null) { - using var cmd = db.CreateCommand(); - cmd.Transaction = tx; - cmd.CommandText = "DELETE FROM npc_chat_messages WHERE accepted_at < @cutoff"; - Param(cmd, "@cutoff", DateTimeOffset.UtcNow.AddDays(-m_RetentionDays).ToUnixTimeSeconds()); - cmd.ExecuteNonQuery(); + Exec(db, tx, "DELETE FROM npc_chat_messages WHERE accepted_at < @cutoff", + ("@cutoff", DateTimeOffset.UtcNow.ToUnixTimeSeconds() - m_RetentionDays * 86400L)); } - private static bool Enabled(SqliteConnection db, Guid owner, SqliteTransaction tx = null) + private static bool Enabled(DbConnection db, DbTransaction tx, Guid owner) { - using var cmd = db.CreateCommand(); - cmd.Transaction = tx; - cmd.CommandText = "SELECT enabled FROM npc_chat_consent WHERE owner=@owner"; - Param(cmd, "@owner", owner.ToString("D")); + using DbCommand cmd = Command(db, tx, + "SELECT enabled FROM npc_chat_consent WHERE owner=@owner", + ("@owner", Id(owner))); return Convert.ToInt32(cmd.ExecuteScalar() ?? 0) == 1; } internal bool IsEnabled(Guid owner) { - lock (m_Guard) - { - using var db = Open(); - return Enabled(db, owner); - } + using DbConnection db = Open(); + return Enabled(db, null, owner); } internal void SetEnabled(Guid owner, bool enabled) { if (owner == Guid.Empty) throw new ArgumentException("Owner required."); - lock (m_Guard) - { - using var db = Open(); - using var tx = db.BeginTransaction(); - using (var cmd = db.CreateCommand()) - { - cmd.Transaction = tx; - cmd.CommandText = @"INSERT INTO npc_chat_consent(owner,enabled,updated_at) - VALUES(@owner,@enabled,@time) - ON CONFLICT(owner) DO UPDATE SET enabled=excluded.enabled,updated_at=excluded.updated_at"; - Param(cmd,"@owner",owner.ToString("D")); - Param(cmd,"@enabled",enabled ? 1 : 0); - Param(cmd,"@time",DateTimeOffset.UtcNow.ToUnixTimeSeconds()); - cmd.ExecuteNonQuery(); - } - if (!enabled) DeleteOwner(db, tx, owner); - tx.Commit(); - } + using DbConnection db = Open(); + using DbTransaction tx = db.BeginTransaction(); + Exec(db, tx, @"INSERT INTO npc_chat_consent(owner,enabled,updated_at) + VALUES(@owner,@enabled,@now) + ON DUPLICATE KEY UPDATE enabled=VALUES(enabled),updated_at=VALUES(updated_at)", + ("@owner", Id(owner)), ("@enabled", enabled ? 1 : 0), + ("@now", DateTimeOffset.UtcNow.ToUnixTimeSeconds())); + if (!enabled) + DeleteOwner(db, tx, owner); + tx.Commit(); } - private static void DeleteOwner(SqliteConnection db, SqliteTransaction tx, Guid owner) + private static void DeleteOwner(DbConnection db, DbTransaction tx, Guid owner) { - using var cmd = db.CreateCommand(); - cmd.Transaction = tx; - cmd.CommandText = "DELETE FROM npc_chat_messages WHERE owner=@owner"; - Param(cmd,"@owner",owner.ToString("D")); - cmd.ExecuteNonQuery(); + Exec(db, tx, "DELETE FROM npc_chat_messages WHERE owner=@owner", + ("@owner", Id(owner))); } internal void DeleteHistory(Guid owner) { - lock (m_Guard) - { - using var db = Open(); - using var tx = db.BeginTransaction(); - DeleteOwner(db,tx,owner); - tx.Commit(); - } + if (owner == Guid.Empty) throw new ArgumentException("Owner required."); + using DbConnection db = Open(); + using DbTransaction tx = db.BeginTransaction(); + DeleteOwner(db, tx, owner); + tx.Commit(); } - - // Only the HMAC-verified ingress may call this, after resolving the - // owner and NPC against a fresh complete simulator snapshot. + // Caller MUST also verify a fresh signed NPC owner snapshot. The + // INSERT ... SELECT enforces consent atomically at database level. internal bool Append(Guid eventID, Guid owner, Guid npc, string sender, string text) { if (eventID == Guid.Empty || owner == Guid.Empty || npc == Guid.Empty || - (sender != "owner" && sender != "npc") || + (sender != "npc" && sender != "owner") || string.IsNullOrWhiteSpace(text) || - System.Text.Encoding.UTF8.GetByteCount(text) > 4096) + Encoding.UTF8.GetByteCount(text) > 4096) return false; - lock (m_Guard) - { - using var db = Open(); - using var tx = db.BeginTransaction(); - Purge(db,tx); - if (!Enabled(db, owner, tx)) return false; - using (var cmd = db.CreateCommand()) - { - cmd.Transaction = tx; - cmd.CommandText = @"INSERT OR IGNORE INTO npc_chat_messages - (event_id,owner,npc_id,sender,text,accepted_at) - VALUES(@event,@owner,@npc,@sender,@text,@time)"; - Param(cmd,"@event",eventID.ToString("D")); - Param(cmd,"@owner",owner.ToString("D")); - Param(cmd,"@npc",npc.ToString("D")); - Param(cmd,"@sender",sender); - Param(cmd,"@text",text); - Param(cmd,"@time",DateTimeOffset.UtcNow.ToUnixTimeSeconds()); - cmd.ExecuteNonQuery(); - } - using (var cmd = db.CreateCommand()) - { - cmd.Transaction = tx; - cmd.CommandText = @"DELETE FROM npc_chat_messages - WHERE owner=@owner AND seq NOT IN - (SELECT seq FROM npc_chat_messages WHERE owner=@owner - ORDER BY seq DESC LIMIT @limit)"; - Param(cmd,"@owner",owner.ToString("D")); - Param(cmd,"@limit",MaxPerOwner); - cmd.ExecuteNonQuery(); - } - tx.Commit(); - return true; - } - } + using DbConnection db = Open(); + using DbTransaction tx = db.BeginTransaction(); + long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + int inserted = Exec(db, tx, @"INSERT IGNORE INTO npc_chat_messages + (event_id,owner,npc_id,sender,body,accepted_at) + SELECT @event,@owner,@npc,@sender,@body,@now + FROM npc_chat_consent WHERE owner=@owner AND enabled=1", + ("@event",Id(eventID)),("@owner",Id(owner)),("@npc",Id(npc)), + ("@sender",sender),("@body",text),("@now",now)); + // A duplicate event remains successfully acknowledged, but + // an owner without consent must never be acknowledged as saved. + bool consent = Enabled(db, tx, owner); + Purge(db, tx); + + // MySQL 1093: do not DELETE using a SELECT from the same table; + // resolve the 10,000-row cutoff first, like NexCitizenImMySqlStore. + object cutoff; + using (DbCommand limit = Command(db, tx, + "SELECT seq FROM npc_chat_messages WHERE owner=@owner " + + "ORDER BY seq DESC LIMIT 1 OFFSET 9999", + ("@owner",Id(owner)))) + cutoff = limit.ExecuteScalar(); + if (cutoff != null && cutoff != DBNull.Value) + Exec(db, tx, "DELETE FROM npc_chat_messages WHERE owner=@owner AND seq<@seq", + ("@owner",Id(owner)),("@seq",Convert.ToInt64(cutoff))); + tx.Commit(); + return inserted > 0 || consent; + } internal (List Messages, string NextCursor) Read(Guid owner, Guid npc, long after, int limit) { - if (after < 0 || limit < 1 || limit > 500) + if (owner == Guid.Empty || npc == Guid.Empty || + after < 0 || limit < 1 || limit > 500) throw new ArgumentException("Invalid NPC chat pagination."); - lock (m_Guard) - { - using var db = Open(); - Purge(db); - var items = new List(); - var ids = new List(); - using var cmd = db.CreateCommand(); - cmd.CommandText = @"SELECT seq,event_id,sender,text,accepted_at + using DbConnection db = Open(); + Purge(db); + var entries = new List(); + long lastSeq = 0; + bool more = false; + using DbCommand cmd = Command(db, null, + @"SELECT seq,event_id,sender,body,accepted_at FROM npc_chat_messages WHERE owner=@owner AND npc_id=@npc AND seq>@after - ORDER BY seq ASC LIMIT @limit"; - Param(cmd,"@owner",owner.ToString("D")); - Param(cmd,"@npc",npc.ToString("D")); - Param(cmd,"@after",after); - Param(cmd,"@limit",limit+1); - using var reader = cmd.ExecuteReader(); - bool more = false; - while (reader.Read()) + ORDER BY seq ASC LIMIT @limit", + ("@owner",Id(owner)),("@npc",Id(npc)),("@after",after),("@limit",limit+1)); + using DbDataReader reader = cmd.ExecuteReader(); + while (reader.Read()) + { + if (entries.Count == limit) { more = true; break; } + lastSeq = Convert.ToInt64(reader.GetValue(0)); + entries.Add(new { - if (items.Count == limit) { more = true; break; } - long seq=reader.GetInt64(0); - ids.Add(seq); - items.Add(new - { - message_id=reader.GetString(1), - npc_id=npc.ToString("D"), - sender=reader.GetString(2), - text=reader.GetString(3), - sent_at=DateTimeOffset.FromUnixTimeSeconds(reader.GetInt64(4)) - .UtcDateTime.ToString("O") - }); - } - return (items, more && ids.Count>0 ? ids[ids.Count-1].ToString() : ""); + message_id = reader.GetString(1), + npc_id = Id(npc), + sender = reader.GetString(2), + text = reader.GetString(3), + sent_at = DateTimeOffset.FromUnixTimeSeconds( + Convert.ToInt64(reader.GetValue(4))).UtcDateTime.ToString("O") + }); } + return (entries, more ? lastSeq.ToString() : ""); } internal int RetentionDays => m_RetentionDays; } diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index d5135837..15cd98e6 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -693,8 +693,12 @@ namespace NexVerse.Server.Api { try { + // Use the existing grid database; NPC data lives + // in separate InnoDB tables, never a local file. + // No independent NPC-DB credentials or SQLite fallback. npcChatStore = new NexNpcChatStore( - npcChatConfig.GetString("StoragePath", "data/nexverse-npc-chat.sqlite"), + databaseStorageProvider, + databaseConnectionString, npcChatConfig.GetInt("RetentionDays", 30)); NexNpcChatIngress npcChatIngress = new NexNpcChatIngress(npcChatSecret, npcIndex, npcChatStore); diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 3153ff20..b331cf35 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -256,6 +256,10 @@ [MediaOnAPrim] [NPC] + ; Private owner NPC directory: requires valid NEX_NPC_INGEST_URL and _SECRET. + NexNPCSnapshotEnabled = false + ; Private owner-NPC IM: NEX_NPC_CHAT_INGEST_URL and NEX_NPC_CHAT_SECRET. + NexNPCChatEnabled = false [Terrain] diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 38b9404d..9856f763 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -747,6 +747,19 @@ RetentionDays = 30 SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}" +; Optional owner-scoped NPC directory and direct-IM archive. Both disabled by default. +; Uses the authoritative [DatabaseService] MariaDB connection, no SQLite. +[NexNPCPortal] + Enabled = false + ; Number of expected reporting regions. Require complete signed snapshots. + ExpectedRegionCount = 0 + +[NexNPCChat] + Enabled = false + ; Creates npc_chat_consent and npc_chat_messages in the existing MariaDB. + RetentionDays = 30 + ; HMAC keys: NEX_NPC_INGEST_SECRET and NEX_NPC_CHAT_SECRET (process environment). + [NexVerseWorldApi] Enabled = true ; Only the Stadtportal BACKEND with a dedicated users:register API key diff --git a/doc/NexVerse/NPC_OWNER_CHAT_R619.md b/doc/NexVerse/NPC_OWNER_CHAT_R619.md index afbb5bfe..1076b80b 100644 --- a/doc/NexVerse/NPC_OWNER_CHAT_R619.md +++ b/doc/NexVerse/NPC_OWNER_CHAT_R619.md @@ -1,4 +1,4 @@ -# R619 – Private NPC-Chatarchivierung mit Eigentümer-Einwilligung +# R620 – NPC-Chatarchivierung in der bestehenden MariaDB Status: Source/CI-Integration. Produktiv **standardmäßig deaktiviert**. Die R617-Liste aktiver NPCs wird vorausgesetzt. @@ -9,7 +9,7 @@ Nur direkte private Instant Messages (IM) zwischen einem aktiv bestätigten NPC - Default: keine Speicherung; ohne Einwilligung wird der signierte IM-Ingest mit 403 abgewiesen. - Abschalten löscht **sämtliche** bisher gespeicherten NPC-IMs dieses Eigentümers, während die Einwilligung deaktiviert wird. - Separater Lösch-Endpunkt entfernt alle archivierten NPC-IMs des Besitzers, ohne die Einwilligung zu ändern. -- SQLite-Datenbank ist separat von OpenSim-IMs und erhält auf Unix-Modulen Rechte 0600. +- Speicherung ausschließlich in der bereits verwendeten OpenGenesisLINK-MariaDB. Die neuen InnoDB-Tabellen `npc_chat_consent` und `npc_chat_messages` sind logisch von den OpenSim- und Bürger-IM-Tabellen getrennt. **Keine SQLite-Dateien, kein SQLite-Fallback und keine zweite Datenbank.** - Standard-Aufbewahrung 30 Tage, konfigurierbar 1–90 Tage; maximal 10.000 Einträge pro Eigentümer, 4 KiB pro Nachricht. - Die Nachrichten sind **best effort**: Simulator-zu-World wird in einem flüchtigen, begrenzten Speicherpuffer mit maximal drei Zustellversuchen übertragen, nicht dauerhaft lokal gepuffert. Der API-Verlauf setzt deshalb `complete=false` und `capture_mode=best_effort_owner_npc_direct_im`. Nach einer Unterbrechung kann ein Teil fehlen. Es gibt **keine** rückwirkende Rekonstruktion. @@ -22,10 +22,11 @@ ExpectedRegionCount = 1 [NexNPCChat] Enabled = true -StoragePath = "/var/lib/opengenesislink/npc-chat/npc-chat.sqlite" RetentionDays = 30 ``` +`NexNpcChatStore` erbt ausschließlich `StorageProvider` und `ConnectionString` aus der bereits konfigurierten ROBUST-Sektion `[DatabaseService]`. Es werden die separaten Tabellen `npc_chat_consent` und `npc_chat_messages` in dieser MariaDB automatisch angelegt. Falls `[DatabaseService]` nicht auf MariaDB/MySQL zeigt oder die Verbindung nicht funktioniert, bleibt das NPC-Chatarchiv deaktiviert; kein SQLite-Fallback. DB-Zugangsdaten bleiben in der bestehenden gesicherten Konfiguration. + `ExpectedRegionCount` muss zur Zahl aller für das Grid erwarteten aktiven Simulator-Regionen passen; fehlende/stale Snapshots führen absichtlich zu 503. Die Freigabe darf erst nach Abgleich der tatsächlich eingesetzten Regionszahl erfolgen. Die R617-Quellverifizierung bleibt Pflicht. World-Prozessumgebung (Secret selbst niemals in Git, INI oder Logs): @@ -35,7 +36,7 @@ NEX_NPC_INGEST_SECRET= NEX_NPC_CHAT_SECRET= ``` -Die Verzeichnisse müssen für den ROBUST-Prozess schreibbar sein. Bei restriktiven Datei-/Container-Nutzern auf Besitzerrechte achten. HMAC-geschützte interne Pfade dürfen **nur** für autorisierte Simulatoren über HTTPS/WireGuard erreichbar sein; der Reverse-Proxy soll diese internen Pfade nicht öffentlich anbieten. +Das bestehende MariaDB-Datenbankkonto des ROBUST-Prozesses benötigt für die beiden neuen Tabellen `CREATE`, `SELECT`, `INSERT`, `UPDATE` und `DELETE`. Bei der initialen Inbetriebnahme muss das Anlegen der Tabellen erlaubt sein. Benutzer- und NPC-IMs erhalten keine lokalen Datenbankdateien. HMAC-geschützte interne Pfade dürfen **nur** für autorisierte Simulatoren über HTTPS/WireGuard erreichbar sein; der Reverse-Proxy soll diese internen Pfade nicht öffentlich anbieten. ## Simulator – Beispiel @@ -85,4 +86,4 @@ Das Lesen eigener NPC-IMs setzt weiterhin `GET /api/v1/npcs/mine` mit bestätigt Diese Version umfasst **keine** vollständige persistente Zustellgarantie und keinen Zugriff auf Gespräche Dritter. Das Portal muss Nutzer ausdrücklich auf den Best-Effort-Status und die begrenzte 30-Tage-Aufbewahrung hinweisen. Für garantiert vollständige Archive wäre künftig ein zustellbestätigter persistenter Outbox-Mechanismus **nach einer vorab synchronisierten Consent-Prüfung** erforderlich. -Vor Aktivierung: NPC-Rechte-/Regionsschnappschuss und JSON-API-Tests, R619-Store-Regressionslauf, vollständiger .NET-Release-Build und abgesicherte Internal-API-Firewall. Ohne diese Nachweise **nicht** von produktiver Freigabe sprechen. +Vor Aktivierung: NPC-Rechte-/Regionsschnappschuss und JSON-API-Tests, R620-Live-MariaDB-Regressionslauf, vollständiger .NET-Release-Build und abgesicherte Internal-API-Firewall. Ohne diese Nachweise **nicht** von produktiver Freigabe sprechen. diff --git a/tools/ci/NexNpcChatStoreRegression/NexNpcChatStoreRegression.csproj b/tools/ci/NexNpcChatStoreRegression/NexNpcChatStoreRegression.csproj index b73fe337..67eaa789 100644 --- a/tools/ci/NexNpcChatStoreRegression/NexNpcChatStoreRegression.csproj +++ b/tools/ci/NexNpcChatStoreRegression/NexNpcChatStoreRegression.csproj @@ -7,8 +7,10 @@ true - - ../../../bin/Mono.Data.Sqlite.dll + + + + ../../../bin/MySql.Data.dll True diff --git a/tools/ci/NexNpcChatStoreRegression/Program.cs b/tools/ci/NexNpcChatStoreRegression/Program.cs index f48bc719..eea9ba0f 100644 --- a/tools/ci/NexNpcChatStoreRegression/Program.cs +++ b/tools/ci/NexNpcChatStoreRegression/Program.cs @@ -1,53 +1,60 @@ // SPDX-License-Identifier: MPL-2.0 +// Real MariaDB regression; uses the same database service as OpenGenesisLINK. using System; -using System.IO; using NexVerse.Server.Api; -string dir=Path.Combine(Path.GetTempPath(),"npc-chat-r619-"+Guid.NewGuid().ToString("N")); -Directory.CreateDirectory(dir); +string connection = Environment.GetEnvironmentVariable("NEX_NPC_CHAT_MARIADB"); +if (string.IsNullOrWhiteSpace(connection)) + throw new InvalidOperationException("NEX_NPC_CHAT_MARIADB is required (real SQL test)."); +Guid owner = Guid.NewGuid(), other = Guid.NewGuid(); +Guid npc = Guid.NewGuid(), otherNpc = Guid.NewGuid(); +NexNpcChatStore store = new NexNpcChatStore("OpenSim.Data.MySQL.dll", connection, 30); try { - string db=Path.Combine(dir,"chat.sqlite"); - Guid owner=Guid.NewGuid(),otherOwner=Guid.NewGuid(); - Guid npc=Guid.NewGuid(),otherNpc=Guid.NewGuid(); - NexNpcChatStore store=new NexNpcChatStore(db,30); - Check(!store.IsEnabled(owner),"owner has no implicit consent"); - Check(!store.Append(Guid.NewGuid(),owner,npc,"npc","pre-consent"), - "no IM recording before opt-in"); - Check(store.Read(owner,npc,0,100).Messages.Count==0,"no pre-consent records"); + Check(!store.IsEnabled(owner) && !store.IsEnabled(other), "no implicit consent"); + Check(!store.Append(Guid.NewGuid(), owner, npc, "npc", "before opt-in"), + "cannot record before opt-in"); + Check(store.Read(owner,npc,0,100).Messages.Count==0,"pre-consent archive empty"); + store.SetEnabled(owner,true); - Check(store.IsEnabled(owner),"explicit consent saved"); - Guid first=Guid.NewGuid(); - Check(store.Append(first,owner,npc,"npc","NPC response"),"NPC message written"); - Check(store.Append(first,owner,npc,"npc","duplicate"),"replay is idempotently accepted"); - Check(store.Read(owner,npc,0,100).Messages.Count==1,"replay is not duplicated"); - Check(store.Append(Guid.NewGuid(),owner,npc,"owner","owner reply"),"owner reply"); - Check(!store.Append(Guid.NewGuid(),otherOwner,npc,"npc","private"), - "other owner cannot record without opt-in"); + Check(store.IsEnabled(owner), "opt-in stored"); + Guid id = Guid.NewGuid(); + Check(store.Append(id,owner,npc,"npc","hello"), "NPC IM inserted"); + Check(store.Append(id,owner,npc,"npc","replay"), "idempotent replay acknowledged"); + Check(store.Read(owner,npc,0,100).Messages.Count==1,"replay not duplicated"); + Check(store.Append(Guid.NewGuid(),owner,npc,"owner","reply"),"owner reply stored"); + Check(!store.Append(Guid.NewGuid(),other,npc,"npc","wrong owner"), + "unconsented owner cannot write"); Check(!store.Append(Guid.NewGuid(),owner,npc,"visitor","third party"), - "other senders never accepted"); - Check(store.Append(Guid.NewGuid(),owner,otherNpc,"npc","other npc"), - "different NPC belongs to same owner in ingest contract"); - Check(store.Read(owner,npc,0,100).Messages.Count==2,"owner sees own NPC only"); - Check(store.Read(otherOwner,npc,0,100).Messages.Count==0,"other owner invisible"); - var page=store.Read(owner,npc,0,1); - Check(page.Messages.Count==1 && page.NextCursor.Length>0,"cursor page"); - var end=store.Read(owner,npc,long.Parse(page.NextCursor),1); - Check(end.Messages.Count==1 && end.NextCursor=="","complete final page"); - NexNpcChatStore reopened=new NexNpcChatStore(db,30); - Check(reopened.IsEnabled(owner) && reopened.Read(owner,npc,0,100).Messages.Count==2, - "durable consent and history"); - reopened.DeleteHistory(owner); - Check(reopened.IsEnabled(owner) && reopened.Read(owner,npc,0,100).Messages.Count==0, - "delete history preserves consent"); - reopened.Append(Guid.NewGuid(),owner,npc,"npc","to erase"); - reopened.SetEnabled(owner,false); - Check(!reopened.IsEnabled(owner) && reopened.Read(owner,npc,0,100).Messages.Count==0, - "withdrawal deletes all owner's records"); - Console.WriteLine("NPC_CHAT_R619_SQLITE_PASS"); + "third party blocked"); + Check(store.Append(Guid.NewGuid(),owner,otherNpc,"npc","other NPC"), + "different NPC separate"); + Check(store.Read(owner,npc,0,100).Messages.Count==2,"NPC filter"); + Check(store.Read(other,npc,0,100).Messages.Count==0,"cross-owner isolation"); + + var first=store.Read(owner,npc,0,1); + Check(first.Messages.Count==1 && first.NextCursor!="","pagination first page"); + var second=store.Read(owner,npc,long.Parse(first.NextCursor),1); + Check(second.Messages.Count==1 && second.NextCursor=="","pagination final page"); + + var restarted = new NexNpcChatStore("OpenSim.Data.MySQL.dll", connection, 30); + Check(restarted.IsEnabled(owner) && + restarted.Read(owner,npc,0,100).Messages.Count==2,"durability"); + restarted.DeleteHistory(owner); + Check(restarted.IsEnabled(owner) && + restarted.Read(owner,npc,0,100).Messages.Count==0,"delete preserves consent"); + restarted.Append(Guid.NewGuid(),owner,npc,"npc","to delete"); + restarted.SetEnabled(owner,false); + Check(!restarted.IsEnabled(owner) && + restarted.Read(owner,npc,0,100).Messages.Count==0,"opt-out purges messages"); + Console.WriteLine("NPC_CHAT_R620_MARIADB_PASS"); } -finally{try{Directory.Delete(dir,true);}catch(IOException){}} -static void Check(bool assertion,string message) +finally { - if(!assertion)throw new InvalidOperationException("NPC_CHAT_TEST_FAILED: "+message); + store.SetEnabled(owner,false); + store.SetEnabled(other,false); +} +static void Check(bool good,string message) +{ + if(!good)throw new InvalidOperationException("NPC_CHAT_MARIADB_FAILED: "+message); } diff --git a/tools/ci/verify_npc_chat_r619.py b/tools/ci/verify_npc_chat_r619.py index 72118009..5c062759 100644 --- a/tools/ci/verify_npc_chat_r619.py +++ b/tools/ci/verify_npc_chat_r619.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""R619 safety regression for owner-consented NPC direct IM archive.""" +"""R620 safety regression for existing-MariaDB-only owner NPC IM archive.""" from pathlib import Path root=Path(__file__).resolve().parents[2] read=lambda name: (root/name).read_text(encoding="utf-8") @@ -13,19 +13,21 @@ connector=read("NexVerse/Server/Api/NexVerseWorldApiConnector.cs") routes=read("NexVerse/Server/Api/NexVerseWorldApiHandlers.cs") project=read("OpenSim/Region/OptionalModules/OpenSim.Region.OptionalModules.csproj") for name,source,needles in ( - ("no pre-consent storage",store,("if (!Enabled(db, owner, tx)) return false;","UNIQUE(owner,event_id)","DELETE FROM npc_chat_messages","MaxPerOwner")), + ("consent-gated InnoDB storage",store,("using MySql.Data.MySqlClient","ENGINE=InnoDB","INSERT IGNORE INTO npc_chat_messages","FROM npc_chat_consent WHERE owner=@owner AND enabled=1","ON DUPLICATE KEY UPDATE","UNIQUE KEY uq_npc_chat_owner_event","DELETE FROM npc_chat_messages","MaxPerOwner")), ("authenticated and source-verified IM ingest",ingress,("HMACSHA256","FixedTimeEquals","TryOwned(owner","m_Store.IsEnabled(owner)","m_Store.Append","8192")), ("owner-only API",api,("NexScopes.RelationshipsRead","NexScopes.RelationshipsWrite","owner != account.PrincipalID.Guid","owned.Any(n => n.npc_id == npcID)","acknowledge_private_owner_npc_im","m_Chat.DeleteHistory(owner)","complete=false")), ("private IM only",npc,("OnOwnerDirectMessage","im.fromAgentID == m_ownerID.Guid","target == m_ownerID","!im.fromGroup")), ("separate signing credential",publisher,("NexNpcChatPublisher","NexNPC","HMACSHA256","Uri.UriSchemeHttps")), ("disabled by default",module,('GetBoolean("NexNPCChatEnabled", false)',"OnOwnerDirectMessage += m_ChatPublisher.Send")), - ("isolated World archive",connector,('config.Configs["NexNPCChat"]','GetBoolean("Enabled", false)','NEX_NPC_CHAT_SECRET','NexNpcChatIngress')), + ("isolated World archive",connector,('config.Configs["NexNPCChat"]','GetBoolean("Enabled", false)','NEX_NPC_CHAT_SECRET','NexNpcChatIngress','databaseStorageProvider,','databaseConnectionString,')), ("OpenAPI",routes,('"/api/v1/npcs/chat/settings"','"/api/v1/npcs/chat/history"')), ("simulator build",project,("World\\NPC\\NexNpcChatPublisher.cs",)), ): for marker in needles: assert marker in source, name+": "+marker print("NPC_CHAT_R619_PASS",name) +assert 'Mono.Data.Sqlite' not in store and 'SqliteConnection' not in store +assert 'StoragePath' not in connector[connector.index('NexNpcChatStore npcChatStore'):connector.index('NexNpcWorldApi npcWorldApi')] assert 'OnChatToNPC' not in module, "No public/local chat capture allowed" assert 'NexCitizenImStore' not in ingress and 'NexCitizenImStore' not in api -print("NPC_CHAT_R619_SAFETY_PASS") +print("NPC_CHAT_R620_MARIADB_SAFETY_PASS")