From e3dd98d66839a92980a86c35b26de88c2b11e08f Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 16 Nov 2026 04:13:30 -0500 Subject: [PATCH 1/6] Revoke the session's authorizations at end-session --- docs/planning/backend-technical-spec.md | 4 +- .../Api/Account/MemberPageModels.cs | 13 +- .../Identity/CmsSignInManager.cs | 24 ++- .../Identity/Members/MemberConnect.cs | 7 + .../Identity/Members/MemberSignInManager.cs | 11 +- .../Identity/Oidc/ConnectEndpoints.cs | 17 ++- .../Identity/Oidc/UserSessions.cs | 58 +++++++ src/FluentCMS.Testing/OAuthFlows.cs | 2 + .../Identity/HostedPagesTests.Logout.cs | 144 ++++++++++++++++++ .../Members/MemberPagesTests.cs | 27 ++++ 10 files changed, 287 insertions(+), 20 deletions(-) create mode 100644 tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs diff --git a/docs/planning/backend-technical-spec.md b/docs/planning/backend-technical-spec.md index 77e5ff5eb..35dacd263 100644 --- a/docs/planning/backend-technical-spec.md +++ b/docs/planning/backend-technical-spec.md @@ -802,7 +802,7 @@ Rows 4.1, 4.2, 4.9 to 4.11, 4.13, 4.15, 4.16, 2.12, 2.13; decisions 7, 30, 33. **Endpoints.** OpenIddict defaults: `/connect/authorize`, `/connect/token`, `/connect/userinfo`, `/connect/introspect`, `/connect/revoke`, `/connect/logout`, `/.well-known/openid-configuration`. Flows: Authorization Code with PKCE for public clients (admin, MCP clients, CLI), rotating refresh tokens, client credentials for service accounts. Access tokens are JWTs signed with keys from a configured certificate or, when none is configured, a generated key persisted in `cms_signing_key` through Data Protection. Audiences: `fluentcms:management` for admins and keys, `fluentcms:members` for members. -**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` of the user the cookie belongs to; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. +**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` of the user the cookie belongs to; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). Ending a sign-in also ends what was issued in it ([#3198](https://github.com/fluentcms/FluentCMS/issues/3198)): every new cookie carries the id of its server session in its properties (`.fcms.server_session`), which its renewals keep as they keep the time of the sign-in, and the authorize endpoint issues the code of a client without a consent step under an ad-hoc authorization marked with that id (the property `fcms_server_session`). The logout revokes, through `UserSessions`, every valid authorization of the signed-in user marked with the session it ends, with its tokens, whichever clients of the pool signed in through it, so its refresh tokens are refused at once and its access tokens from the next request on, since the bearer scheme checks the token and its authorization on each request. It revokes nothing where it ends no sign-in: a logout that is not confirmed and only goes to the logout page, a confirmation the user does not give, and a request without the cookie, with a valid hint included. The user's other sessions, in another browser or on another device, stay, as does the consent of a third-party client, a permanent authorization of no server session that ends on the account page; a cookie from before sessions were marked ends no authorization, and its tokens last as before. A sign-out writes no activity row, and the revocation adds none. `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. **Protected resources as built** ([#2977](https://github.com/fluentcms/FluentCMS/issues/2977)). A plugin's group mapped with `MapProtectedResource(prefix, options)` (`FluentCMS.Plugins.Abstractions`) is an OAuth protected resource of its own (RFC 9728), which is how the MCP plugin maps `/mcp` (5.4). The group gets what `MapGroup` gives (4.13), with four differences. Its operations enter with the origin the plugin names, `Api` or `Mcp`. It takes the Management rate limit and CORS policy, since it takes writes. No endpoint of it opts out of the signed-in caller with `AllowAnonymous()`. And a bearer token needs the scope the plugin names, one of the scopes that say which surface a token is for, which is `mcp` alone today. An API key holds no OAuth scope and is taken by its class, which the evaluator reads; a preview token carries the kind of the principal that minted it, a key's included, so it is told apart by its entry claim and refused as a token without the scope. A request without credentials is a 401 (`FCMS3102`) with `WWW-Authenticate: Bearer resource_metadata="{metadata URL}", scope="{scope}"`, one whose credentials are refused carries `error="invalid_token"` as well, and a token without the scope is a 403 (`FCMS3103`) with `Bearer error="insufficient_scope", scope="{scope}", resource_metadata="{metadata URL}"`. Both come before the per-site gate, as on any group of a plugin. Core serves the metadata, so a plugin still maps nothing under `/.well-known` (`FCMS1524`): `GET /.well-known/oauth-protected-resource{prefix}` answers `{ resource, authorization_servers, scopes_supported, bearer_methods_supported, resource_name }` to anyone, where `resource` is the public URL of the group, `authorization_servers` holds the issuer exactly as the discovery document names it, `scopes_supported` the scope of the resource and `bearer_methods_supported` `header`. `GET /.well-known/oauth-protected-resource`, the document a client tries when it does not know the path of the resource, answers the same while the host has one protected resource and 404 (`FCMS3104`) once it has several, since it could describe one of them only. The documents are endpoints of the `WellKnown` group, so they take its CORS origins and count as the `connect` surface, and they are not gated per site, since an anonymous caller learns nothing of where a plugin is off. The URLs are built from the public origin and the path base (4.15), and from the request when no origin is set, as the issuer is. Under a path base the documents are under it, where RFC 9728 would put the well-known segment before it; the challenge names the URL, which is what a client follows. The authorization server takes the `resource` parameter of RFC 8707 on the authorization request and on the token request when every value is the public URL of a protected resource of the host, compared as an absolute URI with the path as written, and refuses any other with `invalid_target`; like every refusal while the authorization request is checked, it is shown on the error page rather than sent to the client. OpenIddict's own check holds the resources in a list fixed in its options, which cannot name a URL that follows the request, so it is off (`DisableResourceValidation`) and a handler of core's stands in its place. The resource permissions of clients are off too (`IgnoreResourcePermissions`), because the parameter grants nothing: the audience of a token stays `fluentcms:management`, and the scope of the resource, which a client does need a permission for, is what holds a token to it. A token with the `mcp` scope alone manages through `Origin.Mcp` only (4.8) and is refused by the Management API (403). The consent page describes `mcp` as reading and changing content as an AI agent or tool, as far as the user's roles allow. A scope that is not one of those, an origin other than `Api` or `Mcp`, and a prefix mapped as a protected resource twice stop the host with `FCMS1527`; a prefix under a group of core or with a route parameter anywhere in it is `FCMS1524`. Code `FCMS1527`. @@ -846,7 +846,7 @@ Rows 4.1, 4.2, 4.9 to 4.11, 4.13, 4.15, 4.16, 2.12, 2.13; decisions 7, 30, 33. *Groups and permissions.* `cms_member_group (id, name, description, role_id, created_at)` and `cms_member_group_member (group_id, member_id)`. A group has a name of 1 to 64 lower-case letters, digits, `-` and `_`, unique in the instance, so that it is one name on every database and one word of the principal's groups, and is bound to one role, of the instance or of a site; a group always has a role, and one that only names its members for a row rule may be bound to a role without grants. The membership of such a group is managed with `members.manage` alone, in both directions (4.10), so a row rule that must hold against those callers, a negated one above all, reads a group whose role holds a grant they lack. A member holds the Public role of the site of the request, the site's own or else the seeded one as for a visitor, the built-in Member role, and the roles of its groups. The evaluator reads them with their stamps, and the names of the groups, in one query on every request, so a change holds from the next request; a member that is deactivated or deleted holds nothing, not even what a visitor reads, and nothing is taken from the token, whose roles or groups claim is never read. The principal a row rule sees carries the group names in the claim `fcms_groups`, and `Principal.IsInGroup(name)` (`FluentCMS.Content`, in the SDK) reads it, as in `ctx => perk => perk.Tier == (ctx.Principal.IsInGroup("gold") ? "gold" : "standard")`. Only that principal carries them, and `IsInGroup` throws on any other (4.8). A member's token has no scope that manages, so its grants give it published reads and nothing else, a group bound to a role with `*` included (4.8). A role is not deleted while a group is bound to it (`FCMS3044`, 4.10); the foreign key cascades, so a site that is deleted takes the groups bound to its roles along, as it does the API keys bound to them. -*Clients and tokens.* A client of `cms.Clients.Applications` names its pool with `Pool`, `Admins` (the default) or `Members`. A client of the member pool asks for `openid`, `profile`, `email` and `offline_access` only, names no roles, has no consent step, needs redirect URIs or `AllowDirectLogin`, and is not the admin application's client (`FCMS3021`); it may have a secret, and is never a service account: it holds neither the client credentials grant nor introspection. The authorize endpoint answers such a client from the member cookie and never from the admin's, challenging to `/account/members/login`, with `prompt`, `max_age` and the absolute session lifetime as for an admin user. Its tokens carry the audience `fluentcms:members`, `fcms_kind` `Member`, `sub`, `name` (the display name, or the address) and the scopes asked for among those four, whatever else was asked; they carry no roles and no groups. The token endpoint reads the member again for a code or a refresh token and refuses one that is deactivated, deleted, locked out or whose security stamp changed (`invalid_grant`). A code or refresh token says whose it is by its kind and is redeemed only through a client of the pool it was issued in, so a client the configuration moves to the other pool redeems nothing. The bearer scheme accepts both audiences, and a member's token is kept out of the Management API, of drafts and of `/mcp` by its scopes: it never holds `management`, `draft` or `mcp`. `/connect/userinfo` answers a member's token from the member. `/connect/logout` ends the sign-in of the pool of the client the request names, by its `client_id` or the audience of its `id_token_hint`, and the admin's when it names none; the two logout pages share an antiforgery token, so the member page marks its form (`fcms_pool`), neither page passes the mark on from a link, and the endpoint takes a confirmation only from the page of the pool it signs out. Deactivating or deleting a member, a reset and a change of password revoke its authorizations and every token of its subject (`MemberSessions`), so an access token stops on the next request, one of a direct login without a session included. `UserSessions` lists and ends a member's sessions for the Management API, since a member's id is the subject of its tokens. +*Clients and tokens.* A client of `cms.Clients.Applications` names its pool with `Pool`, `Admins` (the default) or `Members`. A client of the member pool asks for `openid`, `profile`, `email` and `offline_access` only, names no roles, has no consent step, needs redirect URIs or `AllowDirectLogin`, and is not the admin application's client (`FCMS3021`); it may have a secret, and is never a service account: it holds neither the client credentials grant nor introspection. The authorize endpoint answers such a client from the member cookie and never from the admin's, challenging to `/account/members/login`, with `prompt`, `max_age` and the absolute session lifetime as for an admin user. Its tokens carry the audience `fluentcms:members`, `fcms_kind` `Member`, `sub`, `name` (the display name, or the address) and the scopes asked for among those four, whatever else was asked; they carry no roles and no groups. The token endpoint reads the member again for a code or a refresh token and refuses one that is deactivated, deleted, locked out or whose security stamp changed (`invalid_grant`). A code or refresh token says whose it is by its kind and is redeemed only through a client of the pool it was issued in, so a client the configuration moves to the other pool redeems nothing. The bearer scheme accepts both audiences, and a member's token is kept out of the Management API, of drafts and of `/mcp` by its scopes: it never holds `management`, `draft` or `mcp`. `/connect/userinfo` answers a member's token from the member. `/connect/logout` ends the sign-in of the pool of the client the request names, by its `client_id` or the audience of its `id_token_hint`, and the admin's when it names none; the two logout pages share an antiforgery token, so the member page marks its form (`fcms_pool`), neither page passes the mark on from a link, and the endpoint takes a confirmation only from the page of the pool it signs out. The member logout page, which ends a member's sign-in itself when no client sent the member there, revokes the authorizations of its server session as the endpoint does. Deactivating or deleting a member, a reset and a change of password revoke its authorizations and every token of its subject (`MemberSessions`), so an access token stops on the next request, one of a direct login without a session included. `UserSessions` lists and ends a member's sessions for the Management API, since a member's id is the subject of its tokens. *Direct login* (Q4). `grant_type=member_password` with `username`, `password` and `client_id` at `/connect/token`, a custom grant of OpenIddict, for a client of the member pool with `AllowDirectLogin` while `cms.Members.AllowDirectLogin` is on; both are off by default. Every refusal is `invalid_grant` with one description: the option off, a client without the flag, an unknown address, a wrong password, an address that is not verified, a member that is deactivated or locked out. The reason is in the log (event 9075, with the client and the client address, never the address typed or the password), and an address or a password that was refused is a `member.login_failed` activity row. A wrong password counts towards the lockout, and the hash runs for an unknown address and for a member that may not sign in, as on the login page. Every client of the member pool holds the grant's permission, so that the endpoint answers; a client of the admin pool does not, and OpenIddict refuses it (`unauthorized_client`). The discovery document names the grant only while the option is on, and the startup report lists `member-direct-login` in Production as the less secure way in (4.15). diff --git a/src/FluentCMS.Core/Api/Account/MemberPageModels.cs b/src/FluentCMS.Core/Api/Account/MemberPageModels.cs index 29f677188..feffa1fe6 100644 --- a/src/FluentCMS.Core/Api/Account/MemberPageModels.cs +++ b/src/FluentCMS.Core/Api/Account/MemberPageModels.cs @@ -1,6 +1,7 @@ using System.ComponentModel.DataAnnotations; using FluentCMS.Core.Identity; using FluentCMS.Core.Identity.Members; +using FluentCMS.Core.Identity.Oidc; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -121,7 +122,8 @@ public sealed class MemberLoginInput // Asks before signing out. With the request of a client, which /connect/logout sent here, the form posts it back there // with an antiforgery token and the mark of this page, so that the endpoint ends the member's sign-in and never the admin -// user's. Without one, the page ends the member's sign-in itself. There is no sign-out by GET. +// user's. Without one, the page ends the member's sign-in itself, with the authorizations of its server session, as the +// endpoint does. There is no sign-out by GET. public sealed class MemberLogoutModel : MemberPageModel { public string? Email { get; private set; } @@ -142,7 +144,14 @@ public async Task OnGetAsync() public async Task OnPostAsync() { - await Service().SignOutAsync(); + var signIn = Service(); + var cookie = await HttpContext.AuthenticateAsync(MemberAuthentication.CookieScheme); + if (cookie.Succeeded) + { + await Service().EndAsync(signIn.UserManager.GetUserId(cookie.Principal), cookie.Properties, CancellationToken.None); + } + + await signIn.SignOutAsync(); return RedirectToPage(); } } diff --git a/src/FluentCMS.Core/Identity/CmsSignInManager.cs b/src/FluentCMS.Core/Identity/CmsSignInManager.cs index 25a3e773b..c583e0335 100644 --- a/src/FluentCMS.Core/Identity/CmsSignInManager.cs +++ b/src/FluentCMS.Core/Identity/CmsSignInManager.cs @@ -32,6 +32,10 @@ internal sealed class CmsSignInManager( // issue time: prompt=login, max_age and the absolute session lifetime read it. internal const string SignedInAtItem = ".fcms.signed_in_at"; + // The id of the server session, kept in the cookie's properties in the same way: the authorizations issued in it carry + // it, so that the logout of that session ends them (#3198). A cookie from before has none. + internal const string ServerSessionItem = ".fcms.server_session"; + public static DateTimeOffset? SignedInAt(AuthenticationProperties properties) { ArgumentNullException.ThrowIfNull(properties); @@ -41,6 +45,20 @@ internal sealed class CmsSignInManager( : properties.IssuedUtc; } + public static string? ServerSession(AuthenticationProperties properties) + { + ArgumentNullException.ThrowIfNull(properties); + + return properties.Items.TryGetValue(ServerSessionItem, out var value) && !string.IsNullOrEmpty(value) ? value : null; + } + + // Marks a new sign-in with its time and the id of its server session, unless the properties are a renewal's. + internal static void MarkSignIn(AuthenticationProperties properties, TimeProvider time) + { + properties.Items.TryAdd(SignedInAtItem, time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)); + properties.Items.TryAdd(ServerSessionItem, Guid.NewGuid().ToString("N")); + } + public override async Task CanSignInAsync(CmsUser user) { ArgumentNullException.ThrowIfNull(user); @@ -114,11 +132,7 @@ public override async Task CheckPasswordSignInAsync(CmsUser user, public override Task SignInWithClaimsAsync(CmsUser user, AuthenticationProperties? authenticationProperties, IEnumerable additionalClaims) { var properties = authenticationProperties ?? new AuthenticationProperties(); - if (!properties.Items.ContainsKey(SignedInAtItem)) - { - properties.Items[SignedInAtItem] = time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); - } - + MarkSignIn(properties, time); return base.SignInWithClaimsAsync(user, properties, additionalClaims); } diff --git a/src/FluentCMS.Core/Identity/Members/MemberConnect.cs b/src/FluentCMS.Core/Identity/Members/MemberConnect.cs index 26ba5cff5..aa266def1 100644 --- a/src/FluentCMS.Core/Identity/Members/MemberConnect.cs +++ b/src/FluentCMS.Core/Identity/Members/MemberConnect.cs @@ -67,6 +67,13 @@ public static async Task AuthorizeAsync(HttpContext context, OpenIddict .SetClaim(Claims.AuthenticationTime, signedInAt.ToUnixTimeSeconds()) .SetClaim(TokenClaims.SessionStart, now.ToUnixTimeSeconds()); TokenClaims.ForMember(identity, member, await signIn.UserManager.GetSecurityStampAsync(member), request.GetScopes(), methods); + if (CmsSignInManager.ServerSession(cookie.Properties!) is { } serverSession + && await context.RequestServices.GetRequiredService().FindByClientIdAsync(request.ClientId!, context.RequestAborted) is { } application) + { + identity.SetAuthorizationId(await context.RequestServices.GetRequiredService() + .BeginAsync(new ClaimsPrincipal(identity), application, serverSession, context.RequestAborted)); + } + return Results.SignIn(new ClaimsPrincipal(identity), properties: null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); } diff --git a/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs b/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs index 1125ff210..5d2689965 100644 --- a/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs +++ b/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs @@ -122,16 +122,13 @@ public override async Task CheckPasswordSignInAsync(CmsMember user return await base.CheckPasswordSignInAsync(user, password, lockoutOnFailure); } - // Every sign-in that makes a new cookie comes here. The time of the sign-in is kept in the cookie's properties, as - // for an admin user: prompt=login, max_age and the absolute session lifetime read it. + // Every sign-in that makes a new cookie comes here. The time of the sign-in and the id of its server session are kept + // in the cookie's properties, as for an admin user: prompt=login, max_age and the absolute session lifetime read the + // time, and the logout ends the authorizations of the session. public override Task SignInWithClaimsAsync(CmsMember user, AuthenticationProperties? authenticationProperties, IEnumerable additionalClaims) { var properties = authenticationProperties ?? new AuthenticationProperties(); - if (!properties.Items.ContainsKey(CmsSignInManager.SignedInAtItem)) - { - properties.Items[CmsSignInManager.SignedInAtItem] = _time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); - } - + CmsSignInManager.MarkSignIn(properties, _time); return base.SignInWithClaimsAsync(user, properties, additionalClaims); } diff --git a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs index cb2eb9008..ec40702f4 100644 --- a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs +++ b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs @@ -176,6 +176,11 @@ private static async Task AuthorizeAsync(HttpContext context) identity.SetAuthorizationId(await context.RequestServices.GetRequiredService().GetIdAsync(consent, context.RequestAborted)); } + else if (CmsSignInManager.ServerSession(cookie.Properties!) is { } serverSession) + { + identity.SetAuthorizationId(await context.RequestServices.GetRequiredService() + .BeginAsync(new ClaimsPrincipal(identity), application, serverSession, context.RequestAborted)); + } return Results.SignIn(new ClaimsPrincipal(identity), properties: null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); } @@ -325,6 +330,7 @@ private static async Task UserInfoAsync(HttpContext context) // or to the logout page. The user confirms on the logout page, whose form posts back with an antiforgery token, or the // client sends a valid id_token_hint of the signed-in user. Anything else, a cross-site POST included, goes to the logout // page, which asks. A request without the sign-in cookie has no sign-in to end, so it sends no expiring cookie either. + // Ending a sign-in revokes the authorizations issued in its server session, with their tokens, and no others. // The client the request names, by its client_id or by the audience of its hint, says whose sign-in ends: a client of // the member pool ends the member's on the member pages, and any other request the admin user's, so that neither // signs the other out. @@ -349,6 +355,8 @@ private static async Task LogoutAsync(HttpContext context) if (cookie.Succeeded) { + // A logout the browser stops waiting for still ends the authorizations of the session. + await context.RequestServices.GetRequiredService().EndAsync(SignedInUserId(context, cookie, members), cookie.Properties!, CancellationToken.None); await context.SignOutAsync(scheme); } @@ -411,12 +419,13 @@ private static bool HintsSignedInUser(HttpContext context, AuthenticateResult hi return HttpMethods.IsGet(context.Request.Method); } - var signedIn = members - ? context.RequestServices.GetRequiredService().GetUserId(cookie.Principal) - : context.RequestServices.GetRequiredService>().GetUserId(cookie.Principal); - return signedIn == subject; + return SignedInUserId(context, cookie, members) == subject; } + private static string? SignedInUserId(HttpContext context, AuthenticateResult cookie, bool members) => members + ? context.RequestServices.GetRequiredService().GetUserId(cookie.Principal!) + : context.RequestServices.GetRequiredService>().GetUserId(cookie.Principal!); + // A new sign-in answers prompt=login and max_age, so the request it comes back with no longer asks for one. internal static IEnumerable> WithoutReauthentication(List> parameters) { diff --git a/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs b/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs index 30ee023b3..a7c4ba9ce 100644 --- a/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs +++ b/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs @@ -1,3 +1,6 @@ +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication; using OpenIddict.Abstractions; using static OpenIddict.Abstractions.OpenIddictConstants; @@ -11,6 +14,61 @@ internal sealed record UserSession(Guid Id, string? ClientId, string? ClientName // every token issued under it, so its refresh token is refused at once, and so is an access token on the next request. internal sealed class UserSessions(IOpenIddictAuthorizationManager authorizations, IOpenIddictApplicationManager applications, IOpenIddictTokenManager tokens, TimeProvider time) { + // The property of an authorization that names the server session, the sign-in cookie, it was issued in. + public const string ServerSessionProperty = "fcms_server_session"; + + // The ad-hoc authorization that OpenIddict would make for a code of the client, marked with the server session the + // user signed in with, so that the logout of that session finds it. Returns its id. + public async Task BeginAsync(ClaimsPrincipal principal, object application, string serverSession, CancellationToken cancellationToken = default) + { + var descriptor = new OpenIddictAuthorizationDescriptor + { + ApplicationId = await applications.GetIdAsync(application, cancellationToken), + CreationDate = time.GetUtcNow(), + Principal = principal, + Status = Statuses.Valid, + Subject = principal.GetClaim(Claims.Subject), + Type = AuthorizationTypes.AdHoc, + }; + descriptor.Scopes.UnionWith(principal.GetScopes()); + descriptor.Properties[ServerSessionProperty] = JsonSerializer.SerializeToElement(serverSession); + + var authorization = await authorizations.CreateAsync(descriptor, cancellationToken); + return await authorizations.GetIdAsync(authorization, cancellationToken) + ?? throw new InvalidOperationException("The authorization was stored without an id."); + } + + // The logout of a server session, the cookie of the signed-in user whose id is given: every valid authorization of + // the user issued in it, with its tokens. The user's other sessions, and a consent, which is no session's, stay. A + // cookie from before sessions were marked ends nothing here. + public async Task EndAsync(string? userId, AuthenticationProperties cookie, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(cookie); + + if (CmsSignInManager.ServerSession(cookie) is not { } serverSession || !Guid.TryParse(userId, out var user)) + { + return; + } + + List ids = []; + await foreach (var authorization in authorizations.FindBySubjectAsync(user.ToString("D"), cancellationToken)) + { + if (await authorizations.HasStatusAsync(authorization, Statuses.Valid, cancellationToken) + && (await authorizations.GetPropertiesAsync(authorization, cancellationToken)).TryGetValue(ServerSessionProperty, out var value) + && value.ValueKind == JsonValueKind.String + && value.GetString() == serverSession + && await authorizations.GetIdAsync(authorization, cancellationToken) is { } id) + { + ids.Add(id); + } + } + + foreach (var id in ids) + { + await RevokeAsync(user, Guid.Parse(id), cancellationToken); + } + } + public async Task> ListAsync(Guid userId, CancellationToken cancellationToken = default) { List sessions = []; diff --git a/src/FluentCMS.Testing/OAuthFlows.cs b/src/FluentCMS.Testing/OAuthFlows.cs index db2336d0a..73e8cb90c 100644 --- a/src/FluentCMS.Testing/OAuthFlows.cs +++ b/src/FluentCMS.Testing/OAuthFlows.cs @@ -58,6 +58,7 @@ public static async Task MemberCookieAsync(IServiceProvider services, Gu var now = provider.GetRequiredService().GetUtcNow(); var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now + options.ExpireTimeSpan }; properties.Items[CmsSignInManager.SignedInAtItem] = now.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); + properties.Items[CmsSignInManager.ServerSessionItem] = Guid.NewGuid().ToString("N"); var ticket = new AuthenticationTicket(principal, properties, MemberAuthentication.CookieScheme); return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; } @@ -74,6 +75,7 @@ public static async Task CookieAsync(IServiceProvider services, Guid use var now = provider.GetRequiredService().GetUtcNow(); var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now + options.ExpireTimeSpan }; properties.Items[CmsSignInManager.SignedInAtItem] = now.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); + properties.Items[CmsSignInManager.ServerSessionItem] = Guid.NewGuid().ToString("N"); var ticket = new AuthenticationTicket(principal, properties, IdentityConstants.ApplicationScheme); return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; } diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs new file mode 100644 index 000000000..77d07ab1d --- /dev/null +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs @@ -0,0 +1,144 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using FluentCMS.Testing; +using Shouldly; +using Xunit; + +namespace FluentCMS.Core.IntegrationTests.Identity; + +// What a logout ends of the sessions of its user (#3198). +public sealed partial class HostedPagesTests +{ + [Fact] + public async Task AConfirmedLogoutRevokesTheTokensOfItsSessionAndLeavesTheUsersOtherSessions() + { + var editor = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host); + using var otherDevice = new HostedPagesBrowser(_host, "10.1.0.9"); + await SignInAsync(browser, editor.Email); + await SignInAsync(otherDevice, editor.Email); + var tokens = await CodeFlowAsync(browser); + var other = await CodeFlowAsync(otherDevice); + + // A logout that is not confirmed, by a GET without a hint or a POST without the page's token, revokes nothing. + using (var asked = await browser.GetAsync("/connect/logout")) + { + asked.Headers.Location!.OriginalString.ShouldBe("/account/logout"); + } + + using (var forged = await browser.PostAsync("/connect/logout", new Dictionary())) + { + forged.Headers.Location!.OriginalString.ShouldBe("/account/logout"); + } + + var refreshToken = await RefreshAsync(Text(tokens, "refresh_token")); + (await MeAsync(Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.OK); + + await SignOutAsync(browser); + + (await RefusedAsync(refreshToken)).ShouldBe("invalid_grant"); + (await MeAsync(Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.Unauthorized); + (await RefreshAsync(Text(other, "refresh_token"))).ShouldNotBeNullOrEmpty(); + (await MeAsync(Text(other, "access_token"))).ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task ALogoutWithAHintRevokesOnlyWhenItEndsTheSessionOfItsCookie() + { + var editor = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host); + await SignInAsync(browser, editor.Email); + var tokens = await CodeFlowAsync(browser); + var hint = "/connect/logout?id_token_hint=" + Uri.EscapeDataString(Text(tokens, "id_token")); + + // Without the cookie there is no session to end, and the hint alone revokes nothing. + using (var stranger = new HostedPagesBrowser(_host, "10.1.0.10")) + using (var returned = await stranger.GetAsync(hint)) + { + returned.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + var refreshToken = await RefreshAsync(Text(tokens, "refresh_token")); + + using (var signedOut = await browser.GetAsync(hint)) + { + signedOut.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + browser.HasCookie(".AspNetCore.Identity.Application").ShouldBeFalse(); + (await RefusedAsync(refreshToken)).ShouldBe("invalid_grant"); + } + + [Fact] + public async Task ALogoutLeavesTheConsentOfAThirdPartyClient() + { + var editor = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host); + await SignInAsync(browser, editor.Email); + + var request = AuthorizeRequest.For(ThirdPartyClientId, ThirdPartyRedirectUri, "openid management"); + using var asked = await browser.GetAsync(request.Url); + var consent = asked.Headers.Location!.OriginalString; + var page = await browser.PageAsync(consent); + using var allowed = await browser.PostAsync(consent, page, new Dictionary { ["decision"] = "allow" }); + using var done = await browser.FollowAsync(allowed, ThirdPartyRedirectUri); + var accessToken = Text(await request.ExchangeAsync(_host, done), "access_token"); + + await SignOutAsync(browser); + + // The consent is no session's: the client keeps its token, and the next sign-in is not asked again. + (await MeAsync(accessToken)).ShouldBe(HttpStatusCode.OK); + await SignInAsync(browser, editor.Email); + using var again = await browser.GetAsync(AuthorizeRequest.For(ThirdPartyClientId, ThirdPartyRedirectUri, "openid management").Url); + again.Headers.Location!.AbsoluteUri.ShouldStartWith(ThirdPartyRedirectUri + "?code="); + } + + // The code flow of the test client in the browser's session. + private async Task CodeFlowAsync(HostedPagesBrowser browser) + { + var request = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri); + using var redirect = await browser.GetAsync(request.Url); + return await request.ExchangeAsync(_host, redirect); + } + + // The rotated refresh token. + private async Task RefreshAsync(string refreshToken) + { + using var response = await PostRefreshAsync(refreshToken); + var body = await response.Content.ReadAsStringAsync(Token); + response.StatusCode.ShouldBe(HttpStatusCode.OK, body); + using var json = JsonDocument.Parse(body); + return json.RootElement.GetProperty("refresh_token").GetString()!; + } + + private async Task RefusedAsync(string refreshToken) + { + using var response = await PostRefreshAsync(refreshToken); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Token)); + return json.RootElement.GetProperty("error").GetString(); + } + + private async Task PostRefreshAsync(string refreshToken) + { + using var client = _host.CreateSecureClient(); + using var content = new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = refreshToken, + ["client_id"] = FluentCmsTestHost.OAuthClientId, + }); + return await client.PostAsync("/connect/token", content, Token); + } + + private async Task MeAsync(string accessToken) + { + using var client = _host.CreateSecureClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); + using var response = await client.GetAsync("/api/management/v1/me", Token); + return response.StatusCode; + } + + private static string Text(JsonElement tokens, string name) => tokens.GetProperty(name).GetString()!; +} diff --git a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs index c272a0a44..0a5afbc74 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs @@ -242,6 +242,33 @@ public async Task AMembersIdTokenAsAHintEndsTheMemberSessionAndLeavesTheAdmins() browser.HasCookie(AdminCookie).ShouldBeTrue(); } + [Fact] + public async Task TheMemberLogoutPageRevokesTheRefreshTokenOfItsSession() + { + var address = await fixture.RegisterVerifiedAsync(); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.6"); + await SignInMemberAsync(browser, address); + var request = AuthorizeRequest.For(FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); + using var code = await browser.GetAsync(request.Url); + var refreshToken = (await request.ExchangeAsync(fixture.Host, code)).GetProperty("refresh_token").GetString()!; + + var page = await browser.PageAsync("/account/members/logout"); + using (var signedOut = await browser.PostAsync("/account/members/logout", page, new Dictionary())) + { + signedOut.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + using var client = fixture.Host.CreateSecureClient(); + using var content = new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = refreshToken, + ["client_id"] = FluentCmsTestHost.OAuthMemberClientId, + }); + using var refreshed = await client.PostAsync("/connect/token", content, Token); + refreshed.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + } + [Theory] [InlineData("https://evil.example/")] [InlineData("//evil.example/")] From b70c300fd63f18b90da5a1291b4787b8caa5535d Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 16 Nov 2026 04:57:36 -0500 Subject: [PATCH 2/6] End a session's authorizations wherever its sign-in ends --- docs/planning/backend-technical-spec.md | 4 +- docs/releases/1.0.0-preview.1.md | 1 + .../Api/Account/MemberPageModels.cs | 2 +- .../Identity/CmsSignInManager.cs | 37 +++- .../Identity/Members/MemberConnect.cs | 4 + .../Identity/Members/MemberSignInManager.cs | 8 +- .../Identity/Oidc/ConnectEndpoints.cs | 42 ++-- .../Identity/Oidc/TokenClaims.cs | 9 +- .../Identity/Oidc/UserSessions.cs | 13 +- .../Identity/Sso/SsoRegistration.cs | 11 +- src/FluentCMS.Testing/OAuthFlows.cs | 13 +- .../AuthorizationServerTests.Hardening.cs | 52 ++++- .../AuthorizationServerTests.Sessions.cs | 2 +- .../Identity/HostedPagesBrowser.cs | 3 + .../Identity/HostedPagesTests.Logout.cs | 180 ++++++++++++++---- .../Identity/HostedPagesTests.Sessions.cs | 7 + .../Members/MemberPagesTests.cs | 39 +++- 17 files changed, 347 insertions(+), 80 deletions(-) diff --git a/docs/planning/backend-technical-spec.md b/docs/planning/backend-technical-spec.md index 35dacd263..9f3690aea 100644 --- a/docs/planning/backend-technical-spec.md +++ b/docs/planning/backend-technical-spec.md @@ -802,7 +802,7 @@ Rows 4.1, 4.2, 4.9 to 4.11, 4.13, 4.15, 4.16, 2.12, 2.13; decisions 7, 30, 33. **Endpoints.** OpenIddict defaults: `/connect/authorize`, `/connect/token`, `/connect/userinfo`, `/connect/introspect`, `/connect/revoke`, `/connect/logout`, `/.well-known/openid-configuration`. Flows: Authorization Code with PKCE for public clients (admin, MCP clients, CLI), rotating refresh tokens, client credentials for service accounts. Access tokens are JWTs signed with keys from a configured certificate or, when none is configured, a generated key persisted in `cms_signing_key` through Data Protection. Audiences: `fluentcms:management` for admins and keys, `fluentcms:members` for members. -**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` of the user the cookie belongs to; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). Ending a sign-in also ends what was issued in it ([#3198](https://github.com/fluentcms/FluentCMS/issues/3198)): every new cookie carries the id of its server session in its properties (`.fcms.server_session`), which its renewals keep as they keep the time of the sign-in, and the authorize endpoint issues the code of a client without a consent step under an ad-hoc authorization marked with that id (the property `fcms_server_session`). The logout revokes, through `UserSessions`, every valid authorization of the signed-in user marked with the session it ends, with its tokens, whichever clients of the pool signed in through it, so its refresh tokens are refused at once and its access tokens from the next request on, since the bearer scheme checks the token and its authorization on each request. It revokes nothing where it ends no sign-in: a logout that is not confirmed and only goes to the logout page, a confirmation the user does not give, and a request without the cookie, with a valid hint included. The user's other sessions, in another browser or on another device, stay, as does the consent of a third-party client, a permanent authorization of no server session that ends on the account page; a cookie from before sessions were marked ends no authorization, and its tokens last as before. A sign-out writes no activity row, and the revocation adds none. `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. +**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` issued in the session of the cookie; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). Ending a sign-in also ends what was issued in it ([#3198](https://github.com/fluentcms/FluentCMS/issues/3198)). Every new cookie carries the id of its server session in its properties (`.fcms.server_session`), which its renewals keep as they keep the time of the sign-in; a sign-in on the login page over a live cookie of the same user keeps that id, so the browser's session goes on. The authorize endpoint issues the code of a client without a consent step under an ad-hoc authorization marked with that id (the property `fcms_server_session`), and the identity token carries it as `sid`, as RP-Initiated Logout names it. A sign-in ends, and `UserSessions` revokes every valid authorization of its user marked with its session, with its tokens, whichever clients of the pool signed in through it, at a confirmed logout or one with the session's hint, at the member logout page, at the remote sign-out of the provider it came from (admin SSO as built), when the authorize endpoint ends it for `prompt=login`, `max_age`, `AbsoluteSessionLifetime` or a second factor, and when another user signs in over it; its refresh tokens are refused at once and its access tokens from the next request on, since the bearer scheme checks the token and its authorization on each request. A hint skips the logout page only when its `sid` is the cookie's session: an identity token of the same user from another session, another device or an earlier sign-in, or one without `sid`, goes to the page, which asks. Nothing is revoked where no sign-in ends: a logout that is not confirmed, a confirmation the user does not give, and a request without the cookie, a valid hint included; such a GET with a hint, as a repeated logout sends, returns to the client without asking. The user's other sessions, in another browser or on another device, stay, as does the consent of a third-party client, a permanent authorization of no server session that ends on the account page and gives no `sid`. A browser logout therefore also ends every client without a consent step that signed in through that browser, a CLI, a native app or a first-party MCP client included, whatever `offline_access` it holds; a client that must outlive a browser logout is registered with `RequireConsent`. A cookie from before sessions were marked ends no authorization, and its tokens last as before. A sign-out writes no activity row, and the revocation adds none. `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. **Protected resources as built** ([#2977](https://github.com/fluentcms/FluentCMS/issues/2977)). A plugin's group mapped with `MapProtectedResource(prefix, options)` (`FluentCMS.Plugins.Abstractions`) is an OAuth protected resource of its own (RFC 9728), which is how the MCP plugin maps `/mcp` (5.4). The group gets what `MapGroup` gives (4.13), with four differences. Its operations enter with the origin the plugin names, `Api` or `Mcp`. It takes the Management rate limit and CORS policy, since it takes writes. No endpoint of it opts out of the signed-in caller with `AllowAnonymous()`. And a bearer token needs the scope the plugin names, one of the scopes that say which surface a token is for, which is `mcp` alone today. An API key holds no OAuth scope and is taken by its class, which the evaluator reads; a preview token carries the kind of the principal that minted it, a key's included, so it is told apart by its entry claim and refused as a token without the scope. A request without credentials is a 401 (`FCMS3102`) with `WWW-Authenticate: Bearer resource_metadata="{metadata URL}", scope="{scope}"`, one whose credentials are refused carries `error="invalid_token"` as well, and a token without the scope is a 403 (`FCMS3103`) with `Bearer error="insufficient_scope", scope="{scope}", resource_metadata="{metadata URL}"`. Both come before the per-site gate, as on any group of a plugin. Core serves the metadata, so a plugin still maps nothing under `/.well-known` (`FCMS1524`): `GET /.well-known/oauth-protected-resource{prefix}` answers `{ resource, authorization_servers, scopes_supported, bearer_methods_supported, resource_name }` to anyone, where `resource` is the public URL of the group, `authorization_servers` holds the issuer exactly as the discovery document names it, `scopes_supported` the scope of the resource and `bearer_methods_supported` `header`. `GET /.well-known/oauth-protected-resource`, the document a client tries when it does not know the path of the resource, answers the same while the host has one protected resource and 404 (`FCMS3104`) once it has several, since it could describe one of them only. The documents are endpoints of the `WellKnown` group, so they take its CORS origins and count as the `connect` surface, and they are not gated per site, since an anonymous caller learns nothing of where a plugin is off. The URLs are built from the public origin and the path base (4.15), and from the request when no origin is set, as the issuer is. Under a path base the documents are under it, where RFC 9728 would put the well-known segment before it; the challenge names the URL, which is what a client follows. The authorization server takes the `resource` parameter of RFC 8707 on the authorization request and on the token request when every value is the public URL of a protected resource of the host, compared as an absolute URI with the path as written, and refuses any other with `invalid_target`; like every refusal while the authorization request is checked, it is shown on the error page rather than sent to the client. OpenIddict's own check holds the resources in a list fixed in its options, which cannot name a URL that follows the request, so it is off (`DisableResourceValidation`) and a handler of core's stands in its place. The resource permissions of clients are off too (`IgnoreResourcePermissions`), because the parameter grants nothing: the audience of a token stays `fluentcms:management`, and the scope of the resource, which a client does need a permission for, is what holds a token to it. A token with the `mcp` scope alone manages through `Origin.Mcp` only (4.8) and is refused by the Management API (403). The consent page describes `mcp` as reading and changing content as an AI agent or tool, as far as the user's roles allow. A scope that is not one of those, an origin other than `Api` or `Mcp`, and a prefix mapped as a protected resource twice stop the host with `FCMS1527`; a prefix under a group of core or with a route parameter anywhere in it is `FCMS1524`. Code `FCMS1527`. @@ -826,7 +826,7 @@ Rows 4.1, 4.2, 4.9 to 4.11, 4.13, 4.15, 4.16, 2.12, 2.13; decisions 7, 30, 33. **Admin SSO.** External OIDC providers (Entra ID, Okta, Keycloak and generic OIDC are the same handler with presets) configured in the host configuration and shown read-only in the admin in the first release (runtime editing is a Should). Federation happens on the hosted login page: auto-provisioning, default role, group claim to role mapping, optional local-login disable. -**Admin SSO as built.** `cms.Sso`, bound from `FluentCms:Sso` (`FCMS3070` names a bad key), lists the providers under `Providers:{name}`. A name is 1 to 64 letters, digits, `-` or `_`, and is the provider's authentication scheme, its login provider in `cms_user_login` and its callback path, `/account/sso/{name}`. A name is found whatever its case: `CmsUserStore` finds a login of a provider under the name as it is written and, failing that, under another case of it (other schemes match as written), so a change of case in configuration keeps the users linked ([#3010](https://github.com/fluentcms/FluentCMS/issues/3010)), and a name that is another authentication scheme's in any case, added before the providers or after them, stops the host (`FCMS3070`). Every provider is ASP.NET Core's OpenID Connect handler, added to the authentication options when the host starts. `Preset` (`Oidc`, `EntraId`, `Okta` or `Keycloak`) only builds the authority and names the button: from `TenantId` (`https://login.microsoftonline.com/{tenant}/v2.0`; `common`, `organizations` and `consumers` are refused, since their tokens come from any tenant), from `Domain` and `AuthorizationServerId` (`https://{domain}`, or `https://{domain}/oauth2/{id}`), or from `BaseUrl` and `Realm` (`{base}/realms/{realm}`). `Authority` overrides it, and generic OIDC requires it. The handler runs the code flow with PKCE, with `ClientSecret` when one is set, asks for `openid profile email` and the `Scopes` listed, takes the answer as a form post, and signs into Identity's external cookie with the token's claims under their own names; a host tunes a provider with `services.Configure(name, ...)`. The login page offers a button per provider, and the external login page asks `SsoSignIn`. A user linked to the login signs in. Someone with no user gets one when `AutoProvision` is on (the default), named and addressed by the `EmailClaim` (`email`), with no password, linked in `cms_user_login` and holding `DefaultRole` and the mapped roles, in one transaction, so the user created and role changed events are staged with it (event 9040). A role is named by its id or by the exact name of an instance-wide role; one that does not exist is not given (`FCMS3071`, event 9042). `RoleMappings` is a list of `Group` and `Role`, matched exactly against the values of `GroupsClaim` (`groups`). No group gives a role by its name, so Super Admin is given only by a mapping or a default role that names it. At every later sign-in of a user who is neither deactivated nor locked out, the mapped roles follow the token's groups: a mapped role whose group is gone is taken away, and the default role and the roles the provider does not map stay. A token with no groups claim at all takes the mapped roles away too, and logs event 9044, since Entra ID's group overage or a missing scope looks the same. Groups that would take Super Admin from its last active holder change no role and refuse the sign-in (`not_allowed`, event 9045, `user.change_refused` with `follow_groups`), since the provider no longer vouches for that user and the instance keeps its last Super Admin (admin users as built). A token without an email address, or that does not say `email_verified` is true while the provider's `RequireVerifiedEmail` is on (the default; off, only a false one is refused) (`FCMS3072`), or whose address belongs to a user not linked to the provider (`FCMS3073`), creates no user, and a creation that fails (`FCMS3074`, with Identity's codes only) leaves none, so an address is never taken over unless the provider links existing users (linking as built). Those refusals log event 9043 and raise `LoginFailedEvent` (`external`, `not_allowed`, no user). The provider's remote sign-out path, `/account/sso/{name}/signout`, signs out the Identity application cookie (`SignOutScheme`), so an IdP-initiated logout ends the admin session (#2854); the cookie holds no session id of the provider for the handler to match, so only a sign-in made through that provider, which the cookie's authentication method names and the stamp check keeps, is ended, and another is left as it is. A provider's error, or a callback that belongs to no sign-in started here, goes back to the login page as a failed sign-in (`invalid_credentials`, event 9041) rather than to an error page. **The provider's `amr`.** It counts only from a provider with `TrustMfaClaim`, which is off by default: a token of such a provider whose `amr` holds `mfa` signs in with `amr=mfa` and without the local second factor. Any other external sign-in carries no `amr`, so a role with `RequireTwoFactor` asks for the local second factor after the provider, or sends the user to `/account/enable-two-factor`, as two-factor as built says. `DisableLocalLogin`, which needs a provider, hides the password form and the forgotten-password link, and `CmsSignInManager` refuses every password sign-in (`not_allowed`). A user created by a provider has no password; with local login on, a reset link gives it one. With local login off, an invitation is accepted through a provider (linking as built). Providers come from configuration only: runtime editing and a read-only list in the admin are not built. Codes `FCMS3070` to `FCMS3074`. +**Admin SSO as built.** `cms.Sso`, bound from `FluentCms:Sso` (`FCMS3070` names a bad key), lists the providers under `Providers:{name}`. A name is 1 to 64 letters, digits, `-` or `_`, and is the provider's authentication scheme, its login provider in `cms_user_login` and its callback path, `/account/sso/{name}`. A name is found whatever its case: `CmsUserStore` finds a login of a provider under the name as it is written and, failing that, under another case of it (other schemes match as written), so a change of case in configuration keeps the users linked ([#3010](https://github.com/fluentcms/FluentCMS/issues/3010)), and a name that is another authentication scheme's in any case, added before the providers or after them, stops the host (`FCMS3070`). Every provider is ASP.NET Core's OpenID Connect handler, added to the authentication options when the host starts. `Preset` (`Oidc`, `EntraId`, `Okta` or `Keycloak`) only builds the authority and names the button: from `TenantId` (`https://login.microsoftonline.com/{tenant}/v2.0`; `common`, `organizations` and `consumers` are refused, since their tokens come from any tenant), from `Domain` and `AuthorizationServerId` (`https://{domain}`, or `https://{domain}/oauth2/{id}`), or from `BaseUrl` and `Realm` (`{base}/realms/{realm}`). `Authority` overrides it, and generic OIDC requires it. The handler runs the code flow with PKCE, with `ClientSecret` when one is set, asks for `openid profile email` and the `Scopes` listed, takes the answer as a form post, and signs into Identity's external cookie with the token's claims under their own names; a host tunes a provider with `services.Configure(name, ...)`. The login page offers a button per provider, and the external login page asks `SsoSignIn`. A user linked to the login signs in. Someone with no user gets one when `AutoProvision` is on (the default), named and addressed by the `EmailClaim` (`email`), with no password, linked in `cms_user_login` and holding `DefaultRole` and the mapped roles, in one transaction, so the user created and role changed events are staged with it (event 9040). A role is named by its id or by the exact name of an instance-wide role; one that does not exist is not given (`FCMS3071`, event 9042). `RoleMappings` is a list of `Group` and `Role`, matched exactly against the values of `GroupsClaim` (`groups`). No group gives a role by its name, so Super Admin is given only by a mapping or a default role that names it. At every later sign-in of a user who is neither deactivated nor locked out, the mapped roles follow the token's groups: a mapped role whose group is gone is taken away, and the default role and the roles the provider does not map stay. A token with no groups claim at all takes the mapped roles away too, and logs event 9044, since Entra ID's group overage or a missing scope looks the same. Groups that would take Super Admin from its last active holder change no role and refuse the sign-in (`not_allowed`, event 9045, `user.change_refused` with `follow_groups`), since the provider no longer vouches for that user and the instance keeps its last Super Admin (admin users as built). A token without an email address, or that does not say `email_verified` is true while the provider's `RequireVerifiedEmail` is on (the default; off, only a false one is refused) (`FCMS3072`), or whose address belongs to a user not linked to the provider (`FCMS3073`), creates no user, and a creation that fails (`FCMS3074`, with Identity's codes only) leaves none, so an address is never taken over unless the provider links existing users (linking as built). Those refusals log event 9043 and raise `LoginFailedEvent` (`external`, `not_allowed`, no user). The provider's remote sign-out path, `/account/sso/{name}/signout`, signs out the Identity application cookie (`SignOutScheme`), so an IdP-initiated logout ends the admin session (#2854), with the authorizations of its server session (#3198); the cookie holds no session id of the provider for the handler to match, so only a sign-in made through that provider, which the cookie's authentication method names and the stamp check keeps, is ended, and another is left as it is. A provider's error, or a callback that belongs to no sign-in started here, goes back to the login page as a failed sign-in (`invalid_credentials`, event 9041) rather than to an error page. **The provider's `amr`.** It counts only from a provider with `TrustMfaClaim`, which is off by default: a token of such a provider whose `amr` holds `mfa` signs in with `amr=mfa` and without the local second factor. Any other external sign-in carries no `amr`, so a role with `RequireTwoFactor` asks for the local second factor after the provider, or sends the user to `/account/enable-two-factor`, as two-factor as built says. `DisableLocalLogin`, which needs a provider, hides the password form and the forgotten-password link, and `CmsSignInManager` refuses every password sign-in (`not_allowed`). A user created by a provider has no password; with local login on, a reset link gives it one. With local login off, an invitation is accepted through a provider (linking as built). Providers come from configuration only: runtime editing and a read-only list in the admin are not built. Codes `FCMS3070` to `FCMS3074`. **Linking external logins as built.** The page that accepts an invitation offers a button per provider of `cms.Sso` next to the password form, and with `DisableLocalLogin` the providers only, since `InvitationService` then refuses a password (`FCMS3093`). The provider comes back to that page, and `SsoSignIn` accepts the invitation with the external login when the address of the provider's `EmailClaim` is the invitation's, as Identity normalizes addresses, and the token does not say `email_verified` is false (`FCMS3072`); another address is refused (`FCMS3092`) and the invitation stays pending. The user is named by the invitation's address, has no password, holds the invitation's roles and is linked in the transaction that uses the invitation up; it then signs in as at any sign-in through the provider, so the mapped roles follow its groups and `TrustMfaClaim` and `RequireTwoFactor` apply as before, and the default role is not given. An error or a cancel at the provider returns to the invitation. `LinkExistingUsers` on a provider, off by default, links at its first sign-in through the provider the user whose address the token carries and who has no login of that provider, only when the token says `email_verified` is true, so a provider that sends no such claim links no one; a user who cannot sign in now is not linked, and without the option or the claim the address is refused as before. An invitation needs no explicit `email_verified` because its link already showed that the person reads the mailbox, and an existing user has no such proof. Linking and removing a login raise `UserLoginLinkedEvent` and `UserLoginUnlinkedEvent` from `CmsUserStore` with the change, the activity rows `user.login_linked` and `user.login_unlinked` with the provider. `GET /users/{id}/logins` (`users.manage`) and `GET /me/logins` list `{ "provider", "providerKey", "displayName" }`, and `DELETE /users/{id}/logins/{provider}` (with every grant of the user's roles too) and `DELETE /me/logins/{provider}` remove the user's logins of that provider (`FCMS3091` when it has none) with a new security stamp, which ends the user's sessions. The last way to sign in is not removed (`FCMS3090`, 409): a login counts while its provider is offered on the login page, and a password while local login is on. With a public origin (4.15), the `redirect_uri` a provider is given, and the code is redeemed with, is built from it in `OnRedirectToIdentityProvider`. Codes `FCMS3090` to `FCMS3093`; event ids 9060 to 9062. diff --git a/docs/releases/1.0.0-preview.1.md b/docs/releases/1.0.0-preview.1.md index 8e05ca41b..bb28ff525 100644 --- a/docs/releases/1.0.0-preview.1.md +++ b/docs/releases/1.0.0-preview.1.md @@ -70,6 +70,7 @@ A media field read with `populate`, and an image of rich text read with `richTex ## Bugs fixed - A setting that is not text, such as `maxOutputTokens` of AI assist, is no longer taken for a secret by its name (#3079). +- A logout revokes the authorizations issued in the browser's sign-in, with their refresh and access tokens, where it ended the sign-in cookie alone. The confirmed logout, one with an `id_token_hint` of that session, the member logout page and a provider's remote sign-out revoke them, and so do a new sign-in for `prompt=login`, `max_age` or a second factor and another user's sign-in in the same browser. An identity token carries the session as `sid`, and a hint from another session goes to the logout page, which asks. The user's other sessions and a third-party client's consent stay; a client without a consent step that must outlive a browser logout, such as a CLI or a native app, is registered with `RequireConsent` (#3198). - Restoring, reading and diffing a version written before a field was renamed with `[FormerNames]` keep the field's value, and a former name that another field of the type holds is refused (#3085). - A media reference read on the Delivery API resolves to its public asset, where it answered null (#3109). - A media reference read on `/graphql` by a caller that may not manage resolves to its public asset, where it answered null (#3112). diff --git a/src/FluentCMS.Core/Api/Account/MemberPageModels.cs b/src/FluentCMS.Core/Api/Account/MemberPageModels.cs index feffa1fe6..968b47f33 100644 --- a/src/FluentCMS.Core/Api/Account/MemberPageModels.cs +++ b/src/FluentCMS.Core/Api/Account/MemberPageModels.cs @@ -148,7 +148,7 @@ public async Task OnPostAsync() var cookie = await HttpContext.AuthenticateAsync(MemberAuthentication.CookieScheme); if (cookie.Succeeded) { - await Service().EndAsync(signIn.UserManager.GetUserId(cookie.Principal), cookie.Properties, CancellationToken.None); + await Service().EndAsync(signIn.UserManager.GetUserId(cookie.Principal), CmsSignInManager.ServerSession(cookie.Properties), CancellationToken.None); } await signIn.SignOutAsync(); diff --git a/src/FluentCMS.Core/Identity/CmsSignInManager.cs b/src/FluentCMS.Core/Identity/CmsSignInManager.cs index c583e0335..4e13d2eed 100644 --- a/src/FluentCMS.Core/Identity/CmsSignInManager.cs +++ b/src/FluentCMS.Core/Identity/CmsSignInManager.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using static OpenIddict.Abstractions.OpenIddictConstants; @@ -55,10 +56,39 @@ internal sealed class CmsSignInManager( // Marks a new sign-in with its time and the id of its server session, unless the properties are a renewal's. internal static void MarkSignIn(AuthenticationProperties properties, TimeProvider time) { + ArgumentNullException.ThrowIfNull(properties); + ArgumentNullException.ThrowIfNull(time); + properties.Items.TryAdd(SignedInAtItem, time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)); properties.Items.TryAdd(ServerSessionItem, Guid.NewGuid().ToString("N")); } + // A new sign-in over a live cookie of the pool: the same user's keeps the browser's server session, so that its logout + // still finds what was issued before; another user's ends that session, as a logout would. + internal static async Task TakeOverAsync(HttpContext context, string scheme, string userId, AuthenticationProperties properties, Func userIdOf) + { + if (properties.Items.ContainsKey(ServerSessionItem)) + { + return; + } + + var live = await context.AuthenticateAsync(scheme); + if (!live.Succeeded || ServerSession(live.Properties!) is not { } serverSession) + { + return; + } + + var previous = userIdOf(live.Principal!); + if (previous == userId) + { + properties.Items[ServerSessionItem] = serverSession; + } + else + { + await context.RequestServices.GetRequiredService().EndAsync(previous, serverSession, CancellationToken.None); + } + } + public override async Task CanSignInAsync(CmsUser user) { ArgumentNullException.ThrowIfNull(user); @@ -129,11 +159,14 @@ public override async Task CheckPasswordSignInAsync(CmsUser user, } // Every sign-in that makes a new cookie comes here; a renewal passes the cookie's properties, which keep the time. - public override Task SignInWithClaimsAsync(CmsUser user, AuthenticationProperties? authenticationProperties, IEnumerable additionalClaims) + public override async Task SignInWithClaimsAsync(CmsUser user, AuthenticationProperties? authenticationProperties, IEnumerable additionalClaims) { + ArgumentNullException.ThrowIfNull(user); + var properties = authenticationProperties ?? new AuthenticationProperties(); + await TakeOverAsync(Context, IdentityConstants.ApplicationScheme, user.Id.ToString("D"), properties, UserManager.GetUserId); MarkSignIn(properties, time); - return base.SignInWithClaimsAsync(user, properties, additionalClaims); + await base.SignInWithClaimsAsync(user, properties, additionalClaims); } public override async Task TwoFactorAuthenticatorSignInAsync(string code, bool isPersistent, bool rememberClient) diff --git a/src/FluentCMS.Core/Identity/Members/MemberConnect.cs b/src/FluentCMS.Core/Identity/Members/MemberConnect.cs index aa266def1..4015c2fcb 100644 --- a/src/FluentCMS.Core/Identity/Members/MemberConnect.cs +++ b/src/FluentCMS.Core/Identity/Members/MemberConnect.cs @@ -58,6 +58,9 @@ public static async Task AuthorizeAsync(HttpContext context, OpenIddict return ConnectEndpoints.Refuse(Errors.LoginRequired, "The sign-in is older than the client or the server accepts."); } + // The sign-in ends with the authorizations of its server session, as at a logout. + await context.RequestServices.GetRequiredService() + .EndAsync(member.Id.ToString("D"), CmsSignInManager.ServerSession(cookie.Properties!), CancellationToken.None); await signIn.SignOutAsync(); return Results.Challenge(new AuthenticationProperties { RedirectUri = afterSignIn }, [MemberAuthentication.CookieScheme]); } @@ -70,6 +73,7 @@ public static async Task AuthorizeAsync(HttpContext context, OpenIddict if (CmsSignInManager.ServerSession(cookie.Properties!) is { } serverSession && await context.RequestServices.GetRequiredService().FindByClientIdAsync(request.ClientId!, context.RequestAborted) is { } application) { + TokenClaims.ForServerSession(identity, serverSession); identity.SetAuthorizationId(await context.RequestServices.GetRequiredService() .BeginAsync(new ClaimsPrincipal(identity), application, serverSession, context.RequestAborted)); } diff --git a/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs b/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs index 5d2689965..f08e2ad0d 100644 --- a/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs +++ b/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs @@ -1,4 +1,3 @@ -using System.Globalization; using System.Security.Claims; using FluentCMS.Content; using FluentCMS.Events; @@ -125,11 +124,14 @@ public override async Task CheckPasswordSignInAsync(CmsMember user // Every sign-in that makes a new cookie comes here. The time of the sign-in and the id of its server session are kept // in the cookie's properties, as for an admin user: prompt=login, max_age and the absolute session lifetime read the // time, and the logout ends the authorizations of the session. - public override Task SignInWithClaimsAsync(CmsMember user, AuthenticationProperties? authenticationProperties, IEnumerable additionalClaims) + public override async Task SignInWithClaimsAsync(CmsMember user, AuthenticationProperties? authenticationProperties, IEnumerable additionalClaims) { + ArgumentNullException.ThrowIfNull(user); + var properties = authenticationProperties ?? new AuthenticationProperties(); + await CmsSignInManager.TakeOverAsync(Context, MemberAuthentication.CookieScheme, user.Id.ToString("D"), properties, _members.GetUserId); CmsSignInManager.MarkSignIn(properties, _time); - return base.SignInWithClaimsAsync(user, properties, additionalClaims); + await base.SignInWithClaimsAsync(user, properties, additionalClaims); } // The member cookie alone. Identity's sign-out also ends its external and two-factor cookies, which are the admin's. diff --git a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs index ec40702f4..4c37ac9b1 100644 --- a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs +++ b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs @@ -115,7 +115,7 @@ private static async Task AuthorizeAsync(HttpContext context) return Refuse(Errors.LoginRequired, "The sign-in is older than the client or the server accepts."); } - await context.SignOutAsync(IdentityConstants.ApplicationScheme); + await EndSignInAsync(context, cookie, members: false); return Results.Challenge(new AuthenticationProperties { RedirectUri = afterSignIn }, [IdentityConstants.ApplicationScheme]); } @@ -133,7 +133,7 @@ private static async Task AuthorizeAsync(HttpContext context) return Refuse(Errors.LoginRequired, "The user's role requires a sign-in with a second factor."); } - await context.SignOutAsync(IdentityConstants.ApplicationScheme); + await EndSignInAsync(context, cookie, members: false); return Results.Challenge(new AuthenticationProperties { RedirectUri = afterSignIn }, [IdentityConstants.ApplicationScheme]); } @@ -178,6 +178,7 @@ private static async Task AuthorizeAsync(HttpContext context) } else if (CmsSignInManager.ServerSession(cookie.Properties!) is { } serverSession) { + TokenClaims.ForServerSession(identity, serverSession); identity.SetAuthorizationId(await context.RequestServices.GetRequiredService() .BeginAsync(new ClaimsPrincipal(identity), application, serverSession, context.RequestAborted)); } @@ -328,8 +329,9 @@ private static async Task UserInfoAsync(HttpContext context) // Ends the user's sign-in on the hosted pages; the server then returns to the client's post-logout URI when it gave one, // or to the logout page. The user confirms on the logout page, whose form posts back with an antiforgery token, or the - // client sends a valid id_token_hint of the signed-in user. Anything else, a cross-site POST included, goes to the logout - // page, which asks. A request without the sign-in cookie has no sign-in to end, so it sends no expiring cookie either. + // client sends a valid id_token_hint issued in the signed-in user's server session. Anything else, a cross-site POST + // included, goes to the logout page, which asks. A request without the sign-in cookie has no sign-in to end, so it + // sends no expiring cookie either. // Ending a sign-in revokes the authorizations issued in its server session, with their tokens, and no others. // The client the request names, by its client_id or by the audience of its hint, says whose sign-in ends: a client of // the member pool ends the member's on the member pages, and any other request the admin user's, so that neither @@ -355,9 +357,7 @@ private static async Task LogoutAsync(HttpContext context) if (cookie.Succeeded) { - // A logout the browser stops waiting for still ends the authorizations of the session. - await context.RequestServices.GetRequiredService().EndAsync(SignedInUserId(context, cookie, members), cookie.Properties!, CancellationToken.None); - await context.SignOutAsync(scheme); + await EndSignInAsync(context, cookie, members); } return Results.SignOut( @@ -405,21 +405,31 @@ private static IResult ErrorPage(HttpContext context, OpenIddictResponse respons })); // OpenIddict passes a hint it cannot read through without a principal, so the hint is checked here. Without the cookie - // a GET, which a browser sends with it, has no one signed in; a POST may be a cross-site one, which never carries it. - // The cookie is the one of the pool the request is for, read by that pool's manager. + // a GET, which a browser sends with it, has no one signed in, so a hint of any kind returns to the client: a repeated + // logout's hint, whose token the first one revoked, included. A POST may be a cross-site one, which never carries it. + // With the cookie, the hint must be of the cookie's server session (its sid), not only of its user: an id token from + // another session or device, or from an earlier sign-in, goes to the logout page. The cookie is the one of the pool the + // request is for, read by that pool's manager. private static bool HintsSignedInUser(HttpContext context, AuthenticateResult hint, AuthenticateResult cookie, bool members) { - if (hint.Principal?.GetClaim(Claims.Subject) is not { } subject) - { - return false; - } - if (!cookie.Succeeded) { - return HttpMethods.IsGet(context.Request.Method); + return HttpMethods.IsGet(context.Request.Method) && !string.IsNullOrEmpty(context.GetOpenIddictServerRequest()?.IdTokenHint); } - return SignedInUserId(context, cookie, members) == subject; + return hint.Principal?.GetClaim(Claims.Subject) is { } subject + && SignedInUserId(context, cookie, members) == subject + && CmsSignInManager.ServerSession(cookie.Properties!) is { } serverSession + && hint.Principal.GetClaim(TokenClaims.ServerSession) == serverSession; + } + + // Ends the cookie's sign-in and, with it, the authorizations of its server session, so that nothing issued in a + // session outlives its cookie; an end the browser stops waiting for still ends them. + private static async Task EndSignInAsync(HttpContext context, AuthenticateResult cookie, bool members) + { + await context.RequestServices.GetRequiredService() + .EndAsync(SignedInUserId(context, cookie, members), CmsSignInManager.ServerSession(cookie.Properties!), CancellationToken.None); + await context.SignOutAsync(members ? MemberAuthentication.CookieScheme : IdentityConstants.ApplicationScheme); } private static string? SignedInUserId(HttpContext context, AuthenticateResult cookie, bool members) => members diff --git a/src/FluentCMS.Core/Identity/Oidc/TokenClaims.cs b/src/FluentCMS.Core/Identity/Oidc/TokenClaims.cs index d70b1846d..3b9c9c3d6 100644 --- a/src/FluentCMS.Core/Identity/Oidc/TokenClaims.cs +++ b/src/FluentCMS.Core/Identity/Oidc/TokenClaims.cs @@ -21,6 +21,10 @@ internal static class TokenClaims // When the session began, in Unix seconds, for its absolute lifetime; in codes and refresh tokens only, too. public const string SessionStart = "fcms_session_start"; + // The server session, RP-Initiated Logout's sid, in the identity token of a code issued under it: a logout whose hint + // carries the sid of the cookie's session needs no confirmation. + public const string ServerSession = "sid"; + // The authentication method reference Identity gives a sign-in with a second factor. public const string MultiFactor = "mfa"; @@ -74,6 +78,9 @@ public static ClaimsIdentity ForMember(ClaimsIdentity identity, CmsMember member return identity; } + public static ClaimsIdentity ForServerSession(ClaimsIdentity identity, string serverSession) => + identity.SetClaim(ServerSession, serverSession).SetDestinations(Destinations); + public static ClaimsIdentity ForServiceAccount(ClaimsIdentity identity, Guid applicationId, string name, IEnumerable roles, IEnumerable scopes) { identity.SetClaim(Claims.Subject, applicationId.ToString("D")) @@ -125,7 +132,7 @@ public static bool SignedInWithSecondFactor(Principal principal) => Claims.Name when claim.Subject?.HasScope(Scopes.Profile) == true => [OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken], Claims.Email when claim.Subject?.HasScope(Scopes.Email) == true => [OpenIddictConstants.Destinations.IdentityToken], Claims.AuthenticationMethodReference => [OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken], - Claims.AuthenticationTime => [OpenIddictConstants.Destinations.IdentityToken], + Claims.AuthenticationTime or ServerSession => [OpenIddictConstants.Destinations.IdentityToken], Claims.Name or CmsClaimTypes.Kind or CmsClaimTypes.Roles or CmsClaimTypes.ClientRole => [OpenIddictConstants.Destinations.AccessToken], _ => [], }; diff --git a/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs b/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs index a7c4ba9ce..3d846017e 100644 --- a/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs +++ b/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs @@ -1,6 +1,5 @@ using System.Security.Claims; using System.Text.Json; -using Microsoft.AspNetCore.Authentication; using OpenIddict.Abstractions; using static OpenIddict.Abstractions.OpenIddictConstants; @@ -38,14 +37,12 @@ public async Task BeginAsync(ClaimsPrincipal principal, object applicati ?? throw new InvalidOperationException("The authorization was stored without an id."); } - // The logout of a server session, the cookie of the signed-in user whose id is given: every valid authorization of - // the user issued in it, with its tokens. The user's other sessions, and a consent, which is no session's, stay. A - // cookie from before sessions were marked ends nothing here. - public async Task EndAsync(string? userId, AuthenticationProperties cookie, CancellationToken cancellationToken = default) + // The end of a server session of the user: every valid authorization of the user issued in it, with its tokens. The + // user's other sessions, and a consent, which is no session's, stay. Without a session id, as for a sign-in from + // before sessions were marked, nothing ends here. + public async Task EndAsync(string? userId, string? serverSession, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(cookie); - - if (CmsSignInManager.ServerSession(cookie) is not { } serverSession || !Guid.TryParse(userId, out var user)) + if (string.IsNullOrEmpty(serverSession) || !Guid.TryParse(userId, out var user)) { return; } diff --git a/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs b/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs index 7b08928f1..7a33f650f 100644 --- a/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs +++ b/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs @@ -1,5 +1,6 @@ using System.Security.Claims; using FluentCMS.Core.DependencyInjection; +using FluentCMS.Core.Identity.Oidc; using FluentCMS.Events; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; @@ -104,14 +105,22 @@ public void Configure(string? name, OpenIdConnectOptions options) // The provider's front-channel logout ends the sign-in on the hosted pages, the admin session. The cookie holds no // session id of the provider for the handler to match, so a sign-in made another way, with a password or another - // provider, is left as it is. + // provider, is left as it is. The sign-in it ends takes the authorizations of its server session with it, as a + // logout does. private static async Task OwnSignInOnlyAsync(RemoteSignOutContext context) { var cookie = await context.HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme); if (!string.Equals(cookie.Principal?.FindFirstValue(ClaimTypes.AuthenticationMethod), context.Scheme.Name, StringComparison.OrdinalIgnoreCase)) { context.HandleResponse(); + return; } + + var services = context.HttpContext.RequestServices; + await services.GetRequiredService().EndAsync( + services.GetRequiredService>().GetUserId(cookie.Principal!), + CmsSignInManager.ServerSession(cookie.Properties!), + CancellationToken.None); } // Identity takes the external login's key from the name identifier, which the token calls sub. diff --git a/src/FluentCMS.Testing/OAuthFlows.cs b/src/FluentCMS.Testing/OAuthFlows.cs index 73e8cb90c..63349056c 100644 --- a/src/FluentCMS.Testing/OAuthFlows.cs +++ b/src/FluentCMS.Testing/OAuthFlows.cs @@ -1,5 +1,4 @@ using System.Buffers.Text; -using System.Globalization; using System.Net; using System.Security.Cryptography; using System.Text; @@ -55,10 +54,10 @@ public static async Task MemberCookieAsync(IServiceProvider services, Gu var principal = await signIn.CreateUserPrincipalAsync(member); var options = provider.GetRequiredService>().Get(MemberAuthentication.CookieScheme); - var now = provider.GetRequiredService().GetUtcNow(); + var time = provider.GetRequiredService(); + var now = time.GetUtcNow(); var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now + options.ExpireTimeSpan }; - properties.Items[CmsSignInManager.SignedInAtItem] = now.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); - properties.Items[CmsSignInManager.ServerSessionItem] = Guid.NewGuid().ToString("N"); + CmsSignInManager.MarkSignIn(properties, time); var ticket = new AuthenticationTicket(principal, properties, MemberAuthentication.CookieScheme); return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; } @@ -72,10 +71,10 @@ public static async Task CookieAsync(IServiceProvider services, Guid use var principal = await provider.GetRequiredService>().CreateUserPrincipalAsync(user); var options = provider.GetRequiredService>().Get(IdentityConstants.ApplicationScheme); - var now = provider.GetRequiredService().GetUtcNow(); + var time = provider.GetRequiredService(); + var now = time.GetUtcNow(); var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now + options.ExpireTimeSpan }; - properties.Items[CmsSignInManager.SignedInAtItem] = now.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); - properties.Items[CmsSignInManager.ServerSessionItem] = Guid.NewGuid().ToString("N"); + CmsSignInManager.MarkSignIn(properties, time); var ticket = new AuthenticationTicket(principal, properties, IdentityConstants.ApplicationScheme); return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; } diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Hardening.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Hardening.cs index f164ddd9f..4b70024c7 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Hardening.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Hardening.cs @@ -1,4 +1,7 @@ +using System.Buffers.Text; using System.Net; +using System.Security.Cryptography; +using System.Text; using FluentCMS.Content; using FluentCMS.Core.Authorization; using FluentCMS.Core.Identity; @@ -12,6 +15,7 @@ using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.XmlEncryption; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.WebUtilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -281,10 +285,11 @@ public async Task LogoutByGetNeedsTheSessionsIdTokenHint() { var editor = await _host.CreateUserAsync(BuiltInRoles.EditorName, cancellationToken: Token); var other = await _host.CreateUserAsync(BuiltInRoles.EditorName, cancellationToken: Token); - var tokens = await _host.SignInAsync(editor, "openid", "management"); var othersTokens = await _host.SignInAsync(other, "openid", "management"); + var anotherSession = await _host.SignInAsync(editor, "openid", "offline_access", "management"); var cookie = await _host.SignInCookieAsync(editor); using var client = _host.CreateSecureClient(); + var tokens = await SignInAsync(client, cookie); // Without the hint the logout page asks the user, and posts the request back. using (var bare = await SendAsync(client, HttpMethod.Get, "/connect/logout?state=abc", cookie)) @@ -308,6 +313,16 @@ public async Task LogoutByGetNeedsTheSessionsIdTokenHint() someoneElse.Headers.Contains("Set-Cookie").ShouldBeFalse(); } + // The user's own hint from another session, another browser or an earlier sign-in, is not this session's: the page + // asks, and nothing ends. + using (var otherSession = await SendAsync(client, HttpMethod.Get, $"/connect/logout?id_token_hint={anotherSession.IdentityToken}", cookie)) + { + otherSession.StatusCode.ShouldBe(HttpStatusCode.Redirect); + new Uri(client.BaseAddress!, otherSession.Headers.Location!).AbsolutePath.ShouldBe("/account/logout"); + otherSession.Headers.Contains("Set-Cookie").ShouldBeFalse(); + } + + tokens = await TokenAsync(client, Refresh(tokens.RefreshToken!), Token); using (var hinted = await SendAsync(client, HttpMethod.Get, $"/connect/logout?id_token_hint={tokens.IdentityToken}", cookie)) { hinted.StatusCode.ShouldBe(HttpStatusCode.Redirect); @@ -315,6 +330,19 @@ public async Task LogoutByGetNeedsTheSessionsIdTokenHint() hinted.Headers.GetValues("Set-Cookie").ShouldContain(value => value.StartsWith(".AspNetCore.Identity.Application=;", StringComparison.Ordinal)); } + // The session's tokens end with it, and the other session's stay. + using (var refused = await PostTokenAsync(client, Refresh(tokens.RefreshToken!))) + { + (await ErrorAsync(refused)).ShouldBe("invalid_grant"); + } + + (await TokenAsync(client, Refresh(anotherSession.RefreshToken!), Token)).RefreshToken.ShouldNotBeNull(); + + // A repeated logout with the hint, whose token the first one revoked, finds no cookie and returns without asking. + using var again = await SendAsync(client, HttpMethod.Get, $"/connect/logout?id_token_hint={tokens.IdentityToken}", ""); + again.StatusCode.ShouldBe(HttpStatusCode.Redirect); + again.Headers.Location!.OriginalString.ShouldBe("/account/logout"); + again.Headers.Contains("Set-Cookie").ShouldBeFalse(); } [Fact] @@ -382,6 +410,28 @@ private async Task WithUserAsync(TestUser user, Func, CmsUs private static string AuthorizePath() => $"/connect/authorize?client_id={FluentCmsTestHost.OAuthClientId}&response_type=code&scope=openid&redirect_uri={Uri.EscapeDataString(FluentCmsTestHost.OAuthRedirectUri)}&code_challenge=abcdefghijabcdefghijabcdefghijabcdefghijabc&code_challenge_method=S256"; + // The tokens of the test client from a code flow in the session of the cookie, so that its identity token is of it. + private static async Task SignInAsync(HttpClient client, string cookie, string scope = "openid offline_access management") + { + var verifier = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32)); + var challenge = Base64Url.EncodeToString(SHA256.HashData(Encoding.ASCII.GetBytes(verifier))); + var path = $"/connect/authorize?client_id={TestClientId}&response_type=code&scope={Uri.EscapeDataString(scope)}&redirect_uri={Uri.EscapeDataString(FluentCmsTestHost.OAuthRedirectUri)}&code_challenge={challenge}&code_challenge_method=S256"; + using var authorize = await SendAsync(client, HttpMethod.Get, path, cookie); + var code = QueryHelpers.ParseQuery(authorize.Headers.Location!.Query)["code"].ToString(); + code.ShouldNotBeNullOrEmpty(); + return await TokenAsync( + client, + new Dictionary + { + ["grant_type"] = "authorization_code", + ["code"] = code, + ["redirect_uri"] = FluentCmsTestHost.OAuthRedirectUri, + ["client_id"] = TestClientId, + ["code_verifier"] = verifier, + }, + Token); + } + private static async Task SendAsync(HttpClient client, HttpMethod method, string path, string cookie, HttpContent? content = null) { using var request = new HttpRequestMessage(method, path) { Content = content }; diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Sessions.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Sessions.cs index 6312fa05c..c00a205a5 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Sessions.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/AuthorizationServerTests.Sessions.cs @@ -34,9 +34,9 @@ public sealed partial class AuthorizationServerTests public async Task ALogoutPostWithoutTheLogoutPagesTokenSignsNoOneOut() { var editor = await _host.CreateUserAsync(BuiltInRoles.EditorName, cancellationToken: Token); - var tokens = await _host.SignInAsync(editor, "openid", "management"); var cookie = await _host.SignInCookieAsync(editor); using var client = _host.CreateSecureClient(); + var tokens = await SignInAsync(client, cookie, "openid management"); // A form on another site that posts here: the logout page asks, and the cookie stays. using (var forged = await SendAsync(client, HttpMethod.Post, "/connect/logout", cookie, Form(("state", "xyz")))) diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesBrowser.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesBrowser.cs index 30e267468..e1d70c0f7 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesBrowser.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesBrowser.cs @@ -30,6 +30,9 @@ public HostedPagesBrowser(FluentCmsTestHost host, string address = "10.1.0.1", U public bool HasCookie(string name) => _cookies.GetCookies(_client.BaseAddress!).Any(cookie => cookie.Name == name && !cookie.Expired); + // A cookie the browser holds without a page having set it, as name=value. + public void SetCookie(string cookie) => _cookies.SetCookies(_client.BaseAddress!, cookie + "; path=/; secure"); + public Task GetAsync(string url) => _client.GetAsync(url, Token); public async Task PageAsync(string url) diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs index 77d07ab1d..2a57183a2 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs @@ -1,7 +1,14 @@ +using System.Buffers.Text; using System.Net; using System.Net.Http.Headers; using System.Text.Json; +using FluentCMS.Core.Identity; using FluentCMS.Testing; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Shouldly; using Xunit; @@ -18,8 +25,9 @@ public async Task AConfirmedLogoutRevokesTheTokensOfItsSessionAndLeavesTheUsersO using var otherDevice = new HostedPagesBrowser(_host, "10.1.0.9"); await SignInAsync(browser, editor.Email); await SignInAsync(otherDevice, editor.Email); - var tokens = await CodeFlowAsync(browser); - var other = await CodeFlowAsync(otherDevice); + var tokens = await CodeFlowAsync(_host, browser); + var secondTab = await CodeFlowAsync(_host, browser); + var other = await CodeFlowAsync(_host, otherDevice); // A logout that is not confirmed, by a GET without a hint or a POST without the page's token, revokes nothing. using (var asked = await browser.GetAsync("/connect/logout")) @@ -32,15 +40,16 @@ public async Task AConfirmedLogoutRevokesTheTokensOfItsSessionAndLeavesTheUsersO forged.Headers.Location!.OriginalString.ShouldBe("/account/logout"); } - var refreshToken = await RefreshAsync(Text(tokens, "refresh_token")); - (await MeAsync(Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.OK); + var refreshToken = await RotatedAsync(_host, Text(tokens, "refresh_token")); + (await MeAsync(_host, Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.OK); await SignOutAsync(browser); - (await RefusedAsync(refreshToken)).ShouldBe("invalid_grant"); - (await MeAsync(Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.Unauthorized); - (await RefreshAsync(Text(other, "refresh_token"))).ShouldNotBeNullOrEmpty(); - (await MeAsync(Text(other, "access_token"))).ShouldBe(HttpStatusCode.OK); + (await RefusedAsync(_host, refreshToken)).ShouldBe("invalid_grant"); + (await RefusedAsync(_host, Text(secondTab, "refresh_token"))).ShouldBe("invalid_grant"); + (await MeAsync(_host, Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.Unauthorized); + (await RotatedAsync(_host, Text(other, "refresh_token"))).ShouldNotBeNullOrEmpty(); + (await MeAsync(_host, Text(other, "access_token"))).ShouldBe(HttpStatusCode.OK); } [Fact] @@ -48,8 +57,10 @@ public async Task ALogoutWithAHintRevokesOnlyWhenItEndsTheSessionOfItsCookie() { var editor = await CreateUserAsync(_host); using var browser = new HostedPagesBrowser(_host); + using var otherDevice = new HostedPagesBrowser(_host, "10.1.0.11"); await SignInAsync(browser, editor.Email); - var tokens = await CodeFlowAsync(browser); + await SignInAsync(otherDevice, editor.Email); + var tokens = await CodeFlowAsync(_host, browser); var hint = "/connect/logout?id_token_hint=" + Uri.EscapeDataString(Text(tokens, "id_token")); // Without the cookie there is no session to end, and the hint alone revokes nothing. @@ -59,15 +70,26 @@ public async Task ALogoutWithAHintRevokesOnlyWhenItEndsTheSessionOfItsCookie() returned.StatusCode.ShouldBe(HttpStatusCode.Redirect); } - var refreshToken = await RefreshAsync(Text(tokens, "refresh_token")); + // The user's hint is not the other device's session: that device is asked, and its cookie and this session stay. + using (var elsewhere = await otherDevice.GetAsync(hint)) + { + elsewhere.Headers.Location!.OriginalString.ShouldStartWith("/account/logout?"); + } + + otherDevice.HasCookie(SignInCookie).ShouldBeTrue(); + var refreshToken = await RotatedAsync(_host, Text(tokens, "refresh_token")); using (var signedOut = await browser.GetAsync(hint)) { signedOut.StatusCode.ShouldBe(HttpStatusCode.Redirect); } - browser.HasCookie(".AspNetCore.Identity.Application").ShouldBeFalse(); - (await RefusedAsync(refreshToken)).ShouldBe("invalid_grant"); + browser.HasCookie(SignInCookie).ShouldBeFalse(); + (await RefusedAsync(_host, refreshToken)).ShouldBe("invalid_grant"); + + // Logging out again with the same hint, as a second tab or a double click does, finds nothing to end and asks nothing. + using var again = await browser.GetAsync(hint); + again.Headers.Location!.OriginalString.ShouldBe("/account/logout"); } [Fact] @@ -83,62 +105,150 @@ public async Task ALogoutLeavesTheConsentOfAThirdPartyClient() var page = await browser.PageAsync(consent); using var allowed = await browser.PostAsync(consent, page, new Dictionary { ["decision"] = "allow" }); using var done = await browser.FollowAsync(allowed, ThirdPartyRedirectUri); - var accessToken = Text(await request.ExchangeAsync(_host, done), "access_token"); + var issued = await request.ExchangeAsync(_host, done); + + // A consent is no session's, so its identity token names none, and its hint is asked about. + Payload(Text(issued, "id_token")).TryGetProperty("sid", out _).ShouldBeFalse(); await SignOutAsync(browser); - // The consent is no session's: the client keeps its token, and the next sign-in is not asked again. - (await MeAsync(accessToken)).ShouldBe(HttpStatusCode.OK); + // The client keeps its token, and the next sign-in is not asked again. + (await MeAsync(_host, Text(issued, "access_token"))).ShouldBe(HttpStatusCode.OK); await SignInAsync(browser, editor.Email); using var again = await browser.GetAsync(AuthorizeRequest.For(ThirdPartyClientId, ThirdPartyRedirectUri, "openid management").Url); again.Headers.Location!.AbsoluteUri.ShouldStartWith(ThirdPartyRedirectUri + "?code="); } + [Fact] + public async Task ASignInOverALiveOneKeepsTheSessionOfItsUserAndEndsAnothersAndAReauthenticationEndsIt() + { + var editor = await CreateUserAsync(_host); + var other = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host); + await SignInAsync(browser, editor.Email); + var before = await CodeFlowAsync(_host, browser); + + // The same user signs in again on the login page: the browser's session goes on, and its logout ends both. + await SignInAsync(browser, editor.Email); + var after = await CodeFlowAsync(_host, browser); + Sid(after).ShouldBe(Sid(before)); + await SignOutAsync(browser); + (await RefusedAsync(_host, Text(before, "refresh_token"))).ShouldBe("invalid_grant"); + (await RefusedAsync(_host, Text(after, "refresh_token"))).ShouldBe("invalid_grant"); + + // Another user signs in over a live sign-in: the first user's session in this browser ends. + await SignInAsync(browser, editor.Email); + var replaced = await CodeFlowAsync(_host, browser); + await SignInAsync(browser, other.Email); + (await RefusedAsync(_host, Text(replaced, "refresh_token"))).ShouldBe("invalid_grant"); + var others = await CodeFlowAsync(_host, browser); + Sid(others).ShouldNotBe(Sid(replaced)); + + // prompt=login ends the sign-in it replaces, with what was issued in it. + var request = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri, prompt: "login"); + using var login = await browser.GetAsync(request.Url); + login.Headers.Location!.AbsolutePath.ShouldBe("/account/login"); + browser.HasCookie(SignInCookie).ShouldBeFalse(); + (await RefusedAsync(_host, Text(others, "refresh_token"))).ShouldBe("invalid_grant"); + } + + [Fact] + public async Task ASignInWithTheSecondFactorAndAPasswordChangeKeepTheSessionThatTheLogoutEnds() + { + var editor = await CreateUserAsync(_host); + var (key, _) = await EnableTwoFactorAsync(_host, editor); + using var browser = new HostedPagesBrowser(_host, "10.1.0.12"); + using (var password = await browser.SubmitAsync("/account/login", Credentials(editor.Email, Password))) + using (var challenged = await browser.SubmitAsync(password.Headers.Location!.OriginalString, new Dictionary { ["Input.Code"] = Totp(key) })) + { + challenged.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + var first = await CodeFlowAsync(_host, browser); + + using (var changed = await browser.SubmitAsync("/account/change-password", new Dictionary(NewPasswordFields("A-changed-password-1")) { ["Input.CurrentPassword"] = Password })) + { + changed.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + var second = await CodeFlowAsync(_host, browser); + Sid(second).ShouldBe(Sid(first)); + + await SignOutAsync(browser); + (await RefusedAsync(_host, Text(second, "refresh_token"))).ShouldBe("invalid_grant"); + } + + [Fact] + public async Task TheLogoutOfACookieFromBeforeSessionsWereMarkedEndsTheCookieAlone() + { + var editor = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host); + browser.SetCookie(await UnmarkedCookieAsync(editor)); + var tokens = await CodeFlowAsync(_host, browser); + Payload(Text(tokens, "id_token")).TryGetProperty("sid", out _).ShouldBeFalse(); + + await SignOutAsync(browser); + + browser.HasCookie(SignInCookie).ShouldBeFalse(); + (await RotatedAsync(_host, Text(tokens, "refresh_token"))).ShouldNotBeNullOrEmpty(); + } + // The code flow of the test client in the browser's session. - private async Task CodeFlowAsync(HostedPagesBrowser browser) + private static async Task CodeFlowAsync(FluentCmsTestHost host, HostedPagesBrowser browser) { var request = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri); using var redirect = await browser.GetAsync(request.Url); - return await request.ExchangeAsync(_host, redirect); + return await request.ExchangeAsync(host, redirect); } // The rotated refresh token. - private async Task RefreshAsync(string refreshToken) + private static async Task RotatedAsync(FluentCmsTestHost host, string refreshToken) { - using var response = await PostRefreshAsync(refreshToken); + using var response = await RefreshAsync(host, refreshToken); var body = await response.Content.ReadAsStringAsync(Token); response.StatusCode.ShouldBe(HttpStatusCode.OK, body); using var json = JsonDocument.Parse(body); return json.RootElement.GetProperty("refresh_token").GetString()!; } - private async Task RefusedAsync(string refreshToken) + private static async Task RefusedAsync(FluentCmsTestHost host, string refreshToken) { - using var response = await PostRefreshAsync(refreshToken); + using var response = await RefreshAsync(host, refreshToken); response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Token)); return json.RootElement.GetProperty("error").GetString(); } - private async Task PostRefreshAsync(string refreshToken) + private static async Task MeAsync(FluentCmsTestHost host, string accessToken) { - using var client = _host.CreateSecureClient(); - using var content = new FormUrlEncodedContent(new Dictionary - { - ["grant_type"] = "refresh_token", - ["refresh_token"] = refreshToken, - ["client_id"] = FluentCmsTestHost.OAuthClientId, - }); - return await client.PostAsync("/connect/token", content, Token); - } - - private async Task MeAsync(string accessToken) - { - using var client = _host.CreateSecureClient(); + using var client = host.CreateSecureClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); using var response = await client.GetAsync("/api/management/v1/me", Token); return response.StatusCode; } + // A sign-in cookie as one made before sessions were marked: the time of the sign-in and no server session. + private async Task UnmarkedCookieAsync(TestUser user) + { + await using var scope = _host.Services.CreateAsyncScope(); + var provider = scope.ServiceProvider; + var stored = await provider.GetRequiredService().FindByIdAsync(user.Id.ToString()); + var principal = await provider.GetRequiredService>().CreateUserPrincipalAsync(stored!); + var options = provider.GetRequiredService>().Get(IdentityConstants.ApplicationScheme); + var now = _host.Time.GetUtcNow(); + var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now + options.ExpireTimeSpan }; + properties.Items[CmsSignInManager.SignedInAtItem] = now.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture); + var ticket = new AuthenticationTicket(principal, properties, IdentityConstants.ApplicationScheme); + return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; + } + private static string Text(JsonElement tokens, string name) => tokens.GetProperty(name).GetString()!; + + private static string? Sid(JsonElement tokens) => Payload(Text(tokens, "id_token")).GetProperty("sid").GetString(); + + private static JsonElement Payload(string jwt) + { + using var document = JsonDocument.Parse(Base64Url.DecodeFromChars(jwt.Split('.')[1])); + return document.RootElement.Clone(); + } } diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs index 6780c898c..3f1d1c694 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs @@ -33,6 +33,8 @@ public async Task TheRemoteSignOutOfAProviderEndsTheAdminSessionItMadeAndNoOther var editor = await CreateUserAsync(host); using var password = new HostedPagesBrowser(host); await SignInAsync(password, editor.Email); + var ssoTokens = await CodeFlowAsync(host, sso); + var passwordTokens = await CodeFlowAsync(host, password); // What the provider's front-channel logout loads in the browser. foreach (var (browser, provider) in new[] { (sso, Trusted), (password, Corp) }) @@ -42,9 +44,14 @@ public async Task TheRemoteSignOutOfAProviderEndsTheAdminSessionItMadeAndNoOther browser.HasCookie(SignInCookie).ShouldBeTrue(); } + var ssoRefresh = await RotatedAsync(host, Text(ssoTokens, "refresh_token")); + + // The sign-in it ends takes the tokens of its session with it (#3198), and the other sign-in keeps its own. using var signedOut = await sso.GetAsync($"/account/sso/{Corp}/signout"); signedOut.StatusCode.ShouldBe(HttpStatusCode.OK); sso.HasCookie(SignInCookie).ShouldBeFalse(); + (await RefusedAsync(host, ssoRefresh)).ShouldBe("invalid_grant"); + (await RotatedAsync(host, Text(passwordTokens, "refresh_token"))).ShouldNotBeNullOrEmpty(); } [Fact] diff --git a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs index 0a5afbc74..e30bbf9c2 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs @@ -258,15 +258,50 @@ public async Task TheMemberLogoutPageRevokesTheRefreshTokenOfItsSession() signedOut.StatusCode.ShouldBe(HttpStatusCode.Redirect); } + (await RefreshAsync(FluentCmsTestHost.OAuthMemberClientId, refreshToken)).ShouldBe(HttpStatusCode.BadRequest); + } + + [Fact] + public async Task TheMemberClientsLogoutRevokesTheMembersSessionAndLeavesTheAdminsTokens() + { + var admin = await CreateAdminAsync(); + var address = await fixture.RegisterVerifiedAsync(); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.7"); + await SignInAdminAsync(browser, admin.Email); + await SignInMemberAsync(browser, address); + var adminRequest = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, "openid offline_access management"); + using var adminCode = await browser.GetAsync(adminRequest.Url); + var adminRefresh = (await adminRequest.ExchangeAsync(fixture.Host, adminCode)).GetProperty("refresh_token").GetString()!; + var memberRequest = AuthorizeRequest.For(FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); + using var memberCode = await browser.GetAsync(memberRequest.Url); + var memberRefresh = (await memberRequest.ExchangeAsync(fixture.Host, memberCode)).GetProperty("refresh_token").GetString()!; + + using (var asked = await browser.GetAsync($"/connect/logout?client_id={FluentCmsTestHost.OAuthMemberClientId}")) + { + var page = await browser.PageAsync(asked.Headers.Location!.OriginalString); + using var confirmed = await browser.PostAsync("/connect/logout", page, new Dictionary + { + ["client_id"] = FluentCmsTestHost.OAuthMemberClientId, + [MemberAuthentication.LogoutPageField] = MemberAuthentication.LogoutPageMark, + }); + confirmed.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + (await RefreshAsync(FluentCmsTestHost.OAuthMemberClientId, memberRefresh)).ShouldBe(HttpStatusCode.BadRequest); + (await RefreshAsync(FluentCmsTestHost.OAuthClientId, adminRefresh)).ShouldBe(HttpStatusCode.OK); + } + + private async Task RefreshAsync(string clientId, string refreshToken) + { using var client = fixture.Host.CreateSecureClient(); using var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "refresh_token", ["refresh_token"] = refreshToken, - ["client_id"] = FluentCmsTestHost.OAuthMemberClientId, + ["client_id"] = clientId, }); using var refreshed = await client.PostAsync("/connect/token", content, Token); - refreshed.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + return refreshed.StatusCode; } [Theory] From 184f70ec3cd00017ccfa4d4f509229434a6712d1 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 16 Nov 2026 05:45:48 -0500 Subject: [PATCH 3/6] Revoke nothing at sign-outs another site can cause --- docs/planning/backend-technical-spec.md | 4 +- docs/releases/1.0.0-preview.1.md | 2 +- .../Identity/Members/MemberConnect.cs | 4 +- .../Identity/Oidc/ConnectEndpoints.cs | 36 +++++++-- .../Identity/Sso/SsoRegistration.cs | 11 +-- .../Identity/HostedPagesTests.Logout.cs | 79 ++++++++++++++++--- .../Identity/HostedPagesTests.Sessions.cs | 7 +- .../Members/MemberPagesTests.cs | 58 ++++++++++++++ 8 files changed, 166 insertions(+), 35 deletions(-) diff --git a/docs/planning/backend-technical-spec.md b/docs/planning/backend-technical-spec.md index 9f3690aea..083235d7b 100644 --- a/docs/planning/backend-technical-spec.md +++ b/docs/planning/backend-technical-spec.md @@ -802,7 +802,7 @@ Rows 4.1, 4.2, 4.9 to 4.11, 4.13, 4.15, 4.16, 2.12, 2.13; decisions 7, 30, 33. **Endpoints.** OpenIddict defaults: `/connect/authorize`, `/connect/token`, `/connect/userinfo`, `/connect/introspect`, `/connect/revoke`, `/connect/logout`, `/.well-known/openid-configuration`. Flows: Authorization Code with PKCE for public clients (admin, MCP clients, CLI), rotating refresh tokens, client credentials for service accounts. Access tokens are JWTs signed with keys from a configured certificate or, when none is configured, a generated key persisted in `cms_signing_key` through Data Protection. Audiences: `fluentcms:management` for admins and keys, `fluentcms:members` for members. -**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` issued in the session of the cookie; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). Ending a sign-in also ends what was issued in it ([#3198](https://github.com/fluentcms/FluentCMS/issues/3198)). Every new cookie carries the id of its server session in its properties (`.fcms.server_session`), which its renewals keep as they keep the time of the sign-in; a sign-in on the login page over a live cookie of the same user keeps that id, so the browser's session goes on. The authorize endpoint issues the code of a client without a consent step under an ad-hoc authorization marked with that id (the property `fcms_server_session`), and the identity token carries it as `sid`, as RP-Initiated Logout names it. A sign-in ends, and `UserSessions` revokes every valid authorization of its user marked with its session, with its tokens, whichever clients of the pool signed in through it, at a confirmed logout or one with the session's hint, at the member logout page, at the remote sign-out of the provider it came from (admin SSO as built), when the authorize endpoint ends it for `prompt=login`, `max_age`, `AbsoluteSessionLifetime` or a second factor, and when another user signs in over it; its refresh tokens are refused at once and its access tokens from the next request on, since the bearer scheme checks the token and its authorization on each request. A hint skips the logout page only when its `sid` is the cookie's session: an identity token of the same user from another session, another device or an earlier sign-in, or one without `sid`, goes to the page, which asks. Nothing is revoked where no sign-in ends: a logout that is not confirmed, a confirmation the user does not give, and a request without the cookie, a valid hint included; such a GET with a hint, as a repeated logout sends, returns to the client without asking. The user's other sessions, in another browser or on another device, stay, as does the consent of a third-party client, a permanent authorization of no server session that ends on the account page and gives no `sid`. A browser logout therefore also ends every client without a consent step that signed in through that browser, a CLI, a native app or a first-party MCP client included, whatever `offline_access` it holds; a client that must outlive a browser logout is registered with `RequireConsent`. A cookie from before sessions were marked ends no authorization, and its tokens last as before. A sign-out writes no activity row, and the revocation adds none. `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. +**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` issued in the session of the cookie; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). A logout ends what was issued in the session it ends ([#3198](https://github.com/fluentcms/FluentCMS/issues/3198)). Every new cookie carries the id of its server session in its properties (`.fcms.server_session`), which its renewals keep as they keep the time of the sign-in; a sign-in on the login page over a live cookie of the same user keeps that id, so the browser's session goes on. The authorize endpoint issues the code of a client without a consent step under an ad-hoc authorization marked with that id (the property `fcms_server_session`), and the identity token carries it as `sid`, as RP-Initiated Logout names it. `UserSessions` revokes every valid authorization of the user marked with a session, with its tokens, whichever clients of the pool signed in through it, where the user ends the session or where no request of another site can cause it: a confirmed logout or one with the session's own hint, the member logout page, another user's sign-in over the cookie, and the authorize endpoint's sign-out of a user whose role now requires a second factor the sign-in did not give, whose refresh tokens the token endpoint refuses anyway. Their refresh tokens are refused at once and their access tokens from the next request on, since the bearer scheme checks the token and its authorization on each request. The sign-outs that one cross-site GET can cause end the cookie alone and revoke nothing: `prompt=login`, `max_age` and `AbsoluteSessionLifetime` at the authorize endpoint, since the request carries nothing secret, and the provider's remote sign-out (admin SSO as built), since nothing authenticates it; carrying the session across a re-authentication (#3203), authenticating the remote sign-out (#3204) and counting the absolute lifetime from the sign-in rather than the authorize request (#3205) are open. A hint skips the logout page only when its `sid` is the cookie's session: an identity token of the same user from another session, another device or an earlier sign-in, or one without `sid`, goes to the page, which asks. Nothing is revoked where no sign-in ends: a logout that is not confirmed, a confirmation the user does not give, and a request without the cookie, a valid hint included; such a GET with an identity token of this server as its hint, an expired one or one a first logout revoked included, returns to the client without asking, and one with any other hint goes to the logout page. The user's other sessions, in another browser or on another device, stay, as does the consent of a third-party client, a permanent authorization of no server session that ends on the account page and gives no `sid`. A browser logout therefore also ends every client without a consent step that signed in through that browser, a CLI, a native app or a first-party MCP client included, whatever `offline_access` it holds; a client that must outlive a browser logout is registered with `RequireConsent`. A cookie from before sessions were marked ends no authorization, and its tokens last as before. A sign-out writes no activity row, and the revocation adds none (#3207). `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. **Protected resources as built** ([#2977](https://github.com/fluentcms/FluentCMS/issues/2977)). A plugin's group mapped with `MapProtectedResource(prefix, options)` (`FluentCMS.Plugins.Abstractions`) is an OAuth protected resource of its own (RFC 9728), which is how the MCP plugin maps `/mcp` (5.4). The group gets what `MapGroup` gives (4.13), with four differences. Its operations enter with the origin the plugin names, `Api` or `Mcp`. It takes the Management rate limit and CORS policy, since it takes writes. No endpoint of it opts out of the signed-in caller with `AllowAnonymous()`. And a bearer token needs the scope the plugin names, one of the scopes that say which surface a token is for, which is `mcp` alone today. An API key holds no OAuth scope and is taken by its class, which the evaluator reads; a preview token carries the kind of the principal that minted it, a key's included, so it is told apart by its entry claim and refused as a token without the scope. A request without credentials is a 401 (`FCMS3102`) with `WWW-Authenticate: Bearer resource_metadata="{metadata URL}", scope="{scope}"`, one whose credentials are refused carries `error="invalid_token"` as well, and a token without the scope is a 403 (`FCMS3103`) with `Bearer error="insufficient_scope", scope="{scope}", resource_metadata="{metadata URL}"`. Both come before the per-site gate, as on any group of a plugin. Core serves the metadata, so a plugin still maps nothing under `/.well-known` (`FCMS1524`): `GET /.well-known/oauth-protected-resource{prefix}` answers `{ resource, authorization_servers, scopes_supported, bearer_methods_supported, resource_name }` to anyone, where `resource` is the public URL of the group, `authorization_servers` holds the issuer exactly as the discovery document names it, `scopes_supported` the scope of the resource and `bearer_methods_supported` `header`. `GET /.well-known/oauth-protected-resource`, the document a client tries when it does not know the path of the resource, answers the same while the host has one protected resource and 404 (`FCMS3104`) once it has several, since it could describe one of them only. The documents are endpoints of the `WellKnown` group, so they take its CORS origins and count as the `connect` surface, and they are not gated per site, since an anonymous caller learns nothing of where a plugin is off. The URLs are built from the public origin and the path base (4.15), and from the request when no origin is set, as the issuer is. Under a path base the documents are under it, where RFC 9728 would put the well-known segment before it; the challenge names the URL, which is what a client follows. The authorization server takes the `resource` parameter of RFC 8707 on the authorization request and on the token request when every value is the public URL of a protected resource of the host, compared as an absolute URI with the path as written, and refuses any other with `invalid_target`; like every refusal while the authorization request is checked, it is shown on the error page rather than sent to the client. OpenIddict's own check holds the resources in a list fixed in its options, which cannot name a URL that follows the request, so it is off (`DisableResourceValidation`) and a handler of core's stands in its place. The resource permissions of clients are off too (`IgnoreResourcePermissions`), because the parameter grants nothing: the audience of a token stays `fluentcms:management`, and the scope of the resource, which a client does need a permission for, is what holds a token to it. A token with the `mcp` scope alone manages through `Origin.Mcp` only (4.8) and is refused by the Management API (403). The consent page describes `mcp` as reading and changing content as an AI agent or tool, as far as the user's roles allow. A scope that is not one of those, an origin other than `Api` or `Mcp`, and a prefix mapped as a protected resource twice stop the host with `FCMS1527`; a prefix under a group of core or with a route parameter anywhere in it is `FCMS1524`. Code `FCMS1527`. @@ -826,7 +826,7 @@ Rows 4.1, 4.2, 4.9 to 4.11, 4.13, 4.15, 4.16, 2.12, 2.13; decisions 7, 30, 33. **Admin SSO.** External OIDC providers (Entra ID, Okta, Keycloak and generic OIDC are the same handler with presets) configured in the host configuration and shown read-only in the admin in the first release (runtime editing is a Should). Federation happens on the hosted login page: auto-provisioning, default role, group claim to role mapping, optional local-login disable. -**Admin SSO as built.** `cms.Sso`, bound from `FluentCms:Sso` (`FCMS3070` names a bad key), lists the providers under `Providers:{name}`. A name is 1 to 64 letters, digits, `-` or `_`, and is the provider's authentication scheme, its login provider in `cms_user_login` and its callback path, `/account/sso/{name}`. A name is found whatever its case: `CmsUserStore` finds a login of a provider under the name as it is written and, failing that, under another case of it (other schemes match as written), so a change of case in configuration keeps the users linked ([#3010](https://github.com/fluentcms/FluentCMS/issues/3010)), and a name that is another authentication scheme's in any case, added before the providers or after them, stops the host (`FCMS3070`). Every provider is ASP.NET Core's OpenID Connect handler, added to the authentication options when the host starts. `Preset` (`Oidc`, `EntraId`, `Okta` or `Keycloak`) only builds the authority and names the button: from `TenantId` (`https://login.microsoftonline.com/{tenant}/v2.0`; `common`, `organizations` and `consumers` are refused, since their tokens come from any tenant), from `Domain` and `AuthorizationServerId` (`https://{domain}`, or `https://{domain}/oauth2/{id}`), or from `BaseUrl` and `Realm` (`{base}/realms/{realm}`). `Authority` overrides it, and generic OIDC requires it. The handler runs the code flow with PKCE, with `ClientSecret` when one is set, asks for `openid profile email` and the `Scopes` listed, takes the answer as a form post, and signs into Identity's external cookie with the token's claims under their own names; a host tunes a provider with `services.Configure(name, ...)`. The login page offers a button per provider, and the external login page asks `SsoSignIn`. A user linked to the login signs in. Someone with no user gets one when `AutoProvision` is on (the default), named and addressed by the `EmailClaim` (`email`), with no password, linked in `cms_user_login` and holding `DefaultRole` and the mapped roles, in one transaction, so the user created and role changed events are staged with it (event 9040). A role is named by its id or by the exact name of an instance-wide role; one that does not exist is not given (`FCMS3071`, event 9042). `RoleMappings` is a list of `Group` and `Role`, matched exactly against the values of `GroupsClaim` (`groups`). No group gives a role by its name, so Super Admin is given only by a mapping or a default role that names it. At every later sign-in of a user who is neither deactivated nor locked out, the mapped roles follow the token's groups: a mapped role whose group is gone is taken away, and the default role and the roles the provider does not map stay. A token with no groups claim at all takes the mapped roles away too, and logs event 9044, since Entra ID's group overage or a missing scope looks the same. Groups that would take Super Admin from its last active holder change no role and refuse the sign-in (`not_allowed`, event 9045, `user.change_refused` with `follow_groups`), since the provider no longer vouches for that user and the instance keeps its last Super Admin (admin users as built). A token without an email address, or that does not say `email_verified` is true while the provider's `RequireVerifiedEmail` is on (the default; off, only a false one is refused) (`FCMS3072`), or whose address belongs to a user not linked to the provider (`FCMS3073`), creates no user, and a creation that fails (`FCMS3074`, with Identity's codes only) leaves none, so an address is never taken over unless the provider links existing users (linking as built). Those refusals log event 9043 and raise `LoginFailedEvent` (`external`, `not_allowed`, no user). The provider's remote sign-out path, `/account/sso/{name}/signout`, signs out the Identity application cookie (`SignOutScheme`), so an IdP-initiated logout ends the admin session (#2854), with the authorizations of its server session (#3198); the cookie holds no session id of the provider for the handler to match, so only a sign-in made through that provider, which the cookie's authentication method names and the stamp check keeps, is ended, and another is left as it is. A provider's error, or a callback that belongs to no sign-in started here, goes back to the login page as a failed sign-in (`invalid_credentials`, event 9041) rather than to an error page. **The provider's `amr`.** It counts only from a provider with `TrustMfaClaim`, which is off by default: a token of such a provider whose `amr` holds `mfa` signs in with `amr=mfa` and without the local second factor. Any other external sign-in carries no `amr`, so a role with `RequireTwoFactor` asks for the local second factor after the provider, or sends the user to `/account/enable-two-factor`, as two-factor as built says. `DisableLocalLogin`, which needs a provider, hides the password form and the forgotten-password link, and `CmsSignInManager` refuses every password sign-in (`not_allowed`). A user created by a provider has no password; with local login on, a reset link gives it one. With local login off, an invitation is accepted through a provider (linking as built). Providers come from configuration only: runtime editing and a read-only list in the admin are not built. Codes `FCMS3070` to `FCMS3074`. +**Admin SSO as built.** `cms.Sso`, bound from `FluentCms:Sso` (`FCMS3070` names a bad key), lists the providers under `Providers:{name}`. A name is 1 to 64 letters, digits, `-` or `_`, and is the provider's authentication scheme, its login provider in `cms_user_login` and its callback path, `/account/sso/{name}`. A name is found whatever its case: `CmsUserStore` finds a login of a provider under the name as it is written and, failing that, under another case of it (other schemes match as written), so a change of case in configuration keeps the users linked ([#3010](https://github.com/fluentcms/FluentCMS/issues/3010)), and a name that is another authentication scheme's in any case, added before the providers or after them, stops the host (`FCMS3070`). Every provider is ASP.NET Core's OpenID Connect handler, added to the authentication options when the host starts. `Preset` (`Oidc`, `EntraId`, `Okta` or `Keycloak`) only builds the authority and names the button: from `TenantId` (`https://login.microsoftonline.com/{tenant}/v2.0`; `common`, `organizations` and `consumers` are refused, since their tokens come from any tenant), from `Domain` and `AuthorizationServerId` (`https://{domain}`, or `https://{domain}/oauth2/{id}`), or from `BaseUrl` and `Realm` (`{base}/realms/{realm}`). `Authority` overrides it, and generic OIDC requires it. The handler runs the code flow with PKCE, with `ClientSecret` when one is set, asks for `openid profile email` and the `Scopes` listed, takes the answer as a form post, and signs into Identity's external cookie with the token's claims under their own names; a host tunes a provider with `services.Configure(name, ...)`. The login page offers a button per provider, and the external login page asks `SsoSignIn`. A user linked to the login signs in. Someone with no user gets one when `AutoProvision` is on (the default), named and addressed by the `EmailClaim` (`email`), with no password, linked in `cms_user_login` and holding `DefaultRole` and the mapped roles, in one transaction, so the user created and role changed events are staged with it (event 9040). A role is named by its id or by the exact name of an instance-wide role; one that does not exist is not given (`FCMS3071`, event 9042). `RoleMappings` is a list of `Group` and `Role`, matched exactly against the values of `GroupsClaim` (`groups`). No group gives a role by its name, so Super Admin is given only by a mapping or a default role that names it. At every later sign-in of a user who is neither deactivated nor locked out, the mapped roles follow the token's groups: a mapped role whose group is gone is taken away, and the default role and the roles the provider does not map stay. A token with no groups claim at all takes the mapped roles away too, and logs event 9044, since Entra ID's group overage or a missing scope looks the same. Groups that would take Super Admin from its last active holder change no role and refuse the sign-in (`not_allowed`, event 9045, `user.change_refused` with `follow_groups`), since the provider no longer vouches for that user and the instance keeps its last Super Admin (admin users as built). A token without an email address, or that does not say `email_verified` is true while the provider's `RequireVerifiedEmail` is on (the default; off, only a false one is refused) (`FCMS3072`), or whose address belongs to a user not linked to the provider (`FCMS3073`), creates no user, and a creation that fails (`FCMS3074`, with Identity's codes only) leaves none, so an address is never taken over unless the provider links existing users (linking as built). Those refusals log event 9043 and raise `LoginFailedEvent` (`external`, `not_allowed`, no user). The provider's remote sign-out path, `/account/sso/{name}/signout`, signs out the Identity application cookie (`SignOutScheme`), so an IdP-initiated logout ends the admin session (#2854); the cookie holds no session id of the provider for the handler to match, so only a sign-in made through that provider, which the cookie's authentication method names and the stamp check keeps, is ended, and another is left as it is. A provider's error, or a callback that belongs to no sign-in started here, goes back to the login page as a failed sign-in (`invalid_credentials`, event 9041) rather than to an error page. **The provider's `amr`.** It counts only from a provider with `TrustMfaClaim`, which is off by default: a token of such a provider whose `amr` holds `mfa` signs in with `amr=mfa` and without the local second factor. Any other external sign-in carries no `amr`, so a role with `RequireTwoFactor` asks for the local second factor after the provider, or sends the user to `/account/enable-two-factor`, as two-factor as built says. `DisableLocalLogin`, which needs a provider, hides the password form and the forgotten-password link, and `CmsSignInManager` refuses every password sign-in (`not_allowed`). A user created by a provider has no password; with local login on, a reset link gives it one. With local login off, an invitation is accepted through a provider (linking as built). Providers come from configuration only: runtime editing and a read-only list in the admin are not built. Codes `FCMS3070` to `FCMS3074`. **Linking external logins as built.** The page that accepts an invitation offers a button per provider of `cms.Sso` next to the password form, and with `DisableLocalLogin` the providers only, since `InvitationService` then refuses a password (`FCMS3093`). The provider comes back to that page, and `SsoSignIn` accepts the invitation with the external login when the address of the provider's `EmailClaim` is the invitation's, as Identity normalizes addresses, and the token does not say `email_verified` is false (`FCMS3072`); another address is refused (`FCMS3092`) and the invitation stays pending. The user is named by the invitation's address, has no password, holds the invitation's roles and is linked in the transaction that uses the invitation up; it then signs in as at any sign-in through the provider, so the mapped roles follow its groups and `TrustMfaClaim` and `RequireTwoFactor` apply as before, and the default role is not given. An error or a cancel at the provider returns to the invitation. `LinkExistingUsers` on a provider, off by default, links at its first sign-in through the provider the user whose address the token carries and who has no login of that provider, only when the token says `email_verified` is true, so a provider that sends no such claim links no one; a user who cannot sign in now is not linked, and without the option or the claim the address is refused as before. An invitation needs no explicit `email_verified` because its link already showed that the person reads the mailbox, and an existing user has no such proof. Linking and removing a login raise `UserLoginLinkedEvent` and `UserLoginUnlinkedEvent` from `CmsUserStore` with the change, the activity rows `user.login_linked` and `user.login_unlinked` with the provider. `GET /users/{id}/logins` (`users.manage`) and `GET /me/logins` list `{ "provider", "providerKey", "displayName" }`, and `DELETE /users/{id}/logins/{provider}` (with every grant of the user's roles too) and `DELETE /me/logins/{provider}` remove the user's logins of that provider (`FCMS3091` when it has none) with a new security stamp, which ends the user's sessions. The last way to sign in is not removed (`FCMS3090`, 409): a login counts while its provider is offered on the login page, and a password while local login is on. With a public origin (4.15), the `redirect_uri` a provider is given, and the code is redeemed with, is built from it in `OnRedirectToIdentityProvider`. Codes `FCMS3090` to `FCMS3093`; event ids 9060 to 9062. diff --git a/docs/releases/1.0.0-preview.1.md b/docs/releases/1.0.0-preview.1.md index bb28ff525..9dbb56024 100644 --- a/docs/releases/1.0.0-preview.1.md +++ b/docs/releases/1.0.0-preview.1.md @@ -70,7 +70,7 @@ A media field read with `populate`, and an image of rich text read with `richTex ## Bugs fixed - A setting that is not text, such as `maxOutputTokens` of AI assist, is no longer taken for a secret by its name (#3079). -- A logout revokes the authorizations issued in the browser's sign-in, with their refresh and access tokens, where it ended the sign-in cookie alone. The confirmed logout, one with an `id_token_hint` of that session, the member logout page and a provider's remote sign-out revoke them, and so do a new sign-in for `prompt=login`, `max_age` or a second factor and another user's sign-in in the same browser. An identity token carries the session as `sid`, and a hint from another session goes to the logout page, which asks. The user's other sessions and a third-party client's consent stay; a client without a consent step that must outlive a browser logout, such as a CLI or a native app, is registered with `RequireConsent` (#3198). +- A logout revokes the authorizations issued in the browser's sign-in, with their refresh and access tokens, where it ended the sign-in cookie alone. The confirmed logout, one with an `id_token_hint` of that session and the member logout page revoke them, and so do another user's sign-in in the same browser and the authorize endpoint's sign-out of a user whose role now requires a second factor. The sign-outs another site can cause with one GET, `prompt=login`, `max_age` and `AbsoluteSessionLifetime` at the authorize endpoint and a provider's remote sign-out, end the cookie alone (#3203, #3204, #3205). An identity token carries the session as `sid`, and a logout whose hint lacks the session's `sid`, such as a third-party client's token or one from a sign-in before this preview, is asked to confirm. The user's other sessions and a third-party client's consent stay; a client without a consent step that must outlive a browser logout, such as a CLI or a native app, is registered with `RequireConsent` (#3198). - Restoring, reading and diffing a version written before a field was renamed with `[FormerNames]` keep the field's value, and a former name that another field of the type holds is refused (#3085). - A media reference read on the Delivery API resolves to its public asset, where it answered null (#3109). - A media reference read on `/graphql` by a caller that may not manage resolves to its public asset, where it answered null (#3112). diff --git a/src/FluentCMS.Core/Identity/Members/MemberConnect.cs b/src/FluentCMS.Core/Identity/Members/MemberConnect.cs index 4015c2fcb..b32144571 100644 --- a/src/FluentCMS.Core/Identity/Members/MemberConnect.cs +++ b/src/FluentCMS.Core/Identity/Members/MemberConnect.cs @@ -58,9 +58,7 @@ public static async Task AuthorizeAsync(HttpContext context, OpenIddict return ConnectEndpoints.Refuse(Errors.LoginRequired, "The sign-in is older than the client or the server accepts."); } - // The sign-in ends with the authorizations of its server session, as at a logout. - await context.RequestServices.GetRequiredService() - .EndAsync(member.Id.ToString("D"), CmsSignInManager.ServerSession(cookie.Properties!), CancellationToken.None); + // The cookie alone ends: another site can send this request, so it revokes nothing (#3203). await signIn.SignOutAsync(); return Results.Challenge(new AuthenticationProperties { RedirectUri = afterSignIn }, [MemberAuthentication.CookieScheme]); } diff --git a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs index 4c37ac9b1..0ab2d0f56 100644 --- a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs +++ b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs @@ -17,7 +17,10 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; using OpenIddict.Abstractions; +using OpenIddict.Server; using OpenIddict.Server.AspNetCore; using static OpenIddict.Abstractions.OpenIddictConstants; @@ -115,7 +118,8 @@ private static async Task AuthorizeAsync(HttpContext context) return Refuse(Errors.LoginRequired, "The sign-in is older than the client or the server accepts."); } - await EndSignInAsync(context, cookie, members: false); + // The cookie alone ends: another site can send this request, so it revokes nothing (#3203). + await context.SignOutAsync(IdentityConstants.ApplicationScheme); return Results.Challenge(new AuthenticationProperties { RedirectUri = afterSignIn }, [IdentityConstants.ApplicationScheme]); } @@ -350,7 +354,7 @@ private static async Task LogoutAsync(HttpContext context) : (IdentityConstants.ApplicationScheme, HostedPagePaths.Logout); var cookie = await context.AuthenticateAsync(scheme); - if (!await ConfirmedAsync(context, members) && !HintsSignedInUser(context, hint, cookie, members)) + if (!await ConfirmedAsync(context, members) && !await HintsSignedInUserAsync(context, hint, cookie, members)) { return Results.Redirect(context.Request.PathBase + page + QueryString.Create(LogoutParameters(context))); } @@ -405,16 +409,17 @@ private static IResult ErrorPage(HttpContext context, OpenIddictResponse respons })); // OpenIddict passes a hint it cannot read through without a principal, so the hint is checked here. Without the cookie - // a GET, which a browser sends with it, has no one signed in, so a hint of any kind returns to the client: a repeated - // logout's hint, whose token the first one revoked, included. A POST may be a cross-site one, which never carries it. + // a GET, which a browser sends with it, has no one signed in, so an identity token of this server returns to the + // client, an expired one or a repeated logout's, whose token the first one revoked, included; a hint that is not one + // goes to the logout page. A POST may be a cross-site one, which never carries it. // With the cookie, the hint must be of the cookie's server session (its sid), not only of its user: an id token from // another session or device, or from an earlier sign-in, goes to the logout page. The cookie is the one of the pool the // request is for, read by that pool's manager. - private static bool HintsSignedInUser(HttpContext context, AuthenticateResult hint, AuthenticateResult cookie, bool members) + private static async Task HintsSignedInUserAsync(HttpContext context, AuthenticateResult hint, AuthenticateResult cookie, bool members) { if (!cookie.Succeeded) { - return HttpMethods.IsGet(context.Request.Method) && !string.IsNullOrEmpty(context.GetOpenIddictServerRequest()?.IdTokenHint); + return HttpMethods.IsGet(context.Request.Method) && await IsOwnIdentityTokenAsync(context, context.GetOpenIddictServerRequest()?.IdTokenHint); } return hint.Principal?.GetClaim(Claims.Subject) is { } subject @@ -423,6 +428,25 @@ private static bool HintsSignedInUser(HttpContext context, AuthenticateResult hi && hint.Principal.GetClaim(TokenClaims.ServerSession) == serverSession; } + // Signed with a key of this server as an identity token, whatever its lifetime or its entry's status. + private static async Task IsOwnIdentityTokenAsync(HttpContext context, string? token) + { + if (string.IsNullOrEmpty(token)) + { + return false; + } + + var options = context.RequestServices.GetRequiredService>().CurrentValue; + var result = await new JsonWebTokenHandler().ValidateTokenAsync(token, new TokenValidationParameters + { + IssuerSigningKeys = [.. options.SigningCredentials.Select(credentials => credentials.Key)], + ValidTypes = [JwtConstants.HeaderType], + ValidateAudience = false, + ValidateIssuer = false, + ValidateLifetime = false, + }); + return result.IsValid; + } // Ends the cookie's sign-in and, with it, the authorizations of its server session, so that nothing issued in a // session outlives its cookie; an end the browser stops waiting for still ends them. private static async Task EndSignInAsync(HttpContext context, AuthenticateResult cookie, bool members) diff --git a/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs b/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs index 7a33f650f..7b08928f1 100644 --- a/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs +++ b/src/FluentCMS.Core/Identity/Sso/SsoRegistration.cs @@ -1,6 +1,5 @@ using System.Security.Claims; using FluentCMS.Core.DependencyInjection; -using FluentCMS.Core.Identity.Oidc; using FluentCMS.Events; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; @@ -105,22 +104,14 @@ public void Configure(string? name, OpenIdConnectOptions options) // The provider's front-channel logout ends the sign-in on the hosted pages, the admin session. The cookie holds no // session id of the provider for the handler to match, so a sign-in made another way, with a password or another - // provider, is left as it is. The sign-in it ends takes the authorizations of its server session with it, as a - // logout does. + // provider, is left as it is. private static async Task OwnSignInOnlyAsync(RemoteSignOutContext context) { var cookie = await context.HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme); if (!string.Equals(cookie.Principal?.FindFirstValue(ClaimTypes.AuthenticationMethod), context.Scheme.Name, StringComparison.OrdinalIgnoreCase)) { context.HandleResponse(); - return; } - - var services = context.HttpContext.RequestServices; - await services.GetRequiredService().EndAsync( - services.GetRequiredService>().GetUserId(cookie.Principal!), - CmsSignInManager.ServerSession(cookie.Properties!), - CancellationToken.None); } // Identity takes the external login's key from the name identifier, which the token calls sub. diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs index 2a57183a2..9ebc2eb42 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs @@ -2,7 +2,9 @@ using System.Net; using System.Net.Http.Headers; using System.Text.Json; +using FluentCMS.Core.Authorization; using FluentCMS.Core.Identity; +using FluentCMS.Core.IntegrationTests.Management; using FluentCMS.Testing; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; @@ -109,7 +111,12 @@ public async Task ALogoutLeavesTheConsentOfAThirdPartyClient() // A consent is no session's, so its identity token names none, and its hint is asked about. Payload(Text(issued, "id_token")).TryGetProperty("sid", out _).ShouldBeFalse(); + using (var hinted = await browser.GetAsync("/connect/logout?id_token_hint=" + Uri.EscapeDataString(Text(issued, "id_token")))) + { + hinted.Headers.Location!.OriginalString.ShouldStartWith("/account/logout?"); + } + browser.HasCookie(SignInCookie).ShouldBeTrue(); await SignOutAsync(browser); // The client keeps its token, and the next sign-in is not asked again. @@ -120,7 +127,7 @@ public async Task ALogoutLeavesTheConsentOfAThirdPartyClient() } [Fact] - public async Task ASignInOverALiveOneKeepsTheSessionOfItsUserAndEndsAnothersAndAReauthenticationEndsIt() + public async Task ASignInOverALiveOneKeepsTheSessionOfItsUserAndEndsAnothers() { var editor = await CreateUserAsync(_host); var other = await CreateUserAsync(_host); @@ -141,17 +148,63 @@ public async Task ASignInOverALiveOneKeepsTheSessionOfItsUserAndEndsAnothersAndA var replaced = await CodeFlowAsync(_host, browser); await SignInAsync(browser, other.Email); (await RefusedAsync(_host, Text(replaced, "refresh_token"))).ShouldBe("invalid_grant"); - var others = await CodeFlowAsync(_host, browser); - Sid(others).ShouldNotBe(Sid(replaced)); + Sid(await CodeFlowAsync(_host, browser)).ShouldNotBe(Sid(replaced)); + } - // prompt=login ends the sign-in it replaces, with what was issued in it. - var request = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri, prompt: "login"); - using var login = await browser.GetAsync(request.Url); - login.Headers.Location!.AbsolutePath.ShouldBe("/account/login"); - browser.HasCookie(SignInCookie).ShouldBeFalse(); - (await RefusedAsync(_host, Text(others, "refresh_token"))).ShouldBe("invalid_grant"); + [Fact] + public async Task AReauthenticationAnotherSiteCanAskForEndsTheCookieAndRevokesNothing() + { + await using var host = NewHost(_emails).Configure(cms => cms.Clients.AbsoluteSessionLifetime = TimeSpan.FromHours(8)); + var editor = await CreateUserAsync(host); + using var browser = new HostedPagesBrowser(host); + + // A top-level GET from another site carries the cookie and nothing secret: prompt=login, max_age=0, and any + // authorize request past the absolute lifetime sign the cookie out and leave the session's tokens working. + var authorize = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri).Url; + var login = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri, prompt: "login").Url; + foreach (var (url, wait) in new[] { (login, TimeSpan.Zero), (authorize + "&max_age=0", TimeSpan.Zero), (authorize, TimeSpan.FromHours(2)) }) + { + await SignInAsync(browser, editor.Email); + host.Time.Advance(TimeSpan.FromHours(7)); + var tokens = await CodeFlowAsync(host, browser); + host.Time.Advance(wait); + + using var foreign = await browser.GetAsync(url); + new Uri(OAuthBase, foreign.Headers.Location!).AbsolutePath.ShouldBe("/account/login", url); + browser.HasCookie(SignInCookie).ShouldBeFalse(); + + var renewed = await RenewedAsync(host, Text(tokens, "refresh_token")); + (await MeAsync(host, Text(renewed, "access_token"))).ShouldBe(HttpStatusCode.OK, url); + } } + [Fact] + public async Task ASecondFactorTheRoleNowRequiresEndsTheSessionAtAuthorize() + { + using var admin = await _host.AsUserAsync(await _host.CreateUserAsync(BuiltInRoles.SuperAdminName, cancellationToken: Token)); + var editor = await CreateUserAsync(_host); + await EnableTwoFactorAsync(_host, editor); + using var browser = new HostedPagesBrowser(_host, "10.1.0.13"); + browser.SetCookie(await _host.SignInCookieAsync(editor)); + var tokens = await CodeFlowAsync(_host, browser); + (await MeAsync(_host, Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.OK); + + (await AdminFixture.SendAsync(admin, HttpMethod.Put, $"users/{editor.Id:D}/roles/{await GuardedRoleAsync(admin)}")).Status.ShouldBe(HttpStatusCode.OK); + using var challenged = await browser.GetAsync(AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri).Url); + challenged.Headers.Location!.AbsolutePath.ShouldBe("/account/login"); + + // The session's tokens, which the token endpoint would refuse at their next refresh anyway, end with the cookie. + (await MeAsync(_host, Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task AnUnreadableHintWithoutTheCookieGoesToTheLogoutPage() + { + using var browser = new HostedPagesBrowser(_host, "10.1.0.14"); + using var response = await browser.GetAsync($"/connect/logout?id_token_hint=not.a.token&client_id={ThirdPartyClientId}&post_logout_redirect_uri={Uri.EscapeDataString(ThirdPartySignedOutUri)}"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location!.OriginalString.ShouldStartWith("/account/logout?"); + } [Fact] public async Task ASignInWithTheSecondFactorAndAPasswordChangeKeepTheSessionThatTheLogoutEnds() { @@ -211,6 +264,14 @@ private static async Task RotatedAsync(FluentCmsTestHost host, string re return json.RootElement.GetProperty("refresh_token").GetString()!; } + private static async Task RenewedAsync(FluentCmsTestHost host, string refreshToken) + { + using var response = await RefreshAsync(host, refreshToken); + var body = await response.Content.ReadAsStringAsync(Token); + response.StatusCode.ShouldBe(HttpStatusCode.OK, body); + using var json = JsonDocument.Parse(body); + return json.RootElement.Clone(); + } private static async Task RefusedAsync(FluentCmsTestHost host, string refreshToken) { using var response = await RefreshAsync(host, refreshToken); diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs index 3f1d1c694..22574b2c1 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Sessions.cs @@ -44,13 +44,12 @@ public async Task TheRemoteSignOutOfAProviderEndsTheAdminSessionItMadeAndNoOther browser.HasCookie(SignInCookie).ShouldBeTrue(); } - var ssoRefresh = await RotatedAsync(host, Text(ssoTokens, "refresh_token")); - - // The sign-in it ends takes the tokens of its session with it (#3198), and the other sign-in keeps its own. + // Nothing authenticates the provider's request, so it ends the cookie alone and the session's tokens work on (#3204). using var signedOut = await sso.GetAsync($"/account/sso/{Corp}/signout"); signedOut.StatusCode.ShouldBe(HttpStatusCode.OK); sso.HasCookie(SignInCookie).ShouldBeFalse(); - (await RefusedAsync(host, ssoRefresh)).ShouldBe("invalid_grant"); + var renewed = await RenewedAsync(host, Text(ssoTokens, "refresh_token")); + (await MeAsync(host, Text(renewed, "access_token"))).ShouldBe(HttpStatusCode.OK); (await RotatedAsync(host, Text(passwordTokens, "refresh_token"))).ShouldNotBeNullOrEmpty(); } diff --git a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs index e30bbf9c2..0a6ac3330 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs @@ -291,6 +291,64 @@ public async Task TheMemberClientsLogoutRevokesTheMembersSessionAndLeavesTheAdmi (await RefreshAsync(FluentCmsTestHost.OAuthClientId, adminRefresh)).ShouldBe(HttpStatusCode.OK); } + [Fact] + public async Task AnAdminLogoutLeavesTheMembersTokens() + { + var admin = await CreateAdminAsync(); + var address = await fixture.RegisterVerifiedAsync(); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.8"); + await SignInAdminAsync(browser, admin.Email); + await SignInMemberAsync(browser, address); + var adminTokens = await CodeFlowAsync(browser, FluentCmsTestHost.OAuthClientId, "openid offline_access management"); + var memberTokens = await CodeFlowAsync(browser, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); + + var page = await browser.PageAsync("/account/logout"); + using (var signedOut = await browser.PostAsync("/connect/logout", page, new Dictionary())) + { + signedOut.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + (await RefreshAsync(FluentCmsTestHost.OAuthClientId, adminTokens.GetProperty("refresh_token").GetString()!)).ShouldBe(HttpStatusCode.BadRequest); + (await RefreshAsync(FluentCmsTestHost.OAuthMemberClientId, memberTokens.GetProperty("refresh_token").GetString()!)).ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task AMemberSignInOverALiveOneKeepsTheSameMembersSessionAndEndsOnlyAnothers() + { + var first = await fixture.RegisterVerifiedAsync(); + var second = await fixture.RegisterVerifiedAsync(); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.9"); + using var otherDevice = new HostedPagesBrowser(fixture.Host, "10.8.0.10"); + await SignInMemberAsync(browser, first); + await SignInMemberAsync(otherDevice, first); + var before = await CodeFlowAsync(browser, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); + var elsewhere = await CodeFlowAsync(otherDevice, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); + + // The same member signs in again: the browser's session goes on. + await SignInMemberAsync(browser, first); + var after = await CodeFlowAsync(browser, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); + Sid(after).ShouldBe(Sid(before)); + (await RefreshAsync(FluentCmsTestHost.OAuthMemberClientId, before.GetProperty("refresh_token").GetString()!)).ShouldBe(HttpStatusCode.OK); + + // Another member signs in over it: the first member's session in this browser ends, and its other device's stays. + await SignInMemberAsync(browser, second); + (await RefreshAsync(FluentCmsTestHost.OAuthMemberClientId, after.GetProperty("refresh_token").GetString()!)).ShouldBe(HttpStatusCode.BadRequest); + (await RefreshAsync(FluentCmsTestHost.OAuthMemberClientId, elsewhere.GetProperty("refresh_token").GetString()!)).ShouldBe(HttpStatusCode.OK); + Sid(await CodeFlowAsync(browser, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access")).ShouldNotBe(Sid(after)); + } + + private async Task CodeFlowAsync(HostedPagesBrowser browser, string clientId, string scope) + { + var request = AuthorizeRequest.For(clientId, scope); + using var code = await browser.GetAsync(request.Url); + return await request.ExchangeAsync(fixture.Host, code); + } + + private static string? Sid(JsonElement tokens) + { + using var payload = JsonDocument.Parse(Base64Url.DecodeFromChars(tokens.GetProperty("id_token").GetString()!.Split('.')[1])); + return payload.RootElement.GetProperty("sid").GetString(); + } private async Task RefreshAsync(string clientId, string refreshToken) { using var client = fixture.Host.CreateSecureClient(); From ce3cd19da779188c661ba0a1635625de1bd81edf Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 16 Nov 2026 06:24:30 -0500 Subject: [PATCH 4/6] Revoke nothing at authorize and bind a hint without the cookie to its client --- docs/planning/backend-technical-spec.md | 2 +- docs/releases/1.0.0-preview.1.md | 2 +- .../Identity/Oidc/ConnectEndpoints.cs | 36 ++++++-- .../Identity/HostedPagesTests.Logout.cs | 84 ++++++++++++++++--- .../Members/MemberPagesTests.cs | 16 ++++ 5 files changed, 119 insertions(+), 21 deletions(-) diff --git a/docs/planning/backend-technical-spec.md b/docs/planning/backend-technical-spec.md index 083235d7b..56e45465d 100644 --- a/docs/planning/backend-technical-spec.md +++ b/docs/planning/backend-technical-spec.md @@ -802,7 +802,7 @@ Rows 4.1, 4.2, 4.9 to 4.11, 4.13, 4.15, 4.16, 2.12, 2.13; decisions 7, 30, 33. **Endpoints.** OpenIddict defaults: `/connect/authorize`, `/connect/token`, `/connect/userinfo`, `/connect/introspect`, `/connect/revoke`, `/connect/logout`, `/.well-known/openid-configuration`. Flows: Authorization Code with PKCE for public clients (admin, MCP clients, CLI), rotating refresh tokens, client credentials for service accounts. Access tokens are JWTs signed with keys from a configured certificate or, when none is configured, a generated key persisted in `cms_signing_key` through Data Protection. Audiences: `fluentcms:management` for admins and keys, `fluentcms:members` for members. -**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` issued in the session of the cookie; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). A logout ends what was issued in the session it ends ([#3198](https://github.com/fluentcms/FluentCMS/issues/3198)). Every new cookie carries the id of its server session in its properties (`.fcms.server_session`), which its renewals keep as they keep the time of the sign-in; a sign-in on the login page over a live cookie of the same user keeps that id, so the browser's session goes on. The authorize endpoint issues the code of a client without a consent step under an ad-hoc authorization marked with that id (the property `fcms_server_session`), and the identity token carries it as `sid`, as RP-Initiated Logout names it. `UserSessions` revokes every valid authorization of the user marked with a session, with its tokens, whichever clients of the pool signed in through it, where the user ends the session or where no request of another site can cause it: a confirmed logout or one with the session's own hint, the member logout page, another user's sign-in over the cookie, and the authorize endpoint's sign-out of a user whose role now requires a second factor the sign-in did not give, whose refresh tokens the token endpoint refuses anyway. Their refresh tokens are refused at once and their access tokens from the next request on, since the bearer scheme checks the token and its authorization on each request. The sign-outs that one cross-site GET can cause end the cookie alone and revoke nothing: `prompt=login`, `max_age` and `AbsoluteSessionLifetime` at the authorize endpoint, since the request carries nothing secret, and the provider's remote sign-out (admin SSO as built), since nothing authenticates it; carrying the session across a re-authentication (#3203), authenticating the remote sign-out (#3204) and counting the absolute lifetime from the sign-in rather than the authorize request (#3205) are open. A hint skips the logout page only when its `sid` is the cookie's session: an identity token of the same user from another session, another device or an earlier sign-in, or one without `sid`, goes to the page, which asks. Nothing is revoked where no sign-in ends: a logout that is not confirmed, a confirmation the user does not give, and a request without the cookie, a valid hint included; such a GET with an identity token of this server as its hint, an expired one or one a first logout revoked included, returns to the client without asking, and one with any other hint goes to the logout page. The user's other sessions, in another browser or on another device, stay, as does the consent of a third-party client, a permanent authorization of no server session that ends on the account page and gives no `sid`. A browser logout therefore also ends every client without a consent step that signed in through that browser, a CLI, a native app or a first-party MCP client included, whatever `offline_access` it holds; a client that must outlive a browser logout is registered with `RequireConsent`. A cookie from before sessions were marked ends no authorization, and its tokens last as before. A sign-out writes no activity row, and the revocation adds none (#3207). `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. +**Authorization server as built.** OpenIddict 7 with its EF Core stores on the system model in `cms_oidc_application`, `cms_oidc_authorization`, `cms_oidc_scope` and `cms_oidc_token` (GUID keys, snake_case columns), and `cms_signing_key`. The endpoints are in the `Connect` route group, which takes the `auth` rate limit, the Management and the Members CORS origins and the security headers; discovery and the key set are at `/.well-known/openid-configuration` and `/.well-known/jwks` in a `WellKnown` group with the same origins. PKCE is required of every client, not only public ones, and only `S256` is offered. A refresh token rotates, and a used one is refused once OpenIddict's reuse leeway of 30 seconds is over, which lets two refreshes that cross, as two tabs of one application make, both succeed; a reuse after it revokes the session's tokens. A zero leeway was the first choice and was given up (#2854), since it signed users out on such a race. The token endpoint reads the user again for a code or a refresh token and refuses one who is deactivated or locked out, or whose security stamp, which codes and refresh tokens carry, has changed, so a password change or reset ends them. A bearer token is read from the `Authorization` header only. Access tokens are signed, not encrypted, JWTs with the audience `fluentcms:management`, and carry `sub`, `name`, `fcms_kind` (`AdminUser`, or `ServiceAccount` for client credentials, whose `sub` is the client's id), `scope`, `client_id` and, for a service account only, `roles`; a user's roles are read from `cms_user_role` on each request as before. `fluentcms:members` is the audience of a member's tokens, and the bearer scheme accepts both (members as built). Scopes are `openid`, `profile`, `email`, `offline_access`, `draft`, `management` and `mcp`, and narrow what roles allow as 4.8 says. The `FluentCms` scheme's bearer scheme is OpenIddict's validation scheme on the local server, which rewrites a valid token's principal to those claims and checks the token and its authorization in the database on each request, so a revoked session stops its access tokens at once. The request bridge sets `OperationContext.ClientId` from `client_id`, and a request from the client named by `cms.Clients.AdminClientId` (`fluentcms-admin` by default) runs with `Origin.Admin`. A refused credential keeps its handler's 401 code over HTTP (`FCMS3016` or `FCMS3019`), and `FCMS3102` otherwise. Tokens are signed with `FluentCms:Security:SigningCertificate` (a PKCS#12 file with an RSA key; `FCMS3022` when it cannot be read) or else with a generated RSA key kept in `cms_signing_key` and protected with Data Protection, which is what `ISigningKeyStatus` reports for `FCMS1102`; the symmetric key that encrypts codes and refresh tokens is always generated and kept there. The first key of each use has a fixed id, so instances that start together on an empty table insert one row and the others read it; the primary key settles that race with no wait, so it does not take `IDistributedLock` (4.15). The Data Protection key ring is in `cms_data_protection_key` under the application name `FluentCMS` unless the host persists it elsewhere. Clients are registered at start from `cms.Clients.Applications`, bound from `FluentCms:Clients:Applications:{clientId}` (`FCMS3021` for a bad one): a client with redirect URIs uses the code flow and refresh tokens, one with a secret is confidential and may use client credentials with the instance-wide roles it names, a listed client is replaced by its options at each start, one the options registered and no longer list is deleted with its sessions and tokens and a warning, unless the options list none at all, and others are left alone. Consent is implicit for these clients unless one sets `RequireConsent` (see the hosted pages as built). The authorize endpoint challenges the Identity application cookie, whose login page is `/account/login`, and answers `login_required` to `prompt=none`; logout ends that cookie on the POST of the logout page, which carries an antiforgery token, or with a valid `id_token_hint` issued in the session of the cookie; any other request, a cross-site POST or a POST with a hint but without the cookie included, goes to the logout page, which asks, and a request without the cookie only returns to the client, with no expiring cookie (#2854). A logout ends what was issued in the session it ends ([#3198](https://github.com/fluentcms/FluentCMS/issues/3198)). Every new cookie carries the id of its server session in its properties (`.fcms.server_session`), which its renewals keep as they keep the time of the sign-in; a sign-in on the login page over a live cookie of the same user keeps that id, so the browser's session goes on. The authorize endpoint issues the code of a client without a consent step under an ad-hoc authorization marked with that id (the property `fcms_server_session`), and the identity token carries it as `sid`, as RP-Initiated Logout names it. `UserSessions` revokes every valid authorization of the user marked with a session, with its tokens, whichever clients of the pool signed in through it, where the user ends the session or where no request of another site can cause it: a confirmed logout or one with the session's own hint, the member logout page, and another user's sign-in over the cookie. Their refresh tokens are refused at once and their access tokens from the next request on, since the bearer scheme checks the token and its authorization on each request. The sign-outs that one cross-site GET can cause end the cookie alone and revoke nothing: `prompt=login`, `max_age`, `AbsoluteSessionLifetime` and a second factor that the user's role now requires and the sign-in did not give, at the authorize endpoint, since the request carries nothing secret, and the provider's remote sign-out (admin SSO as built), since nothing authenticates it; carrying the session across a re-authentication, where the access tokens of a user whose role now requires a second factor also live until they expire (#3203), authenticating the remote sign-out (#3204) and counting the absolute lifetime from the sign-in rather than the authorize request (#3205) are open. A hint skips the logout page only when its `sid` is the cookie's session: an identity token of the same user from another session, another device or an earlier sign-in, or one without `sid`, goes to the page, which asks. Nothing is revoked where no sign-in ends: a logout that is not confirmed, a confirmation the user does not give, and a request without the cookie, a valid hint included; such a GET returns to the client without asking when its hint is an identity token signed by this server, an expired one or one a first logout revoked included, issued to the client its `client_id` names, if it names one, and whose client registered the `post_logout_redirect_uri` it asks for, if it asks for one; any other hint goes to the logout page. The user's other sessions, in another browser or on another device, stay, as does the consent of a third-party client, a permanent authorization of no server session that ends on the account page and gives no `sid`. A browser logout therefore also ends every client without a consent step that signed in through that browser, a CLI, a native app or a first-party MCP client included, whatever `offline_access` it holds; a client that must outlive a browser logout is registered with `RequireConsent`. A cookie from before sessions were marked ends no authorization, and its tokens last as before. A sign-out writes no activity row, and the revocation adds none (#3207). `UserSessions` lists a user's valid authorizations that still hold a token in use as sessions and revokes one with its tokens, for the Management API (#2786), and the `oidc.prune` job removes unusable tokens and authorizations after 14 days. The Data Protection ring is stored unencrypted unless the host adds an encryptor, which `IDataProtectionStatus` reports, and Production refuses to start without one (`FCMS1106`, `UnencryptedKeyRingCheck`) unless `FluentCms:Security:AllowUnencryptedKeyRing` is true. A host adds it with Data Protection's own builder, `AddDataProtection().ProtectKeysWithCertificate(...)` or `ProtectKeysWithAzureKeyVault(...)` or any other `IXmlEncryptor`, which it reaches from `IServiceCollection` like any host, so Core has no pass-through for it. Export and backup packages must never include `cms_data_protection_key`, `cms_signing_key` or `cms_oidc_*`. Codes `FCMS3021` and `FCMS3022`. **Protected resources as built** ([#2977](https://github.com/fluentcms/FluentCMS/issues/2977)). A plugin's group mapped with `MapProtectedResource(prefix, options)` (`FluentCMS.Plugins.Abstractions`) is an OAuth protected resource of its own (RFC 9728), which is how the MCP plugin maps `/mcp` (5.4). The group gets what `MapGroup` gives (4.13), with four differences. Its operations enter with the origin the plugin names, `Api` or `Mcp`. It takes the Management rate limit and CORS policy, since it takes writes. No endpoint of it opts out of the signed-in caller with `AllowAnonymous()`. And a bearer token needs the scope the plugin names, one of the scopes that say which surface a token is for, which is `mcp` alone today. An API key holds no OAuth scope and is taken by its class, which the evaluator reads; a preview token carries the kind of the principal that minted it, a key's included, so it is told apart by its entry claim and refused as a token without the scope. A request without credentials is a 401 (`FCMS3102`) with `WWW-Authenticate: Bearer resource_metadata="{metadata URL}", scope="{scope}"`, one whose credentials are refused carries `error="invalid_token"` as well, and a token without the scope is a 403 (`FCMS3103`) with `Bearer error="insufficient_scope", scope="{scope}", resource_metadata="{metadata URL}"`. Both come before the per-site gate, as on any group of a plugin. Core serves the metadata, so a plugin still maps nothing under `/.well-known` (`FCMS1524`): `GET /.well-known/oauth-protected-resource{prefix}` answers `{ resource, authorization_servers, scopes_supported, bearer_methods_supported, resource_name }` to anyone, where `resource` is the public URL of the group, `authorization_servers` holds the issuer exactly as the discovery document names it, `scopes_supported` the scope of the resource and `bearer_methods_supported` `header`. `GET /.well-known/oauth-protected-resource`, the document a client tries when it does not know the path of the resource, answers the same while the host has one protected resource and 404 (`FCMS3104`) once it has several, since it could describe one of them only. The documents are endpoints of the `WellKnown` group, so they take its CORS origins and count as the `connect` surface, and they are not gated per site, since an anonymous caller learns nothing of where a plugin is off. The URLs are built from the public origin and the path base (4.15), and from the request when no origin is set, as the issuer is. Under a path base the documents are under it, where RFC 9728 would put the well-known segment before it; the challenge names the URL, which is what a client follows. The authorization server takes the `resource` parameter of RFC 8707 on the authorization request and on the token request when every value is the public URL of a protected resource of the host, compared as an absolute URI with the path as written, and refuses any other with `invalid_target`; like every refusal while the authorization request is checked, it is shown on the error page rather than sent to the client. OpenIddict's own check holds the resources in a list fixed in its options, which cannot name a URL that follows the request, so it is off (`DisableResourceValidation`) and a handler of core's stands in its place. The resource permissions of clients are off too (`IgnoreResourcePermissions`), because the parameter grants nothing: the audience of a token stays `fluentcms:management`, and the scope of the resource, which a client does need a permission for, is what holds a token to it. A token with the `mcp` scope alone manages through `Origin.Mcp` only (4.8) and is refused by the Management API (403). The consent page describes `mcp` as reading and changing content as an AI agent or tool, as far as the user's roles allow. A scope that is not one of those, an origin other than `Api` or `Mcp`, and a prefix mapped as a protected resource twice stop the host with `FCMS1527`; a prefix under a group of core or with a route parameter anywhere in it is `FCMS1524`. Code `FCMS1527`. diff --git a/docs/releases/1.0.0-preview.1.md b/docs/releases/1.0.0-preview.1.md index 9dbb56024..648925381 100644 --- a/docs/releases/1.0.0-preview.1.md +++ b/docs/releases/1.0.0-preview.1.md @@ -70,7 +70,7 @@ A media field read with `populate`, and an image of rich text read with `richTex ## Bugs fixed - A setting that is not text, such as `maxOutputTokens` of AI assist, is no longer taken for a secret by its name (#3079). -- A logout revokes the authorizations issued in the browser's sign-in, with their refresh and access tokens, where it ended the sign-in cookie alone. The confirmed logout, one with an `id_token_hint` of that session and the member logout page revoke them, and so do another user's sign-in in the same browser and the authorize endpoint's sign-out of a user whose role now requires a second factor. The sign-outs another site can cause with one GET, `prompt=login`, `max_age` and `AbsoluteSessionLifetime` at the authorize endpoint and a provider's remote sign-out, end the cookie alone (#3203, #3204, #3205). An identity token carries the session as `sid`, and a logout whose hint lacks the session's `sid`, such as a third-party client's token or one from a sign-in before this preview, is asked to confirm. The user's other sessions and a third-party client's consent stay; a client without a consent step that must outlive a browser logout, such as a CLI or a native app, is registered with `RequireConsent` (#3198). +- A logout revokes the authorizations issued in the browser's sign-in, with their refresh and access tokens, where it ended the sign-in cookie alone. The confirmed logout, one with an `id_token_hint` of that session and the member logout page revoke them, and so does another user's sign-in in the same browser. The sign-outs another site can cause with one GET, `prompt=login`, `max_age`, `AbsoluteSessionLifetime` and a second factor the role now requires at the authorize endpoint, and a provider's remote sign-out, end the cookie alone (#3203, #3204, #3205). An identity token carries the session as `sid`, and a logout whose hint lacks the session's `sid`, such as a third-party client's token or one from a sign-in before this preview, is asked to confirm, and a logout without the cookie returns to the client without asking only for an identity token of this server issued to that client. The user's other sessions and a third-party client's consent stay; a client without a consent step that must outlive a browser logout, such as a CLI or a native app, is registered with `RequireConsent` (#3198). - Restoring, reading and diffing a version written before a field was renamed with `[FormerNames]` keep the field's value, and a former name that another field of the type holds is refused (#3085). - A media reference read on the Delivery API resolves to its public asset, where it answered null (#3109). - A media reference read on `/graphql` by a caller that may not manage resolves to its public asset, where it answered null (#3112). diff --git a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs index 0ab2d0f56..3f1f87137 100644 --- a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs +++ b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs @@ -137,7 +137,7 @@ private static async Task AuthorizeAsync(HttpContext context) return Refuse(Errors.LoginRequired, "The user's role requires a sign-in with a second factor."); } - await EndSignInAsync(context, cookie, members: false); + await context.SignOutAsync(IdentityConstants.ApplicationScheme); return Results.Challenge(new AuthenticationProperties { RedirectUri = afterSignIn }, [IdentityConstants.ApplicationScheme]); } @@ -409,9 +409,9 @@ private static IResult ErrorPage(HttpContext context, OpenIddictResponse respons })); // OpenIddict passes a hint it cannot read through without a principal, so the hint is checked here. Without the cookie - // a GET, which a browser sends with it, has no one signed in, so an identity token of this server returns to the - // client, an expired one or a repeated logout's, whose token the first one revoked, included; a hint that is not one - // goes to the logout page. A POST may be a cross-site one, which never carries it. + // a GET, which a browser sends with it, has no one signed in, so an identity token of this server for the client the + // request names returns to it, an expired one or a repeated logout's, whose token the first one revoked, included; any + // other hint goes to the logout page. A POST may be a cross-site one, which never carries it. // With the cookie, the hint must be of the cookie's server session (its sid), not only of its user: an id token from // another session or device, or from an earlier sign-in, goes to the logout page. The cookie is the one of the pool the // request is for, read by that pool's manager. @@ -419,7 +419,7 @@ private static async Task HintsSignedInUserAsync(HttpContext context, Auth { if (!cookie.Succeeded) { - return HttpMethods.IsGet(context.Request.Method) && await IsOwnIdentityTokenAsync(context, context.GetOpenIddictServerRequest()?.IdTokenHint); + return HttpMethods.IsGet(context.Request.Method) && await IsOwnIdentityTokenAsync(context, ServerRequest(context).IdTokenHint); } return hint.Principal?.GetClaim(Claims.Subject) is { } subject @@ -428,7 +428,8 @@ private static async Task HintsSignedInUserAsync(HttpContext context, Auth && hint.Principal.GetClaim(TokenClaims.ServerSession) == serverSession; } - // Signed with a key of this server as an identity token, whatever its lifetime or its entry's status. + // An identity token signed with a key of this server, whatever its lifetime or its entry's status, of the client the + // request names and whose post-logout URI it asks for. OpenIddict checks those only on a hint it can read. private static async Task IsOwnIdentityTokenAsync(HttpContext context, string? token) { if (string.IsNullOrEmpty(token)) @@ -440,12 +441,33 @@ private static async Task IsOwnIdentityTokenAsync(HttpContext context, str var result = await new JsonWebTokenHandler().ValidateTokenAsync(token, new TokenValidationParameters { IssuerSigningKeys = [.. options.SigningCredentials.Select(credentials => credentials.Key)], + ValidAlgorithms = [.. options.SigningCredentials.Select(credentials => credentials.Algorithm).Distinct(StringComparer.Ordinal)], ValidTypes = [JwtConstants.HeaderType], ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, }); - return result.IsValid; + if (!result.IsValid || result.SecurityToken is not JsonWebToken identity) + { + return false; + } + + var audiences = identity.Audiences.ToList(); + var clientId = identity.TryGetPayloadValue(Claims.AuthorizedParty, out var party) ? party : audiences.Count == 1 ? audiences[0] : null; + var request = ServerRequest(context); + if (clientId is null || (request.ClientId is { } named && named != clientId)) + { + return false; + } + + if (string.IsNullOrEmpty(request.PostLogoutRedirectUri)) + { + return true; + } + + var applications = context.RequestServices.GetRequiredService(); + return await applications.FindByClientIdAsync(clientId, context.RequestAborted) is { } application + && await applications.ValidatePostLogoutRedirectUriAsync(application, request.PostLogoutRedirectUri, context.RequestAborted); } // Ends the cookie's sign-in and, with it, the authorizations of its server session, so that nothing issued in a // session outlives its cookie; an end the browser stops waiting for still ends them. diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs index 9ebc2eb42..ceb3ff52b 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs @@ -1,9 +1,11 @@ using System.Buffers.Text; using System.Net; using System.Net.Http.Headers; +using System.Security.Cryptography; using System.Text.Json; using FluentCMS.Core.Authorization; using FluentCMS.Core.Identity; +using FluentCMS.Core.Identity.Oidc; using FluentCMS.Core.IntegrationTests.Management; using FluentCMS.Testing; using Microsoft.AspNetCore.Authentication; @@ -11,6 +13,8 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; using Shouldly; using Xunit; @@ -69,7 +73,7 @@ public async Task ALogoutWithAHintRevokesOnlyWhenItEndsTheSessionOfItsCookie() using (var stranger = new HostedPagesBrowser(_host, "10.1.0.10")) using (var returned = await stranger.GetAsync(hint)) { - returned.StatusCode.ShouldBe(HttpStatusCode.Redirect); + returned.Headers.Location!.OriginalString.ShouldBe("/account/logout"); } // The user's hint is not the other device's session: that device is asked, and its cookie and this session stay. @@ -179,31 +183,86 @@ public async Task AReauthenticationAnotherSiteCanAskForEndsTheCookieAndRevokesNo } [Fact] - public async Task ASecondFactorTheRoleNowRequiresEndsTheSessionAtAuthorize() + public async Task ASecondFactorTheRoleNowRequiresEndsTheCookieAtAuthorizeAndRevokesNothing() { using var admin = await _host.AsUserAsync(await _host.CreateUserAsync(BuiltInRoles.SuperAdminName, cancellationToken: Token)); var editor = await CreateUserAsync(_host); - await EnableTwoFactorAsync(_host, editor); + var (key, _) = await EnableTwoFactorAsync(_host, editor); using var browser = new HostedPagesBrowser(_host, "10.1.0.13"); - browser.SetCookie(await _host.SignInCookieAsync(editor)); - var tokens = await CodeFlowAsync(_host, browser); - (await MeAsync(_host, Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.OK); + // A sign-in with the second factor on a remembered device, then one with the password alone over it, in one session. + using (var password = await browser.SubmitAsync("/account/login", Credentials(editor.Email, Password))) + using (var remembered = await browser.SubmitAsync(password.Headers.Location!.OriginalString, new Dictionary { ["Input.Code"] = Totp(key), ["Input.RememberMachine"] = "true" })) + { + remembered.StatusCode.ShouldBe(HttpStatusCode.Redirect); + } + + var withSecondFactor = await CodeFlowAsync(_host, browser); + await SignInAsync(browser, editor.Email); + var withPassword = await CodeFlowAsync(_host, browser); + Sid(withPassword).ShouldBe(Sid(withSecondFactor)); + + // Another site sends the browser to a plain authorize request once the role requires the second factor: the cookie + // ends, and the tokens are left to the token endpoint, which refuses only those without it. (await AdminFixture.SendAsync(admin, HttpMethod.Put, $"users/{editor.Id:D}/roles/{await GuardedRoleAsync(admin)}")).Status.ShouldBe(HttpStatusCode.OK); using var challenged = await browser.GetAsync(AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, FluentCmsTestHost.OAuthRedirectUri).Url); challenged.Headers.Location!.AbsolutePath.ShouldBe("/account/login"); + browser.HasCookie(SignInCookie).ShouldBeFalse(); - // The session's tokens, which the token endpoint would refuse at their next refresh anyway, end with the cookie. - (await MeAsync(_host, Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.Unauthorized); + (await MeAsync(_host, Text(withSecondFactor, "access_token"))).ShouldBe(HttpStatusCode.OK); + (await RotatedAsync(_host, Text(withSecondFactor, "refresh_token"))).ShouldNotBeNullOrEmpty(); + (await RefusedAsync(_host, Text(withPassword, "refresh_token"))).ShouldBe("invalid_grant"); } [Fact] - public async Task AnUnreadableHintWithoutTheCookieGoesToTheLogoutPage() + public async Task AHintWithoutTheCookieReturnsOnlyAnIdentityTokenOfThisServerToItsOwnClient() { + var editor = await CreateUserAsync(_host); using var browser = new HostedPagesBrowser(_host, "10.1.0.14"); - using var response = await browser.GetAsync($"/connect/logout?id_token_hint=not.a.token&client_id={ThirdPartyClientId}&post_logout_redirect_uri={Uri.EscapeDataString(ThirdPartySignedOutUri)}"); - response.StatusCode.ShouldBe(HttpStatusCode.Redirect); - response.Headers.Location!.OriginalString.ShouldStartWith("/account/logout?"); + using var stranger = new HostedPagesBrowser(_host, "10.1.0.15"); + var signedOut = Uri.EscapeDataString(ThirdPartySignedOutUri); + + // Not an identity token of this server: something else, one signed with another key, and an access token of it. + await SignInAsync(browser, editor.Email); + var tokens = await CodeFlowAsync(_host, browser); + using var otherKey = RSA.Create(2048); + var foreign = new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor + { + Issuer = OAuthBase.AbsoluteUri, + Audience = ThirdPartyClientId, + Claims = new Dictionary { ["sub"] = editor.Id.ToString("D"), ["azp"] = ThirdPartyClientId }, + SigningCredentials = new SigningCredentials(new RsaSecurityKey(otherKey), SecurityAlgorithms.RsaSha256), + }); + foreach (var hint in new[] { "not.a.token", foreign, Text(tokens, "access_token") }) + { + using var response = await stranger.GetAsync($"/connect/logout?id_token_hint={Uri.EscapeDataString(hint)}&client_id={ThirdPartyClientId}&post_logout_redirect_uri={signedOut}"); + response.Headers.Location!.OriginalString.ShouldStartWith("/account/logout?"); + } + + // A revoked identity token of the test client is not the third-party client's, whose signed-out URI it asks for. + await SignOutAsync(browser); + var revoked = Uri.EscapeDataString(Text(tokens, "id_token")); + foreach (var query in new[] { $"&post_logout_redirect_uri={signedOut}", $"&client_id={ThirdPartyClientId}&post_logout_redirect_uri={signedOut}", $"&client_id={ThirdPartyClientId}" }) + { + using var response = await stranger.GetAsync($"/connect/logout?id_token_hint={revoked}{query}&state=s1"); + response.Headers.Location!.OriginalString.ShouldStartWith("/account/logout?", Case.Sensitive, query); + } + + // The third-party client's own revoked hint returns to its own signed-out URI without asking. + await SignInAsync(browser, editor.Email); + var request = AuthorizeRequest.For(ThirdPartyClientId, ThirdPartyRedirectUri, "openid management"); + using var asked = await browser.GetAsync(request.Url); + var consent = asked.Headers.Location!.OriginalString; + using var allowed = await browser.PostAsync(consent, await browser.PageAsync(consent), new Dictionary { ["decision"] = "allow" }); + using var done = await browser.FollowAsync(allowed, ThirdPartyRedirectUri); + var own = Uri.EscapeDataString(Text(await request.ExchangeAsync(_host, done), "id_token")); + await using (var scope = _host.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService().RevokeAllAsync(editor.Id, Token); + } + + using var back = await stranger.GetAsync($"/connect/logout?id_token_hint={own}&client_id={ThirdPartyClientId}&post_logout_redirect_uri={signedOut}&state=s1"); + back.Headers.Location!.AbsoluteUri.ShouldBe(ThirdPartySignedOutUri + "?state=s1"); } [Fact] public async Task ASignInWithTheSecondFactorAndAPasswordChangeKeepTheSessionThatTheLogoutEnds() @@ -272,6 +331,7 @@ private static async Task RenewedAsync(FluentCmsTestHost host, stri using var json = JsonDocument.Parse(body); return json.RootElement.Clone(); } + private static async Task RefusedAsync(FluentCmsTestHost host, string refreshToken) { using var response = await RefreshAsync(host, refreshToken); diff --git a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs index 0a6ac3330..d2ff87a9a 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs @@ -337,6 +337,22 @@ public async Task AMemberSignInOverALiveOneKeepsTheSameMembersSessionAndEndsOnly Sid(await CodeFlowAsync(browser, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access")).ShouldNotBe(Sid(after)); } + [Fact] + public async Task AMemberReauthenticationAnotherSiteCanAskForEndsTheCookieAndRevokesNothing() + { + var address = await fixture.RegisterVerifiedAsync(); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.11"); + foreach (var prompt in new[] { "&prompt=login", "&max_age=0" }) + { + await SignInMemberAsync(browser, address); + var tokens = await CodeFlowAsync(browser, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); + + using var foreign = await browser.GetAsync("/connect/authorize" + AuthorizeRequest.Query(FluentCmsTestHost.OAuthMemberClientId, "openid") + prompt); + foreign.Headers.Location!.OriginalString.ShouldContain("/account/members/login", Case.Sensitive, prompt); + browser.HasCookie(MemberCookie).ShouldBeFalse(); + (await RefreshAsync(FluentCmsTestHost.OAuthMemberClientId, tokens.GetProperty("refresh_token").GetString()!)).ShouldBe(HttpStatusCode.OK, prompt); + } + } private async Task CodeFlowAsync(HostedPagesBrowser browser, string clientId, string scope) { var request = AuthorizeRequest.For(clientId, scope); From ff3539c37434acefd72543a29f175d950ccc554d Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 16 Nov 2026 06:27:06 -0500 Subject: [PATCH 5/6] Separate the logout helpers with a blank line --- src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs index 3f1f87137..6d6ce62c7 100644 --- a/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs +++ b/src/FluentCMS.Core/Identity/Oidc/ConnectEndpoints.cs @@ -469,6 +469,7 @@ private static async Task IsOwnIdentityTokenAsync(HttpContext context, str return await applications.FindByClientIdAsync(clientId, context.RequestAborted) is { } application && await applications.ValidatePostLogoutRedirectUriAsync(application, request.PostLogoutRedirectUri, context.RequestAborted); } + // Ends the cookie's sign-in and, with it, the authorizations of its server session, so that nothing issued in a // session outlives its cookie; an end the browser stops waiting for still ends them. private static async Task EndSignInAsync(HttpContext context, AuthenticateResult cookie, bool members) From f02f5ccda8cea0d5acf523216e8fe023097be32c Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 16 Nov 2026 07:25:21 -0500 Subject: [PATCH 6/6] Give the new logout and member tests their own client addresses --- .../Identity/HostedPagesTests.Logout.cs | 10 +++++----- .../Members/MemberPagesTests.cs | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs index ceb3ff52b..da27491a4 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs @@ -27,7 +27,7 @@ public sealed partial class HostedPagesTests public async Task AConfirmedLogoutRevokesTheTokensOfItsSessionAndLeavesTheUsersOtherSessions() { var editor = await CreateUserAsync(_host); - using var browser = new HostedPagesBrowser(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.16"); using var otherDevice = new HostedPagesBrowser(_host, "10.1.0.9"); await SignInAsync(browser, editor.Email); await SignInAsync(otherDevice, editor.Email); @@ -62,7 +62,7 @@ public async Task AConfirmedLogoutRevokesTheTokensOfItsSessionAndLeavesTheUsersO public async Task ALogoutWithAHintRevokesOnlyWhenItEndsTheSessionOfItsCookie() { var editor = await CreateUserAsync(_host); - using var browser = new HostedPagesBrowser(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.17"); using var otherDevice = new HostedPagesBrowser(_host, "10.1.0.11"); await SignInAsync(browser, editor.Email); await SignInAsync(otherDevice, editor.Email); @@ -102,7 +102,7 @@ public async Task ALogoutWithAHintRevokesOnlyWhenItEndsTheSessionOfItsCookie() public async Task ALogoutLeavesTheConsentOfAThirdPartyClient() { var editor = await CreateUserAsync(_host); - using var browser = new HostedPagesBrowser(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.18"); await SignInAsync(browser, editor.Email); var request = AuthorizeRequest.For(ThirdPartyClientId, ThirdPartyRedirectUri, "openid management"); @@ -135,7 +135,7 @@ public async Task ASignInOverALiveOneKeepsTheSessionOfItsUserAndEndsAnothers() { var editor = await CreateUserAsync(_host); var other = await CreateUserAsync(_host); - using var browser = new HostedPagesBrowser(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.19"); await SignInAsync(browser, editor.Email); var before = await CodeFlowAsync(_host, browser); @@ -294,7 +294,7 @@ public async Task ASignInWithTheSecondFactorAndAPasswordChangeKeepTheSessionThat public async Task TheLogoutOfACookieFromBeforeSessionsWereMarkedEndsTheCookieAlone() { var editor = await CreateUserAsync(_host); - using var browser = new HostedPagesBrowser(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.20"); browser.SetCookie(await UnmarkedCookieAsync(editor)); var tokens = await CodeFlowAsync(_host, browser); Payload(Text(tokens, "id_token")).TryGetProperty("sid", out _).ShouldBeFalse(); diff --git a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs index d2ff87a9a..6d466e366 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs @@ -246,7 +246,7 @@ public async Task AMembersIdTokenAsAHintEndsTheMemberSessionAndLeavesTheAdmins() public async Task TheMemberLogoutPageRevokesTheRefreshTokenOfItsSession() { var address = await fixture.RegisterVerifiedAsync(); - using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.6"); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.20"); await SignInMemberAsync(browser, address); var request = AuthorizeRequest.For(FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); using var code = await browser.GetAsync(request.Url); @@ -266,7 +266,7 @@ public async Task TheMemberClientsLogoutRevokesTheMembersSessionAndLeavesTheAdmi { var admin = await CreateAdminAsync(); var address = await fixture.RegisterVerifiedAsync(); - using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.7"); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.21"); await SignInAdminAsync(browser, admin.Email); await SignInMemberAsync(browser, address); var adminRequest = AuthorizeRequest.For(FluentCmsTestHost.OAuthClientId, "openid offline_access management"); @@ -296,7 +296,7 @@ public async Task AnAdminLogoutLeavesTheMembersTokens() { var admin = await CreateAdminAsync(); var address = await fixture.RegisterVerifiedAsync(); - using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.8"); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.22"); await SignInAdminAsync(browser, admin.Email); await SignInMemberAsync(browser, address); var adminTokens = await CodeFlowAsync(browser, FluentCmsTestHost.OAuthClientId, "openid offline_access management"); @@ -317,8 +317,8 @@ public async Task AMemberSignInOverALiveOneKeepsTheSameMembersSessionAndEndsOnly { var first = await fixture.RegisterVerifiedAsync(); var second = await fixture.RegisterVerifiedAsync(); - using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.9"); - using var otherDevice = new HostedPagesBrowser(fixture.Host, "10.8.0.10"); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.23"); + using var otherDevice = new HostedPagesBrowser(fixture.Host, "10.8.0.24"); await SignInMemberAsync(browser, first); await SignInMemberAsync(otherDevice, first); var before = await CodeFlowAsync(browser, FluentCmsTestHost.OAuthMemberClientId, "openid offline_access"); @@ -341,7 +341,7 @@ public async Task AMemberSignInOverALiveOneKeepsTheSameMembersSessionAndEndsOnly public async Task AMemberReauthenticationAnotherSiteCanAskForEndsTheCookieAndRevokesNothing() { var address = await fixture.RegisterVerifiedAsync(); - using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.11"); + using var browser = new HostedPagesBrowser(fixture.Host, "10.8.0.25"); foreach (var prompt in new[] { "&prompt=login", "&max_age=0" }) { await SignInMemberAsync(browser, address);