Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/decisions/0007-admin-sign-in-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 3 additions & 3 deletions docs/planning/backend-technical-spec.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions docs/releases/1.0.0-preview.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
13 changes: 11 additions & 2 deletions src/FluentCMS.Core/Api/Account/MemberPageModels.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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; }
Expand All @@ -142,7 +144,14 @@ public async Task OnGetAsync()

public async Task<IActionResult> OnPostAsync()
{
await Service<MemberSignInManager>().SignOutAsync();
var signIn = Service<MemberSignInManager>();
var cookie = await HttpContext.AuthenticateAsync(MemberAuthentication.CookieScheme);
if (cookie.Succeeded)
{
await Service<UserSessions>().EndAsync(signIn.UserManager.GetUserId(cookie.Principal), CmsSignInManager.ServerSession(cookie.Properties), CancellationToken.None);
}

await signIn.SignOutAsync();
return RedirectToPage();
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/FluentCMS.Core/Caching/DatabaseDistributedLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
61 changes: 54 additions & 7 deletions src/FluentCMS.Core/Identity/CmsSignInManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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<ClaimsPrincipal, string?> 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<UserSessions>().EndAsync(previous, serverSession, CancellationToken.None);
}
}

public override async Task<bool> CanSignInAsync(CmsUser user)
{
ArgumentNullException.ThrowIfNull(user);
Expand Down Expand Up @@ -111,15 +159,14 @@ public override async Task<SignInResult> 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<Claim> additionalClaims)
public override async Task SignInWithClaimsAsync(CmsUser user, AuthenticationProperties? authenticationProperties, IEnumerable<Claim> 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<SignInResult> TwoFactorAuthenticatorSignInAsync(string code, bool isPersistent, bool rememberClient)
Expand Down
9 changes: 9 additions & 0 deletions src/FluentCMS.Core/Identity/Members/MemberConnect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public static async Task<IResult> 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]);
}
Expand All @@ -67,6 +68,14 @@ public static async Task<IResult> 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<IOpenIddictApplicationManager>().FindByClientIdAsync(request.ClientId!, context.RequestAborted) is { } application)
{
TokenClaims.ForServerSession(identity, serverSession);
identity.SetAuthorizationId(await context.RequestServices.GetRequiredService<UserSessions>()
.BeginAsync(new ClaimsPrincipal(identity), application, serverSession, context.RequestAborted));
}

return Results.SignIn(new ClaimsPrincipal(identity), properties: null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}

Expand Down
19 changes: 9 additions & 10 deletions src/FluentCMS.Core/Identity/Members/MemberSignInManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Globalization;
using System.Security.Claims;
using FluentCMS.Content;
using FluentCMS.Events;
Expand Down Expand Up @@ -122,17 +121,17 @@ public override async Task<SignInResult> 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<Claim> 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<Claim> 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.
Expand Down
Loading
Loading