From 7907c31abcde468f798e39a6cff18ee94fcfc4f9 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Thu, 15 Oct 2026 16:15:03 +0900 Subject: [PATCH 01/11] Add the Cookie Store API to Microsoft.AspNetCore.Components.Platform - Add CookieStore with the get, getAll, set, and delete operations of window.cookieStore, reached through the Window.CookieStore extension property, as proposed in #69844. - Map the Web IDL dictionaries and the enum to CookieListItem, CookieStoreGetOptions, CookieInit, CookieStoreDeleteOptions, and CookieSameSite. Leave out a member when it is null, because the browser treats null and a missing member differently, and Chromium crashes the page on maxAge: null. - Throw NotSupportedException when window.cookieStore is missing, such as on a page that is not a secure context. - Keep the dictionary members in a trimmed WebAssembly app with DynamicDependency. - Add unit tests, including the JSON that reaches the browser, and E2E tests for Interactive Server and WebAssembly. --- src/Components/Platform/src/CookieInit.cs | 53 +++ src/Components/Platform/src/CookieListItem.cs | 20 + src/Components/Platform/src/CookieSameSite.cs | 31 ++ src/Components/Platform/src/CookieStore.cs | 204 +++++++++ .../Platform/src/CookieStoreDeleteOptions.cs | 29 ++ .../Platform/src/CookieStoreGetOptions.cs | 25 ++ ...soft.AspNetCore.Components.Platform.csproj | 4 + .../Platform/src/PublicAPI.Unshipped.txt | 53 +++ .../src/WindowCookieStoreExtensions.cs | 19 + .../Platform/test/CookieStoreTest.cs | 399 ++++++++++++++++++ src/Components/Platform/test/PublicApiTest.cs | 2 + .../Components/CookieStoreDemo.razor | 127 ++++++ .../Pages/CookieStoreWebAssembly.razor | 4 + .../Tests/CookieStoreTests.cs | 114 +++++ .../Components/Pages/CookieStoreServer.razor | 4 + 15 files changed, 1088 insertions(+) create mode 100644 src/Components/Platform/src/CookieInit.cs create mode 100644 src/Components/Platform/src/CookieListItem.cs create mode 100644 src/Components/Platform/src/CookieSameSite.cs create mode 100644 src/Components/Platform/src/CookieStore.cs create mode 100644 src/Components/Platform/src/CookieStoreDeleteOptions.cs create mode 100644 src/Components/Platform/src/CookieStoreGetOptions.cs create mode 100644 src/Components/Platform/src/WindowCookieStoreExtensions.cs create mode 100644 src/Components/Platform/test/CookieStoreTest.cs create mode 100644 src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor create mode 100644 src/Components/Platform/testassets/PlatformTestApp.Client/Pages/CookieStoreWebAssembly.razor create mode 100644 src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs create mode 100644 src/Components/Platform/testassets/PlatformTestApp/Components/Pages/CookieStoreServer.razor diff --git a/src/Components/Platform/src/CookieInit.cs b/src/Components/Platform/src/CookieInit.cs new file mode 100644 index 000000000000..cadb19801b49 --- /dev/null +++ b/src/Components/Platform/src/CookieInit.cs @@ -0,0 +1,53 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text.Json.Serialization; + +namespace Microsoft.AspNetCore.Components.Platform; + +/// +/// Represents the name, value, and attributes of a cookie to set. +/// +public sealed class CookieInit +{ + /// + /// Gets or sets the name of the cookie. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the value of the cookie. + /// + public required string Value { get; set; } + + /// + /// Gets or sets the expiration time of the cookie in milliseconds since the Unix epoch, + /// or for a cookie without an expiration time. + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? Expires { get; set; } + + /// + /// Gets or sets the domain of the cookie, or to restrict the cookie to the host of the current page. + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Domain { get; set; } + + /// + /// Gets or sets the path of the cookie. The default is "/". + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string Path { get; set; } = "/"; + + /// + /// Gets or sets the SameSite attribute of the cookie. The default is . + /// + public CookieSameSite SameSite { get; set; } = CookieSameSite.Strict; + + // Chromium crashes the page on maxAge: null, although null means the same as a missing member. + /// + /// Gets or sets the maximum age of the cookie in seconds, or for a cookie without a maximum age. + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? MaxAge { get; set; } +} diff --git a/src/Components/Platform/src/CookieListItem.cs b/src/Components/Platform/src/CookieListItem.cs new file mode 100644 index 000000000000..36d987fbca50 --- /dev/null +++ b/src/Components/Platform/src/CookieListItem.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Components.Platform; + +/// +/// Represents a cookie returned by the Cookie Store API. +/// +public sealed class CookieListItem +{ + /// + /// Gets the name of the cookie. + /// + public string? Name { get; init; } + + /// + /// Gets the value of the cookie. + /// + public string? Value { get; init; } +} diff --git a/src/Components/Platform/src/CookieSameSite.cs b/src/Components/Platform/src/CookieSameSite.cs new file mode 100644 index 000000000000..e3d480279ff0 --- /dev/null +++ b/src/Components/Platform/src/CookieSameSite.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text.Json.Serialization; + +namespace Microsoft.AspNetCore.Components.Platform; + +/// +/// Specifies the SameSite attribute of a cookie. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum CookieSameSite +{ + /// + /// The browser sends the cookie only with same-site requests. + /// + [JsonStringEnumMemberName("strict")] + Strict, + + /// + /// The browser sends the cookie with same-site requests and with cross-site top-level navigations. + /// + [JsonStringEnumMemberName("lax")] + Lax, + + /// + /// The browser sends the cookie with both same-site and cross-site requests. + /// + [JsonStringEnumMemberName("none")] + None, +} diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs new file mode 100644 index 000000000000..b770fbb3e168 --- /dev/null +++ b/src/Components/Platform/src/CookieStore.cs @@ -0,0 +1,204 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Internal; +using Microsoft.JSInterop; + +namespace Microsoft.AspNetCore.Components.Platform; + +/// +/// Represents the browser Cookie Store API for the current page. +/// +public sealed class CookieStore : IInternalAsyncDisposal +{ + private readonly IJSRuntime _jsRuntime; + private Task? _referenceTask; + private bool _disposed; + + internal CookieStore(IJSRuntime jsRuntime) + { + _jsRuntime = jsRuntime; + } + + /// + /// Gets the first cookie with the specified name. + /// + /// The name of the cookie to retrieve. + /// The first cookie named , or if no such cookie exists. + /// is . + /// The browser does not provide the Cookie Store API for the current page. + public async ValueTask GetAsync(string name) + { + ArgumentNullException.ThrowIfNull(name); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + + return await cookieStore.InvokeAsync("get", name).ConfigureAwait(false); + } + + /// + /// Gets the first cookie that matches the specified options. + /// + /// The options that select the cookie. + /// The first matching cookie, or if no cookie matches. + /// is . + /// The browser does not provide the Cookie Store API for the current page. + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieStoreGetOptions))] + public async ValueTask GetAsync(CookieStoreGetOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + + return await cookieStore.InvokeAsync("get", options).ConfigureAwait(false); + } + + /// + /// Gets all cookies visible to the current page. + /// + /// The cookies visible to the current page. + /// The browser does not provide the Cookie Store API for the current page. + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieListItem))] + public async ValueTask> GetAllAsync() + { + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + + return await cookieStore.InvokeAsync("getAll").ConfigureAwait(false); + } + + /// + /// Gets all cookies with the specified name. + /// + /// The name of the cookies to retrieve. + /// The cookies named . + /// is . + /// The browser does not provide the Cookie Store API for the current page. + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieListItem))] + public async ValueTask> GetAllAsync(string name) + { + ArgumentNullException.ThrowIfNull(name); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + + return await cookieStore.InvokeAsync("getAll", name).ConfigureAwait(false); + } + + /// + /// Gets all cookies that match the specified options. + /// + /// The options that select the cookies. + /// The matching cookies. + /// is . + /// The browser does not provide the Cookie Store API for the current page. + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieStoreGetOptions))] + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieListItem))] + public async ValueTask> GetAllAsync(CookieStoreGetOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + + return await cookieStore.InvokeAsync("getAll", options).ConfigureAwait(false); + } + + /// + /// Sets a cookie with the specified name and value, replacing any existing cookie with the same name. + /// + /// The name of the cookie. + /// The value of the cookie. + /// A representing the completion of the operation. + /// or is . + /// The browser does not provide the Cookie Store API for the current page. + public async ValueTask SetAsync(string name, string value) + { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + await cookieStore.InvokeVoidAsync("set", name, value).ConfigureAwait(false); + } + + /// + /// Sets a cookie with the specified options, replacing any existing cookie with the same name, domain, and path. + /// + /// The name, value, and attributes of the cookie. + /// A representing the completion of the operation. + /// is . + /// The browser does not provide the Cookie Store API for the current page. + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieInit))] + public async ValueTask SetAsync(CookieInit options) + { + ArgumentNullException.ThrowIfNull(options); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + await cookieStore.InvokeVoidAsync("set", options).ConfigureAwait(false); + } + + /// + /// Deletes the cookie with the specified name, if it exists. + /// + /// The name of the cookie to delete. + /// A representing the completion of the operation. + /// is . + /// The browser does not provide the Cookie Store API for the current page. + public async ValueTask DeleteAsync(string name) + { + ArgumentNullException.ThrowIfNull(name); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + await cookieStore.InvokeVoidAsync("delete", name).ConfigureAwait(false); + } + + /// + /// Deletes the cookie that matches the specified options, if it exists. + /// + /// The name and attributes of the cookie to delete. + /// A representing the completion of the operation. + /// is . + /// The browser does not provide the Cookie Store API for the current page. + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieStoreDeleteOptions))] + public async ValueTask DeleteAsync(CookieStoreDeleteOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + await cookieStore.InvokeVoidAsync("delete", options).ConfigureAwait(false); + } + + async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + + // Don't wait for a pending acquisition. It could hold up scope disposal until the JS interop timeout. + if (_referenceTask is { IsCompletedSuccessfully: true } referenceTask) + { + await referenceTask.Result.DisposeAsync().ConfigureAwait(false); + } + } + + private Task GetReferenceAsync() + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (_referenceTask is null || _referenceTask.IsFaulted || _referenceTask.IsCanceled) + { + _referenceTask = AcquireReferenceAsync(); + } + + return _referenceTask; + } + + private async Task AcquireReferenceAsync() + { + // window.cookieStore is undefined on an insecure page or in an older browser, and interop returns null for it. + var reference = await _jsRuntime.GetValueAsync("cookieStore").ConfigureAwait(false); + + return reference ?? throw new NotSupportedException("The Cookie Store API is not available for the current page."); + } +} diff --git a/src/Components/Platform/src/CookieStoreDeleteOptions.cs b/src/Components/Platform/src/CookieStoreDeleteOptions.cs new file mode 100644 index 000000000000..e9643e14c389 --- /dev/null +++ b/src/Components/Platform/src/CookieStoreDeleteOptions.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text.Json.Serialization; + +namespace Microsoft.AspNetCore.Components.Platform; + +/// +/// Represents the name and attributes of a cookie to delete. +/// +public sealed class CookieStoreDeleteOptions +{ + /// + /// Gets or sets the name of the cookie. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the domain of the cookie, or for a cookie restricted to the host of the current page. + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Domain { get; set; } + + /// + /// Gets or sets the path of the cookie. The default is "/". + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string Path { get; set; } = "/"; +} diff --git a/src/Components/Platform/src/CookieStoreGetOptions.cs b/src/Components/Platform/src/CookieStoreGetOptions.cs new file mode 100644 index 000000000000..8de992c96b68 --- /dev/null +++ b/src/Components/Platform/src/CookieStoreGetOptions.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text.Json.Serialization; + +namespace Microsoft.AspNetCore.Components.Platform; + +/// +/// Represents the options that select the cookies to retrieve. +/// +public sealed class CookieStoreGetOptions +{ + /// + /// Gets or sets the name of the cookies to retrieve, or to match any name. + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Name { get; set; } + + /// + /// Gets or sets the URL to match the cookies against, or to use the URL of the current page. + /// The browser accepts only the URL of the current page. + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Url { get; set; } +} diff --git a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj index 154f44525200..75cd97a04839 100644 --- a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj +++ b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj @@ -17,4 +17,8 @@ + + + + diff --git a/src/Components/Platform/src/PublicAPI.Unshipped.txt b/src/Components/Platform/src/PublicAPI.Unshipped.txt index 234165909d99..0dfdfe64f564 100644 --- a/src/Components/Platform/src/PublicAPI.Unshipped.txt +++ b/src/Components/Platform/src/PublicAPI.Unshipped.txt @@ -1,4 +1,54 @@ #nullable enable +Microsoft.AspNetCore.Components.Platform.CookieInit +Microsoft.AspNetCore.Components.Platform.CookieInit.CookieInit() -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.Domain.get -> string? +Microsoft.AspNetCore.Components.Platform.CookieInit.Domain.set -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.Expires.get -> double? +Microsoft.AspNetCore.Components.Platform.CookieInit.Expires.set -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.MaxAge.get -> long? +Microsoft.AspNetCore.Components.Platform.CookieInit.MaxAge.set -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.Name.get -> string! +Microsoft.AspNetCore.Components.Platform.CookieInit.Name.set -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.Path.get -> string! +Microsoft.AspNetCore.Components.Platform.CookieInit.Path.set -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.SameSite.get -> Microsoft.AspNetCore.Components.Platform.CookieSameSite +Microsoft.AspNetCore.Components.Platform.CookieInit.SameSite.set -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.Value.get -> string! +Microsoft.AspNetCore.Components.Platform.CookieInit.Value.set -> void +Microsoft.AspNetCore.Components.Platform.CookieListItem +Microsoft.AspNetCore.Components.Platform.CookieListItem.CookieListItem() -> void +Microsoft.AspNetCore.Components.Platform.CookieListItem.Name.get -> string? +Microsoft.AspNetCore.Components.Platform.CookieListItem.Name.init -> void +Microsoft.AspNetCore.Components.Platform.CookieListItem.Value.get -> string? +Microsoft.AspNetCore.Components.Platform.CookieListItem.Value.init -> void +Microsoft.AspNetCore.Components.Platform.CookieSameSite +Microsoft.AspNetCore.Components.Platform.CookieSameSite.Lax = 1 -> Microsoft.AspNetCore.Components.Platform.CookieSameSite +Microsoft.AspNetCore.Components.Platform.CookieSameSite.None = 2 -> Microsoft.AspNetCore.Components.Platform.CookieSameSite +Microsoft.AspNetCore.Components.Platform.CookieSameSite.Strict = 0 -> Microsoft.AspNetCore.Components.Platform.CookieSameSite +Microsoft.AspNetCore.Components.Platform.CookieStore +Microsoft.AspNetCore.Components.Platform.CookieStore.DeleteAsync(Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions! options) -> System.Threading.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStore.DeleteAsync(string! name) -> System.Threading.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStore.GetAllAsync() -> System.Threading.Tasks.ValueTask!> +Microsoft.AspNetCore.Components.Platform.CookieStore.GetAllAsync(Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions! options) -> System.Threading.Tasks.ValueTask!> +Microsoft.AspNetCore.Components.Platform.CookieStore.GetAllAsync(string! name) -> System.Threading.Tasks.ValueTask!> +Microsoft.AspNetCore.Components.Platform.CookieStore.GetAsync(Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions! options) -> System.Threading.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStore.GetAsync(string! name) -> System.Threading.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStore.SetAsync(Microsoft.AspNetCore.Components.Platform.CookieInit! options) -> System.Threading.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStore.SetAsync(string! name, string! value) -> System.Threading.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.CookieStoreDeleteOptions() -> void +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Domain.get -> string? +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Domain.set -> void +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Name.get -> string! +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Name.set -> void +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Path.get -> string! +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Path.set -> void +Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions +Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.CookieStoreGetOptions() -> void +Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Name.get -> string? +Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Name.set -> void +Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Url.get -> string? +Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Url.set -> void Microsoft.AspNetCore.Components.Platform.IBrowserPlatform Microsoft.AspNetCore.Components.Platform.IBrowserPlatform.Window.get -> Microsoft.AspNetCore.Components.Platform.Window! Microsoft.AspNetCore.Components.Platform.Storage @@ -9,6 +59,9 @@ Microsoft.AspNetCore.Components.Platform.Storage.KeyAsync(uint index) -> System. Microsoft.AspNetCore.Components.Platform.Storage.RemoveItemAsync(string! key) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.Storage.SetItemAsync(string! key, string! value) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.Window +Microsoft.AspNetCore.Components.Platform.WindowCookieStoreExtensions +Microsoft.AspNetCore.Components.Platform.WindowCookieStoreExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!) +Microsoft.AspNetCore.Components.Platform.WindowCookieStoreExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!).CookieStore.get -> Microsoft.AspNetCore.Components.Platform.CookieStore! Microsoft.AspNetCore.Components.Platform.WindowWebStorageExtensions Microsoft.AspNetCore.Components.Platform.WindowWebStorageExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!) Microsoft.AspNetCore.Components.Platform.WindowWebStorageExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!).LocalStorage.get -> Microsoft.AspNetCore.Components.Platform.Storage! diff --git a/src/Components/Platform/src/WindowCookieStoreExtensions.cs b/src/Components/Platform/src/WindowCookieStoreExtensions.cs new file mode 100644 index 000000000000..dc9acdd7e74c --- /dev/null +++ b/src/Components/Platform/src/WindowCookieStoreExtensions.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Components.Platform; + +/// +/// Provides access to the Cookie Store API from a . +/// +public static class WindowCookieStoreExtensions +{ + extension(Window window) + { + /// + /// Gets the cookie store of the current page. + /// + public CookieStore CookieStore + => window.GetOrAddFeature(static jsRuntime => new CookieStore(jsRuntime)); + } +} diff --git a/src/Components/Platform/test/CookieStoreTest.cs b/src/Components/Platform/test/CookieStoreTest.cs new file mode 100644 index 000000000000..175cd326b5fb --- /dev/null +++ b/src/Components/Platform/test/CookieStoreTest.cs @@ -0,0 +1,399 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable enable + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.JSInterop; +using Microsoft.JSInterop.Infrastructure; +using Xunit; + +namespace Microsoft.AspNetCore.Components.Platform.Tests; + +public class CookieStoreTest +{ + [Fact] + public async Task CookieStore_IsStableAndNotAcquiredBeforeUse() + { + var jsRuntime = new RecordingJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var window = provider.GetRequiredService().Window; + + Assert.Same(window.CookieStore, window.CookieStore); + Assert.Equal(0, jsRuntime.GetValueCallCount); + } + + [Fact] + public async Task CookieStore_ForwardsOperationsAndAcquiresReferenceOnce() + { + var jsRuntime = new RecordingJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + var getOptions = new CookieStoreGetOptions { Name = "name" }; + var init = new CookieInit { Name = "name", Value = "value" }; + var deleteOptions = new CookieStoreDeleteOptions { Name = "name" }; + + var byName = await cookieStore.GetAsync("name"); + var byOptions = await cookieStore.GetAsync(getOptions); + var all = await cookieStore.GetAllAsync(); + var allByName = await cookieStore.GetAllAsync("name"); + var allByOptions = await cookieStore.GetAllAsync(getOptions); + await cookieStore.SetAsync("name", "value"); + await cookieStore.SetAsync(init); + await cookieStore.DeleteAsync("name"); + await cookieStore.DeleteAsync(deleteOptions); + + Assert.Equal("stored-value", byName?.Value); + Assert.Equal("stored-value", byOptions?.Value); + Assert.Equal("stored-value", Assert.Single(all).Value); + Assert.Single(allByName); + Assert.Single(allByOptions); + Assert.Equal(1, jsRuntime.GetValueCallCount); + Assert.Equal("cookieStore", jsRuntime.RequestedProperty); + Assert.Collection( + jsRuntime.ObjectReference.Invocations, + invocation => AssertInvocation(invocation, "get", "name"), + invocation => AssertInvocation(invocation, "get", getOptions), + invocation => AssertInvocation(invocation, "getAll"), + invocation => AssertInvocation(invocation, "getAll", "name"), + invocation => AssertInvocation(invocation, "getAll", getOptions), + invocation => AssertInvocation(invocation, "set", "name", "value"), + invocation => AssertInvocation(invocation, "set", init), + invocation => AssertInvocation(invocation, "delete", "name"), + invocation => AssertInvocation(invocation, "delete", deleteOptions)); + } + + [Fact] + public async Task CookieStore_RejectsNullArguments() + { + var jsRuntime = new RecordingJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + await Assert.ThrowsAsync("name", () => cookieStore.GetAsync(default(string)!).AsTask()); + await Assert.ThrowsAsync("options", () => cookieStore.GetAsync(default(CookieStoreGetOptions)!).AsTask()); + await Assert.ThrowsAsync("name", () => cookieStore.GetAllAsync(default(string)!).AsTask()); + await Assert.ThrowsAsync("options", () => cookieStore.GetAllAsync(default(CookieStoreGetOptions)!).AsTask()); + await Assert.ThrowsAsync("name", () => cookieStore.SetAsync(null!, "value").AsTask()); + await Assert.ThrowsAsync("value", () => cookieStore.SetAsync("name", null!).AsTask()); + await Assert.ThrowsAsync("options", () => cookieStore.SetAsync(null!).AsTask()); + await Assert.ThrowsAsync("name", () => cookieStore.DeleteAsync(default(string)!).AsTask()); + await Assert.ThrowsAsync("options", () => cookieStore.DeleteAsync(default(CookieStoreDeleteOptions)!).AsTask()); + Assert.Equal(0, jsRuntime.GetValueCallCount); + } + + [Fact] + public async Task CookieStore_ReacquiresReferenceAfterAcquisitionIsCanceled() + { + var jsRuntime = new RecordingJSRuntime { CancelNextGetValue = true }; + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + await Assert.ThrowsAnyAsync(() => cookieStore.GetAllAsync().AsTask()); + var all = await cookieStore.GetAllAsync(); + + Assert.Single(all); + Assert.Equal(2, jsRuntime.GetValueCallCount); + } + + [Fact] + public async Task CookieStore_ThrowsNotSupportedExceptionWhenTheBrowserHasNoCookieStore() + { + var jsRuntime = new RecordingJSRuntime { CookieStoreMissing = true }; + var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + await Assert.ThrowsAsync(() => cookieStore.GetAllAsync().AsTask()); + await Assert.ThrowsAsync(() => cookieStore.SetAsync("name", "value").AsTask()); + await provider.DisposeAsync(); + + Assert.Equal(2, jsRuntime.GetValueCallCount); + Assert.Empty(jsRuntime.ObjectReference.Invocations); + } + + [Fact] + public async Task ScopeDisposal_DisposesTheAcquiredReference() + { + var jsRuntime = new RecordingJSRuntime(); + var provider = CreateServiceProvider(jsRuntime); + + await using (provider) + { + await provider.GetRequiredService().Window.CookieStore.GetAllAsync(); + } + + Assert.True(jsRuntime.ObjectReference.Disposed); + } + + [Fact] + public async Task ScopeDisposal_MakesCookieStoreUnusable() + { + var jsRuntime = new RecordingJSRuntime(); + var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + await cookieStore.GetAllAsync(); + + await provider.DisposeAsync(); + + await Assert.ThrowsAsync(() => cookieStore.GetAllAsync().AsTask()); + Assert.Equal(1, jsRuntime.GetValueCallCount); + } + + [Fact] + public async Task ScopeDisposal_DoesNotWaitForPendingAcquisition() + { + var neverCompletes = new TaskCompletionSource(); + var jsRuntime = new RecordingJSRuntime { PendingNextGetValue = neverCompletes }; + var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + _ = cookieStore.GetAllAsync(); + + await provider.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.False(jsRuntime.ObjectReference.Disposed); + } + + // A mock IJSRuntime records arguments before serialization, so the tests below check the JSON the browser receives. + [Fact] + public async Task SetAsync_SendsCookieInitWithoutNullMembers() + { + var jsRuntime = new SerializingJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + await cookieStore.SetAsync(new CookieInit { Name = "a", Value = "1" }); + await cookieStore.SetAsync(new CookieInit + { + Name = "b", + Value = "2", + Expires = 1767225600000, + Domain = "example.com", + Path = "/app", + SameSite = CookieSameSite.Lax, + MaxAge = 3600, + }); + await cookieStore.SetAsync(new CookieInit { Name = "c", Value = "3", Path = null! }); + await cookieStore.SetAsync("d", "4"); + + Assert.Equal( + [ + """[{"name":"a","value":"1","path":"/","sameSite":"strict"}]""", + """[{"name":"b","value":"2","expires":1767225600000,"domain":"example.com","path":"/app","sameSite":"lax","maxAge":3600}]""", + """[{"name":"c","value":"3","sameSite":"strict"}]""", + """["d","4"]""", + ], + jsRuntime.ArgumentsSentTo("set")); + } + + [Theory] + [InlineData(CookieSameSite.Strict, "strict")] + [InlineData(CookieSameSite.Lax, "lax")] + [InlineData(CookieSameSite.None, "none")] + public async Task SetAsync_SendsSameSiteAsTheWebIdlString(CookieSameSite sameSite, string expected) + { + var jsRuntime = new SerializingJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + await cookieStore.SetAsync(new CookieInit { Name = "a", Value = "1", SameSite = sameSite }); + + Assert.Contains($"\"sameSite\":\"{expected}\"", Assert.Single(jsRuntime.ArgumentsSentTo("set"))); + } + + [Fact] + public async Task GetAsync_SendsOnlyTheOptionsThatAreSet() + { + var jsRuntime = new SerializingJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + await cookieStore.GetAsync(new CookieStoreGetOptions()); + await cookieStore.GetAsync(new CookieStoreGetOptions { Name = "a" }); + await cookieStore.GetAllAsync(new CookieStoreGetOptions { Url = "https://localhost/" }); + + Assert.Equal(["""[{}]""", """[{"name":"a"}]"""], jsRuntime.ArgumentsSentTo("get")); + Assert.Equal(["""[{"url":"https://localhost/"}]"""], jsRuntime.ArgumentsSentTo("getAll")); + } + + [Fact] + public async Task DeleteAsync_SendsDeleteOptionsWithoutNullMembers() + { + var jsRuntime = new SerializingJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + await cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "a" }); + await cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "b", Domain = "example.com", Path = "/app" }); + await cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "c", Path = null! }); + + Assert.Equal( + [ + """[{"name":"a","path":"/"}]""", + """[{"name":"b","domain":"example.com","path":"/app"}]""", + """[{"name":"c"}]""", + ], + jsRuntime.ArgumentsSentTo("delete")); + } + + [Fact] + public async Task GetAllAsync_ReadsNameAndValueAndIgnoresOtherMembers() + { + // Chromium still returns members that were removed from the specification, such as domain and expires. + var jsRuntime = new SerializingJSRuntime + { + GetAllResult = """[{"name":"a","value":"1","domain":null,"path":"/","expires":null,"secure":true,"sameSite":"strict","partitioned":false},{"name":"b","value":"2"}]""", + }; + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + var cookies = await cookieStore.GetAllAsync(); + var missing = await cookieStore.GetAsync("missing"); + + Assert.Collection( + cookies, + cookie => Assert.Equal(("a", "1"), (cookie.Name, cookie.Value)), + cookie => Assert.Equal(("b", "2"), (cookie.Name, cookie.Value))); + Assert.Null(missing); + } + + private static ServiceProvider CreateServiceProvider(IJSRuntime jsRuntime) + { + var services = new ServiceCollection(); + services.AddSingleton(jsRuntime); + services.AddBrowserPlatform(); + + return services.BuildServiceProvider(); + } + + private static void AssertInvocation(Invocation invocation, string identifier, params object?[] arguments) + { + Assert.Equal(identifier, invocation.Identifier); + Assert.Equal(arguments, invocation.Arguments); + } + + private sealed class RecordingJSRuntime : IJSRuntime + { + public RecordingJSObjectReference ObjectReference { get; } = new(); + + public int GetValueCallCount { get; private set; } + + public string? RequestedProperty { get; private set; } + + public bool CancelNextGetValue { get; set; } + + public bool CookieStoreMissing { get; set; } + + public TaskCompletionSource? PendingNextGetValue { get; set; } + + public ValueTask InvokeAsync(string identifier, object?[]? args) + { + throw new NotSupportedException(); + } + + public ValueTask InvokeAsync( + string identifier, + CancellationToken cancellationToken, + object?[]? args) + { + throw new NotSupportedException(); + } + + public ValueTask GetValueAsync(string identifier) + { + GetValueCallCount++; + RequestedProperty = identifier; + + if (CancelNextGetValue) + { + CancelNextGetValue = false; + + return ValueTask.FromCanceled(new CancellationToken(canceled: true)); + } + + if (PendingNextGetValue is { } pending) + { + PendingNextGetValue = null; + + return new ValueTask((Task)(object)pending.Task); + } + + // JS interop returns a null reference when window.cookieStore is undefined. + return ValueTask.FromResult(CookieStoreMissing ? default! : (TValue)(object)ObjectReference); + } + } + + private sealed class RecordingJSObjectReference : IJSObjectReference + { + private static readonly CookieListItem _storedCookie = new() { Name = "name", Value = "stored-value" }; + + public List Invocations { get; } = []; + + public bool Disposed { get; private set; } + + public ValueTask InvokeAsync(string identifier, object?[]? args) + { + return InvokeAsync(identifier, CancellationToken.None, args); + } + + public ValueTask InvokeAsync( + string identifier, + CancellationToken cancellationToken, + object?[]? args) + { + Invocations.Add(new Invocation(identifier, args ?? [])); + + object? result = identifier switch + { + "get" => _storedCookie, + "getAll" => new[] { _storedCookie }, + _ => default(TValue), + }; + + return ValueTask.FromResult((TValue?)result!); + } + + public ValueTask DisposeAsync() + { + Disposed = true; + + return ValueTask.CompletedTask; + } + } + + private sealed record Invocation(string Identifier, object?[] Arguments); + + // Runs the real JSRuntime serializer and answers each call as the browser would. + private sealed class SerializingJSRuntime : JSRuntime + { + private readonly List<(string Identifier, string? ArgsJson)> _calls = []; + + public string GetAllResult { get; init; } = "[]"; + + public string[] ArgumentsSentTo(string identifier) + => [.. _calls.Where(call => call.Identifier == identifier).Select(call => call.ArgsJson ?? string.Empty)]; + + protected override void BeginInvokeJS(in JSInvocationInfo invocationInfo) + { + _calls.Add((invocationInfo.Identifier, invocationInfo.ArgsJson)); + + var result = invocationInfo.Identifier switch + { + "cookieStore" => """{"__jsObjectId":1}""", + "getAll" => GetAllResult, + _ => "null", + }; + + if (invocationInfo.AsyncHandle != 0) + { + DotNetDispatcher.EndInvokeJS(this, $"[{invocationInfo.AsyncHandle},true,{result}]"); + } + } + + protected override void BeginInvokeJS(long taskId, string identifier, string? argsJson, JSCallResultType resultType, long targetInstanceId) + => throw new NotSupportedException(); + + protected override void EndInvokeDotNet(DotNetInvocationInfo invocationInfo, in DotNetInvocationResult invocationResult) + => throw new NotSupportedException(); + } +} diff --git a/src/Components/Platform/test/PublicApiTest.cs b/src/Components/Platform/test/PublicApiTest.cs index 6e22189e5315..2075ae02bcc5 100644 --- a/src/Components/Platform/test/PublicApiTest.cs +++ b/src/Components/Platform/test/PublicApiTest.cs @@ -25,6 +25,7 @@ public void PublicSurface_DoesNotExposeJavaScriptInteropTypes() [Theory] [InlineData(typeof(Window))] [InlineData(typeof(Storage))] + [InlineData(typeof(CookieStore))] public void SharedInstances_CannotBeDisposedByApplicationCode(Type type) { Assert.False(typeof(IAsyncDisposable).IsAssignableFrom(type)); @@ -38,6 +39,7 @@ public void LiveBrowserObjectMethods_AreAsynchronous() Type[] liveBrowserObjectTypes = [ typeof(Storage), + typeof(CookieStore), ]; var synchronousMethods = liveBrowserObjectTypes diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor new file mode 100644 index 000000000000..df81ad840028 --- /dev/null +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -0,0 +1,127 @@ +@using Microsoft.JSInterop +@inject Microsoft.AspNetCore.Components.Platform.IBrowserPlatform Browser +@inject NavigationManager Navigation + +

Cookie Store

+ + + + + + +
+ + + + +
+
+ + + + + +
+
+ + +
+ + +@code { + // A path other than the page path shows that the Path member reaches the browser. + private const string OptionsPath = "/cookie-path"; + + private string name = "cookie"; + private string value = "initial"; + private string result = "No operation has run."; + + private async Task SetAsync() + { + await Browser.Window.CookieStore.SetAsync(name, value); + result = $"Set: {name}"; + } + + private async Task SetWithOptionsAsync() + { + await Browser.Window.CookieStore.SetAsync(new CookieInit + { + Name = name, + Value = value, + Expires = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(), + Path = OptionsPath, + SameSite = CookieSameSite.Lax, + }); + result = $"Set with options: {name}"; + } + + private async Task SetWithMaxAgeAsync() + { + await Browser.Window.CookieStore.SetAsync(new CookieInit + { + Name = name, + Value = value, + MaxAge = 3600, + SameSite = CookieSameSite.None, + }); + result = $"Set with max age: {name}"; + } + + private async Task SetWithOtherDomainAsync() + { + // The browser rejects a domain that does not match the page, so the error shows that Domain reaches it. + try + { + await Browser.Window.CookieStore.SetAsync(new CookieInit { Name = name, Value = value, Domain = "example.com" }); + result = $"Set with another domain: {name}"; + } + catch (JSException) + { + result = "Another domain was rejected."; + } + } + + private async Task GetAsync() + { + result = Format(await Browser.Window.CookieStore.GetAsync(name)); + } + + private async Task GetWithOptionsAsync() + { + result = Format(await Browser.Window.CookieStore.GetAsync(new CookieStoreGetOptions { Name = name })); + } + + private async Task GetAllAsync() + { + result = Format(await Browser.Window.CookieStore.GetAllAsync()); + } + + private async Task GetAllWithNameAsync() + { + result = Format(await Browser.Window.CookieStore.GetAllAsync(name)); + } + + private async Task GetAllWithOptionsAsync() + { + // The browser accepts only the URL of the current page. + result = Format(await Browser.Window.CookieStore.GetAllAsync(new CookieStoreGetOptions { Name = name, Url = Navigation.Uri })); + } + + private async Task DeleteAsync() + { + await Browser.Window.CookieStore.DeleteAsync(name); + result = $"Deleted: {name}"; + } + + private async Task DeleteWithOptionsAsync() + { + await Browser.Window.CookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = name, Path = OptionsPath }); + result = $"Deleted with options: {name}"; + } + + private static string Format(CookieListItem? cookie) + => cookie is null ? "Cookie is missing." : $"Found: {cookie.Name}={cookie.Value}"; + + private static string Format(IReadOnlyList cookies) + => cookies.Count == 0 ? "No cookies." : $"Found: {string.Join("; ", cookies.Select(cookie => $"{cookie.Name}={cookie.Value}"))}"; +} diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Pages/CookieStoreWebAssembly.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Pages/CookieStoreWebAssembly.razor new file mode 100644 index 000000000000..d6fa48d6c323 --- /dev/null +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Pages/CookieStoreWebAssembly.razor @@ -0,0 +1,4 @@ +@page "/cookiestore-wasm" +@rendermode InteractiveWebAssembly + + diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs new file mode 100644 index 000000000000..2c9561e28132 --- /dev/null +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -0,0 +1,114 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Components.Testing.Infrastructure; +using Microsoft.AspNetCore.Components.Testing.Playwright; +using Microsoft.Playwright; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using PlatformTestApp.Components; +using PlatformTestApp.E2E.Tests.Fixtures; + +namespace PlatformTestApp.E2E.Tests.Tests; + +[UITest] +public partial class CookieStoreTests : BrowserTest +{ + private static readonly string[] CookieStorePaths = ["/cookiestore-server", "/cookiestore-wasm"]; + + private ServerInstance _server = null!; + private IBrowserContext _context = null!; + private IPage _page = null!; + + protected override async Task InitializeCoreAsync() + { + await base.InitializeCoreAsync(); + _server = await StartServerAsync(TestRoot.Servers); + _context = await NewContext(new BrowserNewContextOptions().WithServerRouting(_server)); + _page = await _context.NewPageAsync(); + } + + [TestMethod] + public async Task CookieStore_SetsGetsAndDeletesCookiesInBothRenderModes() + { + foreach (var path in CookieStorePaths) + { + await NavigateAsync(path, "#set-cookie"); + + var name = path == "/cookiestore-server" ? "server-cookie" : "wasm-cookie"; + await _page.Locator("#cookie-name").FillAsync(name); + await _page.Locator("#cookie-value").FillAsync("value"); + await RunAsync("#set-cookie", $"Set: {name}"); + + await RunAsync("#get-cookie", $"Found: {name}=value"); + await RunAsync("#get-cookie-with-options", $"Found: {name}=value"); + await RunAsync("#get-all-cookies", $"Found: {name}=value"); + await RunAsync("#get-all-cookies-with-name", $"Found: {name}=value"); + await RunAsync("#get-all-cookies-with-options", $"Found: {name}=value"); + + await RunAsync("#delete-cookie", $"Deleted: {name}"); + await RunAsync("#get-cookie", "Cookie is missing."); + await RunAsync("#get-all-cookies", "No cookies."); + } + } + + [TestMethod] + public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() + { + foreach (var path in CookieStorePaths) + { + await NavigateAsync(path, "#set-cookie"); + + var name = path == "/cookiestore-server" ? "server-options" : "wasm-options"; + await _page.Locator("#cookie-name").FillAsync(name); + + await RunAsync("#set-cookie-with-options", $"Set with options: {name}"); + var cookie = await GetBrowserCookieAsync(name); + // The browser adds a trailing slash to the path. + Assert.AreEqual("/cookie-path/", cookie.Path); + Assert.AreEqual(SameSiteAttribute.Lax, cookie.SameSite); + AssertExpiresIn(cookie, TimeSpan.FromDays(1)); + + await RunAsync("#delete-cookie-with-options", $"Deleted with options: {name}"); + Assert.DoesNotContain(name, (await _context.CookiesAsync()).Select(browserCookie => browserCookie.Name)); + + await RunAsync("#set-cookie-with-max-age", $"Set with max age: {name}"); + cookie = await GetBrowserCookieAsync(name); + Assert.AreEqual("/", cookie.Path); + Assert.AreEqual(SameSiteAttribute.None, cookie.SameSite); + AssertExpiresIn(cookie, TimeSpan.FromHours(1)); + await RunAsync("#delete-cookie", $"Deleted: {name}"); + + await RunAsync("#set-cookie-with-other-domain", "Another domain was rejected."); + Assert.DoesNotContain(name, (await _context.CookiesAsync()).Select(browserCookie => browserCookie.Name)); + } + } + + private async Task NavigateAsync(string path, string interactiveSelector) + { + await _page.GotoAsync($"{_server.TestUrl}{path}"); + await _page.WaitForInteractiveAsync(interactiveSelector); + } + + private async Task RunAsync(string buttonSelector, string expectedResult) + { + await _page.Locator(buttonSelector).ClickAsync(); + await Expect(_page.Locator("#cookie-result")).ToHaveTextAsync(expectedResult); + } + + private async Task GetBrowserCookieAsync(string name) + { + var cookies = await _context.CookiesAsync(); + + return cookies.Single(cookie => cookie.Name == name); + } + + private static void AssertExpiresIn(BrowserContextCookiesResult cookie, TimeSpan expected) + { + var actual = DateTimeOffset.FromUnixTimeMilliseconds((long)(cookie.Expires * 1000)) - DateTimeOffset.UtcNow; + + Assert.IsLessThan( + TimeSpan.FromMinutes(5), + (actual - expected).Duration(), + $"The cookie expires in {actual}, not in {expected}."); + } +} diff --git a/src/Components/Platform/testassets/PlatformTestApp/Components/Pages/CookieStoreServer.razor b/src/Components/Platform/testassets/PlatformTestApp/Components/Pages/CookieStoreServer.razor new file mode 100644 index 000000000000..1c8bd86d2835 --- /dev/null +++ b/src/Components/Platform/testassets/PlatformTestApp/Components/Pages/CookieStoreServer.razor @@ -0,0 +1,4 @@ +@page "/cookiestore-server" +@rendermode InteractiveServer + + From c895529757d9b976eae25e4e2d93e38490dbbe14 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 16 Oct 2026 15:59:24 +0900 Subject: [PATCH 02/11] Throw NotSupportedException when window.cookieStore is not defined - GetValueAsync throws JSException for a property that does not exist, such as cookieStore on a page that is not a secure context. It returns null only when the property exists and holds null or undefined. - Translate that JSException to NotSupportedException and keep it as the inner exception. Keep the null check as well. - Let other failures, such as JSDisconnectedException or a canceled call, reach the caller unchanged, so the next call acquires the reference again. - Simulate the missing API with JSException in the unit tests, and cover the null reference and other failures in separate tests. --- src/Components/Platform/src/CookieStore.cs | 16 ++++- .../Platform/test/CookieStoreTest.cs | 64 +++++++++++++++++-- 2 files changed, 73 insertions(+), 7 deletions(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index b770fbb3e168..749850f8b93a 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -196,9 +196,19 @@ private Task GetReferenceAsync() private async Task AcquireReferenceAsync() { - // window.cookieStore is undefined on an insecure page or in an older browser, and interop returns null for it. - var reference = await _jsRuntime.GetValueAsync("cookieStore").ConfigureAwait(false); + const string NotAvailableMessage = "The Cookie Store API is not available for the current page."; - return reference ?? throw new NotSupportedException("The Cookie Store API is not available for the current page."); + IJSObjectReference? reference; + try + { + reference = await _jsRuntime.GetValueAsync("cookieStore").ConfigureAwait(false); + } + catch (JSException ex) + { + // Interop throws for a missing window.cookieStore, such as on an insecure page or in an older browser. + throw new NotSupportedException(NotAvailableMessage, ex); + } + + return reference ?? throw new NotSupportedException(NotAvailableMessage); } } diff --git a/src/Components/Platform/test/CookieStoreTest.cs b/src/Components/Platform/test/CookieStoreTest.cs index 175cd326b5fb..d8e40f99f89c 100644 --- a/src/Components/Platform/test/CookieStoreTest.cs +++ b/src/Components/Platform/test/CookieStoreTest.cs @@ -99,7 +99,39 @@ public async Task CookieStore_ReacquiresReferenceAfterAcquisitionIsCanceled() [Fact] public async Task CookieStore_ThrowsNotSupportedExceptionWhenTheBrowserHasNoCookieStore() { - var jsRuntime = new RecordingJSRuntime { CookieStoreMissing = true }; + // JS interop throws this for a missing window.cookieStore, such as on a page that is not a secure context. + var missingProperty = new JSException("The property 'cookieStore' is not defined or is not readable."); + var jsRuntime = new RecordingJSRuntime { GetValueException = missingProperty }; + var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + Func[] members = + [ + () => cookieStore.GetAsync("name").AsTask(), + () => cookieStore.GetAsync(new CookieStoreGetOptions()).AsTask(), + () => cookieStore.GetAllAsync().AsTask(), + () => cookieStore.GetAllAsync("name").AsTask(), + () => cookieStore.GetAllAsync(new CookieStoreGetOptions()).AsTask(), + () => cookieStore.SetAsync("name", "value").AsTask(), + () => cookieStore.SetAsync(new CookieInit { Name = "name", Value = "value" }).AsTask(), + () => cookieStore.DeleteAsync("name").AsTask(), + () => cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "name" }).AsTask(), + ]; + + foreach (var member in members) + { + var exception = await Assert.ThrowsAsync(member); + Assert.Same(missingProperty, exception.InnerException); + } + await provider.DisposeAsync(); + + Assert.Equal(members.Length, jsRuntime.GetValueCallCount); + Assert.Empty(jsRuntime.ObjectReference.Invocations); + } + + [Fact] + public async Task CookieStore_ThrowsNotSupportedExceptionWhenCookieStoreIsNull() + { + var jsRuntime = new RecordingJSRuntime { CookieStoreNull = true }; var provider = CreateServiceProvider(jsRuntime); var cookieStore = provider.GetRequiredService().Window.CookieStore; @@ -111,6 +143,23 @@ public async Task CookieStore_ThrowsNotSupportedExceptionWhenTheBrowserHasNoCook Assert.Empty(jsRuntime.ObjectReference.Invocations); } + [Fact] + public async Task CookieStore_PassesThroughOtherAcquisitionFailuresAndReacquires() + { + var disconnected = new JSDisconnectedException("The circuit is disconnected."); + var jsRuntime = new RecordingJSRuntime { GetValueException = disconnected }; + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + var exception = await Assert.ThrowsAsync(() => cookieStore.GetAllAsync().AsTask()); + jsRuntime.GetValueException = null; + var all = await cookieStore.GetAllAsync(); + + Assert.Same(disconnected, exception); + Assert.Single(all); + Assert.Equal(2, jsRuntime.GetValueCallCount); + } + [Fact] public async Task ScopeDisposal_DisposesTheAcquiredReference() { @@ -282,7 +331,9 @@ private sealed class RecordingJSRuntime : IJSRuntime public bool CancelNextGetValue { get; set; } - public bool CookieStoreMissing { get; set; } + public bool CookieStoreNull { get; set; } + + public Exception? GetValueException { get; set; } public TaskCompletionSource? PendingNextGetValue { get; set; } @@ -318,8 +369,13 @@ public ValueTask GetValueAsync(string identifier) return new ValueTask((Task)(object)pending.Task); } - // JS interop returns a null reference when window.cookieStore is undefined. - return ValueTask.FromResult(CookieStoreMissing ? default! : (TValue)(object)ObjectReference); + if (GetValueException is { } exception) + { + return ValueTask.FromException(exception); + } + + // JS interop returns a null reference when window.cookieStore exists and holds null or undefined. + return ValueTask.FromResult(CookieStoreNull ? default! : (TValue)(object)ObjectReference); } } From ddb0b3664c2b9c36c0bdd4d29b27433530604d6c Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 16 Oct 2026 17:37:19 +0900 Subject: [PATCH 03/11] Describe which cookie the name-only SetAsync and DeleteAsync touch SetAsync(name, value) and DeleteAsync(name) work only on the cookie for the host of the current page and the path "/". A cookie with another domain or path, such as one that the server set with Path=/app, is not replaced or deleted, and no error tells the caller. --- src/Components/Platform/src/CookieStore.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index 749850f8b93a..af8a07dd7d91 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -103,7 +103,8 @@ public async ValueTask> GetAllAsync(CookieStoreGet } /// - /// Sets a cookie with the specified name and value, replacing any existing cookie with the same name. + /// Sets a cookie with the specified name and value for the host of the current page and the path "/", + /// replacing any existing cookie with the same name, host, and path. /// /// The name of the cookie. /// The value of the cookie. @@ -136,7 +137,8 @@ public async ValueTask SetAsync(CookieInit options) } /// - /// Deletes the cookie with the specified name, if it exists. + /// Deletes the cookie with the specified name that is restricted to the host of the current page and has the path "/", if it exists. + /// A cookie with another domain or path is not deleted. /// /// The name of the cookie to delete. /// A representing the completion of the operation. From 79d78243521d74125172eff273ca898c312338fc Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 16 Oct 2026 17:37:19 +0900 Subject: [PATCH 04/11] Cover the shared acquisition and the GetAsync result in unit tests - Add a test where two calls start before the reference is acquired. Both must wait for the same acquisition, so the browser is asked for window.cookieStore only once. The porting rules require this case, and no test covered it. - Move the null result of GetAsync out of the GetAllAsync test, whose name did not say that it checks GetAsync. A new GetAsync test reads a cookie from JSON with the members that Chromium still returns, and then reads null for a missing cookie. Until now only GetAllAsync read a cookie from JSON. - The tests for a missing cookieStore dispose the scope by hand to show that disposal does not throw after failed acquisitions. Say so in a comment, because the line looked like plain cleanup. --- .../Platform/test/CookieStoreTest.cs | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Components/Platform/test/CookieStoreTest.cs b/src/Components/Platform/test/CookieStoreTest.cs index d8e40f99f89c..0e06df0f03d2 100644 --- a/src/Components/Platform/test/CookieStoreTest.cs +++ b/src/Components/Platform/test/CookieStoreTest.cs @@ -63,6 +63,23 @@ public async Task CookieStore_ForwardsOperationsAndAcquiresReferenceOnce() invocation => AssertInvocation(invocation, "delete", deleteOptions)); } + [Fact] + public async Task CookieStore_SharesPendingAcquisitionBetweenCallers() + { + var pending = new TaskCompletionSource(); + var jsRuntime = new RecordingJSRuntime { PendingNextGetValue = pending }; + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + var first = cookieStore.GetAllAsync().AsTask(); + var second = cookieStore.GetAsync("name").AsTask(); + pending.SetResult(jsRuntime.ObjectReference); + await Task.WhenAll(first, second); + + Assert.Equal(1, jsRuntime.GetValueCallCount); + Assert.Equal(2, jsRuntime.ObjectReference.Invocations.Count); + } + [Fact] public async Task CookieStore_RejectsNullArguments() { @@ -122,6 +139,7 @@ public async Task CookieStore_ThrowsNotSupportedExceptionWhenTheBrowserHasNoCook var exception = await Assert.ThrowsAsync(member); Assert.Same(missingProperty, exception.InnerException); } + // Disposal must not throw for the failed acquisitions. await provider.DisposeAsync(); Assert.Equal(members.Length, jsRuntime.GetValueCallCount); @@ -137,6 +155,7 @@ public async Task CookieStore_ThrowsNotSupportedExceptionWhenCookieStoreIsNull() await Assert.ThrowsAsync(() => cookieStore.GetAllAsync().AsTask()); await Assert.ThrowsAsync(() => cookieStore.SetAsync("name", "value").AsTask()); + // Disposal must not throw for the failed acquisitions. await provider.DisposeAsync(); Assert.Equal(2, jsRuntime.GetValueCallCount); @@ -297,12 +316,28 @@ public async Task GetAllAsync_ReadsNameAndValueAndIgnoresOtherMembers() var cookieStore = provider.GetRequiredService().Window.CookieStore; var cookies = await cookieStore.GetAllAsync(); - var missing = await cookieStore.GetAsync("missing"); Assert.Collection( cookies, cookie => Assert.Equal(("a", "1"), (cookie.Name, cookie.Value)), cookie => Assert.Equal(("b", "2"), (cookie.Name, cookie.Value))); + } + + [Fact] + public async Task GetAsync_ReadsTheCookieOrNull() + { + var jsRuntime = new SerializingJSRuntime + { + GetResult = """{"name":"a","value":"1","domain":null,"path":"/","expires":null,"secure":true,"sameSite":"strict","partitioned":false}""", + }; + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + + var cookie = await cookieStore.GetAsync("a"); + jsRuntime.GetResult = "null"; + var missing = await cookieStore.GetAsync("missing"); + + Assert.Equal(("a", "1"), (cookie?.Name, cookie?.Value)); Assert.Null(missing); } @@ -426,6 +461,8 @@ private sealed class SerializingJSRuntime : JSRuntime public string GetAllResult { get; init; } = "[]"; + public string GetResult { get; set; } = "null"; + public string[] ArgumentsSentTo(string identifier) => [.. _calls.Where(call => call.Identifier == identifier).Select(call => call.ArgsJson ?? string.Empty)]; @@ -436,6 +473,7 @@ protected override void BeginInvokeJS(in JSInvocationInfo invocationInfo) var result = invocationInfo.Identifier switch { "cookieStore" => """{"__jsObjectId":1}""", + "get" => GetResult, "getAll" => GetAllResult, _ => "null", }; From b1c76ea4f3da568e49fc047bb3d4e8424c193691 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 16 Oct 2026 17:37:31 +0900 Subject: [PATCH 05/11] Check the default cookie attributes and several cookies in E2E tests - After SetAsync(name, value), read the cookie from the browser and check that it has the path "/", SameSite=Strict, and no expiration time. Until now the test only read the cookie back through the same API, so a wrong default would not show. - Add a "Set with defaults" button that passes a CookieInit with only the name and value, and check the same attributes. The other buttons set SameSite to Lax or None, so the Strict default of CookieInit never reached a browser. - Add a test that sets two cookies and reads both with GetAllAsync. Every other test reads a list with one cookie, so reading more than one item from a real browser, also in the published WebAssembly app, was not covered. --- .../Components/CookieStoreDemo.razor | 7 ++++ .../Tests/CookieStoreTests.cs | 39 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index df81ad840028..e6a13362e8b6 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -11,6 +11,7 @@
+ @@ -42,6 +43,12 @@ result = $"Set: {name}"; } + private async Task SetWithDefaultsAsync() + { + await Browser.Window.CookieStore.SetAsync(new CookieInit { Name = name, Value = value }); + result = $"Set with defaults: {name}"; + } + private async Task SetWithOptionsAsync() { await Browser.Window.CookieStore.SetAsync(new CookieInit diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs index 2c9561e28132..5472ad07bc9b 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -38,6 +38,7 @@ public async Task CookieStore_SetsGetsAndDeletesCookiesInBothRenderModes() await _page.Locator("#cookie-name").FillAsync(name); await _page.Locator("#cookie-value").FillAsync("value"); await RunAsync("#set-cookie", $"Set: {name}"); + AssertDefaultAttributes(await GetBrowserCookieAsync(name)); await RunAsync("#get-cookie", $"Found: {name}=value"); await RunAsync("#get-cookie-with-options", $"Found: {name}=value"); @@ -51,6 +52,32 @@ public async Task CookieStore_SetsGetsAndDeletesCookiesInBothRenderModes() } } + [TestMethod] + public async Task CookieStore_GetsAllOfSeveralCookies() + { + foreach (var path in CookieStorePaths) + { + await NavigateAsync(path, "#set-cookie"); + + var prefix = path == "/cookiestore-server" ? "server" : "wasm"; + await _page.Locator("#cookie-value").FillAsync("value"); + foreach (var name in new[] { $"{prefix}-first", $"{prefix}-second" }) + { + await _page.Locator("#cookie-name").FillAsync(name); + await RunAsync("#set-cookie", $"Set: {name}"); + } + + // Cookies with the same path come back in the order of creation. + await RunAsync("#get-all-cookies", $"Found: {prefix}-first=value; {prefix}-second=value"); + + foreach (var name in new[] { $"{prefix}-first", $"{prefix}-second" }) + { + await _page.Locator("#cookie-name").FillAsync(name); + await RunAsync("#delete-cookie", $"Deleted: {name}"); + } + } + } + [TestMethod] public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() { @@ -61,6 +88,10 @@ public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() var name = path == "/cookiestore-server" ? "server-options" : "wasm-options"; await _page.Locator("#cookie-name").FillAsync(name); + await RunAsync("#set-cookie-with-defaults", $"Set with defaults: {name}"); + AssertDefaultAttributes(await GetBrowserCookieAsync(name)); + await RunAsync("#delete-cookie", $"Deleted: {name}"); + await RunAsync("#set-cookie-with-options", $"Set with options: {name}"); var cookie = await GetBrowserCookieAsync(name); // The browser adds a trailing slash to the path. @@ -102,6 +133,14 @@ private async Task GetBrowserCookieAsync(string nam return cookies.Single(cookie => cookie.Name == name); } + private static void AssertDefaultAttributes(BrowserContextCookiesResult cookie) + { + Assert.AreEqual("/", cookie.Path); + Assert.AreEqual(SameSiteAttribute.Strict, cookie.SameSite); + // Playwright reports a session cookie with -1. + Assert.AreEqual(-1, cookie.Expires); + } + private static void AssertExpiresIn(BrowserContextCookiesResult cookie, TimeSpan expected) { var actual = DateTimeOffset.FromUnixTimeMilliseconds((long)(cookie.Expires * 1000)) - DateTimeOffset.UtcNow; From 611ade28e1a1e2bfde7484e167fc6483f0a32718 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 16 Oct 2026 17:37:49 +0900 Subject: [PATCH 06/11] Check NotSupportedException for a missing cookieStore in E2E tests The unit tests fake the JSException that JS interop throws when window.cookieStore is not defined. Only a real browser shows that both render modes really get a JSException there, and not a null reference, so that CookieStore turns it into NotSupportedException. - Remove window.cookieStore with an init script, as on a page that is not a secure context. Window defines cookieStore on the window object itself, not on Window.prototype, so the script deletes it there. Each test gets its own browser context, so the other tests still see the API. - Check that the page really lost cookieStore before the call, so the test cannot pass without the init script taking effect. - The Get button now shows NotSupportedException with the type of its inner exception, and the test expects JSException. A result from the null reference path would show no inner exception and fail the test. --- .../Components/CookieStoreDemo.razor | 9 ++++++++- .../Tests/CookieStoreTests.cs | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index e6a13362e8b6..c857275cec4a 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -90,7 +90,14 @@ private async Task GetAsync() { - result = Format(await Browser.Window.CookieStore.GetAsync(name)); + try + { + result = Format(await Browser.Window.CookieStore.GetAsync(name)); + } + catch (NotSupportedException ex) + { + result = $"Not supported: {ex.InnerException?.GetType().Name}"; + } } private async Task GetWithOptionsAsync() diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs index 5472ad07bc9b..5e8f0999654f 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -114,6 +114,21 @@ public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() } } + [TestMethod] + public async Task CookieStore_ThrowsNotSupportedExceptionWithoutTheBrowserApi() + { + // Same as a page that is not a secure context. The context belongs to this test only. + await _context.AddInitScriptAsync("delete window.cookieStore;"); + + foreach (var path in CookieStorePaths) + { + await NavigateAsync(path, "#get-cookie"); + Assert.IsFalse(await _page.EvaluateAsync("'cookieStore' in window")); + + await RunAsync("#get-cookie", "Not supported: JSException"); + } + } + private async Task NavigateAsync(string path, string interactiveSelector) { await _page.GotoAsync($"{_server.TestUrl}{path}"); From f10981c735abb171887fcead5d35047c6a0b7b46 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Tue, 20 Oct 2026 13:27:07 +0900 Subject: [PATCH 07/11] Add the experimental partitioned option to CookieInit and CookieStoreDeleteOptions API review asked to ship partitioned now, marked [Experimental] with the next free ASP diagnostic ID, because Safari does not support it and so it is not Baseline. - Add Partitioned to CookieInit and CookieStoreDeleteOptions. Web IDL declares boolean partitioned = false on both dictionaries, so the property is a bool that is always sent. CookieListItem is unchanged. - Mark both properties [Experimental("ASP0040")], the same form as ASP0039, and add ASP0040 to docs/list-of-diagnostics.md. PublicAPI files use no prefix for experimental members. - Check the JSON that reaches the browser for set and delete, with the default and with true. Unit tests and the demo page suppress ASP0040 with a pragma, as the passkey tests do. - Add an E2E test that sets a partitioned cookie, sees that deleting without Partitioned leaves it, and sees that deleting with Partitioned removes it, in both render modes. --- docs/list-of-diagnostics.md | 3 ++- src/Components/Platform/src/CookieInit.cs | 10 +++++++ .../Platform/src/CookieStoreDeleteOptions.cs | 10 +++++++ .../Platform/src/PublicAPI.Unshipped.txt | 4 +++ .../Platform/test/CookieStoreTest.cs | 16 +++++++----- .../Components/CookieStoreDemo.razor | 18 +++++++++++++ .../Tests/CookieStoreTests.cs | 26 +++++++++++++++++++ 7 files changed, 79 insertions(+), 8 deletions(-) diff --git a/docs/list-of-diagnostics.md b/docs/list-of-diagnostics.md index 7389024afa85..5cb0f5c8fbab 100644 --- a/docs/list-of-diagnostics.md +++ b/docs/list-of-diagnostics.md @@ -2,7 +2,7 @@ ## Analyzer Warnings -### ASP (`ASP0000-ASP0039`) +### ASP (`ASP0000-ASP0040`) | Diagnostic ID | Description | | :---------------- | :---------- | @@ -44,6 +44,7 @@ | __`ASP0037`__ | \[ValidatableType] cannot be used in generated code | | __`ASP0038`__ | \[ValidatableType] should not be used without a call to 'AddValidation' | | __`ASP0039`__ | Experimental warning for well-known passkey endpoints APIs | +| __`ASP0040`__ | Experimental warning for Components.Platform browser API members that have not met the package's stability criteria | ### API (`API1000-API1003`) diff --git a/src/Components/Platform/src/CookieInit.cs b/src/Components/Platform/src/CookieInit.cs index cadb19801b49..2a56e5e2fbf1 100644 --- a/src/Components/Platform/src/CookieInit.cs +++ b/src/Components/Platform/src/CookieInit.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; namespace Microsoft.AspNetCore.Components.Platform; @@ -44,6 +45,15 @@ public sealed class CookieInit /// public CookieSameSite SameSite { get; set; } = CookieSameSite.Strict; + /// + /// Gets or sets a value that indicates whether the cookie is partitioned by the top-level site. The default is . + /// + /// + /// A browser that does not support partitioned cookies ignores this setting and creates a cookie that is not partitioned. + /// + [Experimental("ASP0040", UrlFormat = "https://aka.ms/aspnet/analyzer/{0}")] + public bool Partitioned { get; set; } + // Chromium crashes the page on maxAge: null, although null means the same as a missing member. /// /// Gets or sets the maximum age of the cookie in seconds, or for a cookie without a maximum age. diff --git a/src/Components/Platform/src/CookieStoreDeleteOptions.cs b/src/Components/Platform/src/CookieStoreDeleteOptions.cs index e9643e14c389..c15c566c6458 100644 --- a/src/Components/Platform/src/CookieStoreDeleteOptions.cs +++ b/src/Components/Platform/src/CookieStoreDeleteOptions.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; namespace Microsoft.AspNetCore.Components.Platform; @@ -26,4 +27,13 @@ public sealed class CookieStoreDeleteOptions /// [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string Path { get; set; } = "/"; + + /// + /// Gets or sets a value that indicates whether the cookie to delete is partitioned. The default is . + /// + /// + /// A browser that does not support partitioned cookies ignores this setting and deletes the cookie that is not partitioned. + /// + [Experimental("ASP0040", UrlFormat = "https://aka.ms/aspnet/analyzer/{0}")] + public bool Partitioned { get; set; } } diff --git a/src/Components/Platform/src/PublicAPI.Unshipped.txt b/src/Components/Platform/src/PublicAPI.Unshipped.txt index 0dfdfe64f564..6e25fc25dfa6 100644 --- a/src/Components/Platform/src/PublicAPI.Unshipped.txt +++ b/src/Components/Platform/src/PublicAPI.Unshipped.txt @@ -9,6 +9,8 @@ Microsoft.AspNetCore.Components.Platform.CookieInit.MaxAge.get -> long? Microsoft.AspNetCore.Components.Platform.CookieInit.MaxAge.set -> void Microsoft.AspNetCore.Components.Platform.CookieInit.Name.get -> string! Microsoft.AspNetCore.Components.Platform.CookieInit.Name.set -> void +Microsoft.AspNetCore.Components.Platform.CookieInit.Partitioned.get -> bool +Microsoft.AspNetCore.Components.Platform.CookieInit.Partitioned.set -> void Microsoft.AspNetCore.Components.Platform.CookieInit.Path.get -> string! Microsoft.AspNetCore.Components.Platform.CookieInit.Path.set -> void Microsoft.AspNetCore.Components.Platform.CookieInit.SameSite.get -> Microsoft.AspNetCore.Components.Platform.CookieSameSite @@ -41,6 +43,8 @@ Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Domain.get -> Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Domain.set -> void Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Name.get -> string! Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Name.set -> void +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Partitioned.get -> bool +Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Partitioned.set -> void Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Path.get -> string! Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Path.set -> void Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions diff --git a/src/Components/Platform/test/CookieStoreTest.cs b/src/Components/Platform/test/CookieStoreTest.cs index 0e06df0f03d2..2f4adad071da 100644 --- a/src/Components/Platform/test/CookieStoreTest.cs +++ b/src/Components/Platform/test/CookieStoreTest.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. #nullable enable +#pragma warning disable ASP0040 // Partitioned is experimental. using Microsoft.Extensions.DependencyInjection; using Microsoft.JSInterop; @@ -239,6 +240,7 @@ await cookieStore.SetAsync(new CookieInit Domain = "example.com", Path = "/app", SameSite = CookieSameSite.Lax, + Partitioned = true, MaxAge = 3600, }); await cookieStore.SetAsync(new CookieInit { Name = "c", Value = "3", Path = null! }); @@ -246,9 +248,9 @@ await cookieStore.SetAsync(new CookieInit Assert.Equal( [ - """[{"name":"a","value":"1","path":"/","sameSite":"strict"}]""", - """[{"name":"b","value":"2","expires":1767225600000,"domain":"example.com","path":"/app","sameSite":"lax","maxAge":3600}]""", - """[{"name":"c","value":"3","sameSite":"strict"}]""", + """[{"name":"a","value":"1","path":"/","sameSite":"strict","partitioned":false}]""", + """[{"name":"b","value":"2","expires":1767225600000,"domain":"example.com","path":"/app","sameSite":"lax","partitioned":true,"maxAge":3600}]""", + """[{"name":"c","value":"3","sameSite":"strict","partitioned":false}]""", """["d","4"]""", ], jsRuntime.ArgumentsSentTo("set")); @@ -292,14 +294,14 @@ public async Task DeleteAsync_SendsDeleteOptionsWithoutNullMembers() var cookieStore = provider.GetRequiredService().Window.CookieStore; await cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "a" }); - await cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "b", Domain = "example.com", Path = "/app" }); + await cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "b", Domain = "example.com", Path = "/app", Partitioned = true }); await cookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = "c", Path = null! }); Assert.Equal( [ - """[{"name":"a","path":"/"}]""", - """[{"name":"b","domain":"example.com","path":"/app"}]""", - """[{"name":"c"}]""", + """[{"name":"a","path":"/","partitioned":false}]""", + """[{"name":"b","domain":"example.com","path":"/app","partitioned":true}]""", + """[{"name":"c","partitioned":false}]""", ], jsRuntime.ArgumentsSentTo("delete")); } diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index c857275cec4a..ed22d13d5017 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -15,6 +15,7 @@ +
@@ -26,6 +27,7 @@
+
@@ -88,6 +90,14 @@ } } + private async Task SetPartitionedAsync() + { +#pragma warning disable ASP0040 // Partitioned is experimental. + await Browser.Window.CookieStore.SetAsync(new CookieInit { Name = name, Value = value, Partitioned = true }); +#pragma warning restore ASP0040 + result = $"Set partitioned: {name}"; + } + private async Task GetAsync() { try @@ -133,6 +143,14 @@ result = $"Deleted with options: {name}"; } + private async Task DeletePartitionedAsync() + { +#pragma warning disable ASP0040 // Partitioned is experimental. + await Browser.Window.CookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = name, Partitioned = true }); +#pragma warning restore ASP0040 + result = $"Deleted partitioned: {name}"; + } + private static string Format(CookieListItem? cookie) => cookie is null ? "Cookie is missing." : $"Found: {cookie.Name}={cookie.Value}"; diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs index 5e8f0999654f..8b4974c16085 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -114,6 +114,32 @@ public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() } } + [TestMethod] + public async Task CookieStore_SetsAndDeletesPartitionedCookies() + { + foreach (var path in CookieStorePaths) + { + await NavigateAsync(path, "#set-cookie"); + + var name = path == "/cookiestore-server" ? "server-partitioned" : "wasm-partitioned"; + await _page.Locator("#cookie-name").FillAsync(name); + + await RunAsync("#set-cookie-partitioned", $"Set partitioned: {name}"); + var cookie = await GetBrowserCookieAsync(name); + Assert.IsNotNull(cookie.PartitionKey); + await RunAsync("#get-cookie", $"Found: {name}=initial"); + + // Deleting without Partitioned leaves the partitioned cookie in place. + await RunAsync("#delete-cookie", $"Deleted: {name}"); + await RunAsync("#get-cookie", $"Found: {name}=initial"); + Assert.IsNotNull((await GetBrowserCookieAsync(name)).PartitionKey); + + await RunAsync("#delete-cookie-partitioned", $"Deleted partitioned: {name}"); + await RunAsync("#get-cookie", "Cookie is missing."); + Assert.DoesNotContain(name, (await _context.CookiesAsync()).Select(browserCookie => browserCookie.Name)); + } + } + [TestMethod] public async Task CookieStore_ThrowsNotSupportedExceptionWithoutTheBrowserApi() { From 4d3680469e2de95cf8f9fe1121e1e2987046bf21 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Tue, 20 Oct 2026 13:59:12 +0900 Subject: [PATCH 08/11] Wait for each operation's own result in the Cookie Store E2E tests Several steps expected the same text, such as "Found: name=value" after five reads. The result stayed on the page until the next operation finished, so a step could pass on the text of the previous step, and a failed or wrong read went unnoticed. - The demo now shows each result as ": ", and the result element has a data-run counter that goes up only after the operation completes. - RunAsync reads the counter before the click, waits for the next value, and then checks the text. An exception now fails the test at its own step. --- .../Components/CookieStoreDemo.razor | 98 +++++++++---------- .../Tests/CookieStoreTests.cs | 48 +++++---- 2 files changed, 76 insertions(+), 70 deletions(-) diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index ed22d13d5017..9116a5ce61f1 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -29,7 +29,7 @@
- + @code { // A path other than the page path shows that the Path member reaches the browser. @@ -38,20 +38,21 @@ private string name = "cookie"; private string value = "initial"; private string result = "No operation has run."; + private int runCount; - private async Task SetAsync() + private Task SetAsync() => RunAsync("Set", async () => { await Browser.Window.CookieStore.SetAsync(name, value); - result = $"Set: {name}"; - } + return name; + }); - private async Task SetWithDefaultsAsync() + private Task SetWithDefaultsAsync() => RunAsync("Set with defaults", async () => { await Browser.Window.CookieStore.SetAsync(new CookieInit { Name = name, Value = value }); - result = $"Set with defaults: {name}"; - } + return name; + }); - private async Task SetWithOptionsAsync() + private Task SetWithOptionsAsync() => RunAsync("Set with options", async () => { await Browser.Window.CookieStore.SetAsync(new CookieInit { @@ -61,10 +62,10 @@ Path = OptionsPath, SameSite = CookieSameSite.Lax, }); - result = $"Set with options: {name}"; - } + return name; + }); - private async Task SetWithMaxAgeAsync() + private Task SetWithMaxAgeAsync() => RunAsync("Set with max age", async () => { await Browser.Window.CookieStore.SetAsync(new CookieInit { @@ -73,82 +74,81 @@ MaxAge = 3600, SameSite = CookieSameSite.None, }); - result = $"Set with max age: {name}"; - } + return name; + }); - private async Task SetWithOtherDomainAsync() + private Task SetWithOtherDomainAsync() => RunAsync("Set with another domain", async () => { // The browser rejects a domain that does not match the page, so the error shows that Domain reaches it. try { await Browser.Window.CookieStore.SetAsync(new CookieInit { Name = name, Value = value, Domain = "example.com" }); - result = $"Set with another domain: {name}"; + return name; } catch (JSException) { - result = "Another domain was rejected."; + return "Rejected."; } - } + }); - private async Task SetPartitionedAsync() + private Task SetPartitionedAsync() => RunAsync("Set partitioned", async () => { #pragma warning disable ASP0040 // Partitioned is experimental. await Browser.Window.CookieStore.SetAsync(new CookieInit { Name = name, Value = value, Partitioned = true }); #pragma warning restore ASP0040 - result = $"Set partitioned: {name}"; - } + return name; + }); - private async Task GetAsync() + private Task GetAsync() => RunAsync("Get", async () => { try { - result = Format(await Browser.Window.CookieStore.GetAsync(name)); + return Format(await Browser.Window.CookieStore.GetAsync(name)); } catch (NotSupportedException ex) { - result = $"Not supported: {ex.InnerException?.GetType().Name}"; + return $"Not supported: {ex.InnerException?.GetType().Name}"; } - } + }); - private async Task GetWithOptionsAsync() - { - result = Format(await Browser.Window.CookieStore.GetAsync(new CookieStoreGetOptions { Name = name })); - } + private Task GetWithOptionsAsync() => RunAsync("Get with options", async () => + Format(await Browser.Window.CookieStore.GetAsync(new CookieStoreGetOptions { Name = name }))); - private async Task GetAllAsync() - { - result = Format(await Browser.Window.CookieStore.GetAllAsync()); - } + private Task GetAllAsync() => RunAsync("Get all", async () => + Format(await Browser.Window.CookieStore.GetAllAsync())); - private async Task GetAllWithNameAsync() - { - result = Format(await Browser.Window.CookieStore.GetAllAsync(name)); - } + private Task GetAllWithNameAsync() => RunAsync("Get all with name", async () => + Format(await Browser.Window.CookieStore.GetAllAsync(name))); - private async Task GetAllWithOptionsAsync() - { - // The browser accepts only the URL of the current page. - result = Format(await Browser.Window.CookieStore.GetAllAsync(new CookieStoreGetOptions { Name = name, Url = Navigation.Uri })); - } + // The browser accepts only the URL of the current page. + private Task GetAllWithOptionsAsync() => RunAsync("Get all with options", async () => + Format(await Browser.Window.CookieStore.GetAllAsync(new CookieStoreGetOptions { Name = name, Url = Navigation.Uri }))); - private async Task DeleteAsync() + private Task DeleteAsync() => RunAsync("Delete", async () => { await Browser.Window.CookieStore.DeleteAsync(name); - result = $"Deleted: {name}"; - } + return name; + }); - private async Task DeleteWithOptionsAsync() + private Task DeleteWithOptionsAsync() => RunAsync("Delete with options", async () => { await Browser.Window.CookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = name, Path = OptionsPath }); - result = $"Deleted with options: {name}"; - } + return name; + }); - private async Task DeletePartitionedAsync() + private Task DeletePartitionedAsync() => RunAsync("Delete partitioned", async () => { #pragma warning disable ASP0040 // Partitioned is experimental. await Browser.Window.CookieStore.DeleteAsync(new CookieStoreDeleteOptions { Name = name, Partitioned = true }); #pragma warning restore ASP0040 - result = $"Deleted partitioned: {name}"; + return name; + }); + + private async Task RunAsync(string operation, Func> run) + { + result = $"{operation}: {await run()}"; + // Counts only completed runs, so a test waits for its own click and an exception fails at its step. + runCount++; } private static string Format(CookieListItem? cookie) diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs index 8b4974c16085..b348724ea7e5 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Globalization; using Microsoft.AspNetCore.Components.Testing.Infrastructure; using Microsoft.AspNetCore.Components.Testing.Playwright; using Microsoft.Playwright; @@ -40,15 +41,15 @@ public async Task CookieStore_SetsGetsAndDeletesCookiesInBothRenderModes() await RunAsync("#set-cookie", $"Set: {name}"); AssertDefaultAttributes(await GetBrowserCookieAsync(name)); - await RunAsync("#get-cookie", $"Found: {name}=value"); - await RunAsync("#get-cookie-with-options", $"Found: {name}=value"); - await RunAsync("#get-all-cookies", $"Found: {name}=value"); - await RunAsync("#get-all-cookies-with-name", $"Found: {name}=value"); - await RunAsync("#get-all-cookies-with-options", $"Found: {name}=value"); + await RunAsync("#get-cookie", $"Get: Found: {name}=value"); + await RunAsync("#get-cookie-with-options", $"Get with options: Found: {name}=value"); + await RunAsync("#get-all-cookies", $"Get all: Found: {name}=value"); + await RunAsync("#get-all-cookies-with-name", $"Get all with name: Found: {name}=value"); + await RunAsync("#get-all-cookies-with-options", $"Get all with options: Found: {name}=value"); - await RunAsync("#delete-cookie", $"Deleted: {name}"); - await RunAsync("#get-cookie", "Cookie is missing."); - await RunAsync("#get-all-cookies", "No cookies."); + await RunAsync("#delete-cookie", $"Delete: {name}"); + await RunAsync("#get-cookie", "Get: Cookie is missing."); + await RunAsync("#get-all-cookies", "Get all: No cookies."); } } @@ -68,12 +69,12 @@ public async Task CookieStore_GetsAllOfSeveralCookies() } // Cookies with the same path come back in the order of creation. - await RunAsync("#get-all-cookies", $"Found: {prefix}-first=value; {prefix}-second=value"); + await RunAsync("#get-all-cookies", $"Get all: Found: {prefix}-first=value; {prefix}-second=value"); foreach (var name in new[] { $"{prefix}-first", $"{prefix}-second" }) { await _page.Locator("#cookie-name").FillAsync(name); - await RunAsync("#delete-cookie", $"Deleted: {name}"); + await RunAsync("#delete-cookie", $"Delete: {name}"); } } } @@ -90,7 +91,7 @@ public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() await RunAsync("#set-cookie-with-defaults", $"Set with defaults: {name}"); AssertDefaultAttributes(await GetBrowserCookieAsync(name)); - await RunAsync("#delete-cookie", $"Deleted: {name}"); + await RunAsync("#delete-cookie", $"Delete: {name}"); await RunAsync("#set-cookie-with-options", $"Set with options: {name}"); var cookie = await GetBrowserCookieAsync(name); @@ -99,7 +100,7 @@ public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() Assert.AreEqual(SameSiteAttribute.Lax, cookie.SameSite); AssertExpiresIn(cookie, TimeSpan.FromDays(1)); - await RunAsync("#delete-cookie-with-options", $"Deleted with options: {name}"); + await RunAsync("#delete-cookie-with-options", $"Delete with options: {name}"); Assert.DoesNotContain(name, (await _context.CookiesAsync()).Select(browserCookie => browserCookie.Name)); await RunAsync("#set-cookie-with-max-age", $"Set with max age: {name}"); @@ -107,9 +108,9 @@ public async Task CookieStore_SendsEveryCookieOptionToTheBrowser() Assert.AreEqual("/", cookie.Path); Assert.AreEqual(SameSiteAttribute.None, cookie.SameSite); AssertExpiresIn(cookie, TimeSpan.FromHours(1)); - await RunAsync("#delete-cookie", $"Deleted: {name}"); + await RunAsync("#delete-cookie", $"Delete: {name}"); - await RunAsync("#set-cookie-with-other-domain", "Another domain was rejected."); + await RunAsync("#set-cookie-with-other-domain", "Set with another domain: Rejected."); Assert.DoesNotContain(name, (await _context.CookiesAsync()).Select(browserCookie => browserCookie.Name)); } } @@ -127,15 +128,15 @@ public async Task CookieStore_SetsAndDeletesPartitionedCookies() await RunAsync("#set-cookie-partitioned", $"Set partitioned: {name}"); var cookie = await GetBrowserCookieAsync(name); Assert.IsNotNull(cookie.PartitionKey); - await RunAsync("#get-cookie", $"Found: {name}=initial"); + await RunAsync("#get-cookie", $"Get: Found: {name}=initial"); // Deleting without Partitioned leaves the partitioned cookie in place. - await RunAsync("#delete-cookie", $"Deleted: {name}"); - await RunAsync("#get-cookie", $"Found: {name}=initial"); + await RunAsync("#delete-cookie", $"Delete: {name}"); + await RunAsync("#get-cookie", $"Get: Found: {name}=initial"); Assert.IsNotNull((await GetBrowserCookieAsync(name)).PartitionKey); - await RunAsync("#delete-cookie-partitioned", $"Deleted partitioned: {name}"); - await RunAsync("#get-cookie", "Cookie is missing."); + await RunAsync("#delete-cookie-partitioned", $"Delete partitioned: {name}"); + await RunAsync("#get-cookie", "Get: Cookie is missing."); Assert.DoesNotContain(name, (await _context.CookiesAsync()).Select(browserCookie => browserCookie.Name)); } } @@ -151,7 +152,7 @@ public async Task CookieStore_ThrowsNotSupportedExceptionWithoutTheBrowserApi() await NavigateAsync(path, "#get-cookie"); Assert.IsFalse(await _page.EvaluateAsync("'cookieStore' in window")); - await RunAsync("#get-cookie", "Not supported: JSException"); + await RunAsync("#get-cookie", "Get: Not supported: JSException"); } } @@ -163,8 +164,13 @@ private async Task NavigateAsync(string path, string interactiveSelector) private async Task RunAsync(string buttonSelector, string expectedResult) { + var result = _page.Locator("#cookie-result"); + // Waiting for the next run keeps a step from passing on the text of the previous step. + var nextRun = int.Parse(await result.GetAttributeAsync("data-run") ?? "", CultureInfo.InvariantCulture) + 1; + await _page.Locator(buttonSelector).ClickAsync(); - await Expect(_page.Locator("#cookie-result")).ToHaveTextAsync(expectedResult); + await Expect(result).ToHaveAttributeAsync("data-run", nextRun.ToString(CultureInfo.InvariantCulture)); + await Expect(result).ToHaveTextAsync(expectedResult); } private async Task GetBrowserCookieAsync(string name) From eb4a2902930f59e253e83a19fc8f341641b33014 Mon Sep 17 00:00:00 2001 From: Jun-ichi Sakamoto <102948935+jsakamotoIGJP@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:40:11 +0900 Subject: [PATCH 09/11] Update src/Components/Platform/src/CookieStore.cs Co-authored-by: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> --- src/Components/Platform/src/CookieStore.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index af8a07dd7d91..619c0fc6a593 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -137,8 +137,8 @@ public async ValueTask SetAsync(CookieInit options) } /// - /// Deletes the cookie with the specified name that is restricted to the host of the current page and has the path "/", if it exists. - /// A cookie with another domain or path is not deleted. + /// Deletes the unpartitioned cookie with the specified name that is restricted to the host of the current page and has the path "/", if it exists. + /// A partitioned cookie, or a cookie with another domain or path, is not deleted. /// /// The name of the cookie to delete. /// A representing the completion of the operation. From 867cb03c2511fe9e9695fe36ee42e57b617a10de Mon Sep 17 00:00:00 2001 From: Jun-ichi Sakamoto <102948935+jsakamotoIGJP@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:40:28 +0900 Subject: [PATCH 10/11] Update src/Components/Platform/src/CookieStore.cs Co-authored-by: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> --- src/Components/Platform/src/CookieStore.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index 619c0fc6a593..898e57e6acb0 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -103,8 +103,8 @@ public async ValueTask> GetAllAsync(CookieStoreGet } /// - /// Sets a cookie with the specified name and value for the host of the current page and the path "/", - /// replacing any existing cookie with the same name, host, and path. + /// Sets the unpartitioned cookie with the specified name and value for the host of the current page and the path "/", + /// replacing any existing unpartitioned cookie with the same name, host, and path. /// /// The name of the cookie. /// The value of the cookie. From 90cb47fe7bd2c2f8f8550ff40b8b6b32c2002826 Mon Sep 17 00:00:00 2001 From: Jun-ichi Sakamoto <102948935+jsakamotoIGJP@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:40:42 +0900 Subject: [PATCH 11/11] Update src/Components/Platform/src/CookieStore.cs Co-authored-by: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> --- src/Components/Platform/src/CookieStore.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index 898e57e6acb0..1071e802672d 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -121,7 +121,7 @@ public async ValueTask SetAsync(string name, string value) } /// - /// Sets a cookie with the specified options, replacing any existing cookie with the same name, domain, and path. + /// Sets a cookie with the specified options, replacing any existing cookie with the same name, domain, and path that has the same partitioning. /// /// The name, value, and attributes of the cookie. /// A representing the completion of the operation.