diff --git a/NexVerse/Core/Security/NexApiKeyStore.cs b/NexVerse/Core/Security/NexApiKeyStore.cs index 29067bca..5e9b643e 100644 --- a/NexVerse/Core/Security/NexApiKeyStore.cs +++ b/NexVerse/Core/Security/NexApiKeyStore.cs @@ -100,7 +100,10 @@ namespace NexVerse.Core.Security NexScopes.EstatesManage, NexScopes.EconomyRead, NexScopes.EconomyTransfer, - NexScopes.ExperiencesScript + NexScopes.ExperiencesScript, + // Separate trusted simulator CAP transport. This is + // deliberately NOT experiences:manage or admin:*. + NexScopes.ExperiencesViewerPermissions }, StringComparer.OrdinalIgnoreCase); @@ -114,6 +117,19 @@ namespace NexVerse.Core.Security } } + if (normalizedScopes.Contains( + NexScopes.ExperiencesViewerPermissions, + StringComparer.OrdinalIgnoreCase) && + normalizedScopes.Length != 1) + throw new ArgumentException( + "Experiences viewer permission credentials must have only experiences:viewer:permissions.", + nameof(scopes)); + + string normalizedName = string.IsNullOrWhiteSpace(name) + ? "NexVerse API key" : name.Trim(); + if (normalizedName.Length > 120) + throw new ArgumentException("API key name is too long.", nameof(name)); + string keyId = "nxk_" + Guid.NewGuid().ToString("N"); string secret = @@ -131,9 +147,7 @@ namespace NexVerse.Core.Security NexApiKeyRecord record = new NexApiKeyRecord { KeyId = keyId, - Name = string.IsNullOrWhiteSpace(name) - ? "NexVerse API key" - : name.Trim(), + Name = normalizedName, Scopes = normalizedScopes, SecretSalt = salt, SecretHash = hash, @@ -144,6 +158,18 @@ namespace NexVerse.Core.Security lock (m_Sync) { + // A secret is only returned once. Accidentally recreating + // an already active *identical service identity* leaves + // orphaned credentials. Require explicit disable/rotation. + if (m_Document.Keys.Any(existing => + existing.Enabled && + string.Equals(existing.Name?.Trim(), normalizedName, + StringComparison.OrdinalIgnoreCase) && + SameScopes(existing.Scopes, normalizedScopes))) + throw new InvalidOperationException( + "An enabled API key with this name and these scopes already exists. " + + "Review and explicitly disable the old key before replacing it."); + m_Document.Keys.Add(record); SaveLocked(); } @@ -184,6 +210,17 @@ namespace NexVerse.Core.Security if (record == null) return false; + // Re-enabling a superseded key must not undo the duplicate + // protection enforced at creation time. + if (enabled && !record.Enabled && + m_Document.Keys.Any(other => + !string.Equals(other.KeyId, keyId, StringComparison.Ordinal) && + other.Enabled && + string.Equals(other.Name?.Trim(), record.Name?.Trim(), + StringComparison.OrdinalIgnoreCase) && + SameScopes(other.Scopes, NormalizeScopes(record.Scopes)))) + return false; + record.Enabled = enabled; record.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); @@ -197,7 +234,13 @@ namespace NexVerse.Core.Security if (string.IsNullOrWhiteSpace(keyId)) return false; lock (m_Sync) { - int removed = m_Document.Keys.RemoveAll(x => string.Equals(x.KeyId, keyId, StringComparison.Ordinal)); + // Key deletion is irreversible and is only allowed after + // explicitly disabling it. Never delete an active key. + NexApiKeyRecord record = m_Document.Keys.FirstOrDefault(x => + string.Equals(x.KeyId, keyId, StringComparison.Ordinal)); + if (record == null || record.Enabled) return false; + int removed = m_Document.Keys.RemoveAll(x => + string.Equals(x.KeyId, keyId, StringComparison.Ordinal)); if (removed > 0) SaveLocked(); return removed > 0; } @@ -284,6 +327,12 @@ namespace NexVerse.Core.Security File.Move(temp, m_Path, true); } + private static bool SameScopes(string[] left, string[] right) + { + string[] normalized = NormalizeScopes(left); + return normalized.SequenceEqual(right, StringComparer.OrdinalIgnoreCase); + } + private static string[] NormalizeScopes( IEnumerable scopes) { @@ -368,7 +417,8 @@ namespace NexVerse.Core.Security SecretHash = value.SecretHash, Enabled = value.Enabled, CreatedAt = value.CreatedAt, - UpdatedAt = value.UpdatedAt + UpdatedAt = value.UpdatedAt, + LastUsedAt = value.LastUsedAt }; } diff --git a/NexVerse/Server/Api/NexApiDocsPage.cs b/NexVerse/Server/Api/NexApiDocsPage.cs index cf8d7e11..510d53b8 100644 --- a/NexVerse/Server/Api/NexApiDocsPage.cs +++ b/NexVerse/Server/Api/NexApiDocsPage.cs @@ -454,7 +454,8 @@ input,textarea,select{width:100%;background:#08131e;color:var(--text);border:1px

Bereits eingerichtete Schlüssel nicht unnötig neu erzeugen. Neue API-Schlüssel bleiben zusätzlich zu bestehenden registriert, bis sie ausdrücklich deaktiviert werden.

- + +

Der NexBus-SharedKey ist kein World-API-Key. Er wird lokal im Browser per kryptografisch sicherem Zufall erzeugt und muss auf allen beteiligten Nodes identisch sein.

@@ -477,6 +478,14 @@ input,textarea,select{width:100%;background:#08131e;color:var(--text);border:1px

Die vollständigen API-Keys zeigt die World API nur beim Erstellen an. Eine Seite oder den Browser erst verlassen, wenn du die neuen Werte sicher übernommen hast. Sie werden weder dauerhaft im Browserspeicher noch in Cookies oder URLs abgelegt.

Setze für die Secret-Datei chmod 600 /etc/nexverse/nexverse.env. Starte zunächst Robust mit dem neuen NexBus-Key und dem PR-#104-Code neu, danach die Simulatoren. Bereits vorhandene Prozessvariablen haben Vorrang vor der Datei.

+
+

4. Schlüsselbestand und Duplikate bereinigen

+

Es erscheinen nur ID, Name, Scopes und letzte Nutzung, niemals geheime Werte. Duplikate sind gleichnamige aktive Schlüssel mit identischen Scopes. Prüfe vor der Deaktivierung alle vorhandenen nexverse.env-Dateien auf Robust und den Simulatoren.

+
+
Als Administrator anmelden, dann Schlüsselbestand laden.
+
+

Bereinigung in zwei Schritten: Schlüssel einzeln deaktivieren, anschließend optional dauerhaft löschen. Aktive Schlüssel können serverseitig nicht gelöscht werden. Jede Änderung benötigt eine Bestätigung und wird auditiert.

+
@@ -1411,10 +1420,91 @@ function secretValidateEndpoint(text) { } function secretBuildLines(values) { const names=['NEXVERSE_ECONOMY_API_KEY','NEXVERSE_EXPERIENCES_API_KEY', + 'NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY', 'NEXVERSE_NEXBUS_SHARED_KEY','NEXVERSE_NEXBUS_PEER_URL','NEXVERSE_NEXBUS_PEERS']; $('secretOutput').value=names.filter(name=>Object.hasOwn(values,name)).map(name=>name+'='+values[name]).join('\n')+'\n'; $('secretCopy').disabled=!Object.keys(values).length; } +/* Only metadata is available after issuance; server never re-exposes secrets. */ +function secretKeyFingerprint(key) { + return JSON.stringify([(key.name||'').trim().toLowerCase(), + [...(key.scopes||[])].map(x=>String(x).toLowerCase()).sort()]); +} +function secretRenderKeyInventory(keys) { + const host=$('secretKeyList');host.replaceChildren(); + const activeCounts=new Map(); + keys.filter(k=>k.enabled).forEach(k=>{ + const fingerprint=secretKeyFingerprint(k); + activeCounts.set(fingerprint,(activeCounts.get(fingerprint)||0)+1); + }); + const duplicates=[...activeCounts.values()].filter(count=>count>1).length; + $('secretListStatus').textContent=keys.length+' Schlüssel registriert. '+ + duplicates+' aktive Duplikatgruppe(n) gefunden. Kein Schlüssel wurde automatisch verändert.'; + for(const key of keys){ + const card=document.createElement('div');card.className='change'; + const title=document.createElement('strong'); + title.textContent=(key.name||'Unbenannt')+(key.enabled?' · Aktiv':' · Deaktiviert'); + card.append(title); + const fp=secretKeyFingerprint(key),repeated=key.enabled&&activeCounts.get(fp)>1; + if(repeated){ + const warning=document.createElement('p'); + warning.textContent='Duplikat: Gleicher aktiver Name und identische Scopes (Geheimwerte können abweichen).'; + warning.className='status-bad';card.append(warning); + } + const description=document.createElement('p'); + description.textContent='ID: '+key.key_id+' | Scopes: '+(key.scopes||[]).join(', ')+ + ' | Letzte Nutzung: '+(key.last_used_at? + new Date(key.last_used_at*1000).toLocaleString('de-DE'):'noch nicht erfasst'); + description.style.overflowWrap='anywhere';card.append(description); + const controls=document.createElement('div');controls.className='row'; + const toggle=document.createElement('button');toggle.className='action'; + toggle.textContent=key.enabled?'Deaktivieren':'Aktivieren'; + toggle.addEventListener('click',()=>secretManageKey(key,'toggle')); + controls.append(toggle); + if(!key.enabled){ + const remove=document.createElement('button');remove.className='action'; + remove.textContent='Endgültig löschen'; + remove.addEventListener('click',()=>secretManageKey(key,'delete')); + controls.append(remove); + } + card.append(controls);host.append(card); + } +} +async function secretLoadKeys() { + try{ + if(!window.isSecureContext)throw new Error('Nur über HTTPS verfügbar.'); + const token=await secretAdminToken(); + const response=await secretJson('/api/v1/auth/api-keys',{ + headers:{'Authorization':'Bearer '+token}}); + secretRenderKeyInventory(response.keys||[]); + }catch(error){ + $('secretListStatus').textContent='Schlüsselbestand konnte nicht geladen werden: '+ + String(error.message||error); + $('secretKeyList').replaceChildren(); + } +} +async function secretManageKey(key,action) { + try{ + if(!window.isSecureContext)throw new Error('Nur über HTTPS verfügbar.'); + const token=await secretAdminToken(); + const verb=action==='delete'?'endgültig löschen':key.enabled?'deaktivieren':'aktivieren'; + if(!window.confirm('Maschinen-API-Schlüssel '+key.key_id+' ('+key.name+') '+verb+ + '? Vorher alle nexverse.env-Dateien und aktive Simulatoren prüfen.'))return; + if(action==='delete'){ + if(key.enabled)throw new Error('Aktive Schlüssel zuerst deaktivieren.'); + await secretJson('/api/v1/auth/api-keys/'+encodeURIComponent(key.key_id),{ + method:'DELETE',headers:{'Authorization':'Bearer '+token}}); + }else{ + await secretJson('/api/v1/auth/api-keys',{ + method:'PATCH', + headers:{'Authorization':'Bearer '+token,'Content-Type':'application/json'}, + body:JSON.stringify({key_id:key.key_id,enabled:!key.enabled})}); + } + await secretLoadKeys(); + }catch(error){ + $('secretListStatus').textContent='Aktion nicht abgeschlossen: '+String(error.message||error); + } +} async function secretJson(url,opts) { const response=await fetch(url,{cache:'no-store',credentials:'same-origin',...opts}); let data={}; @@ -1430,8 +1520,9 @@ async function secretAdminToken() { async function secretGenerate() { const wantEconomy=$('secretEconomy').checked; const wantExperiences=$('secretExperiences').checked; + const wantPermissions=$('secretExperiencePermissions').checked; const wantBus=$('secretNexBus').checked; - if(!wantEconomy&&!wantExperiences&&!wantBus){ + if(!wantEconomy&&!wantExperiences&&!wantPermissions&&!wantBus){ secretStatus('Bitte mindestens einen Schlüssel auswählen.',false);return; } const values={}; @@ -1445,6 +1536,26 @@ async function secretGenerate() { } if(!window.isSecureContext)throw new Error('Schlüssel nur über HTTPS generieren.'); const token=await secretAdminToken(); + const plan=[ + {wanted:wantEconomy,name:'NexVerse Simulator Economy', + scopes:['economy:read','economy:transfer'],env:'NEXVERSE_ECONOMY_API_KEY'}, + {wanted:wantExperiences,name:'NexVerse Simulator Experiences', + scopes:['experiences:script'],env:'NEXVERSE_EXPERIENCES_API_KEY'}, + {wanted:wantPermissions,name:'NexVerse Simulator Experience Permissions', + scopes:['experiences:viewer:permissions'], + env:'NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY'} + ].filter(item=>item.wanted); + if(plan.length){ + const inventory=await secretJson('/api/v1/auth/api-keys',{ + headers:{'Authorization':'Bearer '+token}}); + const existing=inventory.keys||[]; + const match=plan.find(item=>existing.some(key=>key.enabled && + key.name?.trim().toLowerCase()===item.name.toLowerCase() && + JSON.stringify([...(key.scopes||[])].map(s=>s.toLowerCase()).sort())=== + JSON.stringify([...item.scopes].sort()))); + if(match)throw new Error('Ein aktiver Schlüssel für '+match.name+ + ' existiert bereits. Unter Abschnitt 4 prüfen und bei nötiger Rotation gezielt deaktivieren.'); + } if(!window.confirm('Neue Maschinen-API-Schlüssel werden sofort serverseitig registriert. Erstellung starten?'))return; $('secretGenerate').disabled=true; $('secretCopy').disabled=true; @@ -1456,14 +1567,8 @@ async function secretGenerate() { values.NEXVERSE_NEXBUS_PEERS=peers.join(','); secretBuildLines(values); } - if(wantEconomy||wantExperiences){ - for(const item of [ - {wanted:wantEconomy,name:'NexVerse Simulator Economy', - scopes:['economy:read','economy:transfer'],env:'NEXVERSE_ECONOMY_API_KEY'}, - {wanted:wantExperiences,name:'NexVerse Simulator Experiences', - scopes:['experiences:script'],env:'NEXVERSE_EXPERIENCES_API_KEY'} - ]){ - if(!item.wanted)continue; + if(plan.length){ + for(const item of plan){ const data=await secretJson('/api/v1/auth/api-keys',{ method:'POST', headers:{'Content-Type':'application/json','Authorization':'Bearer '+token}, @@ -1476,6 +1581,7 @@ async function secretGenerate() { } } secretStatus('Alle ausgewählten Schlüssel erstellt. Konfigurationsblock jetzt sicher kopieren.',true); + if(plan.length)await secretLoadKeys(); }catch(err){ secretBuildLines(values); secretStatus('Einrichtung nicht vollständig: '+String(err.message||err)+ @@ -1529,6 +1635,7 @@ $('adminLoginTotp').addEventListener('keydown',event=>{if(event.key==='Enter'){e $('secretGenerate').addEventListener('click',secretGenerate); $('secretCopy').addEventListener('click',secretCopy); $('secretClear').addEventListener('click',secretClear); +$('secretLoadKeys').addEventListener('click',secretLoadKeys); $('search').addEventListener('input',renderEndpointList);$('run').addEventListener('click',execute);$('clear').addEventListener('click',()=>{$('bearer').value='';$('apiKey').value='';$('idem').value=''}); $('loadStats').addEventListener('click',loadStatistics);$('clearStats').addEventListener('click',()=>{$('statsBearer').value='';$('statsApiKey').value=''}); $('loadGrid').addEventListener('click',loadGridLayout);$('clearGridCredentials').addEventListener('click',()=>{$('gridBearer').value='';$('gridApiKey').value='';$('gridMutationIdempotency').value=''}); diff --git a/NexVerse/Server/Api/NexVerseUserApi.cs b/NexVerse/Server/Api/NexVerseUserApi.cs index 37ee054c..d0d46b43 100644 --- a/NexVerse/Server/Api/NexVerseUserApi.cs +++ b/NexVerse/Server/Api/NexVerseUserApi.cs @@ -890,6 +890,12 @@ namespace NexVerse.Server.Api HandleApiKeys(request, response); return; } + if (path.StartsWith("/api/v1/auth/api-keys/", StringComparison.OrdinalIgnoreCase)) + { + HandleApiKeyDelete(request, response, + path.Substring("/api/v1/auth/api-keys/".Length)); + return; + } if (string.Equals(path, "/api/v1/auth/authorization-model", StringComparison.OrdinalIgnoreCase)) { @@ -1278,6 +1284,10 @@ namespace NexVerse.Server.Api out UserAccount _)) return; + // Key inventory metadata and one-time plaintext secret responses + // must never be stored by shared/intermediary HTTP caches. + response.AddHeader("Cache-Control", "no-store"); + if (m_ApiKeys == null) { WriteError( @@ -1402,6 +1412,14 @@ namespace NexVerse.Server.Api "invalid_api_key_metadata", e.Message); } + catch (InvalidOperationException) + { + WriteError( + response, + HttpStatusCode.Conflict, + "api_key_duplicate", + "An enabled key with this name and scope set already exists. Disable it explicitly before rotation."); + } return; } @@ -1435,11 +1453,16 @@ namespace NexVerse.Server.Api keyId, enabled)) { + bool exists = m_ApiKeys.List().Any(x => + string.Equals(x.KeyId, keyId, StringComparison.Ordinal)); WriteError( response, - HttpStatusCode.NotFound, - "api_key_not_found", - "API key was not found."); + exists && enabled ? HttpStatusCode.Conflict : + HttpStatusCode.NotFound, + exists && enabled ? "api_key_duplicate" : "api_key_not_found", + exists && enabled ? + "An enabled key with the same name and scopes exists. Re-enabling this key would create an active duplicate." : + "API key was not found."); return; } @@ -1493,6 +1516,82 @@ namespace NexVerse.Server.Api "GET, POST or PATCH is required."); } + /// + /// Permanently remove one *disabled* machine credential only. + /// This is intentionally separate from list/create/state updates; + /// an active key cannot be deleted and all actions are audited. + /// + private void HandleApiKeyDelete( + IOSHttpRequest request, IOSHttpResponse response, string keyId) + { + if (!IsMethod(request, "DELETE")) + { + WriteError(response, HttpStatusCode.MethodNotAllowed, + "method_not_allowed", "DELETE is required."); + return; + } + if (!Authenticate(request, response, NexScopes.AdminAll, + out NexPrincipal principal, out UserAccount _)) + return; + + response.AddHeader("Cache-Control", "no-store"); + if (m_ApiKeys == null) + { + WriteError(response, HttpStatusCode.ServiceUnavailable, + "api_key_store_unavailable", "API key storage is not available."); + return; + } + if (string.IsNullOrWhiteSpace(keyId) || keyId.Length != 36 || + !keyId.StartsWith("nxk_", StringComparison.Ordinal) || + !Guid.TryParseExact(keyId.Substring(4), "N", out Guid _)) + { + WriteError(response, HttpStatusCode.BadRequest, + "invalid_key_id", "Valid API key ID is required."); + return; + } + NexApiKeyRecord candidate = m_ApiKeys.List().FirstOrDefault( + x => string.Equals(x.KeyId, keyId, StringComparison.Ordinal)); + if (candidate == null) + { + WriteError(response, HttpStatusCode.NotFound, + "api_key_not_found", "API key was not found."); + return; + } + if (candidate.Enabled) + { + WriteError(response, HttpStatusCode.Conflict, + "api_key_still_enabled", + "Disable the key before permanent removal."); + return; + } + // Store.Delete rechecks enabled state under its own lock. + if (!m_ApiKeys.Delete(keyId)) + { + WriteError(response, HttpStatusCode.Conflict, + "api_key_state_changed", + "API key changed during deletion; refresh and retry."); + return; + } + string correlationId = AddCorrelation(response); + m_Audit.Record(new NexAuditEvent( + principal.Subject, "auth.api_key.delete", keyId, + correlationId, new Dictionary + { + ["name"] = candidate.Name, + ["scopes"] = string.Join(" ", candidate.Scopes) + })); + m_EventBus.Publish(new NexEvent( + "auth.api_key.deleted", "nexverse.world-api", + new Dictionary { ["key_id"] = keyId }, + correlationId)); + WriteJson(response, new + { + deleted = true, + key_id = keyId, + correlation_id = correlationId + }); + } + private void HandleAdminSessionInfo( IOSHttpRequest request, IOSHttpResponse response) @@ -3017,7 +3116,8 @@ namespace NexVerse.Server.Api scopes = record.Scopes, enabled = record.Enabled, created_at = record.CreatedAt, - updated_at = record.UpdatedAt + updated_at = record.UpdatedAt, + last_used_at = record.LastUsedAt }; } diff --git a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs index 5efa3431..f8ddafea 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs @@ -149,9 +149,11 @@ namespace NexVerse.Server.Api AuthenticatedOperations( ("get", "Aktive Administratorsitzung und tatsächlichen UserLevel prüfen", "admin:*", "200"))), ["/api/v1/auth/api-keys"] = AuthenticatedOperations( - ("get", "Eingeschränkte Maschinen-API-Schlüssel auflisten", "admin:*", "200"), - ("post", "Eingeschränkten Maschinen-API-Schlüssel mit Berechtigungsumfang erstellen", "admin:*", "201"), + ("get", "Eingeschränkte Maschinen-API-Schlüssel inklusive letzter Verwendung auflisten", "admin:*", "200"), + ("post", "Dedizierten Maschinen-API-Schlüssel ohne doppelte aktive Identität erstellen", "admin:*", "201"), ("patch", "Maschinen-API-Schlüssel aktivieren oder deaktivieren", "admin:*", "200")), + ["/api/v1/auth/api-keys/{keyId}"] = AuthenticatedOperations( + ("delete", "Nur zuvor deaktivierten Maschinen-API-Schlüssel dauerhaft entfernen", "admin:*", "200")), ["/api/v1/auth/authorization-model"] = AuthenticatedOperations( ("get", "Verfügbare Einwohnerrollen, Einzel-Scopes und privilegierte Zuweisungen lesen", "security:manage", "200")), ["/oauth/authorize"] = AuthenticatedOperations( @@ -751,6 +753,13 @@ namespace NexVerse.Server.Api "ApiKeyStateRequest", null, "200"); + ApplyJsonContract( + paths, + "/api/v1/auth/api-keys/{keyId}", + "delete", + null, + "ApiKeyDeleteResponse", + "200"); ApplyJsonContract( paths, "/api/v1/audit", @@ -4632,7 +4641,8 @@ namespace NexVerse.Server.Api }, ["enabled"] = new { type = "boolean" }, ["created_at"] = new { type = "integer" }, - ["updated_at"] = new { type = "integer" } + ["updated_at"] = new { type = "integer" }, + ["last_used_at"] = new { type = "integer" } } }, ["ApiKeyCreateRequest"] = new @@ -4679,6 +4689,16 @@ namespace NexVerse.Server.Api ["enabled"] = new { type = "boolean" } } }, + ["ApiKeyDeleteResponse"] = new + { + type = "object", + properties = new Dictionary + { + ["deleted"] = new { type = "boolean" }, + ["key_id"] = new { type = "string" }, + ["correlation_id"] = new { type = "string" } + } + }, ["ApiKeyListResponse"] = new { type = "object", diff --git a/bin/nexverse.env.example b/bin/nexverse.env.example new file mode 100644 index 00000000..52ceff4c --- /dev/null +++ b/bin/nexverse.env.example @@ -0,0 +1,36 @@ +# OpenGenesisLINK 0.9.3.10 Dev – nexverse.env TEMPLATE (NO REAL SECRETS) +# Ziel: /etc/nexverse/nexverse.env (chmod 600, root or service owner). +# Geheimwerte ausschliesslich ueber die HTTPS World API Admin-Oberflaeche +# /api/v1/docs -> "Schluessel & Einrichtung" erstellen. +# Bestehende funktionierende Werte NICHT mit leeren Vorlagen ueberschreiben. +# Diese Datei kann mehrere Maschinen teilen, muss aber nach Rollen und +# Servern getrennt und mit minimalen Rechten verteilt werden. + +# ROBUST: zentraler World-API Token-Signaturschluessel (min. 32 Bytes). +NEXVERSE_NATIVE_TOKEN_SIGNING_KEY= + +# SIMULATOR: dedizierte Machine API Keys, nicht auf Robust publizieren. +# Die Gueltigkeit und Scopes werden zentral im World API Key Store verwaltet. +NEXVERSE_ECONOMY_API_KEY= +NEXVERSE_EXPERIENCES_API_KEY= +# Firestorm Allow/Block/Forget: NUR bei kontrolliert aktiviertem +# [NexExperiencesViewer] FirestormPermissionCaps=true. +# Scope: ausschliesslich experiences:viewer:permissions. +NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY= + +# ROBUST + SIMULATOREN: gemeinsam geheimer NexBus HMAC-Key. +# Als neuer SharedKey fuer alle Nodes gleich; keine separate API-Key-ID. +NEXVERSE_NEXBUS_SHARED_KEY= +# Simulator -> Robust; Beispiel: +# NEXVERSE_NEXBUS_PEER_URL=https://robust.internal/internal/nexbus/v1/events +NEXVERSE_NEXBUS_PEER_URL= +# Robust -> Simulator(en), kommagetrennt: +NEXVERSE_NEXBUS_PEERS= + +# Bestehende Portal-/IM-Secrets bei Benutzung NICHT rotieren. +NEX_PORTAL_IM_SECRET= +NEXVERSE_IM_RELAY_SIGNING_KEY= +NEXVERSE_IM_RELAY_IMAP_PASSWORD= + +# OGLVoice bleibt im Release 0.9.3.10 Dev zurueckgestellt. +# Keine Medienprovider-, LiveKit- oder Viewer-Voice-Secrets hier aktivieren. diff --git a/doc/NexVerse/WORLD_API.md b/doc/NexVerse/WORLD_API.md index db317efa..b7700e04 100644 --- a/doc/NexVerse/WORLD_API.md +++ b/doc/NexVerse/WORLD_API.md @@ -576,8 +576,9 @@ Administrative management endpoint: - `GET /api/v1/auth/api-keys` - `POST /api/v1/auth/api-keys` - `PATCH /api/v1/auth/api-keys` +- `DELETE /api/v1/auth/api-keys/{keyId}` — permanently removes a **previously disabled** key -All three management operations require `admin:*` through a resident/OAuth administrator credential. API keys themselves can never receive `admin:*`, wildcard or interactive OIDC scopes. +All four management operations require `admin:*` through a resident/OAuth administrator credential. API keys themselves can never receive `admin:*`, wildcard or interactive OIDC scopes. A creation body is: @@ -588,14 +589,38 @@ A creation body is: } ``` -The full key is returned exactly once. Its secret is persisted only as a PBKDF2-SHA256 hash. Runtime storage defaults to: +The full key is returned exactly once. Its secret is persisted only as a PBKDF2-SHA256 hash. The GET inventory exposes `last_used_at` for maintenance (zero means no recorded use), but **never** plaintext keys, salts or hashes. Duplicate active issuance with the same normalized name and identical set of scopes is rejected with HTTP 409 (`api_key_duplicate`). Disable the old entry explicitly before a rotation; the new secret is not retrievable for an existing key. Runtime storage defaults to: `data/nexverse-api-keys.json` -Supported machine scopes are explicit NexVerse functional scopes such as `regions:read`, `regions:manage`, `users:read`, `inventory:read`, `estates:read`, `estates:manage`, `economy:read` and their documented write/transfer counterparts. The simulator's Experiences adapter may receive only the `experiences:script` machine scope for Experience script operations; `experiences:manage` and administrator permissions remain unavailable to machine API keys. +Supported machine scopes are explicit NexVerse functional scopes such as `regions:read`, `regions:manage`, `users:read`, `inventory:read`, `estates:read`, `estates:manage`, `economy:read` and their documented write/transfer counterparts. The simulator's Experiences adapter uses dedicated `experiences:script` credentials for LSL and, **separately**, an `experiences:viewer:permissions` machine key for Firestorm Allow/Block/Forget. The latter MUST be issued as its **only** scope, not bundled with script or other permissions. The broader `experiences:manage` and administrator permissions remain unavailable to machine API keys. API-key principals use subjects in the form `api-key:`. Disabling a key takes effect immediately because validation is performed against the persistent key store on every request. +### Key inventory and safe duplicate cleanup (0.9.3.10 Dev) + +The World API docs/control-center page `/api/v1/docs` > **Schluessel & Einrichtung** now offers a read-only inventory with normalized same-name/same-scope duplicate indicators and last-used timestamps. Every disable/reactivate/delete operation requires an explicit click and confirmation. Permanent deletion is forbidden for active keys on the server, even if a client sends DELETE directly. All state changes and deletions emit audit events. The key ID is public metadata to administrators, **not** the secret. + +**Before disabling an apparent duplicate:** compare `/etc/nexverse/nexverse.env` on Robust and all relevant simulators, identify which key ID the running process is using, and validate a replacement with restricted permissions. The inventory cannot detect whether a key has been copied into an inactive simulator, nor whether two different IDs share a usage role. The duplicate label is a review hint, not authority to bulk delete. + +The new `bin/nexverse.env.example` documents the keys, including: +- `NEXVERSE_EXPERIENCES_API_KEY` — `experiences:script` +- `NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY` — **only** `experiences:viewer:permissions` +- existing `NEXVERSE_ECONOMY_API_KEY`, NexBus and server signing secrets (unchanged) + +Example simulator configuration: +```ini +[NexExperiencesViewer] + Enabled = true + ApiKey = "${Environment|NEXVERSE_EXPERIENCES_API_KEY}" + FirestormReadCaps = false + FirestormPermissionCaps = false + ScriptPendingConsent = false + ViewerPermissionsApiKey = "${Environment|NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY}" +``` + +Leave all opt-in Firestorm permissions flags disabled until dedicated viewer tests pass. Existing secret values must be preserved; never commit a populated `nexverse.env` and do not print secrets into CI logs. The World API does not modify your host's env file automatically. + The selectable-region endpoint now requires `regions:read` rather than `admin:*`, making it usable by restricted machine integrations while administrator bearer tokens continue to satisfy the scope through their administrative wildcard. diff --git a/tools/ci/NexApiKeyRegression/Program.cs b/tools/ci/NexApiKeyRegression/Program.cs index cc8da50d..fc5c18ca 100644 --- a/tools/ci/NexApiKeyRegression/Program.cs +++ b/tools/ci/NexApiKeyRegression/Program.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using NexVerse.Core.Security; internal static class Program @@ -139,6 +140,75 @@ internal static class Program rejectedExperienceManagement, "Machine API keys must not receive experiences:manage"); + // Firestorm viewer-permission CAPS use a *separate* machine + // credential; it must never carry administrator or script rights. + NexApiKeyRegistration viewerPermissions = + experiencesReloaded.Create( + "NexVerse Simulator Experience Permissions", + new[] { NexScopes.ExperiencesViewerPermissions }); + Require(experiencesReloaded.TryValidate( + viewerPermissions.ApiKey, out NexApiKeyRecord scopedViewer) && + scopedViewer.Scopes.Length == 1 && + scopedViewer.Scopes[0] == NexScopes.ExperiencesViewerPermissions, + "Dedicated Firestorm permissions machine key failed"); + + bool rejectedMixedPermissions = false; + try + { + experiencesReloaded.Create("unsafe mixed permissions", + new[] { NexScopes.ExperiencesViewerPermissions, + NexScopes.ExperiencesScript }); + } + catch (ArgumentException) { rejectedMixedPermissions = true; } + Require(rejectedMixedPermissions, + "Viewer permission credentials must not be mixed with script rights"); + + // Duplicate detection is scoped to the exact service identity, + // case-insensitive name and normalized set of scopes. It must + // never reveal or silently replace the existing plaintext secret. + bool rejectedDuplicate = false; + try + { + experiencesReloaded.Create( + " nexverse simulator experience permissions ", + new[] { NexScopes.ExperiencesViewerPermissions }); + } + catch (InvalidOperationException) { rejectedDuplicate = true; } + Require(rejectedDuplicate, "Duplicate enabled service key accepted"); + Require(experiencesReloaded.List().Count == 3, + "Duplicate rejection modified the persistent key inventory"); + + // Deletion is an irreversible second step after explicit disable. + Require(!experiencesReloaded.Delete(viewerPermissions.Record.KeyId), + "Deleting an active machine key must be forbidden"); + Require(experiencesReloaded.SetEnabled( + viewerPermissions.Record.KeyId, false), + "Disabling permission key failed"); + NexApiKeyRegistration replacement = experiencesReloaded.Create( + "NexVerse Simulator Experience Permissions", + new[] { NexScopes.ExperiencesViewerPermissions }); + Require(!experiencesReloaded.SetEnabled( + viewerPermissions.Record.KeyId, true), + "Re-enabling an old credential must not create an active duplicate"); + Require(experiencesReloaded.Delete(viewerPermissions.Record.KeyId), + "Deleting disabled key failed"); + Require(!experiencesReloaded.TryValidate( + viewerPermissions.ApiKey, out _), + "Deleted viewer permission credential still validated"); + Require(replacement.Record.KeyId != viewerPermissions.Record.KeyId && + experiencesReloaded.TryValidate(replacement.ApiKey, out _), + "Explicit credential rotation failed"); + + NexApiKeyRecord metadata = experiencesReloaded.List() + .First(x => x.KeyId == replacement.Record.KeyId); + Require(metadata.LastUsedAt > 0, + "Last-used metadata lost when cloning records"); + PersistentNexApiKeyStore afterCleanup = + new PersistentNexApiKeyStore(path); + Require(afterCleanup.List().Count == 3 && + afterCleanup.TryValidate(replacement.ApiKey, out _), + "Key cleanup or replacement did not survive restart"); + Console.WriteLine( "NexVerse scoped API key regression: OK"); return 0; diff --git a/tools/ci/verify_experiences_nexbus_enabled.py b/tools/ci/verify_experiences_nexbus_enabled.py index 75ce32c9..97ed283a 100644 --- a/tools/ci/verify_experiences_nexbus_enabled.py +++ b/tools/ci/verify_experiences_nexbus_enabled.py @@ -59,7 +59,25 @@ assert "return new InMemoryNexEventBus();" in connector store=contents("NexVerse/Core/Security/NexApiKeyStore.cs") assert "NexScopes.ExperiencesScript" in store +assert "NexScopes.ExperiencesViewerPermissions" in store +assert "normalizedScopes.Length != 1" in store +assert "existing.Enabled" in store and "SameScopes(existing.Scopes, normalizedScopes)" in store +assert "record == null || record.Enabled" in store, "cannot delete enabled keys" +assert "LastUsedAt = value.LastUsedAt" in store +assert '"api_key_duplicate"' in user +assert '"api_key_still_enabled"' in user +assert "private void HandleApiKeyDelete(" in user +assert '"auth.api_key.delete"' in user api=contents("NexVerse/Server/Api/NexVerseWorldApiHandlers.cs") +assert '"/api/v1/auth/api-keys/{keyId}"' in api +assert '"last_used_at"' in api +assert '"ApiKeyDeleteResponse"' in api +template=contents("bin/nexverse.env.example") +for name in ("NEXVERSE_EXPERIENCES_API_KEY", + "NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY", + "NEXVERSE_ECONOMY_API_KEY", + "NEXVERSE_NEXBUS_SHARED_KEY"): + assert name in template, name assert admin_route in api ui=contents("NexVerse/Server/Api/NexApiDocsPage.cs") for marker in ('data-page="adminlogin"','id="page-adminlogin"','id="adminLoginPassword"', @@ -70,6 +88,12 @@ for marker in ('data-page="adminlogin"','id="page-adminlogin"','id="adminLoginPa assert "localStorage.setItem(" not in ui assert "sessionStorage.setItem(" not in ui assert 'id="secretAdminPassword"' not in ui, "secrets must use shared admin session" +for marker in ('id="secretExperiencePermissions"', 'id="secretLoadKeys"', + 'id="secretKeyList"', + "async function secretManageKey(", + "function secretKeyFingerprint(", + "NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY"): + assert marker in ui, f"key inventory UI missing: {marker}" # Browser script is embedded in C# HTML raw string; parse syntax using Node.js when installed. match=re.search(r"",ui,re.S)