diff --git a/docs/decisions/0007-admin-sign-in-flow.md b/docs/decisions/0007-admin-sign-in-flow.md index 1bc2767b6..3fbe4e888 100644 --- a/docs/decisions/0007-admin-sign-in-flow.md +++ b/docs/decisions/0007-admin-sign-in-flow.md @@ -43,5 +43,5 @@ We will write the sign-in in the admin, in C#, as `AdminSession` in `FluentCMS.A - Drafts are in `sessionStorage` in clear text until they are restored and saved, discarded, removed at sign-out, or the tab closes. - A wrong `authority` in `config.json` sends the code, the PKCE verifier and a stored refresh token to that origin; `config.json` is as trusted as `index.html` (spec 2.5). - Every page of the same origin, the hosted pages and the API reference among them, can read the tab's `sessionStorage`. - - A logout the user does not confirm on the hosted page leaves the server's session alive, so opening the admin again signs in without a prompt. + - A logout the user does not confirm on the hosted page leaves the server's session and its tokens alive, so opening the admin again signs in without a prompt. A confirmed logout ends the server's session and revokes every authorization issued in it, with its refresh and access tokens (#3198), so a revocation at `/connect/revoke` that is cut off or fails at sign-out leaves no refresh token redeemable once the logout is confirmed. A logout does not end a sign-in from before #3198, whose cookie carries no session id, or the consent of a third-party client. - The browser end-to-end tests of A-11 prove the flow in a browser against the reference host; the component and API tests cannot show the whole-page redirects, `sessionStorage` itself, or the Content-Security-Policy. diff --git a/docs/planning/backend-technical-spec.md b/docs/planning/backend-technical-spec.md index e262f30dc..1906a7ad8 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` 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`. @@ -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). @@ -1169,7 +1169,7 @@ Rows 10.3, 10.5 to 10.8, 10.11 to 10.15. **Multi-instance.** Stateless API; Data Protection and signing keys persisted to the database by default; jobs lease through the database; `IDistributedLock` defaults to a `cms_lock` table and gets a Redis provider in `FluentCMS.Caching.Redis`; output cache in memory by default or Redis; media on shared storage. -**Multi-instance as built.** `IDistributedLock` (`FluentCMS.Providers`, in the SDK) has one method, `TryAcquireAsync(name, timeout)`, which returns a handle that releases the lock when disposed, or null when the timeout passed first (`TimeSpan.Zero` tries once, `Timeout.InfiniteTimeSpan` waits until the lock is free); the handle's `Lost` token is canceled when the lock is lost while held. Core's default, added with `TryAdd` and with no options, keeps one row per name in `cms_lock (name, owner, acquired_at, lease_until)`. A holder takes a 30 second lease and renews it every 10 seconds while it holds the lock, so a holder that stopped without releasing it blocks the others until its lease runs out, and the next holder takes it over with a warning (event id 9160). Taking the lock is an update conditional on the row being free or its lease over, so of two that try at once one wins, and a waiter only reads the row while the lock is held, polling from every 50 milliseconds up to once a second. A free lock keeps its row with no owner, so only the first use of a name inserts, and lock names are a fixed set, one per task rather than one per item. A renewal that finds another holder, or that fails until the lease has run out, cancels `Lost` (9161); a renewal or a release that fails is logged (9162, 9163), and a release changes nothing once another holder has the lock. SQLite has one writer, so while another connection keeps a write transaction open, such as the schema apply or schema sync that holds the lock, a renewal waits for it and gives up after the busy timeout and the retries of Microsoft.Data.Sqlite, about 35 seconds, and so does a take; in the rollback journal mode a read of the row can wait too. Such a command, which `IDataProvider.IsBusy` recognises (SQLite's busy and locked errors by their primary code, never on PostgreSQL or SQL Server), changed nothing: a waiter counts the lock as held and ends with the lock or its timeout, which it can overshoot by one such wait, and the holder reads the row, which in WAL mode does not wait, and keeps the lock while the row still names it, renewing again at once and logging once that it waits (9165). A take and a renewal each run in a transaction of their own and read the clock once it has begun, so on SQLite, where beginning it waits for the writer, a lease starts when the database let the write in, not when it was asked for; on PostgreSQL and SQL Server the clock is still read before a statement that can wait on the row, as before. Before, a holder whose transaction lasted longer than about 45 seconds lost the lock, which canceled the rest of its work and rolled the transaction back, and a waiter failed with `SqliteException` ([#3176](https://github.com/fluentcms/FluentCMS/issues/3176)). One race remains: a waiter that found the lease over while such a transaction lasted waits for the writer beside the holder's renewal, and when the transaction ends it can come first. The renewal then finds the other holder and cancels `Lost`, but a holder with more than one unit of work under the lock may have work left: schema apply records the schema history after its change, and EF commits what came before a SQLite table rebuild. With a waiter present at the end of a long transaction, the waiter took the lock in 4 of 16 measured rounds, and the holder's `Lost` fired 64 to 119 milliseconds after the commit; when the holder began its next write at once, the waiter took it in none of 16. Known and left to [#3186](https://github.com/fluentcms/FluentCMS/issues/3186): a `schema apply` that loses the lock this way after its change ends with the generic `FCMS3302 ... TaskCanceledException`, not with a message that says to run it again, which records the history; and the waiter's event 9160 then says that a holder stopped without releasing the lock while that holder is alive. Leases are read against each instance's clock, so instances keep their clocks in step, as the job leases already need. The Data Protection ring is in `cms_data_protection_key` (4.7), so instances on one database read each other's cookies and protected payloads, and the keys survive a restart. Data Protection makes a key when its ring has none it can use, and instances that started together on an empty ring each made one; one that had read only its own kept it for up to a day, refusing the others' cookies once the two minutes in which Data Protection reloads the ring for an unknown key were over. The key manager now makes a key under the lock `fluentcms:data-protection-key`, after reading the ring again, and returns a key that another instance made in the last five minutes (the clock skew Data Protection allows) instead of making a second; when the lock is not free within 10 seconds it makes the key without it (9164). The wait blocks the thread Data Protection asks on, since `IKeyManager` is synchronous, so it covers a live holder, which makes its key within a second, and not one that stopped without releasing the lock, whose 30 second lease it used to wait out. A synchronous `TryAcquire` on `IDistributedLock` is declined: the default lock is a table read through EF Core's asynchronous calls, so it would only move the blocking, and every provider of the slot would have to implement it (item 6 of [#2887](https://github.com/fluentcms/FluentCMS/issues/2887)). The changes that can take Super Admin from its last holder run under `fluentcms:super-admins` (4.7), and fail rather than go on without it. The Delivery output cache is the `IOutputCacheStore` slot, in memory by default, which evicts only the copies of its own instance; a host that registers a shared store, such as `Microsoft.AspNetCore.OutputCaching.StackExchangeRedis`, evicts for every instance, and the key's schema hash keeps instances on different schemas apart (4.10). The member mail limit (4.7) is kept in the `IDistributedCache` slot, the framework's `MemoryDistributedCache` by default, one per instance, so N instances behind a load balancer send an address up to N mails a minute of each slot; a host with several instances registers a shared cache, such as `RedisCache`, and the startup report lists `member-mail-limit-per-instance` in Production while an email sender is set up and the cache is the in-memory one ([#3073](https://github.com/fluentcms/FluentCMS/issues/3073)). Each instance keeps its own copy of the sites and their locales, of plugin enablement and of settings, and sees a change another instance made within 30 seconds (4.6, 4.13); role changes are seen on the next request everywhere, since every request reads the role stamps (4.8). The Redis provider in `FluentCMS.Caching.Redis` is still to come. +**Multi-instance as built.** `IDistributedLock` (`FluentCMS.Providers`, in the SDK) has one method, `TryAcquireAsync(name, timeout)`, which returns a handle that releases the lock when disposed, or null when the timeout passed first (`TimeSpan.Zero` tries once, `Timeout.InfiniteTimeSpan` waits until the lock is free); the handle's `Lost` token is canceled when the lock is lost while held. Core's default, added with `TryAdd` and with no options, keeps one row per name in `cms_lock (name, owner, acquired_at, lease_until)`. A holder takes a 30 second lease and renews it every 10 seconds while it holds the lock, so a holder that stopped without releasing it blocks the others until its lease runs out, and the next holder takes it over with a warning (event id 9160). Taking the lock is an update conditional on the row being free or its lease over, so of two that try at once one wins, and a waiter only reads the row while the lock is held, polling from every 50 milliseconds up to once a second. A free lock keeps its row with no owner, so only the first use of a name inserts, and lock names are a fixed set, one per task rather than one per item. A renewal that finds another holder, or that fails until the lease has run out, cancels `Lost` (9161); a renewal or a release that fails is logged (9162, 9163), and a release changes nothing once another holder has the lock. SQLite has one writer, so while another connection keeps a write transaction open, such as the schema apply or schema sync that holds the lock, a renewal waits for it and gives up after the busy timeout and the retries of Microsoft.Data.Sqlite, about 35 seconds, and so does a take; in the rollback journal mode a read of the row can wait too. Such a command, which `IDataProvider.IsBusy` recognises (SQLite's busy and locked errors by their primary code, never on PostgreSQL or SQL Server), changed nothing: a waiter counts the lock as held and ends with the lock or its timeout, which it can overshoot by one such wait, and the holder reads the row, which in WAL mode does not wait, and keeps the lock while the row still names it, renewing again at once and logging once that it waits (9165). A take and a renewal each run in a transaction of their own and read the clock once it has begun, so on SQLite, where beginning it waits for the writer, a lease starts when the database let the write in, not when it was asked for; on PostgreSQL and SQL Server the clock is still read before a statement that can wait on the row, as before. A take that loses the insert of a name's first row rolls its transaction back before it reads the row, since a read on another connection of the in-memory database waits for it ([#3200](https://github.com/fluentcms/FluentCMS/issues/3200)). Before, a holder whose transaction lasted longer than about 45 seconds lost the lock, which canceled the rest of its work and rolled the transaction back, and a waiter failed with `SqliteException` ([#3176](https://github.com/fluentcms/FluentCMS/issues/3176)). One race remains: a waiter that found the lease over while such a transaction lasted waits for the writer beside the holder's renewal, and when the transaction ends it can come first. The renewal then finds the other holder and cancels `Lost`, but a holder with more than one unit of work under the lock may have work left: schema apply records the schema history after its change, and EF commits what came before a SQLite table rebuild. With a waiter present at the end of a long transaction, the waiter took the lock in 4 of 16 measured rounds, and the holder's `Lost` fired 64 to 119 milliseconds after the commit; when the holder began its next write at once, the waiter took it in none of 16. Known and left to [#3186](https://github.com/fluentcms/FluentCMS/issues/3186): a `schema apply` that loses the lock this way after its change ends with the generic `FCMS3302 ... TaskCanceledException`, not with a message that says to run it again, which records the history; and the waiter's event 9160 then says that a holder stopped without releasing the lock while that holder is alive. Leases are read against each instance's clock, so instances keep their clocks in step, as the job leases already need. The Data Protection ring is in `cms_data_protection_key` (4.7), so instances on one database read each other's cookies and protected payloads, and the keys survive a restart. Data Protection makes a key when its ring has none it can use, and instances that started together on an empty ring each made one; one that had read only its own kept it for up to a day, refusing the others' cookies once the two minutes in which Data Protection reloads the ring for an unknown key were over. The key manager now makes a key under the lock `fluentcms:data-protection-key`, after reading the ring again, and returns a key that another instance made in the last five minutes (the clock skew Data Protection allows) instead of making a second; when the lock is not free within 10 seconds it makes the key without it (9164). The wait blocks the thread Data Protection asks on, since `IKeyManager` is synchronous, so it covers a live holder, which makes its key within a second, and not one that stopped without releasing the lock, whose 30 second lease it used to wait out. A synchronous `TryAcquire` on `IDistributedLock` is declined: the default lock is a table read through EF Core's asynchronous calls, so it would only move the blocking, and every provider of the slot would have to implement it (item 6 of [#2887](https://github.com/fluentcms/FluentCMS/issues/2887)). The changes that can take Super Admin from its last holder run under `fluentcms:super-admins` (4.7), and fail rather than go on without it. The Delivery output cache is the `IOutputCacheStore` slot, in memory by default, which evicts only the copies of its own instance; a host that registers a shared store, such as `Microsoft.AspNetCore.OutputCaching.StackExchangeRedis`, evicts for every instance, and the key's schema hash keeps instances on different schemas apart (4.10). The member mail limit (4.7) is kept in the `IDistributedCache` slot, the framework's `MemoryDistributedCache` by default, one per instance, so N instances behind a load balancer send an address up to N mails a minute of each slot; a host with several instances registers a shared cache, such as `RedisCache`, and the startup report lists `member-mail-limit-per-instance` in Production while an email sender is set up and the cache is the in-memory one ([#3073](https://github.com/fluentcms/FluentCMS/issues/3073)). Each instance keeps its own copy of the sites and their locales, of plugin enablement and of settings, and sees a change another instance made within 30 seconds (4.6, 4.13); role changes are seen on the next request everywhere, since every request reads the role stamps (4.8). The Redis provider in `FluentCMS.Caching.Redis` is still to come. **Reverse proxy.** Forwarded headers, `PathBase` option for sub-path hosting, HTTPS redirection and HSTS options; documented for Nginx, Caddy, YARP, Azure Front Door and Cloudflare. diff --git a/docs/releases/1.0.0-preview.1.md b/docs/releases/1.0.0-preview.1.md index 8e05ca41b..648925381 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 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/Api/Account/MemberPageModels.cs b/src/FluentCMS.Core/Api/Account/MemberPageModels.cs index 29f677188..968b47f33 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), CmsSignInManager.ServerSession(cookie.Properties), CancellationToken.None); + } + + await signIn.SignOutAsync(); return RedirectToPage(); } } diff --git a/src/FluentCMS.Core/Caching/DatabaseDistributedLock.cs b/src/FluentCMS.Core/Caching/DatabaseDistributedLock.cs index 5726db84d..61b260b15 100644 --- a/src/FluentCMS.Core/Caching/DatabaseDistributedLock.cs +++ b/src/FluentCMS.Core/Caching/DatabaseDistributedLock.cs @@ -92,7 +92,9 @@ internal sealed class DatabaseDistributedLock(IServiceScopeFactory scopes, TimeP } catch (DbUpdateException) { - // Another holder made the row first. Only the first use of a name inserts, so this is rare. + // Another holder made the row first. Only the first use of a name inserts, so this is rare. The open + // transaction holds the write lock, which a read on another connection of the in-memory database waits for. + await transaction.RollbackAsync(CancellationToken.None); if (await ExistsAsync(name)) { return null; diff --git a/src/FluentCMS.Core/Identity/CmsSignInManager.cs b/src/FluentCMS.Core/Identity/CmsSignInManager.cs index 25a3e773b..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; @@ -32,6 +33,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 +46,49 @@ 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) + { + 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); @@ -111,15 +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) { - var properties = authenticationProperties ?? new AuthenticationProperties(); - if (!properties.Items.ContainsKey(SignedInAtItem)) - { - properties.Items[SignedInAtItem] = time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); - } + ArgumentNullException.ThrowIfNull(user); - return base.SignInWithClaimsAsync(user, properties, additionalClaims); + var properties = authenticationProperties ?? new AuthenticationProperties(); + await TakeOverAsync(Context, IdentityConstants.ApplicationScheme, user.Id.ToString("D"), properties, UserManager.GetUserId); + MarkSignIn(properties, time); + 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 26ba5cff5..b32144571 100644 --- a/src/FluentCMS.Core/Identity/Members/MemberConnect.cs +++ b/src/FluentCMS.Core/Identity/Members/MemberConnect.cs @@ -58,6 +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 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]); } @@ -67,6 +68,14 @@ 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) + { + TokenClaims.ForServerSession(identity, 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); } diff --git a/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs b/src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs index 1125ff210..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; @@ -122,17 +121,17 @@ 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. - public override Task SignInWithClaimsAsync(CmsMember user, AuthenticationProperties? authenticationProperties, IEnumerable additionalClaims) + // 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 async 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); - } + ArgumentNullException.ThrowIfNull(user); - return base.SignInWithClaimsAsync(user, properties, additionalClaims); + var properties = authenticationProperties ?? new AuthenticationProperties(); + await CmsSignInManager.TakeOverAsync(Context, MemberAuthentication.CookieScheme, user.Id.ToString("D"), properties, _members.GetUserId); + CmsSignInManager.MarkSignIn(properties, _time); + 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 cb2eb9008..6d6ce62c7 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,6 +118,7 @@ private static async Task AuthorizeAsync(HttpContext context) return Refuse(Errors.LoginRequired, "The sign-in is older than the client or the server accepts."); } + // 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]); } @@ -176,6 +180,12 @@ 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) + { + TokenClaims.ForServerSession(identity, 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); } @@ -323,8 +333,10 @@ 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 // signs the other out. @@ -342,14 +354,14 @@ 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))); } if (cookie.Succeeded) { - await context.SignOutAsync(scheme); + await EndSignInAsync(context, cookie, members); } return Results.SignOut( @@ -397,26 +409,80 @@ 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. - private static bool HintsSignedInUser(HttpContext context, AuthenticateResult hint, AuthenticateResult cookie, bool members) + // 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. + private static async Task HintsSignedInUserAsync(HttpContext context, AuthenticateResult hint, AuthenticateResult cookie, bool members) { - if (hint.Principal?.GetClaim(Claims.Subject) is not { } subject) + if (!cookie.Succeeded) + { + return HttpMethods.IsGet(context.Request.Method) && await IsOwnIdentityTokenAsync(context, ServerRequest(context).IdTokenHint); + } + + 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; + } + + // 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)) { return false; } - if (!cookie.Succeeded) + var options = context.RequestServices.GetRequiredService>().CurrentValue; + 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, + }); + 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 HttpMethods.IsGet(context.Request.Method); + return true; } - var signedIn = members - ? context.RequestServices.GetRequiredService().GetUserId(cookie.Principal) - : context.RequestServices.GetRequiredService>().GetUserId(cookie.Principal); - return signedIn == subject; + 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. + 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 + ? 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/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 30ee023b3..3d846017e 100644 --- a/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs +++ b/src/FluentCMS.Core/Identity/Oidc/UserSessions.cs @@ -1,3 +1,5 @@ +using System.Security.Claims; +using System.Text.Json; using OpenIddict.Abstractions; using static OpenIddict.Abstractions.OpenIddictConstants; @@ -11,6 +13,59 @@ 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 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) + { + if (string.IsNullOrEmpty(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..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,9 +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); + CmsSignInManager.MarkSignIn(properties, time); var ticket = new AuthenticationTicket(principal, properties, MemberAuthentication.CookieScheme); return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; } @@ -71,9 +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); + 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/Caching/DistributedLockTests.cs b/tests/FluentCMS.Core.IntegrationTests/Caching/DistributedLockTests.cs index 7e1e3cc46..431e0ed72 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Caching/DistributedLockTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Caching/DistributedLockTests.cs @@ -333,6 +333,25 @@ public async Task ABadNameOrTimeoutIsRefused() await Should.ThrowAsync(() => locks.TryAcquireAsync(Name, TimeSpan.FromSeconds(-2), Token)); } + // The first use of a name inserts its row, so takes that start together race on the insert, and a loser reads the row + // on another connection. On the in-memory database that read waited for the loser's own transaction, for 30 seconds. + [Fact] + public async Task TakesThatRaceOnTheFirstUseOfANameEndWithinTheirTimeout() + { + await using var host = new FluentCmsTestHost(); + var locks = host.Services.GetRequiredService(); + var watch = Stopwatch.StartNew(); + + var attempts = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => Task.Run(() => locks.TryAcquireAsync(Name, TimeSpan.FromMilliseconds(500), Token), Token))); + + watch.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10)); + attempts.Count(held => held is not null).ShouldBe(1); + foreach (var held in attempts.OfType()) + { + await held.DisposeAsync(); + } + } + // The second instance starts after the first has migrated the database, as the instances of a deployment do. private (IDistributedLock First, IDistributedLock Second) BothInstances() { diff --git a/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryCacheTests.cs b/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryCacheTests.cs index 8714df524..485324b1b 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryCacheTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryCacheTests.cs @@ -434,14 +434,24 @@ public async Task AnErrorIsNotCachedAndSaysNoStore() private static async Task SharingAsync(IOutputCacheStore store, bool other, bool grant) { - var host = new FluentCmsTestHost().WithServices(services => services.AddSingleton(store)); + // No worker drains the outbox: the grant evicts the default site, whose tag every host of the store shares, so it is + // delivered here rather than between the reads, where it would evict the first host's copy before the second reads it. + var host = new FluentCmsTestHost() + .WithServices(services => services.AddSingleton(store)) + .Configure(cms => cms.Jobs.Options.Queues[OutboxDrainJob.Queue] = 0); host = other ? host.WithContentTypes() : host.WithContentTypes(); if (grant) { - await using var scope = host.Services.CreateAsyncScope(); - var context = scope.ServiceProvider.GetRequiredService(); - context.Set().Add(new RoleGrant { Id = Guid.CreateVersion7(), RoleId = DefaultSite.PublicRole, Permission = "content.note.read" }); - await context.SaveChangesAsync(Token); + await using (var scope = host.Services.CreateAsyncScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + context.Set().Add(new RoleGrant { Id = Guid.CreateVersion7(), RoleId = DefaultSite.PublicRole, Permission = "content.note.read" }); + await context.SaveChangesAsync(Token); + } + + while (await host.Services.GetRequiredService().DrainAsync(Token) > 0) + { + } } return host; diff --git a/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryHostSiteTests.cs b/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryHostSiteTests.cs index 391170b17..4b00030b9 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryHostSiteTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Delivery/DeliveryHostSiteTests.cs @@ -1,4 +1,5 @@ using System.Net; +using FluentCMS.Core.Events; using FluentCMS.Core.Sites; using FluentCMS.Core.Storage; using FluentCMS.Core.Storage.Entities; @@ -24,6 +25,8 @@ public DeliveryHostSiteTests() _host = new FluentCmsTestHost() .WithContentTypes() .WithServices(services => services.AddSingleton(_hosts)) + // The seeded grant evicts the site once its outbox row is delivered, which a worker could do between the two reads. + .Configure(cms => cms.Jobs.Options.Queues[OutboxDrainJob.Queue] = 0) .Seed(async services => { var context = services.GetRequiredService(); 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 new file mode 100644 index 000000000..da27491a4 --- /dev/null +++ b/tests/FluentCMS.Core.IntegrationTests/Identity/HostedPagesTests.Logout.cs @@ -0,0 +1,375 @@ +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; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; +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, "10.1.0.16"); + using var otherDevice = new HostedPagesBrowser(_host, "10.1.0.9"); + await SignInAsync(browser, editor.Email); + await SignInAsync(otherDevice, editor.Email); + 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")) + { + 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 RotatedAsync(_host, Text(tokens, "refresh_token")); + (await MeAsync(_host, Text(tokens, "access_token"))).ShouldBe(HttpStatusCode.OK); + + await SignOutAsync(browser); + + (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] + public async Task ALogoutWithAHintRevokesOnlyWhenItEndsTheSessionOfItsCookie() + { + var editor = await CreateUserAsync(_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); + 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. + using (var stranger = new HostedPagesBrowser(_host, "10.1.0.10")) + using (var returned = await stranger.GetAsync(hint)) + { + 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. + 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(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] + public async Task ALogoutLeavesTheConsentOfAThirdPartyClient() + { + var editor = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.18"); + 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 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(); + 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. + (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 ASignInOverALiveOneKeepsTheSessionOfItsUserAndEndsAnothers() + { + var editor = await CreateUserAsync(_host); + var other = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.19"); + 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"); + Sid(await CodeFlowAsync(_host, browser)).ShouldNotBe(Sid(replaced)); + } + + [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 ASecondFactorTheRoleNowRequiresEndsTheCookieAtAuthorizeAndRevokesNothing() + { + using var admin = await _host.AsUserAsync(await _host.CreateUserAsync(BuiltInRoles.SuperAdminName, cancellationToken: Token)); + var editor = await CreateUserAsync(_host); + var (key, _) = await EnableTwoFactorAsync(_host, editor); + using var browser = new HostedPagesBrowser(_host, "10.1.0.13"); + + // 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(); + + (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 AHintWithoutTheCookieReturnsOnlyAnIdentityTokenOfThisServerToItsOwnClient() + { + var editor = await CreateUserAsync(_host); + using var browser = new HostedPagesBrowser(_host, "10.1.0.14"); + 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() + { + 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, "10.1.0.20"); + 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 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); + } + + // The rotated refresh token. + private static async Task RotatedAsync(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.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); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Token)); + return json.RootElement.GetProperty("error").GetString(); + } + + private static async Task MeAsync(FluentCmsTestHost host, 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; + } + + // 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..22574b2c1 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,13 @@ public async Task TheRemoteSignOutOfAProviderEndsTheAdminSessionItMadeAndNoOther browser.HasCookie(SignInCookie).ShouldBeTrue(); } + // 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(); + 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(); } [Fact] diff --git a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs index c272a0a44..6d466e366 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Members/MemberPagesTests.cs @@ -242,6 +242,142 @@ 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.20"); + 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); + } + + (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.21"); + 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); + } + + [Fact] + public async Task AnAdminLogoutLeavesTheMembersTokens() + { + var admin = await CreateAdminAsync(); + var address = await fixture.RegisterVerifiedAsync(); + 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"); + 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.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"); + 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)); + } + + [Fact] + public async Task AMemberReauthenticationAnotherSiteCanAskForEndsTheCookieAndRevokesNothing() + { + var address = await fixture.RegisterVerifiedAsync(); + 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); + 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); + 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(); + using var content = new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = refreshToken, + ["client_id"] = clientId, + }); + using var refreshed = await client.PostAsync("/connect/token", content, Token); + return refreshed.StatusCode; + } + [Theory] [InlineData("https://evil.example/")] [InlineData("//evil.example/")]