From b50a2959a7ba5190e4aed53774fa29cf08c36df7 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:42:40 +0200 Subject: [PATCH] NEXJAST: retire legacy World API auth bootstrap --- .github/workflows/nexjast-ci.yml | 4 + NexVerse/Core/Identity/INexUserService.cs | 1 + NexVerse/Server/Api/NexVerseUserApi.cs | 502 +++++++++++------- .../Server/Api/NexVerseWorldApiConnector.cs | 7 +- .../Server/Api/NexVerseWorldApiHandlers.cs | 129 ++++- doc/NexVerse/ROADMAP.md | 7 +- doc/NexVerse/WORLD_API.md | 59 +- tools/ci/verify_native_auth_cutover.py | 65 +++ 8 files changed, 539 insertions(+), 235 deletions(-) create mode 100644 tools/ci/verify_native_auth_cutover.py diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index 789527f4..c479d144 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -101,6 +101,10 @@ jobs: shell: bash run: dotnet run --configuration Release --project tools/ci/NexOAuthRegression/NexOAuthRegression.csproj + - name: Verify native auth cutover + shell: bash + run: python3 tools/ci/verify_native_auth_cutover.py + - name: Verify NexBus distributed core shell: bash run: dotnet run --configuration Release --project tools/ci/NexBusRegression/NexBusRegression.csproj diff --git a/NexVerse/Core/Identity/INexUserService.cs b/NexVerse/Core/Identity/INexUserService.cs index ad38ecad..818fd4fc 100644 --- a/NexVerse/Core/Identity/INexUserService.cs +++ b/NexVerse/Core/Identity/INexUserService.cs @@ -153,6 +153,7 @@ namespace NexVerse.Core.Identity string userTitle, string userCountry); + bool VerifyPassword(string principalId, string password); bool SetUserLevel(string principalId, int userLevel); bool SetPassword(string principalId, string password); NexUserRecord SetAccountState(string principalId, string state, string reason); diff --git a/NexVerse/Server/Api/NexVerseUserApi.cs b/NexVerse/Server/Api/NexVerseUserApi.cs index 3dcb7f39..e31f07e0 100644 --- a/NexVerse/Server/Api/NexVerseUserApi.cs +++ b/NexVerse/Server/Api/NexVerseUserApi.cs @@ -23,33 +23,27 @@ namespace NexVerse.Server.Api { internal sealed class NexApiAuthenticator { - private readonly IAuthenticationService m_Authentication; private readonly IUserAccountService m_UserAccounts; private readonly INexAuthorizationService m_Authorization; private readonly INexAccessTokenService m_NativeTokens; private readonly INexOAuthStore m_OAuthStore; private readonly INexApiKeyStore m_ApiKeys; private readonly int m_AdminMinimumLevel; - private readonly int m_TokenLifetimeSeconds; public NexApiAuthenticator( - IAuthenticationService authentication, IUserAccountService userAccounts, INexAuthorizationService authorization, INexAccessTokenService nativeTokens, INexOAuthStore oauthStore, INexApiKeyStore apiKeys, - int adminMinimumLevel, - int tokenLifetimeSeconds) + int adminMinimumLevel) { - m_Authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); m_UserAccounts = userAccounts ?? throw new ArgumentNullException(nameof(userAccounts)); m_Authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); m_NativeTokens = nativeTokens; m_OAuthStore = oauthStore; m_ApiKeys = apiKeys; m_AdminMinimumLevel = adminMinimumLevel; - m_TokenLifetimeSeconds = Math.Max(60, tokenLifetimeSeconds); } public bool TryAuthenticate( @@ -89,8 +83,7 @@ namespace NexVerse.Server.Api principal, requiredScope)) { - statusCode = - (int)HttpStatusCode.Forbidden; + statusCode = (int)HttpStatusCode.Forbidden; error = "insufficient_scope"; return false; } @@ -103,71 +96,95 @@ namespace NexVerse.Server.Api if (!TryReadBearer(request, out string token)) return false; - if (m_NativeTokens != null && - m_NativeTokens.TryValidate(token, out NexAccessTokenClaims nativeClaims)) + if (m_NativeTokens == null || + !m_NativeTokens.TryValidate( + token, + out NexAccessTokenClaims nativeClaims)) { - if (m_OAuthStore != null && m_OAuthStore.IsAccessTokenRevoked(nativeClaims.TokenId)) + error = "invalid_access_token"; + return false; + } + + if (m_OAuthStore != null && + m_OAuthStore.IsAccessTokenRevoked( + nativeClaims.TokenId)) + { + error = "access_token_revoked"; + return false; + } + + if (UUID.TryParse( + nativeClaims.Subject, + out UUID principalId)) + { + account = + m_UserAccounts.GetUserAccount( + UUID.Zero, + principalId); + + if (account == null) { - error = "access_token_revoked"; + error = "account_not_found"; return false; } - if (UUID.TryParse(nativeClaims.Subject, out UUID principalId)) + if (!account.LoginAllowed) { - account = m_UserAccounts.GetUserAccount(UUID.Zero, principalId); - if (account == null) - { - error = "account_not_found"; - return false; - } - - if (!account.LoginAllowed) - { - statusCode = (int)HttpStatusCode.Forbidden; - error = "account_blocked"; - return false; - } - - if (nativeClaims.SecurityStamp != account.NexVerseStateChanged) - { - error = "stale_access_token"; - return false; - } - - List scopes = new List(nativeClaims.Scopes); - if (account.UserLevel < m_AdminMinimumLevel) - scopes.RemoveAll(x => string.Equals(x, NexScopes.AdminAll, StringComparison.OrdinalIgnoreCase)); - - principal = new NexPrincipal(principalId.ToString(), scopes, true); - } - else if (m_OAuthStore != null && - m_OAuthStore.ValidateServicePrincipal( - nativeClaims.Subject, - nativeClaims.SecurityStamp, - nativeClaims.Scopes)) - { - principal = new NexPrincipal(nativeClaims.Subject, nativeClaims.Scopes, true); - } - else - { - error = "invalid_access_token"; + statusCode = (int)HttpStatusCode.Forbidden; + error = "account_blocked"; return false; } + + if (nativeClaims.SecurityStamp != + account.NexVerseStateChanged) + { + error = "stale_access_token"; + return false; + } + + List scopes = + new List( + nativeClaims.Scopes); + + if (account.UserLevel < + m_AdminMinimumLevel) + { + scopes.RemoveAll(x => + string.Equals( + x, + NexScopes.AdminAll, + StringComparison.OrdinalIgnoreCase)); + } + + principal = + new NexPrincipal( + principalId.ToString(), + scopes, + true); + } + else if ( + m_OAuthStore != null && + m_OAuthStore.ValidateServicePrincipal( + nativeClaims.Subject, + nativeClaims.SecurityStamp, + nativeClaims.Scopes)) + { + principal = + new NexPrincipal( + nativeClaims.Subject, + nativeClaims.Scopes, + true); } else { - if (!TryAuthenticateLegacyToken( - request, - token, - out principal, - out account, - out statusCode, - out error)) - return false; + error = "invalid_access_token"; + return false; } if (!string.IsNullOrWhiteSpace(requiredScope) && - !m_Authorization.IsAllowed(principal, requiredScope)) + !m_Authorization.IsAllowed( + principal, + requiredScope)) { statusCode = (int)HttpStatusCode.Forbidden; error = "insufficient_scope"; @@ -179,97 +196,28 @@ namespace NexVerse.Server.Api return true; } - public bool TryAuthenticateLegacyExchange( + private static bool TryReadBearer( IOSHttpRequest request, - out NexPrincipal principal, - out UserAccount account, - out int statusCode, - out string error) - { - principal = NexPrincipal.Anonymous; - account = null; - statusCode = (int)HttpStatusCode.Unauthorized; - error = "authentication_required"; - - if (!TryReadBearer(request, out string token)) - return false; - - return TryAuthenticateLegacyToken( - request, - token, - out principal, - out account, - out statusCode, - out error); - } - - private bool TryAuthenticateLegacyToken( - IOSHttpRequest request, - string token, - out NexPrincipal principal, - out UserAccount account, - out int statusCode, - out string error) - { - principal = NexPrincipal.Anonymous; - account = null; - statusCode = (int)HttpStatusCode.Unauthorized; - error = "invalid_authentication"; - - string principalHeader = request?.Headers?["X-NexVerse-Principal"]; - if (string.IsNullOrWhiteSpace(principalHeader) || - !UUID.TryParse(principalHeader, out UUID principalId)) - return false; - - if (!m_Authentication.Verify(principalId, token, m_TokenLifetimeSeconds)) - { - error = "invalid_or_expired_token"; - return false; - } - - account = m_UserAccounts.GetUserAccount(UUID.Zero, principalId); - if (account == null) - { - error = "account_not_found"; - return false; - } - - if (!account.LoginAllowed) - { - statusCode = (int)HttpStatusCode.Forbidden; - error = "account_blocked"; - return false; - } - - principal = new NexPrincipal(principalId.ToString(), BuildScopes(account), true); - statusCode = (int)HttpStatusCode.OK; - error = string.Empty; - return true; - } - - private List BuildScopes(UserAccount account) - { - List scopes = new List - { - NexScopes.UsersRead, - NexScopes.UsersWrite - }; - - if (account.UserLevel >= m_AdminMinimumLevel) - scopes.Add(NexScopes.AdminAll); - - return scopes; - } - - private static bool TryReadBearer(IOSHttpRequest request, out string token) + out string token) { token = string.Empty; - string authorization = request?.Headers?["Authorization"]; - if (string.IsNullOrWhiteSpace(authorization) || - !authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) - return false; - token = authorization.Substring("Bearer ".Length).Trim(); + string authorization = + request?.Headers?["Authorization"]; + + if (string.IsNullOrWhiteSpace(authorization) || + !authorization.StartsWith( + "Bearer ", + StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + token = + authorization + .Substring("Bearer ".Length) + .Trim(); + return !string.IsNullOrWhiteSpace(token); } } @@ -483,6 +431,66 @@ namespace NexVerse.Server.Api return Convert(account); } + public bool VerifyPassword( + string principalId, + string password) + { + if (!UUID.TryParse( + principalId, + out UUID id) || + string.IsNullOrEmpty(password) || + password.Length > 256) + { + return false; + } + + UserAccount account = + m_UserAccounts.GetUserAccount( + UUID.Zero, + id); + + if (account == null || + !account.LoginAllowed) + { + return false; + } + + AuthInfo auth = + m_Authentication.GetAuthInfo(id); + + if (auth == null || + string.IsNullOrWhiteSpace( + auth.PasswordHash) || + string.IsNullOrWhiteSpace( + auth.PasswordSalt)) + { + return false; + } + + string candidate = + OpenSim.Framework.Util.Md5Hash( + OpenSim.Framework.Util.Md5Hash( + password) + + ":" + + auth.PasswordSalt); + + byte[] expected = + Encoding.ASCII.GetBytes( + auth.PasswordHash + .ToLowerInvariant()); + + byte[] actual = + Encoding.ASCII.GetBytes( + candidate + .ToLowerInvariant()); + + return + expected.Length == actual.Length && + CryptographicOperations.FixedTimeEquals( + expected, + actual); + } + public bool SetUserLevel(string principalId, int userLevel) { if (!UUID.TryParse(principalId, out UUID id)) @@ -594,6 +602,7 @@ namespace NexVerse.Server.Api private readonly INexIdempotencyStore m_IdempotencyStore; private readonly INexApiKeyStore m_ApiKeys; private readonly int m_IdempotencyTtlSeconds; + private readonly int m_AdminMinimumLevel; public NexUserApiRouter( INexUserService users, @@ -605,7 +614,8 @@ namespace NexVerse.Server.Api INexAuditStore auditStore, INexIdempotencyStore idempotencyStore, int idempotencyTtlSeconds, - INexApiKeyStore apiKeys) + INexApiKeyStore apiKeys, + int adminMinimumLevel) { m_Users = users ?? throw new ArgumentNullException(nameof(users)); m_Authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); @@ -617,6 +627,7 @@ namespace NexVerse.Server.Api m_IdempotencyStore = idempotencyStore; m_IdempotencyTtlSeconds = Math.Max(60, idempotencyTtlSeconds); m_ApiKeys = apiKeys; + m_AdminMinimumLevel = adminMinimumLevel; } public void Handle(IOSHttpRequest request, IOSHttpResponse response) @@ -638,9 +649,9 @@ namespace NexVerse.Server.Api activity?.SetTag("http.request.method", request?.HttpMethod ?? string.Empty); activity?.SetTag("url.path", path); - if (string.Equals(path, "/api/v1/auth/token", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(path, "/api/v1/auth/session", StringComparison.OrdinalIgnoreCase)) { - HandleTokenExchange(request, response); + HandleNativeSessionLogin(request, response); return; } @@ -953,62 +964,169 @@ namespace NexVerse.Server.Api "GET, POST or PATCH is required."); } - private void HandleTokenExchange(IOSHttpRequest request, IOSHttpResponse response) + private void HandleNativeSessionLogin( + IOSHttpRequest request, + IOSHttpResponse response) { - if (!RequireMethod(request, response, "POST")) + if (!RequireMethod( + request, + response, + "POST")) + { return; + } if (m_Tokens == null) { - WriteError(response, HttpStatusCode.ServiceUnavailable, "native_tokens_disabled", "NexVerse native access-token issuance is disabled."); + WriteError( + response, + HttpStatusCode.ServiceUnavailable, + "native_tokens_disabled", + "NexVerse native access-token issuance is disabled."); return; } - if (!m_Authenticator.TryAuthenticateLegacyExchange( + if (!TryReadJson( request, - out NexPrincipal principal, - out UserAccount account, - out int statusCode, - out string error)) + response, + out JsonDocument document)) { - response.AddHeader("WWW-Authenticate", "Bearer"); - WriteError(response, (HttpStatusCode)statusCode, error, "Legacy token exchange authentication failed."); return; } - string accessToken = m_Tokens.Issue( - principal.Subject, - principal.Scopes, - account.NexVerseStateChanged); - - string correlationId = AddCorrelation(response); - m_Audit.Record(new NexAuditEvent( - principal.Subject, - "auth.token.issue", - principal.Subject, - correlationId, - new Dictionary - { - ["scope"] = string.Join(" ", principal.Scopes) - })); - - m_EventBus.Publish(new NexEvent( - "auth.token.issued", - "nexverse.world-api", - new Dictionary - { - ["principal_id"] = principal.Subject - }, - correlationId)); - - WriteJson(response, new + using (document) { - access_token = accessToken, - token_type = "Bearer", - expires_in = m_Tokens.LifetimeSeconds, - scope = string.Join(" ", principal.Scopes), - correlation_id = correlationId - }); + JsonElement root = + document.RootElement; + + string username = + GetOptionalString( + root, + "username"); + + string password = + GetOptionalString( + root, + "password"); + + if (string.IsNullOrWhiteSpace(username) || + string.IsNullOrEmpty(password) || + password.Length > 256) + { + WriteError( + response, + HttpStatusCode.BadRequest, + "invalid_request", + "username and password are required."); + return; + } + + if (!NexResidentNameResolver.TryResolveLoginInput( + username, + string.Empty, + out NexResidentName residentName)) + { + WriteError( + response, + HttpStatusCode.Unauthorized, + "invalid_credentials", + "Resident credentials are invalid."); + return; + } + + NexUserRecord user = + m_Users.GetByName( + residentName.FirstName, + residentName.LastName); + + if (user == null || + !m_Users.VerifyPassword( + user.PrincipalId, + password)) + { + WriteError( + response, + HttpStatusCode.Unauthorized, + "invalid_credentials", + "Resident credentials are invalid."); + return; + } + + List scopes = + new List + { + NexScopes.UsersRead, + NexScopes.UsersWrite + }; + + if (user.UserLevel >= + m_AdminMinimumLevel) + { + scopes.Add( + NexScopes.AdminAll); + } + + string accessToken = + m_Tokens.Issue( + user.PrincipalId, + scopes, + user.AccountStateChanged); + + string correlationId = + AddCorrelation(response); + + response.AddHeader( + "Cache-Control", + "no-store"); + response.AddHeader( + "Pragma", + "no-cache"); + + m_Audit.Record( + new NexAuditEvent( + user.PrincipalId, + "auth.session.login", + user.PrincipalId, + correlationId, + new Dictionary + { + ["scope"] = + string.Join( + " ", + scopes) + })); + + m_EventBus.Publish( + new NexEvent( + "auth.session.created", + "nexverse.world-api", + new Dictionary + { + ["principal_id"] = + user.PrincipalId + }, + correlationId)); + + WriteJson( + response, + new + { + access_token = + accessToken, + token_type = + "Bearer", + expires_in = + m_Tokens.LifetimeSeconds, + scope = + string.Join( + " ", + scopes), + principal_id = + user.PrincipalId, + correlation_id = + correlationId + }); + } } private void HandleAuditSearch( diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index 68dabdd2..4d1a8e5a 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -186,14 +186,12 @@ namespace NexVerse.Server.Api } NexApiAuthenticator authenticator = new NexApiAuthenticator( - authentication, userAccounts, authorization, nativeTokens, oauthStore, apiKeyStore, - adminMinimumLevel, - tokenLifetimeSeconds); + adminMinimumLevel); OpenSimNexUserService userService = new OpenSimNexUserService( userAccounts, @@ -212,7 +210,8 @@ namespace NexVerse.Server.Api auditStore, idempotencyStore, idempotencyTtlSeconds, - apiKeyStore); + apiKeyStore, + adminMinimumLevel); if (nativeTokens != null && oauthStore != null && oidcSigner != null) { diff --git a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs index ed2f4a2a..e1d62a4e 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs @@ -126,8 +126,8 @@ namespace NexVerse.Server.Api ["/api/v1/capabilities"] = GetOperation("NexVerse capability and compatibility levels"), ["/api/v1/openapi.json"] = GetOperation("OpenAPI document"), ["/api/v1/docs"] = GetOperation("Self-hosted searchable API documentation and live explorer"), - ["/api/v1/auth/token"] = AuthenticatedOperations( - ("post", "Exchange a legacy AuthenticationService token for a NexVerse scoped access token", null, "200")), + ["/api/v1/auth/session"] = CredentialPostOperation( + "Create a native NexVerse resident session"), ["/api/v1/auth/api-keys"] = AuthenticatedOperations( ("get", "List restricted machine API keys", "admin:*", "200"), ("post", "Create a restricted scoped machine API key", "admin:*", "201"), @@ -230,6 +230,13 @@ namespace NexVerse.Server.Api "PasswordRequest", null, "200"); + ApplyJsonContract( + paths, + "/api/v1/auth/session", + "post", + "ResidentSessionRequest", + "ResidentSessionResponse", + "200"); ApplyJsonContract( paths, "/api/v1/auth/api-keys", @@ -583,6 +590,64 @@ namespace NexVerse.Server.Api }; } + private static object CredentialPostOperation( + string summary) + { + Dictionary operation = + new Dictionary + { + ["summary"] = summary, + ["security"] = Array.Empty(), + ["responses"] = + new Dictionary + { + ["200"] = + new + { + description = + "Successful response" + }, + ["400"] = + JsonResponse( + "Invalid request", + "Error"), + ["401"] = + JsonResponse( + "Invalid resident credentials", + "Error"), + ["429"] = + JsonResponse( + "Rate limit exceeded", + "Error"), + ["503"] = + JsonResponse( + "Native token service unavailable", + "Error") + }, + ["x-nexverse-audience"] = + new[] + { + "citizen", + "admin" + }, + ["x-nexverse-purpose"] = summary, + ["x-nexverse-ai-instruction"] = + "Use this endpoint only to create a resident session from credentials explicitly supplied for that purpose. Never infer, reuse, persist or expose a password.", + ["x-nexverse-security-constraints"] = + new[] + { + "TLS or an equivalent protected transport is mandatory.", + "Send the password only in the JSON request body.", + "Never log, cache or persist the password or returned access token." + } + }; + + return new Dictionary + { + ["post"] = operation + }; + } + private static object AuthenticatedOperations( params (string method, string summary, string scope, string successCode)[] operations) { @@ -1133,6 +1198,66 @@ namespace NexVerse.Server.Api ["user_level"] = new { type = "integer" } } }, + ["ResidentSessionRequest"] = new + { + type = "object", + required = new[] + { + "username", + "password" + }, + properties = new Dictionary + { + ["username"] = new + { + type = "string", + minLength = 1, + maxLength = 129, + description = "Canonical NexVerse resident login name, for example Antonia.Porta or a single-name Resident login." + }, + ["password"] = new + { + type = "string", + minLength = 1, + maxLength = 256, + writeOnly = true + } + } + }, + ["ResidentSessionResponse"] = new + { + type = "object", + required = new[] + { + "access_token", + "token_type", + "expires_in", + "scope", + "principal_id", + "correlation_id" + }, + properties = new Dictionary + { + ["access_token"] = new + { + type = "string", + description = "Native lifecycle-bound NexVerse bearer token." + }, + ["token_type"] = new + { + type = "string", + @enum = new[] { "Bearer" } + }, + ["expires_in"] = new { type = "integer" }, + ["scope"] = new { type = "string" }, + ["principal_id"] = new + { + type = "string", + format = "uuid" + }, + ["correlation_id"] = new { type = "string" } + } + }, ["PasswordRequest"] = new { type = "object", diff --git a/doc/NexVerse/ROADMAP.md b/doc/NexVerse/ROADMAP.md index 041e3028..34073309 100644 --- a/doc/NexVerse/ROADMAP.md +++ b/doc/NexVerse/ROADMAP.md @@ -230,14 +230,15 @@ Implemented during NEXJAST: - [x] Robust loads the World API connector on the public listener. - [x] `/api/v1`, `/health`, `/version`, `/capabilities` and `/openapi.json` implemented. - [x] World API correlation IDs, API version headers, audit events and NexBus request events implemented. -- [x] interim AuthenticationService bearer-token validation connected (privileged routes remain disabled by default on plaintext HTTP). +- [x] interim AuthenticationService bearer-token bootstrap retired from World API authentication after native resident-session cutover. - [x] user API phase 1 connected: self/account lookup, admin search, account creation/provisioning, account profile update, password set/reset and UserLevel update. - [x] account creation requires an explicit selectable Home/Start region and initializes both Home and initial Last/Start position. - [x] complete current OSSL function surface enabled through an explicit NexVerse permission profile. - [x] CI rejects newly added threat-checked OSSL functions without an explicit enabled policy rule. - [x] Hypergrid grid-identity URI normalization handles default ports, trailing slashes and host casing consistently. -- [ ] NexVerse-native OIDC/scoped token issuance fully replaces the interim authentication bridge. -- [x] native HMAC-signed scoped access-token foundation and legacy-token exchange implemented; native tokens are lifecycle-stamp bound. +- [x] NexVerse-native resident sessions plus OIDC/scoped token issuance fully replace the interim AuthenticationService bearer-token bridge. +- [x] native HMAC-signed scoped access-token foundation implemented; native tokens are lifecycle-stamp bound. +- [x] native resident session login verifies credentials internally and issues NexVerse tokens without exposing legacy AuthenticationService tokens. - [x] persistent OAuth2/OIDC core implemented: Authorization Code + PKCE S256, refresh-token rotation/revocation, ES256 ID tokens/JWKS, persistent client registration and service-account client_credentials. - [x] password, account-state and explicit session revocation invalidate resident access/refresh sessions. - [x] complete user lifecycle API connected: create, update, soft-delete/deactivate, lock/unlock, ban/unban and password workflow. diff --git a/doc/NexVerse/WORLD_API.md b/doc/NexVerse/WORLD_API.md index fd0173cb..db66d8dd 100644 --- a/doc/NexVerse/WORLD_API.md +++ b/doc/NexVerse/WORLD_API.md @@ -93,43 +93,36 @@ Supported administrator states are `active`, `locked`, `banned` and `deactivated The API does not access the database directly. It uses a NexVerse `INexUserService` abstraction backed by the existing `IUserAccountService` while the identity subsystem is being migrated. -## NexVerse native access-token transition +## NexVerse native resident sessions and access tokens -NexVerse now has a native signed/scoped access-token foundation. Native tokens use an HMAC-SHA256 signed JWT-shaped format containing issuer, audience, subject, issue/expiry timestamps, token ID, scopes and an account security stamp. +NexVerse now uses native signed/scoped access tokens for World API resident authentication. Native tokens use an HMAC-SHA256 signed JWT-shaped format containing issuer, audience, subject, issue/expiry timestamps, token ID, scopes and an account security stamp. -When native tokens are enabled, an existing AuthenticationService bearer token can be exchanged at: +Resident bootstrap is native: -`POST /api/v1/auth/token` +`POST /api/v1/auth/session` -The exchange request uses the transitional headers: +Request body: -```text -Authorization: Bearer -X-NexVerse-Principal: +```json +{ + "username": "Antonia.Porta", + "password": "resident-password" +} ``` -The response returns a NexVerse `access_token`, `token_type=Bearer`, `expires_in` and the granted scope set. Subsequent World API requests using the NexVerse token no longer require `X-NexVerse-Principal`. +Single-name residents may use their normal Resident-compatible login name. The server resolves the canonical NexVerse resident identity, verifies the password internally against the existing credential store, and directly issues a NexVerse access token. It does not mint or expose an AuthenticationService bearer token during this flow. + +The response contains `access_token`, `token_type=Bearer`, `expires_in`, the granted scope set, the resident principal UUID and the request correlation ID. Token responses use `Cache-Control: no-store`. + +The retired bootstrap endpoint `POST /api/v1/auth/token` and the transitional `X-NexVerse-Principal` header are no longer accepted by the World API. Existing AuthenticationService bearer tokens are not valid World API credentials. Native token issuance is disabled by default and requires `EnableNativeTokens=true` plus a protected signing key of at least 32 UTF-8 bytes. The signing key must not be committed to the repository. -A native token is bound to the account lifecycle security stamp. Lock, ban, deactivation, unlock, unban and reactivation advance that stamp monotonically, invalidating tokens issued against an older account state. +A native token is bound to the account lifecycle security stamp. Lock, ban, deactivation, unlock, unban, reactivation, password change and explicit session revocation advance that stamp and invalidate older resident sessions. -### Interim bootstrap bridge +Administrators at or above `AdminMinimumUserLevel` receive the NexVerse `admin:*` scope. The default minimum is 200. Normal resident bootstrap sessions receive `users:read` and `users:write`. -The current transition layer still accepts an existing AuthenticationService token as a bootstrap mechanism while full NexVerse OIDC/client authorization is developed. - -Required request headers when privileged endpoints are enabled: - -```text -Authorization: Bearer -X-NexVerse-Principal: -``` - -A legacy bootstrap token is verified by `IAuthenticationService.Verify`. A native NexVerse token is verified cryptographically and its subject is loaded from `IUserAccountService`. Tokens belonging to locked, banned, deactivated or incomplete-provisioning accounts are rejected. Native tokens with a stale account security stamp are also rejected. - -For the initial bridge, an account at or above `AdminMinimumUserLevel` receives the NexVerse `admin:*` scope. The default minimum is 200. - -This is not the final NexVerse identity model. The roadmap target remains a NexVerse-native scoped token/OIDC-style authentication system. +World API bearer authentication now accepts only native NexVerse access tokens. Restricted machine integrations use `X-NexVerse-Api-Key`; OAuth service clients use `client_credentials`. ## Transport safety @@ -144,7 +137,7 @@ This is intentional because the current production Robust endpoint is plain HTTP Bearer tokens must not be enabled on a public plaintext transport. Privileged endpoints should only be enabled once the API is protected by TLS or an equivalent trusted/private transport. -No password-login endpoint is exposed by the World API over HTTP. +The resident session endpoint carries a password and therefore must never be exposed over public plaintext HTTP. It is available only with privileged World API endpoints and must be protected by TLS or an equivalent trusted transport. ## Architecture @@ -161,8 +154,8 @@ The current foundation provides: - correlation IDs; - API version response headers; - citizen/admin AI metadata; -- interim AuthenticationService token validation; -- initial authenticated user-management routes. +- native resident session authentication without a legacy bearer-token bridge; +- authenticated user-management routes. ## Audit and events @@ -209,12 +202,9 @@ Selecting a free cell in the raster will prefill the create-region form. Region- ## Next API work -The core user lifecycle is now connected. The next identity/API work is: +The core user lifecycle, persistent audit history, native session revocation, OAuth/OIDC client flows, API keys and request rate limiting are connected. -- durable account audit/history queries; -- password-change/manual session revocation for already issued native tokens; -- full OIDC authorization/client flows and persistent client registration; -- rate limiting and production security controls. +The next identity/API work is the browser-facing authorization/login and consent surface, followed by production external OpenTelemetry collection and the Region Control Plane. ## OAuth 2.0 / OpenID Connect identity foundation @@ -244,7 +234,7 @@ OIDC ID tokens are signed with ES256 using a persistent P-256 key. The private k Resident password changes, account lock/ban/deactivation and explicit session revocation advance the resident security stamp. Existing native access tokens therefore fail validation and all persisted refresh sessions for the resident are revoked. -The authorization endpoint currently expects an already authenticated NexVerse/legacy bearer session. A browser consent/login surface and complete replacement of the legacy bootstrap path remain separate roadmap work. +The authorization endpoint now accepts an already authenticated native NexVerse resident bearer session. Legacy AuthenticationService bearer tokens are rejected. A browser-facing login/consent surface remains separate roadmap work. ## API rate limiting and request metadata @@ -402,6 +392,7 @@ Current schema coverage includes: - standardized `Error` and `Pagination`; - `User`, `UserCreateRequest`, `UserCreateResponse` and profile/lifecycle request bodies; +- `ResidentSessionRequest` and `ResidentSessionResponse` for native resident login; - `Region` and `RegionSearchResponse`; - `ApiKey`, API-key create/state requests and list/create responses; - `AuditEvent` and paginated audit search responses. diff --git a/tools/ci/verify_native_auth_cutover.py b/tools/ci/verify_native_auth_cutover.py new file mode 100644 index 00000000..79076582 --- /dev/null +++ b/tools/ci/verify_native_auth_cutover.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Reject regressions back to the legacy World API AuthenticationService bearer bridge.""" + +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[2] + +user_api = (ROOT / "NexVerse/Server/Api/NexVerseUserApi.cs").read_text(encoding="utf-8-sig") +connector = (ROOT / "NexVerse/Server/Api/NexVerseWorldApiConnector.cs").read_text(encoding="utf-8-sig") +handlers = (ROOT / "NexVerse/Server/Api/NexVerseWorldApiHandlers.cs").read_text(encoding="utf-8-sig") +identity = (ROOT / "NexVerse/Core/Identity/INexUserService.cs").read_text(encoding="utf-8-sig") +roadmap = (ROOT / "doc/NexVerse/ROADMAP.md").read_text(encoding="utf-8-sig") + +errors = [] + +required_user_api = ( + '"/api/v1/auth/session"', + "HandleNativeSessionLogin", + "VerifyPassword(", + '"auth.session.login"', + '"auth.session.created"', + '"Cache-Control",', + '"no-store"', +) +for token in required_user_api: + if token not in user_api: + errors.append(f"NexVerseUserApi.cs missing native auth cutover marker: {token}") + +for forbidden in ( + '"/api/v1/auth/token"', + "TryAuthenticateLegacyExchange", + "TryAuthenticateLegacyToken", + '"X-NexVerse-Principal"', +): + if forbidden in user_api: + errors.append(f"NexVerseUserApi.cs still contains retired legacy auth bridge marker: {forbidden}") + +if "IAuthenticationService authentication," in connector.split("NexApiAuthenticator authenticator = new NexApiAuthenticator(", 1)[-1].split(");", 1)[0]: + errors.append("NexApiAuthenticator is still wired to IAuthenticationService") + +for token in ( + '["/api/v1/auth/session"]', + '"ResidentSessionRequest"', + '"ResidentSessionResponse"', + "CredentialPostOperation", +): + if token not in handlers: + errors.append(f"OpenAPI contract missing native resident session marker: {token}") + +if '["/api/v1/auth/token"]' in handlers: + errors.append("OpenAPI still advertises retired legacy token exchange") + +if "bool VerifyPassword(string principalId, string password);" not in identity: + errors.append("INexUserService does not expose password verification for native session bootstrap") + +if "[x] NexVerse-native resident sessions plus OIDC/scoped token issuance fully replace" not in roadmap: + errors.append("Roadmap does not mark native auth cutover complete") + +if errors: + for error in errors: + print("::error::" + error) + sys.exit(1) + +print("NexVerse native auth cutover verified: resident session + native bearer/OIDC/API-key only; legacy bearer bridge retired.")