diff --git a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/DPoPProofValidator.cs b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/DPoPProofValidator.cs index 65e6485e2..d00a03f73 100644 --- a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/DPoPProofValidator.cs +++ b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/DPoPProofValidator.cs @@ -70,7 +70,7 @@ internal class DPoPProofValidator : IDPoPProofValidator /// /// Validates the DPoP proof. /// - public async Task Validate(DPoPProofValidationContext context, CT ct = default) + public async Task Validate(DPoPProofValidationContext context, Ct ct = default) { using var activity = Tracing.ActivitySource.StartActivity("DPoPProofValidator.Validate"); @@ -368,7 +368,7 @@ internal class DPoPProofValidator : IDPoPProofValidator internal async Task ValidateReplay( DPoPProofValidationContext context, DPoPProofValidationResult result, - CT ct = default) + Ct ct = default) { var dPoPOptions = OptionsMonitor.Get(context.Scheme); diff --git a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IDPoPProofValidator.cs b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IDPoPProofValidator.cs index a49515050..9520221f5 100644 --- a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IDPoPProofValidator.cs +++ b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IDPoPProofValidator.cs @@ -11,5 +11,5 @@ public interface IDPoPProofValidator /// /// Validates the DPoP proof. /// - Task Validate(DPoPProofValidationContext context, CT ct = default); + Task Validate(DPoPProofValidationContext context, Ct ct = default); } diff --git a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IReplayCache.cs b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IReplayCache.cs index f8c076fd5..b774ca060 100644 --- a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IReplayCache.cs +++ b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/IReplayCache.cs @@ -11,11 +11,11 @@ public interface IReplayCache /// /// Adds a hashed jti to the cache. /// - Task Add(string jtiHash, TimeSpan expiration, CT ct = default); + Task Add(string jtiHash, TimeSpan expiration, Ct ct = default); /// /// Checks if a cached jti hash exists in the hash. /// - Task Exists(string jtiHash, CT ct = default); + Task Exists(string jtiHash, Ct ct = default); } diff --git a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/ReplayCache.cs b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/ReplayCache.cs index ca2518462..6d1ee8bcd 100644 --- a/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/ReplayCache.cs +++ b/aspnetcore-authentication-jwtbearer/src/AspNetCore.Authentication.JwtBearer/DPoP/ReplayCache.cs @@ -24,7 +24,7 @@ internal class ReplayCache(DPoPHybridCacheProvider cacheProvider) : IReplayCache } } - public async Task Add(string handle, TimeSpan expiration, CT ct) + public async Task Add(string handle, TimeSpan expiration, Ct ct) { using var activity = Tracing.ActivitySource.StartActivity("ReplayCache.Add"); @@ -43,14 +43,14 @@ internal class ReplayCache(DPoPHybridCacheProvider cacheProvider) : IReplayCache | HybridCacheEntryFlags.DisableUnderlyingData }; - public async Task Exists(string handle, CT ct) + public async Task Exists(string handle, Ct ct) { using var activity = Tracing.ActivitySource.StartActivity("ReplayCache.Exists"); + // The factory will never be invoked because the ReadOnlyEntryOptions set the DisableUnderlyingData flag return await Cache.GetOrCreateAsync( Prefix + handle, - // The factory will never be invoked because the ReadOnlyEntryOptions set the DisableUnderlyingData flag - cancel => throw new InvalidOperationException("Can't Happen"), + _ => throw new InvalidOperationException("Can't Happen"), ReadOnlyEntryOptions, cancellationToken: ct); } diff --git a/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestBrowserClient.cs b/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestBrowserClient.cs index 8c2c3019c..b4a5b65c2 100644 --- a/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestBrowserClient.cs +++ b/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestBrowserClient.cs @@ -15,7 +15,7 @@ public class TestBrowserClient : HttpClient public HttpResponseMessage LastResponse { get; private set; } = default!; protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { CurrentUri = request.RequestUri!; var cookieHeader = CookieContainer.GetCookieHeader(request.RequestUri!); diff --git a/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestHybridCache.cs b/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestHybridCache.cs index 4da5065c3..279a85dac 100644 --- a/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestHybridCache.cs +++ b/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestHybridCache.cs @@ -11,8 +11,8 @@ internal class TestHybridCache : HybridCache private readonly List<(string key, object value, HybridCacheEntryOptions? options)> _setAsyncCalls = new(); private readonly List<(string key, HybridCacheEntryOptions? options)> _getOrCreateAsyncCalls = new(); - public override async ValueTask GetOrCreateAsync(string key, TState state, Func> factory, HybridCacheEntryOptions? options = null, - IEnumerable? tags = null, CT ct = new()) + public override async ValueTask GetOrCreateAsync(string key, TState state, Func> factory, HybridCacheEntryOptions? options = null, + IEnumerable? tags = null, Ct ct = new()) { _getOrCreateAsyncCalls.Add((key, options)); @@ -25,16 +25,16 @@ internal class TestHybridCache : HybridCache } public override ValueTask SetAsync(string key, T value, HybridCacheEntryOptions? options = null, IEnumerable? tags = null, - CT ct = new()) + Ct ct = new()) { _setAsyncCalls.Add((key, value!, options)); _cache[key] = value!; return ValueTask.CompletedTask; } - public override ValueTask RemoveAsync(string key, CT ct = new()) => throw new NotImplementedException(); + public override ValueTask RemoveAsync(string key, Ct ct = new()) => throw new NotImplementedException(); - public override ValueTask RemoveByTagAsync(string tag, CT ct = new()) => throw new NotImplementedException(); + public override ValueTask RemoveByTagAsync(string tag, Ct ct = new()) => throw new NotImplementedException(); public IReadOnlyList<(string key, object value, HybridCacheEntryOptions? options)> SetAsyncCalls => _setAsyncCalls; public IReadOnlyList<(string key, HybridCacheEntryOptions? options)> GetOrCreateAsyncCalls => _getOrCreateAsyncCalls; diff --git a/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestReplayCache.cs b/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestReplayCache.cs index 6e0c51784..79a7a0cfd 100644 --- a/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestReplayCache.cs +++ b/aspnetcore-authentication-jwtbearer/test/AspNetCore.Authentication.JwtBearer.Tests/TestFramework/TestReplayCache.cs @@ -14,14 +14,14 @@ public class TestReplayCache : IReplayCache // Configuration for test behavior public Func? ExistsFunc { get; set; } - public Task Add(string jtiHash, TimeSpan expiration, CT ct = default) + public Task Add(string jtiHash, TimeSpan expiration, Ct ct = default) { _addCalls.Add((jtiHash, expiration)); _cache[jtiHash] = (expiration, DateTime.UtcNow); return Task.CompletedTask; } - public Task Exists(string jtiHash, CT ct = default) + public Task Exists(string jtiHash, Ct ct = default) { _existsCalls.Add(jtiHash); diff --git a/bff/hosts/Hosts.Bff.InMemory/ImpersonationAccessTokenRetriever.cs b/bff/hosts/Hosts.Bff.InMemory/ImpersonationAccessTokenRetriever.cs index f1f18da42..bac852ad3 100644 --- a/bff/hosts/Hosts.Bff.InMemory/ImpersonationAccessTokenRetriever.cs +++ b/bff/hosts/Hosts.Bff.InMemory/ImpersonationAccessTokenRetriever.cs @@ -9,7 +9,7 @@ namespace Bff; public class ImpersonationAccessTokenRetriever(IAccessTokenRetriever inner) : IAccessTokenRetriever { - public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, CT ct = default) + public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, Ct ct = default) { var result = await inner.GetAccessTokenAsync(context, ct); diff --git a/bff/hosts/Hosts.Bff.MultiFrontend/ImpersonationAccessTokenRetriever.cs b/bff/hosts/Hosts.Bff.MultiFrontend/ImpersonationAccessTokenRetriever.cs index f1f18da42..bac852ad3 100644 --- a/bff/hosts/Hosts.Bff.MultiFrontend/ImpersonationAccessTokenRetriever.cs +++ b/bff/hosts/Hosts.Bff.MultiFrontend/ImpersonationAccessTokenRetriever.cs @@ -9,7 +9,7 @@ namespace Bff; public class ImpersonationAccessTokenRetriever(IAccessTokenRetriever inner) : IAccessTokenRetriever { - public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, CT ct = default) + public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, Ct ct = default) { var result = await inner.GetAccessTokenAsync(context, ct); diff --git a/bff/hosts/Hosts.Bff.MultiFrontend/Program.cs b/bff/hosts/Hosts.Bff.MultiFrontend/Program.cs index 3296ec36c..7aad37e6e 100644 --- a/bff/hosts/Hosts.Bff.MultiFrontend/Program.cs +++ b/bff/hosts/Hosts.Bff.MultiFrontend/Program.cs @@ -166,7 +166,7 @@ app.MapGet("/local/self-contained", (CurrentFrontendAccessor currentFrontendAcce return data; }); -app.MapGet("/local/invokes-external-api", async (CurrentFrontendAccessor currentFrontendAccessor, IHttpClientFactory httpClientFactory, HttpContext c, CT ct) => +app.MapGet("/local/invokes-external-api", async (CurrentFrontendAccessor currentFrontendAccessor, IHttpClientFactory httpClientFactory, HttpContext c, Ct ct) => { var httpClient = httpClientFactory.CreateClient("api"); var apiResult = await httpClient.GetAsync("/user-token"); @@ -235,7 +235,7 @@ RouteConfig[] BuildYarpRoutes() public class FrontendAwareIndexHtmlTransformer : IIndexHtmlTransformer { - public Task Transform(string indexHtml, BffFrontend frontend, CT ct = default) + public Task Transform(string indexHtml, BffFrontend frontend, Ct ct = default) { indexHtml = indexHtml.Replace("[FrontendName]", frontend.Name); indexHtml = indexHtml.Replace("[Path]", frontend.MatchingCriteria.MatchingPath + "/"); // Note, the path must end with a slash diff --git a/bff/hosts/Hosts.Bff.Performance/Services/ApiHostedService.cs b/bff/hosts/Hosts.Bff.Performance/Services/ApiHostedService.cs index 7ee61e2b1..d3c31553c 100644 --- a/bff/hosts/Hosts.Bff.Performance/Services/ApiHostedService.cs +++ b/bff/hosts/Hosts.Bff.Performance/Services/ApiHostedService.cs @@ -9,7 +9,7 @@ public class ApiHostedService(IOptions apiSettings) : BackgroundSer { public ApiSettings Settings { get; } = apiSettings.Value; - protected override Task ExecuteAsync(CT stoppingToken) + protected override Task ExecuteAsync(Ct stoppingToken) { var builder = WebApplication.CreateBuilder(); builder.AddServiceDefaults(); diff --git a/bff/hosts/Hosts.Bff.Performance/Services/BffService.cs b/bff/hosts/Hosts.Bff.Performance/Services/BffService.cs index 6fcd0ed1c..730540d7c 100644 --- a/bff/hosts/Hosts.Bff.Performance/Services/BffService.cs +++ b/bff/hosts/Hosts.Bff.Performance/Services/BffService.cs @@ -15,7 +15,7 @@ public abstract class BffService(string[] urlConfigKeys, IConfiguration config, public IConfiguration Config { get; } = config; public BffSettings Settings { get; } = bffSettings.Value; - protected override async Task ExecuteAsync(CT stoppingToken) + protected override async Task ExecuteAsync(Ct stoppingToken) { var urls = urlConfigKeys .Select(x => Config[x]) diff --git a/bff/hosts/Hosts.Bff.Performance/Services/IdentityServerService.cs b/bff/hosts/Hosts.Bff.Performance/Services/IdentityServerService.cs index 4d2534b2d..96be741ad 100644 --- a/bff/hosts/Hosts.Bff.Performance/Services/IdentityServerService.cs +++ b/bff/hosts/Hosts.Bff.Performance/Services/IdentityServerService.cs @@ -17,7 +17,7 @@ public class IdentityServerService(IOptions settings, IC { public IdentityServerSettings Settings { get; } = settings.Value; - protected override Task ExecuteAsync(CT stoppingToken) + protected override Task ExecuteAsync(Ct stoppingToken) { var builder = WebApplication.CreateBuilder(); builder.AddServiceDefaults(); diff --git a/bff/performance/Bff.Benchmarks/Hosts/CookieHandler.cs b/bff/performance/Bff.Benchmarks/Hosts/CookieHandler.cs index 00bf0059b..1f696bf13 100644 --- a/bff/performance/Bff.Benchmarks/Hosts/CookieHandler.cs +++ b/bff/performance/Bff.Benchmarks/Hosts/CookieHandler.cs @@ -9,7 +9,7 @@ namespace Bff.Benchmarks.Hosts; internal class CookieHandler(HttpMessageHandler innerHandler, CookieContainer cookieContainer) : DelegatingHandler(innerHandler) { - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct ct) { var requestUri = request.RequestUri; var header = cookieContainer.GetCookieHeader(requestUri!); diff --git a/bff/performance/Bff.Benchmarks/Hosts/RedirectHandler.cs b/bff/performance/Bff.Benchmarks/Hosts/RedirectHandler.cs index d410a2d5b..3488b4eb4 100644 --- a/bff/performance/Bff.Benchmarks/Hosts/RedirectHandler.cs +++ b/bff/performance/Bff.Benchmarks/Hosts/RedirectHandler.cs @@ -12,7 +12,7 @@ internal class RedirectHandler() : DelegatingHandler public bool AutoFollowRedirects { get; set; } = true; protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { var originalUri = request.RequestUri; diff --git a/bff/performance/Bff.Benchmarks/Hosts/RoutingMessageHandler.cs b/bff/performance/Bff.Benchmarks/Hosts/RoutingMessageHandler.cs index 8458d3628..c0222cf7c 100644 --- a/bff/performance/Bff.Benchmarks/Hosts/RoutingMessageHandler.cs +++ b/bff/performance/Bff.Benchmarks/Hosts/RoutingMessageHandler.cs @@ -27,7 +27,7 @@ internal class RoutingMessageHandler : HttpMessageHandler protected override Task SendAsync( HttpRequestMessage request, - CT ct) + Ct ct) { var host = $"{request.RequestUri?.Host}:{request.RequestUri?.Port}"; @@ -46,7 +46,7 @@ internal class RoutingMessageHandler : HttpMessageHandler { internal Task SuppressedSend( HttpRequestMessage request, - CT ct) + Ct ct) { Task t; if (ExecutionContext.IsFlowSuppressed()) diff --git a/bff/performance/Bff.Benchmarks/Hosts/SimulatedInternet.cs b/bff/performance/Bff.Benchmarks/Hosts/SimulatedInternet.cs index 6e4cc2ee8..1cfaa63a0 100644 --- a/bff/performance/Bff.Benchmarks/Hosts/SimulatedInternet.cs +++ b/bff/performance/Bff.Benchmarks/Hosts/SimulatedInternet.cs @@ -64,7 +64,7 @@ internal class SimulatedInternet : DelegatingHandler protected override async Task SendAsync( HttpRequestMessage request, - CT ct) + Ct ct) { var httpResponseMessage = await base.SendAsync(request, ct); return httpResponseMessage; diff --git a/bff/performance/Bff.Performance/TestInfra/AutoFollowRedirectHandler.cs b/bff/performance/Bff.Performance/TestInfra/AutoFollowRedirectHandler.cs index d33c82d40..56088f197 100644 --- a/bff/performance/Bff.Performance/TestInfra/AutoFollowRedirectHandler.cs +++ b/bff/performance/Bff.Performance/TestInfra/AutoFollowRedirectHandler.cs @@ -8,7 +8,7 @@ namespace Bff.Performance.TestInfra; public class AutoFollowRedirectHandler(Action writeOutput) : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { var previousUri = request.RequestUri; for (var i = 0; i < 20; i++) diff --git a/bff/performance/Bff.Performance/TestInfra/CloningHttpMessageHandler.cs b/bff/performance/Bff.Performance/TestInfra/CloningHttpMessageHandler.cs index bdfb56601..91998edba 100644 --- a/bff/performance/Bff.Performance/TestInfra/CloningHttpMessageHandler.cs +++ b/bff/performance/Bff.Performance/TestInfra/CloningHttpMessageHandler.cs @@ -9,7 +9,7 @@ public class CloningHttpMessageHandler(HttpClient innerHttpClient) : HttpMessage innerHttpClient ?? throw new ArgumentNullException(nameof(innerHttpClient)); protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { // Clone the incoming request var clonedRequest = await CloneHttpRequestMessageAsync(request); diff --git a/bff/performance/Bff.Performance/TestInfra/RequestLoggingHandler.cs b/bff/performance/Bff.Performance/TestInfra/RequestLoggingHandler.cs index fc3abae9e..81d9102ae 100644 --- a/bff/performance/Bff.Performance/TestInfra/RequestLoggingHandler.cs +++ b/bff/performance/Bff.Performance/TestInfra/RequestLoggingHandler.cs @@ -12,7 +12,7 @@ public class RequestLoggingHandler( : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { if (!shouldLog(request)) { diff --git a/bff/src/Bff.Blazor.Client/Internals/AntiforgeryHandler.cs b/bff/src/Bff.Blazor.Client/Internals/AntiforgeryHandler.cs index 6d6d05b9d..98ef58f0c 100644 --- a/bff/src/Bff.Blazor.Client/Internals/AntiforgeryHandler.cs +++ b/bff/src/Bff.Blazor.Client/Internals/AntiforgeryHandler.cs @@ -6,7 +6,7 @@ namespace Duende.Bff.Blazor.Client.Internals; internal class AntiForgeryHandler : DelegatingHandler { protected override Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { request.Headers.Add("X-CSRF", "1"); return base.SendAsync(request, ct); diff --git a/bff/src/Bff.Blazor/BffServerAuthenticationStateProvider.cs b/bff/src/Bff.Blazor/BffServerAuthenticationStateProvider.cs index a3084be75..c5a22d567 100644 --- a/bff/src/Bff.Blazor/BffServerAuthenticationStateProvider.cs +++ b/bff/src/Bff.Blazor/BffServerAuthenticationStateProvider.cs @@ -126,7 +126,7 @@ internal sealed class BffServerAuthenticationStateProvider : RevalidatingServerA /// The current authentication state. /// A token that can be used to request cancellation of the asynchronous operation. /// A boolean indicating whether the authentication state is valid. - protected override async Task ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CT ct) + protected override async Task ValidateAuthenticationStateAsync(AuthenticationState authenticationState, Ct ct) { using var scope = _serviceScopeFactory.CreateScope(); var sessionStore = scope.ServiceProvider.GetRequiredService(); diff --git a/bff/src/Bff.Blazor/ServerSideTokenStore.cs b/bff/src/Bff.Blazor/ServerSideTokenStore.cs index 34cf00413..172331fbc 100644 --- a/bff/src/Bff.Blazor/ServerSideTokenStore.cs +++ b/bff/src/Bff.Blazor/ServerSideTokenStore.cs @@ -32,7 +32,7 @@ internal class ServerSideTokenStore( ?? throw new ArgumentException("AuthenticationStateProvider must implement IHostEnvironmentAuthenticationStateProvider"); public async Task> GetTokenAsync(ClaimsPrincipal user, UserTokenRequestParameters? parameters = null, - CT ct = default) + Ct ct = default) { logger.RetrievingTokenForUser(LogLevel.Debug, user.Identity?.Name); var session = await GetSession(user); @@ -83,7 +83,7 @@ internal class ServerSideTokenStore( } public async Task StoreTokenAsync(ClaimsPrincipal user, UserToken token, - UserTokenRequestParameters? parameters = null, CT ct = default) + UserTokenRequestParameters? parameters = null, Ct ct = default) { logger.StoringTokenForUser(LogLevel.Debug, user.Identity?.Name); await UpdateTicket(user, @@ -91,7 +91,7 @@ internal class ServerSideTokenStore( } - public async Task ClearTokenAsync(ClaimsPrincipal user, UserTokenRequestParameters? parameters = null, CT ct = default) + public async Task ClearTokenAsync(ClaimsPrincipal user, UserTokenRequestParameters? parameters = null, Ct ct = default) { logger.RemovingTokenForUser(LogLevel.Debug, user.Identity?.Name); await UpdateTicket(user, ticket => diff --git a/bff/src/Bff.EntityFramework/ISessionDbContext.cs b/bff/src/Bff.EntityFramework/ISessionDbContext.cs index 8adf7956d..75c552952 100644 --- a/bff/src/Bff.EntityFramework/ISessionDbContext.cs +++ b/bff/src/Bff.EntityFramework/ISessionDbContext.cs @@ -23,5 +23,5 @@ public interface ISessionDbContext /// Saves the changes. /// /// - Task SaveChangesAsync(CT ct = default); + Task SaveChangesAsync(Ct ct = default); } diff --git a/bff/src/Bff.EntityFramework/Internal/UserSessionStore.cs b/bff/src/Bff.EntityFramework/Internal/UserSessionStore.cs index 5bdcda9ff..831e00983 100644 --- a/bff/src/Bff.EntityFramework/Internal/UserSessionStore.cs +++ b/bff/src/Bff.EntityFramework/Internal/UserSessionStore.cs @@ -18,7 +18,7 @@ internal sealed class UserSessionStore( : IUserSessionStore, IUserSessionStoreCleanup { /// - public async Task CreateUserSessionAsync(UserSession session, CT ct) + public async Task CreateUserSessionAsync(UserSession session, Ct ct) { if (!session.PartitionKey.HasValue) { @@ -67,7 +67,7 @@ internal sealed class UserSessionStore( } /// - public async Task DeleteUserSessionAsync(UserSessionKey key, CT ct) + public async Task DeleteUserSessionAsync(UserSessionKey key, Ct ct) { var userKey = key.UserKey; var partitionKey = key.PartitionKey; @@ -104,7 +104,7 @@ internal sealed class UserSessionStore( } /// - public async Task DeleteUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, CT ct) + public async Task DeleteUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, Ct ct) { filter.Validate(); var query = sessionDbContext.UserSessions.Where(x => x.PartitionKey == partitionKey).AsQueryable(); @@ -152,7 +152,7 @@ internal sealed class UserSessionStore( } /// - public async Task GetUserSessionAsync(UserSessionKey key, CT ct) + public async Task GetUserSessionAsync(UserSessionKey key, Ct ct) { var userKey = key.UserKey; var partitionKey = key.PartitionKey; @@ -175,7 +175,7 @@ internal sealed class UserSessionStore( } /// - public async Task> GetUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, CT ct) + public async Task> GetUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, Ct ct) { filter.Validate(); var query = sessionDbContext.UserSessions.Where(x => x.PartitionKey == partitionKey).AsQueryable(); @@ -213,7 +213,7 @@ internal sealed class UserSessionStore( } /// - public async Task UpdateUserSessionAsync(UserSessionKey key, UserSessionUpdate session, CT ct) + public async Task UpdateUserSessionAsync(UserSessionKey key, UserSessionUpdate session, Ct ct) { var userKey = key.UserKey; var partitionKey = key.PartitionKey; @@ -235,7 +235,7 @@ internal sealed class UserSessionStore( } /// - public async Task DeleteExpiredSessionsAsync(CT ct = default) + public async Task DeleteExpiredSessionsAsync(Ct ct = default) { var removed = 0; diff --git a/bff/src/Bff.Yarp/GlobalAliasses.cs b/bff/src/Bff.Yarp/GlobalAliases.cs similarity index 100% rename from bff/src/Bff.Yarp/GlobalAliasses.cs rename to bff/src/Bff.Yarp/GlobalAliases.cs diff --git a/bff/src/Bff.Yarp/Internal/RemoteRouteHandler.cs b/bff/src/Bff.Yarp/Internal/RemoteRouteHandler.cs index 492ccd4c1..d8f6ab937 100644 --- a/bff/src/Bff.Yarp/Internal/RemoteRouteHandler.cs +++ b/bff/src/Bff.Yarp/Internal/RemoteRouteHandler.cs @@ -68,7 +68,7 @@ internal class RemoteRouteHandler : IDisposable public void ClearTransformerCacheFor(BffFrontend frontend) => _cache.TryRemove(frontend.Name, out _); - public async Task HandleAsync(HttpContext context, CT ct) + public async Task HandleAsync(HttpContext context, Ct ct) { if (!_currentFrontendAccessor.TryGet(out var frontend)) { diff --git a/bff/src/Bff/AccessTokenManagement/IAccessTokenRetriever.cs b/bff/src/Bff/AccessTokenManagement/IAccessTokenRetriever.cs index 9127a0d56..f70128fea 100644 --- a/bff/src/Bff/AccessTokenManagement/IAccessTokenRetriever.cs +++ b/bff/src/Bff/AccessTokenManagement/IAccessTokenRetriever.cs @@ -15,5 +15,5 @@ public interface IAccessTokenRetriever /// A task that contains the access token result, which is an /// object model that can represent various types of tokens (bearer, dpop), /// the absence of an optional token, or an error. - public Task GetAccessTokenAsync(AccessTokenRetrievalContext context, CT ct = default); + public Task GetAccessTokenAsync(AccessTokenRetrievalContext context, Ct ct = default); } diff --git a/bff/src/Bff/Diagnostics/DiagnosticDataService.cs b/bff/src/Bff/Diagnostics/DiagnosticDataService.cs index bb804ac37..e67237821 100644 --- a/bff/src/Bff/Diagnostics/DiagnosticDataService.cs +++ b/bff/src/Bff/Diagnostics/DiagnosticDataService.cs @@ -8,7 +8,7 @@ namespace Duende.Bff.Diagnostics; internal class DiagnosticDataService(DateTime serverStartTime, IEnumerable entries) { - public async Task> GetJsonBytesAsync(CT ct = default) + public async Task> GetJsonBytesAsync(Ct ct = default) { var bufferWriter = new ArrayBufferWriter(); await using var writer = new Utf8JsonWriter(bufferWriter, new JsonWriterOptions { Indented = false }); diff --git a/bff/src/Bff/Diagnostics/DiagnosticHostedService.cs b/bff/src/Bff/Diagnostics/DiagnosticHostedService.cs index f6fa0775d..d2be6eb35 100644 --- a/bff/src/Bff/Diagnostics/DiagnosticHostedService.cs +++ b/bff/src/Bff/Diagnostics/DiagnosticHostedService.cs @@ -14,7 +14,7 @@ internal class DiagnosticHostedService( ILogger logger, TimeProvider timeProvider) : BackgroundService { - protected override async Task ExecuteAsync(CT stoppingToken) + protected override async Task ExecuteAsync(Ct stoppingToken) { using var timer = new PeriodicTimer(options.Value.Diagnostics.LogFrequency, timeProvider); try @@ -40,7 +40,7 @@ internal class DiagnosticHostedService( } } - public override async Task StopAsync(CT ct) + public override async Task StopAsync(Ct ct) { await diagnosticsSummary.PrintSummaryAsync(ct); diff --git a/bff/src/Bff/Diagnostics/DiagnosticSummary.cs b/bff/src/Bff/Diagnostics/DiagnosticSummary.cs index a93dce9bb..a320f0d56 100644 --- a/bff/src/Bff/Diagnostics/DiagnosticSummary.cs +++ b/bff/src/Bff/Diagnostics/DiagnosticSummary.cs @@ -15,7 +15,7 @@ internal class DiagnosticSummary( { private readonly ILogger _logger = loggerFactory.CreateLogger("Duende.BFF.Diagnostics.Summary"); - public async Task PrintSummaryAsync(CT ct = default) + public async Task PrintSummaryAsync(Ct ct = default) { var bffOptions = options.Value; var jsonMemory = await diagnosticDataService.GetJsonBytesAsync(ct); diff --git a/bff/src/Bff/DynamicFrontends/IIndexHtmlTransformer.cs b/bff/src/Bff/DynamicFrontends/IIndexHtmlTransformer.cs index bae1cb126..67ab4fd12 100644 --- a/bff/src/Bff/DynamicFrontends/IIndexHtmlTransformer.cs +++ b/bff/src/Bff/DynamicFrontends/IIndexHtmlTransformer.cs @@ -10,5 +10,5 @@ namespace Duende.Bff.DynamicFrontends; /// public interface IIndexHtmlTransformer { - Task Transform(string indexHtml, BffFrontend frontend, CT ct = default); + Task Transform(string indexHtml, BffFrontend frontend, Ct ct = default); } diff --git a/bff/src/Bff/DynamicFrontends/IStaticFilesClient.cs b/bff/src/Bff/DynamicFrontends/IStaticFilesClient.cs index 3a4dedc36..d9b1bb102 100644 --- a/bff/src/Bff/DynamicFrontends/IStaticFilesClient.cs +++ b/bff/src/Bff/DynamicFrontends/IStaticFilesClient.cs @@ -20,7 +20,7 @@ public interface IStaticFilesClient /// /// CancellationToken /// Index HTML - Task GetIndexHtmlAsync(CT ct = default); + Task GetIndexHtmlAsync(Ct ct = default); /// /// This method proxies all static asset requests to the configured CDN URL for the current frontend. @@ -34,5 +34,5 @@ public interface IStaticFilesClient /// HttpContext /// CancellationToken /// - Task ProxyStaticAssetsAsync(HttpContext context, CT ct = default); + Task ProxyStaticAssetsAsync(HttpContext context, Ct ct = default); } diff --git a/bff/src/Bff/DynamicFrontends/Internal/BffCacheClearingHostedService.cs b/bff/src/Bff/DynamicFrontends/Internal/BffCacheClearingHostedService.cs index a6e4d3cc1..bac8ecae1 100644 --- a/bff/src/Bff/DynamicFrontends/Internal/BffCacheClearingHostedService.cs +++ b/bff/src/Bff/DynamicFrontends/Internal/BffCacheClearingHostedService.cs @@ -30,7 +30,7 @@ internal class BffCacheClearingHostedService( private ChannelWriter Writer => _channel.Writer; private ChannelReader Reader => _channel.Reader; - protected override async Task ExecuteAsync(CT ct) + protected override async Task ExecuteAsync(Ct ct) { // Subscribe to frontend changes and publish messages to the channel frontendCollection.OnFrontendChanged += changedFrontend => @@ -55,7 +55,7 @@ internal class BffCacheClearingHostedService( await ProcessFrontendChangesAsync(ct); } - private async Task ProcessFrontendChangesAsync(CT ct) + private async Task ProcessFrontendChangesAsync(Ct ct) { try { @@ -77,7 +77,7 @@ internal class BffCacheClearingHostedService( } } - private async Task ProcessFrontendChangeAsync(BffFrontend changedFrontend, CT ct) + private async Task ProcessFrontendChangeAsync(BffFrontend changedFrontend, Ct ct) { try { diff --git a/bff/src/Bff/DynamicFrontends/Internal/StaticFilesHttpClient.cs b/bff/src/Bff/DynamicFrontends/Internal/StaticFilesHttpClient.cs index 79f5b6c5f..0f27230c2 100644 --- a/bff/src/Bff/DynamicFrontends/Internal/StaticFilesHttpClient.cs +++ b/bff/src/Bff/DynamicFrontends/Internal/StaticFilesHttpClient.cs @@ -23,7 +23,7 @@ internal class StaticFilesHttpClient( { private readonly CancellationTokenSource _stopping = new(); - public async Task GetIndexHtmlAsync(CT ct = default) + public async Task GetIndexHtmlAsync(Ct ct = default) { var frontend = currentFrontendAccessor.Get(); @@ -67,7 +67,7 @@ internal class StaticFilesHttpClient( } } - public async Task ProxyStaticAssetsAsync(HttpContext context, CT ct = default) + public async Task ProxyStaticAssetsAsync(HttpContext context, Ct ct = default) { var frontend = currentFrontendAccessor.Get(); diff --git a/bff/src/Bff/Endpoints/IBffEndpoint.cs b/bff/src/Bff/Endpoints/IBffEndpoint.cs index 5a0cdf4b2..4b42bfaa8 100644 --- a/bff/src/Bff/Endpoints/IBffEndpoint.cs +++ b/bff/src/Bff/Endpoints/IBffEndpoint.cs @@ -14,5 +14,5 @@ public interface IBffEndpoint /// Process a request /// /// - Task ProcessRequestAsync(HttpContext context, CT ct = default); + Task ProcessRequestAsync(HttpContext context, Ct ct = default); } diff --git a/bff/src/Bff/Endpoints/IUserEndpointClaimsEnricher.cs b/bff/src/Bff/Endpoints/IUserEndpointClaimsEnricher.cs index 8c5681980..7f81dc4e7 100644 --- a/bff/src/Bff/Endpoints/IUserEndpointClaimsEnricher.cs +++ b/bff/src/Bff/Endpoints/IUserEndpointClaimsEnricher.cs @@ -26,5 +26,5 @@ public interface IUserEndpointClaimsEnricher /// The current set of claims to be returned. /// Cancellation token /// The updated list of claims. - Task> EnrichClaimsAsync(AuthenticateResult authenticateResult, IReadOnlyList claims, CT ct = default); + Task> EnrichClaimsAsync(AuthenticateResult authenticateResult, IReadOnlyList claims, Ct ct = default); } diff --git a/bff/src/Bff/Endpoints/Internal/DefaultBackchannelLogoutEndpoint.cs b/bff/src/Bff/Endpoints/Internal/DefaultBackchannelLogoutEndpoint.cs index 56447292b..f53a7441a 100644 --- a/bff/src/Bff/Endpoints/Internal/DefaultBackchannelLogoutEndpoint.cs +++ b/bff/src/Bff/Endpoints/Internal/DefaultBackchannelLogoutEndpoint.cs @@ -27,7 +27,7 @@ internal class DefaultBackchannelLogoutEndpoint( ILogger logger) : IBackchannelLogoutEndpoint { /// - public async Task ProcessRequestAsync(HttpContext context, CT ct = default) + public async Task ProcessRequestAsync(HttpContext context, Ct ct = default) { logger.ProcessingBackChannelLogoutRequest(LogLevel.Debug); @@ -167,7 +167,7 @@ internal class DefaultBackchannelLogoutEndpoint( var config = options.Configuration; if (config == null) { - config = await options.ConfigurationManager?.GetConfigurationAsync(CT.None)!; + config = await options.ConfigurationManager?.GetConfigurationAsync(Ct.None)!; } if (config == null) diff --git a/bff/src/Bff/Endpoints/Internal/DefaultDiagnosticsEndpoint.cs b/bff/src/Bff/Endpoints/Internal/DefaultDiagnosticsEndpoint.cs index 04c8e7402..513a78b07 100644 --- a/bff/src/Bff/Endpoints/Internal/DefaultDiagnosticsEndpoint.cs +++ b/bff/src/Bff/Endpoints/Internal/DefaultDiagnosticsEndpoint.cs @@ -24,7 +24,7 @@ internal class DefaultDiagnosticsEndpoint(IWebHostEnvironment environment, IOpti }; /// - public async Task ProcessRequestAsync(HttpContext context, CT ct = default) + public async Task ProcessRequestAsync(HttpContext context, Ct ct = default) { if (options.Value.DiagnosticsEnvironments?.Contains(environment.EnvironmentName) is null or false) { diff --git a/bff/src/Bff/Endpoints/Internal/DefaultLoginEndpoint.cs b/bff/src/Bff/Endpoints/Internal/DefaultLoginEndpoint.cs index 07b6794b5..3d5b5d5db 100644 --- a/bff/src/Bff/Endpoints/Internal/DefaultLoginEndpoint.cs +++ b/bff/src/Bff/Endpoints/Internal/DefaultLoginEndpoint.cs @@ -27,7 +27,7 @@ internal class DefaultLoginEndpoint( : ILoginEndpoint { /// - public async Task ProcessRequestAsync(HttpContext context, CT ct = default) + public async Task ProcessRequestAsync(HttpContext context, Ct ct = default) { logger.ProcessingLoginRequest(LogLevel.Debug); @@ -85,7 +85,7 @@ internal class DefaultLoginEndpoint( await context.ChallengeAsync(props); } - private async Task?> GetPromptValuesAsync(CT ct = default) + private async Task?> GetPromptValuesAsync(Ct ct = default) { Scheme scheme; diff --git a/bff/src/Bff/Endpoints/Internal/DefaultLogoutEndpoint.cs b/bff/src/Bff/Endpoints/Internal/DefaultLogoutEndpoint.cs index 05a2496af..2991909a4 100644 --- a/bff/src/Bff/Endpoints/Internal/DefaultLogoutEndpoint.cs +++ b/bff/src/Bff/Endpoints/Internal/DefaultLogoutEndpoint.cs @@ -22,7 +22,7 @@ internal class DefaultLogoutEndpoint(IOptions options, : ILogoutEndpoint { /// - public async Task ProcessRequestAsync(HttpContext context, CT ct = default) + public async Task ProcessRequestAsync(HttpContext context, Ct ct = default) { logger.ProcessingLogoutRequest(LogLevel.Debug); diff --git a/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginCallbackEndpoint.cs b/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginCallbackEndpoint.cs index c9cee60d6..9779d72ff 100644 --- a/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginCallbackEndpoint.cs +++ b/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginCallbackEndpoint.cs @@ -21,7 +21,7 @@ internal class DefaultSilentLoginCallbackEndpoint( { /// - public async Task ProcessRequestAsync(HttpContext context, CT ct = default) + public async Task ProcessRequestAsync(HttpContext context, Ct ct = default) { logger.ProcessingSilentLoginCallbackRequest(LogLevel.Debug); diff --git a/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginEndpoint.cs b/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginEndpoint.cs index e231b690d..57b44a75a 100644 --- a/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginEndpoint.cs +++ b/bff/src/Bff/Endpoints/Internal/DefaultSilentLoginEndpoint.cs @@ -23,7 +23,7 @@ internal class DefaultSilentLoginEndpoint(IOptions options, ILogger< private readonly BffOptions _options = options.Value; /// - public async Task ProcessRequestAsync(HttpContext context, CT ct = default) + public async Task ProcessRequestAsync(HttpContext context, Ct ct = default) { logger.ProcessingSilentLoginRequest(LogLevel.Debug); diff --git a/bff/src/Bff/Endpoints/Internal/DefaultUserEndpoint.cs b/bff/src/Bff/Endpoints/Internal/DefaultUserEndpoint.cs index 27c934bbf..3f8387995 100644 --- a/bff/src/Bff/Endpoints/Internal/DefaultUserEndpoint.cs +++ b/bff/src/Bff/Endpoints/Internal/DefaultUserEndpoint.cs @@ -26,7 +26,7 @@ internal class DefaultUserEndpoint(IOptions options, ILogger - public async Task ProcessRequestAsync(HttpContext context, CT ct = default) + public async Task ProcessRequestAsync(HttpContext context, Ct ct = default) { logger.ProcessingUserRequest(LogLevel.Debug); @@ -76,7 +76,7 @@ internal class DefaultUserEndpoint(IOptions options, ILogger /// - private static Task> GetUserClaimsAsync(AuthenticateResult authenticateResult, CT ct = default) => + private static Task> GetUserClaimsAsync(AuthenticateResult authenticateResult, Ct ct = default) => Task.FromResult(authenticateResult.Principal?.Claims.Select(x => new ClaimRecord(x.Type, x.Value)) ?? Enumerable.Empty()); /// @@ -86,7 +86,7 @@ internal class DefaultUserEndpoint(IOptions options, ILogger> GetManagementClaimsAsync( HttpContext context, AuthenticateResult authenticateResult, - CT ct = default) + Ct ct = default) { var claims = new List(); diff --git a/bff/src/Bff/HttpContextExtensions.cs b/bff/src/Bff/HttpContextExtensions.cs index f2254abac..f995a975c 100644 --- a/bff/src/Bff/HttpContextExtensions.cs +++ b/bff/src/Bff/HttpContextExtensions.cs @@ -51,7 +51,7 @@ internal static class HttpContextExtensions this HttpContext context, RequiredTokenType requiredTokenType, BffUserAccessTokenParameters? userAccessTokenParameters = null, - CT ct = default) + Ct ct = default) { if (requiredTokenType == RequiredTokenType.None) { diff --git a/bff/src/Bff/Internal/DefaultAccessTokenRetriever.cs b/bff/src/Bff/Internal/DefaultAccessTokenRetriever.cs index 8da2852b5..db4c900d3 100644 --- a/bff/src/Bff/Internal/DefaultAccessTokenRetriever.cs +++ b/bff/src/Bff/Internal/DefaultAccessTokenRetriever.cs @@ -12,7 +12,7 @@ namespace Duende.Bff.Internal; internal class DefaultAccessTokenRetriever() : IAccessTokenRetriever { /// - public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, CT ct = default) + public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, Ct ct = default) { if (context.Metadata.TokenType.HasValue) { diff --git a/bff/src/Bff/SessionManagement/Revocation/ISessionRevocationService.cs b/bff/src/Bff/SessionManagement/Revocation/ISessionRevocationService.cs index d8506663c..2c9a4b917 100644 --- a/bff/src/Bff/SessionManagement/Revocation/ISessionRevocationService.cs +++ b/bff/src/Bff/SessionManagement/Revocation/ISessionRevocationService.cs @@ -17,5 +17,5 @@ public interface ISessionRevocationService /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task RevokeSessionsAsync(UserSessionsFilter filter, CT ct = default); + Task RevokeSessionsAsync(UserSessionsFilter filter, Ct ct = default); } diff --git a/bff/src/Bff/SessionManagement/Revocation/NopSessionRevocationService.cs b/bff/src/Bff/SessionManagement/Revocation/NopSessionRevocationService.cs index 87a632758..53d5d094c 100644 --- a/bff/src/Bff/SessionManagement/Revocation/NopSessionRevocationService.cs +++ b/bff/src/Bff/SessionManagement/Revocation/NopSessionRevocationService.cs @@ -13,7 +13,7 @@ namespace Duende.Bff.SessionManagement.Revocation; internal class NopSessionRevocationService(ILogger logger) : ISessionRevocationService { /// - public Task RevokeSessionsAsync(UserSessionsFilter filter, CT ct = default) + public Task RevokeSessionsAsync(UserSessionsFilter filter, Ct ct = default) { logger.NopSessionRevocation(LogLevel.Debug, filter.SubjectId, filter.SessionId); return Task.CompletedTask; diff --git a/bff/src/Bff/SessionManagement/Revocation/SessionRevocationService.cs b/bff/src/Bff/SessionManagement/Revocation/SessionRevocationService.cs index 2ba398864..ddca3b7e3 100644 --- a/bff/src/Bff/SessionManagement/Revocation/SessionRevocationService.cs +++ b/bff/src/Bff/SessionManagement/Revocation/SessionRevocationService.cs @@ -27,7 +27,7 @@ internal class SessionRevocationService( private readonly BffOptions _options = options.Value; /// - public async Task RevokeSessionsAsync(UserSessionsFilter filter, CT ct = default) + public async Task RevokeSessionsAsync(UserSessionsFilter filter, Ct ct = default) { if (_options.BackchannelLogoutAllUserSessions) { diff --git a/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStore.cs b/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStore.cs index 115f5806e..5436894d8 100644 --- a/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStore.cs +++ b/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStore.cs @@ -15,7 +15,7 @@ public interface IUserSessionStore /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task GetUserSessionAsync(UserSessionKey key, CT ct = default); + Task GetUserSessionAsync(UserSessionKey key, Ct ct = default); /// /// Creates a user session @@ -23,7 +23,7 @@ public interface IUserSessionStore /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task CreateUserSessionAsync(UserSession session, CT ct = default); + Task CreateUserSessionAsync(UserSession session, Ct ct = default); /// /// Updates a user session @@ -32,7 +32,7 @@ public interface IUserSessionStore /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task UpdateUserSessionAsync(UserSessionKey key, UserSessionUpdate session, CT ct = default); + Task UpdateUserSessionAsync(UserSessionKey key, UserSessionUpdate session, Ct ct = default); /// /// Deletes a user session @@ -40,7 +40,7 @@ public interface IUserSessionStore /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task DeleteUserSessionAsync(UserSessionKey key, CT ct = default); + Task DeleteUserSessionAsync(UserSessionKey key, Ct ct = default); /// /// Queries user sessions based on the filter. @@ -49,7 +49,7 @@ public interface IUserSessionStore /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task> GetUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, CT ct = default); + Task> GetUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, Ct ct = default); /// /// Deletes user sessions based on the filter. @@ -58,5 +58,5 @@ public interface IUserSessionStore /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task DeleteUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, CT ct = default); + Task DeleteUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, Ct ct = default); } diff --git a/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStoreCleanup.cs b/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStoreCleanup.cs index 1a3968292..c802f8436 100644 --- a/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStoreCleanup.cs +++ b/bff/src/Bff/SessionManagement/SessionStore/IUserSessionStoreCleanup.cs @@ -12,5 +12,5 @@ public interface IUserSessionStoreCleanup /// /// Deletes expired sessions /// - Task DeleteExpiredSessionsAsync(CT ct = default); + Task DeleteExpiredSessionsAsync(Ct ct = default); } diff --git a/bff/src/Bff/SessionManagement/SessionStore/InMemoryUserSessionStore.cs b/bff/src/Bff/SessionManagement/SessionStore/InMemoryUserSessionStore.cs index 995f95ac0..f02d0f91b 100644 --- a/bff/src/Bff/SessionManagement/SessionStore/InMemoryUserSessionStore.cs +++ b/bff/src/Bff/SessionManagement/SessionStore/InMemoryUserSessionStore.cs @@ -19,7 +19,7 @@ internal class InMemoryUserSessionStore( // A dictionary of dictionaries, where the outer dictionary is keyed by partition key private readonly ConcurrentDictionary _store = new(); - public Task CreateUserSessionAsync(UserSession session, CT ct = default) + public Task CreateUserSessionAsync(UserSession session, Ct ct = default) { if (!session.PartitionKey.HasValue) { @@ -47,7 +47,7 @@ internal class InMemoryUserSessionStore( return partition; } - public Task GetUserSessionAsync(UserSessionKey key, CT ct = default) + public Task GetUserSessionAsync(UserSessionKey key, Ct ct = default) { var partition = GetPartition(key.PartitionKey); partition.TryGetValue(key.UserKey, out var item); @@ -55,7 +55,7 @@ internal class InMemoryUserSessionStore( return Task.FromResult(item?.Clone()); } - public Task UpdateUserSessionAsync(UserSessionKey key, UserSessionUpdate session, CT ct = default) + public Task UpdateUserSessionAsync(UserSessionKey key, UserSessionUpdate session, Ct ct = default) { var partition = GetPartition(key.PartitionKey); if (!partition.TryGetValue(key.UserKey, out var existing)) @@ -70,14 +70,14 @@ internal class InMemoryUserSessionStore( return Task.CompletedTask; } - public Task DeleteUserSessionAsync(UserSessionKey key, CT ct = default) + public Task DeleteUserSessionAsync(UserSessionKey key, Ct ct = default) { var partition = GetPartition(key.PartitionKey); partition.TryRemove(key.UserKey, out _); return Task.CompletedTask; } - public Task> GetUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, CT ct = default) + public Task> GetUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, Ct ct = default) { filter.Validate(); var partition = GetPartition(partitionKey); @@ -97,7 +97,7 @@ internal class InMemoryUserSessionStore( return Task.FromResult((IReadOnlyCollection)results); } - public Task DeleteUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, CT ct = default) + public Task DeleteUserSessionsAsync(PartitionKey partitionKey, UserSessionsFilter filter, Ct ct = default) { filter.Validate(); var partition = GetPartition(partitionKey); diff --git a/bff/src/Bff/SessionManagement/SessionStore/SessionCleanupHost.cs b/bff/src/Bff/SessionManagement/SessionStore/SessionCleanupHost.cs index ff113b321..abacbd09c 100644 --- a/bff/src/Bff/SessionManagement/SessionStore/SessionCleanupHost.cs +++ b/bff/src/Bff/SessionManagement/SessionStore/SessionCleanupHost.cs @@ -23,7 +23,7 @@ internal class SessionCleanupHost( private TimeSpan CleanupInterval => _options.SessionCleanupInterval; - public override Task StartAsync(CT ct) + public override Task StartAsync(Ct ct) { if (!IsIUserSessionStoreCleanupRegistered()) { @@ -34,7 +34,7 @@ internal class SessionCleanupHost( return base.StartAsync(ct); } - protected override async Task ExecuteAsync(CT ct) + protected override async Task ExecuteAsync(Ct ct) { while (true) { @@ -70,7 +70,7 @@ internal class SessionCleanupHost( } } - internal async Task RunAsync(CT ct = default) + internal async Task RunAsync(Ct ct = default) { try { diff --git a/bff/src/Bff/SessionManagement/TicketStore/IServerTicketStore.cs b/bff/src/Bff/SessionManagement/TicketStore/IServerTicketStore.cs index ee4e1e3c3..a1dc53f1d 100644 --- a/bff/src/Bff/SessionManagement/TicketStore/IServerTicketStore.cs +++ b/bff/src/Bff/SessionManagement/TicketStore/IServerTicketStore.cs @@ -18,5 +18,5 @@ public interface IServerTicketStore : ITicketStore /// /// A token that can be used to request cancellation of the asynchronous operation. /// - Task> GetUserTicketsAsync(UserSessionsFilter filter, CT ct = default); + Task> GetUserTicketsAsync(UserSessionsFilter filter, Ct ct = default); } diff --git a/bff/src/Bff/SessionManagement/TicketStore/ServerSideTicketStore.cs b/bff/src/Bff/SessionManagement/TicketStore/ServerSideTicketStore.cs index 51435b27a..e49fa97ca 100644 --- a/bff/src/Bff/SessionManagement/TicketStore/ServerSideTicketStore.cs +++ b/bff/src/Bff/SessionManagement/TicketStore/ServerSideTicketStore.cs @@ -31,7 +31,7 @@ internal class ServerSideTicketStore( private readonly IDataProtector _protector = dataProtectionProvider.CreateProtector(DataProtectorPurpose); - private CT ct => accessor.HttpContext?.RequestAborted ?? CT.None; + private Ct _ct => accessor.HttpContext?.RequestAborted ?? Ct.None; /// public async Task StoreAsync(AuthenticationTicket ticket) @@ -43,7 +43,7 @@ internal class ServerSideTicketStore( { SubjectId = ticket.GetSubjectId(), SessionId = ticket.GetSessionId() - }, ct); + }, _ct); var key = CryptoRandom.CreateUniqueId(format: CryptoRandom.OutputFormat.Hex); @@ -68,7 +68,7 @@ internal class ServerSideTicketStore( Ticket = ticket.Serialize(_protector) }; - await store.CreateUserSessionAsync(session, ct); + await store.CreateUserSessionAsync(session, _ct); metrics.SessionStarted(); } @@ -78,7 +78,7 @@ internal class ServerSideTicketStore( logger.RetrieveAuthenticationTicket(LogLevel.Debug, key); var userSessionKey = BuildUserSessionKey(key); - var session = await store.GetUserSessionAsync(userSessionKey, ct); + var session = await store.GetUserSessionAsync(userSessionKey, _ct); if (session == null) { logger.NoAuthenticationTicketFoundForKey(LogLevel.Debug, key); @@ -111,7 +111,7 @@ internal class ServerSideTicketStore( public async Task RenewAsync(string key, AuthenticationTicket ticket) { var userSessionKey = BuildUserSessionKey(key); - var session = await store.GetUserSessionAsync(userSessionKey, ct); + var session = await store.GetUserSessionAsync(userSessionKey, _ct); if (session == null) { // https://github.com/dotnet/aspnetcore/issues/41516#issuecomment-1178076544 @@ -134,7 +134,7 @@ internal class ServerSideTicketStore( Renewed = ticket.GetIssued(timeProvider.GetUtcNow()), Expires = ticket.GetExpiration(), Ticket = ticket.Serialize(_protector) - }, ct); + }, _ct); } /// @@ -150,11 +150,11 @@ internal class ServerSideTicketStore( logger.RemovingAuthenticationTicket(LogLevel.Debug, userSessionKey.ToString()); metrics.SessionEnded(); - return store.DeleteUserSessionAsync(userSessionKey, ct); + return store.DeleteUserSessionAsync(userSessionKey, _ct); } /// - public async Task> GetUserTicketsAsync(UserSessionsFilter filter, CT ct) + public async Task> GetUserTicketsAsync(UserSessionsFilter filter, Ct ct) { logger.GettingAuthenticationTickets(LogLevel.Debug, filter.SubjectId, filter.SessionId); diff --git a/bff/test/Bff.Tests/BffFrontendIndexTests.cs b/bff/test/Bff.Tests/BffFrontendIndexTests.cs index 63b122525..b90097a52 100644 --- a/bff/test/Bff.Tests/BffFrontendIndexTests.cs +++ b/bff/test/Bff.Tests/BffFrontendIndexTests.cs @@ -171,7 +171,7 @@ public class BffFrontendIndexTests : BffTestBase { private int count = 1; - public Task Transform(string html, BffFrontend frontend, CT ct = default) => Task.FromResult($"{html} - transformed {count++}"); + public Task Transform(string html, BffFrontend frontend, Ct ct = default) => Task.FromResult($"{html} - transformed {count++}"); } [Fact] diff --git a/bff/test/Bff.Tests/BffFrontendSigninTests.cs b/bff/test/Bff.Tests/BffFrontendSigninTests.cs index 918be7852..50c99a202 100644 --- a/bff/test/Bff.Tests/BffFrontendSigninTests.cs +++ b/bff/test/Bff.Tests/BffFrontendSigninTests.cs @@ -60,7 +60,7 @@ public class BffFrontendSigninTests : BffTestBase Bff.OnConfigureApp += app => { - app.MapGet(pathString, (HttpContext c, CT ct) => "ok"); + app.MapGet(pathString, (HttpContext c, Ct ct) => "ok"); }; await InitializeAsync(); diff --git a/bff/test/Bff.Tests/BffRemoteApiTests.cs b/bff/test/Bff.Tests/BffRemoteApiTests.cs index f0182ab81..d5b7ee867 100644 --- a/bff/test/Bff.Tests/BffRemoteApiTests.cs +++ b/bff/test/Bff.Tests/BffRemoteApiTests.cs @@ -143,7 +143,7 @@ public class BffRemoteApiTests : BffTestBase public bool WasCalled = false; public Task> GetAccessTokenAsync(ClaimsPrincipal user, UserTokenRequestParameters? parameters = null, - CT ct = new CT()) + Ct ct = new Ct()) { WasCalled = true; // We don't care actually about the result token. Just if it was called or not. @@ -151,7 +151,7 @@ public class BffRemoteApiTests : BffTestBase } public Task RevokeRefreshTokenAsync(ClaimsPrincipal user, UserTokenRequestParameters? parameters = null, - CT ct = new CT()) => throw new NotImplementedException(); + Ct ct = new Ct()) => throw new NotImplementedException(); } [Fact] diff --git a/bff/test/Bff.Tests/BffScenarioTests.cs b/bff/test/Bff.Tests/BffScenarioTests.cs index 1fdbb346d..c5764b9b7 100644 --- a/bff/test/Bff.Tests/BffScenarioTests.cs +++ b/bff/test/Bff.Tests/BffScenarioTests.cs @@ -47,7 +47,7 @@ public class BffScenarioTests : BffTestBase TaskCompletionSource contentReceived, TaskCompletionSource workerIsAllowedToStart) : BackgroundService { - protected override async Task ExecuteAsync(CT stoppingToken) + protected override async Task ExecuteAsync(Ct stoppingToken) { await workerIsAllowedToStart.Task; diff --git a/bff/test/Bff.Tests/BffWithoutExplicitFrontendTests.cs b/bff/test/Bff.Tests/BffWithoutExplicitFrontendTests.cs index 40f11c29b..18059beaf 100644 --- a/bff/test/Bff.Tests/BffWithoutExplicitFrontendTests.cs +++ b/bff/test/Bff.Tests/BffWithoutExplicitFrontendTests.cs @@ -11,7 +11,7 @@ public class BffWithoutExplicitFrontendTests : BffTestBase { Bff.OnConfigureApp += app => { - app.MapGet("/secret", (HttpContext c, CT ct) => + app.MapGet("/secret", (HttpContext c, Ct ct) => { if (!c.User.IsAuthenticated()) { diff --git a/bff/test/Bff.Tests/Blazor/Client/AntiforgeryHandlerTests.cs b/bff/test/Bff.Tests/Blazor/Client/AntiforgeryHandlerTests.cs index 30a7b2949..1510efc29 100644 --- a/bff/test/Bff.Tests/Blazor/Client/AntiforgeryHandlerTests.cs +++ b/bff/test/Bff.Tests/Blazor/Client/AntiforgeryHandlerTests.cs @@ -23,7 +23,7 @@ public class AntiForgeryHandlerTests var client = new HttpClient(sut); - await client.SendAsync(request, CT.None); + await client.SendAsync(request, Ct.None); request.Headers.ShouldContain(h => h.Key == "X-CSRF" && h.Value.Contains("1")); } @@ -31,5 +31,5 @@ public class AntiForgeryHandlerTests public class NoOpHttpMessageHandler : HttpMessageHandler { - protected override Task SendAsync(HttpRequestMessage request, CT ct) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); + protected override Task SendAsync(HttpRequestMessage request, Ct ct) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); } diff --git a/bff/test/Bff.Tests/Blazor/Client/FetchUserServiceTests.cs b/bff/test/Bff.Tests/Blazor/Client/FetchUserServiceTests.cs index 8b0b24987..3f31bf19d 100644 --- a/bff/test/Bff.Tests/Blazor/Client/FetchUserServiceTests.cs +++ b/bff/test/Bff.Tests/Blazor/Client/FetchUserServiceTests.cs @@ -60,7 +60,7 @@ public class MockHttpMessageHandler : HttpMessageHandler } protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { if (request.Content != null) // Could be a GET-request without a body { diff --git a/bff/test/Bff.Tests/ConventionTests.cs b/bff/test/Bff.Tests/ConventionTests.cs index 315bddc53..99488431e 100644 --- a/bff/test/Bff.Tests/ConventionTests.cs +++ b/bff/test/Bff.Tests/ConventionTests.cs @@ -211,12 +211,12 @@ public class ConventionTests failures.Add($"{type.FullName}.{method.Name}: Async method should be suffixed with 'Async'."); } - // 2. Last parameter should be a CT (if there are any parameters) + // 2. Last parameter should be a Ct (if there are any parameters) var parameters = method.GetParameters(); - if (parameters.Length == 0 || parameters.Last().ParameterType != typeof(CT)) + if (parameters.Length == 0 || parameters.Last().ParameterType != typeof(Ct)) { failures.Add( - $"{type.FullName}.{method.Name}: Async method should have a CT as the last parameter."); + $"{type.FullName}.{method.Name}: Async method should have a Ct as the last parameter."); } } } @@ -273,7 +273,7 @@ public class ConventionTests } var ctParam = parameters.Last(); - if (ctParam.ParameterType != typeof(CT)) + if (ctParam.ParameterType != typeof(Ct)) { failures.Add($"{type.FullName}.{method.Name}: Last parameter should be CancellationToken."); continue; diff --git a/bff/test/Bff.Tests/Endpoints/Management/UserEndpointTests.cs b/bff/test/Bff.Tests/Endpoints/Management/UserEndpointTests.cs index 684510229..0aa7b554f 100644 --- a/bff/test/Bff.Tests/Endpoints/Management/UserEndpointTests.cs +++ b/bff/test/Bff.Tests/Endpoints/Management/UserEndpointTests.cs @@ -33,7 +33,7 @@ public class UserEndpointTests : BffTestBase private class TestClaimsEnricher(IHttpClientFactory factory) : IUserEndpointClaimsEnricher { - public async Task> EnrichClaimsAsync(AuthenticateResult authenticateResult, IReadOnlyList claims, CT ct = default) + public async Task> EnrichClaimsAsync(AuthenticateResult authenticateResult, IReadOnlyList claims, Ct ct = default) { var client = factory.CreateClient("c1"); diff --git a/bff/test/Bff.Tests/IAccessTokenRetriever_Extensibility_tests.cs b/bff/test/Bff.Tests/IAccessTokenRetriever_Extensibility_tests.cs index cb381ed83..d351ec1c4 100644 --- a/bff/test/Bff.Tests/IAccessTokenRetriever_Extensibility_tests.cs +++ b/bff/test/Bff.Tests/IAccessTokenRetriever_Extensibility_tests.cs @@ -92,7 +92,7 @@ public class IAccessTokenRetriever_Extensibility_tests : BffTestBase { } - public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, CT ct = default) + public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, Ct ct = default) { UsedContext = context; if (context.Metadata.TokenType.HasValue) diff --git a/bff/test/Bff.Tests/SessionManagement/ServerSideTokenStoreTests.cs b/bff/test/Bff.Tests/SessionManagement/ServerSideTokenStoreTests.cs index fd3517d53..23ffff2e4 100644 --- a/bff/test/Bff.Tests/SessionManagement/ServerSideTokenStoreTests.cs +++ b/bff/test/Bff.Tests/SessionManagement/ServerSideTokenStoreTests.cs @@ -117,7 +117,7 @@ public class ServerSideTokenStoreTests public Task SetUserTokenAsync(UserToken token, AuthenticationProperties authenticationProperties, - UserTokenRequestParameters? parameters = null, CT ct = new CT()) + UserTokenRequestParameters? parameters = null, Ct ct = new Ct()) { Stored = token; return Task.CompletedTask; @@ -127,7 +127,7 @@ public class ServerSideTokenStoreTests UserTokenRequestParameters? parameters = null) => Stored = null; public Task GetSchemeAsync(UserTokenRequestParameters? parameters = null, - CT ct = new CT()) => + Ct ct = new Ct()) => Task.FromResult(Scheme.Bearer); } diff --git a/bff/test/Bff.Tests/TestFramework/FailureAccessTokenRetriever.cs b/bff/test/Bff.Tests/TestFramework/FailureAccessTokenRetriever.cs index e4db35e36..11eb626f5 100644 --- a/bff/test/Bff.Tests/TestFramework/FailureAccessTokenRetriever.cs +++ b/bff/test/Bff.Tests/TestFramework/FailureAccessTokenRetriever.cs @@ -7,7 +7,7 @@ namespace Duende.Bff.Tests.TestFramework; public class FailureAccessTokenRetriever : IAccessTokenRetriever { - public Task GetAccessTokenAsync(AccessTokenRetrievalContext context, CT ct = default) => + public Task GetAccessTokenAsync(AccessTokenRetrievalContext context, Ct ct = default) => Task.FromResult(new AccessTokenRetrievalError { Error = "no access token" diff --git a/bff/test/Bff.Tests/TestFramework/MockSessionRevocationService.cs b/bff/test/Bff.Tests/TestFramework/MockSessionRevocationService.cs index 163aa365d..441ded8bc 100644 --- a/bff/test/Bff.Tests/TestFramework/MockSessionRevocationService.cs +++ b/bff/test/Bff.Tests/TestFramework/MockSessionRevocationService.cs @@ -10,7 +10,7 @@ public class MockSessionRevocationService : ISessionRevocationService { public bool DeleteUserSessionsWasCalled { get; set; } public UserSessionsFilter? DeleteUserSessionsFilter { get; set; } - public Task RevokeSessionsAsync(UserSessionsFilter filter, CT ct) + public Task RevokeSessionsAsync(UserSessionsFilter filter, Ct ct) { DeleteUserSessionsWasCalled = true; DeleteUserSessionsFilter = filter; diff --git a/bff/test/Bff.Tests/TestFramework/TestAccessTokenRetriever.cs b/bff/test/Bff.Tests/TestFramework/TestAccessTokenRetriever.cs index 04b4e7cb4..905a57ac5 100644 --- a/bff/test/Bff.Tests/TestFramework/TestAccessTokenRetriever.cs +++ b/bff/test/Bff.Tests/TestFramework/TestAccessTokenRetriever.cs @@ -7,5 +7,5 @@ namespace Duende.Bff.Tests.TestFramework; public class TestAccessTokenRetriever(Func> accessTokenGetter) : IAccessTokenRetriever { - public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, CT ct = default) => await accessTokenGetter(); + public async Task GetAccessTokenAsync(AccessTokenRetrievalContext context, Ct ct = default) => await accessTokenGetter(); } diff --git a/bff/test/Bff.Tests/TestFramework/TestBrowserClient.cs b/bff/test/Bff.Tests/TestFramework/TestBrowserClient.cs index 115d232f5..f4398d6ad 100644 --- a/bff/test/Bff.Tests/TestFramework/TestBrowserClient.cs +++ b/bff/test/Bff.Tests/TestFramework/TestBrowserClient.cs @@ -15,7 +15,7 @@ public class TestBrowserClient : HttpClient public HttpResponseMessage? LastResponse { get; private set; } protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { CurrentUri = request.RequestUri ?? throw new NullReferenceException("RequestUri is not set"); var cookieHeader = CookieContainer.GetCookieHeader(request.RequestUri); @@ -83,7 +83,7 @@ public class TestBrowserClient : HttpClient internal async Task CallBffHostApi( string url, HttpStatusCode? expectedStatusCode = null, - CT ct = default) + Ct ct = default) { var req = new HttpRequestMessage(HttpMethod.Get, url); req.Headers.Add("x-csrf", "1"); @@ -112,7 +112,7 @@ public class TestBrowserClient : HttpClient HttpMethod method, HttpContent? content = null, HttpStatusCode? expectedStatusCode = null, - CT ct = default) + Ct ct = default) { var req = new HttpRequestMessage(method, url); if (req.Content == null) diff --git a/bff/test/Bff.Tests/TestInfra/BffHttpClient.cs b/bff/test/Bff.Tests/TestInfra/BffHttpClient.cs index 6483082d4..eaa33a0c6 100644 --- a/bff/test/Bff.Tests/TestInfra/BffHttpClient.cs +++ b/bff/test/Bff.Tests/TestInfra/BffHttpClient.cs @@ -51,7 +51,7 @@ public class BffHttpClient(RedirectHandler handler, CookieContainer cookies, Ide HttpContent? content = null, HttpStatusCode? expectedStatusCode = null, Dictionary? headers = null, - CT ct = default) => CallBffHostApi( + Ct ct = default) => CallBffHostApi( url: new Uri(path, UriKind.Relative), method: method, content: content, @@ -65,7 +65,7 @@ public class BffHttpClient(RedirectHandler handler, CookieContainer cookies, Ide HttpContent? content = null, HttpStatusCode? expectedStatusCode = null, Dictionary? headers = null, - CT ct = default) + Ct ct = default) { method ??= HttpMethod.Get; var req = new HttpRequestMessage(method, url); diff --git a/bff/test/Bff.Tests/TestInfra/CookieHandler.cs b/bff/test/Bff.Tests/TestInfra/CookieHandler.cs index 94fe8901f..391a9d4b2 100644 --- a/bff/test/Bff.Tests/TestInfra/CookieHandler.cs +++ b/bff/test/Bff.Tests/TestInfra/CookieHandler.cs @@ -9,7 +9,7 @@ namespace Duende.Bff.Tests.TestInfra; public class CookieHandler(HttpMessageHandler innerHandler, CookieContainer cookieContainer) : DelegatingHandler(innerHandler) { - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct ct) { var requestUri = request.RequestUri; var header = cookieContainer.GetCookieHeader(requestUri!); diff --git a/bff/test/Bff.Tests/TestInfra/RedirectHandler.cs b/bff/test/Bff.Tests/TestInfra/RedirectHandler.cs index feb390c3e..81207d738 100644 --- a/bff/test/Bff.Tests/TestInfra/RedirectHandler.cs +++ b/bff/test/Bff.Tests/TestInfra/RedirectHandler.cs @@ -12,7 +12,7 @@ public class RedirectHandler(WriteTestOutput output) : DelegatingHandler public bool AutoFollowRedirects { get; set; } = true; protected override async Task SendAsync(HttpRequestMessage request, - CT ct) + Ct ct) { var originalUri = request.RequestUri; diff --git a/bff/test/Bff.Tests/TestInfra/RoutingMessageHandler.cs b/bff/test/Bff.Tests/TestInfra/RoutingMessageHandler.cs index 708ba204a..9d1502f14 100644 --- a/bff/test/Bff.Tests/TestInfra/RoutingMessageHandler.cs +++ b/bff/test/Bff.Tests/TestInfra/RoutingMessageHandler.cs @@ -27,7 +27,7 @@ public class RoutingMessageHandler : HttpMessageHandler protected override Task SendAsync( HttpRequestMessage request, - CT ct) + Ct ct) { var host = $"{request.RequestUri?.Host}:{request.RequestUri?.Port}"; @@ -46,7 +46,7 @@ public class RoutingMessageHandler : HttpMessageHandler { internal Task SuppressedSend( HttpRequestMessage request, - CT ct) + Ct ct) { Task t; if (ExecutionContext.IsFlowSuppressed()) diff --git a/bff/test/Bff.Tests/TestInfra/SimulatedInternet.cs b/bff/test/Bff.Tests/TestInfra/SimulatedInternet.cs index d7aa10cdb..316ba1999 100644 --- a/bff/test/Bff.Tests/TestInfra/SimulatedInternet.cs +++ b/bff/test/Bff.Tests/TestInfra/SimulatedInternet.cs @@ -59,7 +59,7 @@ public class SimulatedInternet : DelegatingHandler protected override async Task SendAsync( HttpRequestMessage request, - CT ct) + Ct ct) { var requestId = Interlocked.Increment(ref _requestIdSeed); diff --git a/bff/test/Bff.Tests/TestInfra/TestHybridCache.cs b/bff/test/Bff.Tests/TestInfra/TestHybridCache.cs index 08a21cfbf..24ec0cd22 100644 --- a/bff/test/Bff.Tests/TestInfra/TestHybridCache.cs +++ b/bff/test/Bff.Tests/TestInfra/TestHybridCache.cs @@ -10,19 +10,19 @@ internal class TestHybridCache : HybridCache { private ConcurrentDictionary> _cache = new(); public override async ValueTask GetOrCreateAsync(string key, TState state, - Func> factory, HybridCacheEntryOptions? options = null, - IEnumerable? tags = null, CT ct = new CT()) => (T)await _cache.GetOrAdd(key, async _ => (await factory(state, ct))!); + Func> factory, HybridCacheEntryOptions? options = null, + IEnumerable? tags = null, Ct ct = new Ct()) => (T)await _cache.GetOrAdd(key, async _ => (await factory(state, ct))!); public override ValueTask SetAsync(string key, T value, HybridCacheEntryOptions? options = null, IEnumerable? tags = null, - CT ct = new CT()) + Ct ct = new Ct()) { _cache[key] = new ValueTask(value!); return ValueTask.CompletedTask; } public override ValueTask - RemoveAsync(string key, CT ct = new CT()) + RemoveAsync(string key, Ct ct = new Ct()) { _waitUntilRemoveAsyncCalled.Set(); _cache.TryRemove(key, out _); @@ -33,7 +33,7 @@ internal class TestHybridCache : HybridCache ManualResetEventSlim _waitUntilRemoveAsyncCalled = new ManualResetEventSlim(); public override ValueTask RemoveByTagAsync(string tag, - CT ct = new CT()) + Ct ct = new Ct()) { _waitUntilRemoveByTagAsyncCalled.Set(); _cache.Clear(); diff --git a/bff/test/Bff.Tests/TestInfra/TestTokenRetriever.cs b/bff/test/Bff.Tests/TestInfra/TestTokenRetriever.cs index 8a7e3eaed..458f50c79 100644 --- a/bff/test/Bff.Tests/TestInfra/TestTokenRetriever.cs +++ b/bff/test/Bff.Tests/TestInfra/TestTokenRetriever.cs @@ -11,7 +11,7 @@ public class TestTokenRetriever : IAccessTokenRetriever public AccessTokenRetrievalContext? UsedContext { get; set; } public Task GetAccessTokenAsync(AccessTokenRetrievalContext context, - CT ct = default) + Ct ct = default) { UsedContext = context; return Task.FromResult(new NoAccessTokenResult()); diff --git a/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpoint.cs b/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpoint.cs index bbabbcd0e..77e3f6cb8 100644 --- a/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpoint.cs +++ b/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpoint.cs @@ -41,7 +41,7 @@ internal sealed partial class ConformanceReportEndpoint /// /// Processes requests for the HTML conformance report. /// - public async Task GetHtmlReportAsync(HttpContext context, CT ct = default) + public async Task GetHtmlReportAsync(HttpContext context, Ct ct) { LogProcessingRequest(); @@ -53,7 +53,7 @@ internal sealed partial class ConformanceReportEndpoint try { - var report = await _assessmentService.GenerateReportAsync(ct: ct); + var report = await _assessmentService.GenerateReportAsync(ct); using var slice = Duende.ConformanceReport.Slices.ConformanceReport.Create(report); var sb = new StringBuilder(); diff --git a/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpointExtensions.cs b/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpointExtensions.cs index cc0235f50..c8d586980 100644 --- a/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpointExtensions.cs +++ b/conformance-report/src/ConformanceReport/Endpoints/ConformanceReportEndpointExtensions.cs @@ -25,7 +25,7 @@ public static class ConformanceReportEndpointExtensions var group = endpoints.MapGroup(basePath); // HTML endpoint - requires custom authorization policy - _ = group.MapGet("", async (ConformanceReportEndpoint endpoint, HttpContext context, CT ct) => + _ = group.MapGet("", async (ConformanceReportEndpoint endpoint, HttpContext context, Ct ct) => await endpoint.GetHtmlReportAsync(context, ct)) .RequireAuthorization(options.AuthorizationPolicyName) .WithName("GetConformanceHtmlReport") diff --git a/conformance-report/src/ConformanceReport/IConformanceReportClientStore.cs b/conformance-report/src/ConformanceReport/IConformanceReportClientStore.cs index da7896d14..d369010f8 100644 --- a/conformance-report/src/ConformanceReport/IConformanceReportClientStore.cs +++ b/conformance-report/src/ConformanceReport/IConformanceReportClientStore.cs @@ -5,5 +5,5 @@ namespace Duende.ConformanceReport; internal interface IConformanceReportClientStore { - Task> GetAllClientsAsync(CT ct = default); + Task> GetAllClientsAsync(Ct ct); } diff --git a/conformance-report/src/ConformanceReport/Services/ConformanceReportAssessmentService.cs b/conformance-report/src/ConformanceReport/Services/ConformanceReportAssessmentService.cs index b082eee63..dc4242ac2 100644 --- a/conformance-report/src/ConformanceReport/Services/ConformanceReportAssessmentService.cs +++ b/conformance-report/src/ConformanceReport/Services/ConformanceReportAssessmentService.cs @@ -44,7 +44,7 @@ internal class ConformanceReportAssessmentService /// /// The cancellation token. /// A conformance report containing the assessment results. - public async Task GenerateReportAsync(CT ct = default) + public async Task GenerateReportAsync(Ct ct) { var clients = await _clientStore.GetAllClientsAsync(ct); var clientList = clients.ToList(); @@ -91,7 +91,7 @@ internal class ConformanceReportAssessmentService /// A profile result containing the assessment findings. public async Task AssessProfileAsync( ConformanceReportProfile profile, - CT ct = default) + Ct ct) { var clients = await _clientStore.GetAllClientsAsync(ct); var clientList = clients.ToList(); diff --git a/conformance-report/test/ConformanceReport.Tests/Endpoints/ConformanceEndpointTests.cs b/conformance-report/test/ConformanceReport.Tests/Endpoints/ConformanceEndpointTests.cs index 1b6aaf762..50c8363c9 100644 --- a/conformance-report/test/ConformanceReport.Tests/Endpoints/ConformanceEndpointTests.cs +++ b/conformance-report/test/ConformanceReport.Tests/Endpoints/ConformanceEndpointTests.cs @@ -99,7 +99,7 @@ public class ConformanceReportEndpointTests private sealed class InMemoryClientStore(IEnumerable clients) : IConformanceReportClientStore { - public Task> GetAllClientsAsync(CancellationToken ct = default) + public Task> GetAllClientsAsync(CancellationToken ct) => Task.FromResult(clients); } @@ -124,13 +124,14 @@ public class ConformanceReportEndpointTests public class HtmlEndpointTests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; [Fact] public async Task GetHtmlReportWhenEnabledReturnsHtmlContent() { var endpoint = CreateEndpoint(); var context = CreateHttpContext(); - var result = await endpoint.GetHtmlReportAsync(context); + var result = await endpoint.GetHtmlReportAsync(context, _ct); _ = result.ShouldNotBeNull(); _ = result.ShouldBeOfType(); @@ -145,7 +146,7 @@ public class ConformanceReportEndpointTests var endpoint = CreateEndpoint(options: options); var context = CreateHttpContext(); - var result = await endpoint.GetHtmlReportAsync(context); + var result = await endpoint.GetHtmlReportAsync(context, _ct); _ = result.ShouldBeOfType(); } @@ -163,7 +164,7 @@ public class ConformanceReportEndpointTests var endpoint = CreateEndpoint(licenseInfo: licenseInfo); var context = CreateHttpContext(); - var result = await endpoint.GetHtmlReportAsync(context); + var result = await endpoint.GetHtmlReportAsync(context, _ct); var contentResult = (Microsoft.AspNetCore.Http.HttpResults.ContentHttpResult)result; var html = contentResult.ResponseContent!; diff --git a/conformance-report/test/ConformanceReport.Tests/Services/ConformanceAssessmentServiceTests.cs b/conformance-report/test/ConformanceReport.Tests/Services/ConformanceAssessmentServiceTests.cs index be744dd56..f0e34198d 100644 --- a/conformance-report/test/ConformanceReport.Tests/Services/ConformanceAssessmentServiceTests.cs +++ b/conformance-report/test/ConformanceReport.Tests/Services/ConformanceAssessmentServiceTests.cs @@ -104,7 +104,7 @@ public class ConformanceAssessmentServiceTests private sealed class InMemoryClientStore(IEnumerable clients) : IConformanceReportClientStore { - public Task> GetAllClientsAsync(CancellationToken ct = default) => Task.FromResult(clients); + public Task> GetAllClientsAsync(CancellationToken ct) => Task.FromResult(clients); } private sealed class TestHttpContextAccessor : IHttpContextAccessor @@ -123,12 +123,13 @@ public class ConformanceAssessmentServiceTests public class ReportGenerationTests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; [Fact] public async Task GenerateReportWithBothProfilesEnabledReturnsCompleteReport() { var service = CreateService(); - var report = await service.GenerateReportAsync(); + var report = await service.GenerateReportAsync(_ct); _ = report.ShouldNotBeNull(); _ = report.Profiles.ShouldNotBeNull(); @@ -142,7 +143,7 @@ public class ConformanceAssessmentServiceTests var options = CreateDefaultOptions(enableOAuth21: true, enableFapi2: false); var service = CreateService(options: options); - var report = await service.GenerateReportAsync(); + var report = await service.GenerateReportAsync(_ct); _ = report.Profiles.OAuth21.ShouldNotBeNull(); report.Profiles.Fapi2Security.ShouldBeNull(); @@ -154,7 +155,7 @@ public class ConformanceAssessmentServiceTests var options = CreateDefaultOptions(enableOAuth21: false, enableFapi2: true); var service = CreateService(options: options); - var report = await service.GenerateReportAsync(); + var report = await service.GenerateReportAsync(_ct); report.Profiles.OAuth21.ShouldBeNull(); _ = report.Profiles.Fapi2Security.ShouldNotBeNull(); @@ -166,7 +167,7 @@ public class ConformanceAssessmentServiceTests var service = CreateService(); var beforeTime = DateTimeOffset.UtcNow; - var report = await service.GenerateReportAsync(); + var report = await service.GenerateReportAsync(_ct); var afterTime = DateTimeOffset.UtcNow; report.AssessedAt.ShouldBeGreaterThanOrEqualTo(beforeTime); @@ -184,7 +185,7 @@ public class ConformanceAssessmentServiceTests }; var service = CreateService(clients: clients); - var report = await service.GenerateReportAsync(); + var report = await service.GenerateReportAsync(_ct); // Overall summary report.OverallSummary.TotalClients.ShouldBe(3); diff --git a/hosts_and_clients.props b/hosts_and_clients.props index 65eaec4fc..12ee61826 100644 --- a/hosts_and_clients.props +++ b/hosts_and_clients.props @@ -21,7 +21,7 @@ true - + diff --git a/identity-server/clients/src/ConsoleCode/SystemBrowser.cs b/identity-server/clients/src/ConsoleCode/SystemBrowser.cs index 3e041c3b2..f636ccbf7 100644 --- a/identity-server/clients/src/ConsoleCode/SystemBrowser.cs +++ b/identity-server/clients/src/ConsoleCode/SystemBrowser.cs @@ -45,7 +45,7 @@ public class SystemBrowser : IBrowser return port; } - public async Task InvokeAsync(BrowserOptions options, CT ct = default) + public async Task InvokeAsync(BrowserOptions options, Ct ct = default) { using (var listener = new LoopbackHttpListener(Port, _path)) { diff --git a/identity-server/clients/src/ConsoleResourceIndicators/SystemBrowser.cs b/identity-server/clients/src/ConsoleResourceIndicators/SystemBrowser.cs index 1effbbfc4..32c0af430 100644 --- a/identity-server/clients/src/ConsoleResourceIndicators/SystemBrowser.cs +++ b/identity-server/clients/src/ConsoleResourceIndicators/SystemBrowser.cs @@ -37,7 +37,7 @@ public class SystemBrowser : IBrowser return port; } - public async Task InvokeAsync(BrowserOptions options, CT ct = default) + public async Task InvokeAsync(BrowserOptions options, Ct ct = default) { using (var listener = new LoopbackHttpListener(Port, _path)) { diff --git a/identity-server/clients/src/MvcDPoP/TestHandler.cs b/identity-server/clients/src/MvcDPoP/TestHandler.cs index cef0d4180..3f10942a9 100644 --- a/identity-server/clients/src/MvcDPoP/TestHandler.cs +++ b/identity-server/clients/src/MvcDPoP/TestHandler.cs @@ -8,7 +8,7 @@ public class TestHandler : DelegatingHandler private readonly ILogger _logger; public TestHandler(ILogger logger) => _logger = logger; - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct ct) { var response = await base.SendAsync(request, ct); if (response.Headers.Contains("WWW-Authenticate")) diff --git a/identity-server/clients/src/MvcJarJwt/ClientAssertionService.cs b/identity-server/clients/src/MvcJarJwt/ClientAssertionService.cs index 05bd8331a..273ea9912 100644 --- a/identity-server/clients/src/MvcJarJwt/ClientAssertionService.cs +++ b/identity-server/clients/src/MvcJarJwt/ClientAssertionService.cs @@ -10,7 +10,7 @@ namespace MvcJarJwt; public class ClientAssertionService(AssertionService assertionService) : IClientAssertionService { public Task GetClientAssertionAsync(ClientCredentialsClientName? clientName = null, TokenRequestParameters parameters = null, - CT ct = new()) + Ct ct = new()) { var assertion = new ClientAssertion { diff --git a/identity-server/clients/src/MvcJarUriJwt/ClientAssertionService.cs b/identity-server/clients/src/MvcJarUriJwt/ClientAssertionService.cs index 6ed71961c..587ddc2ef 100644 --- a/identity-server/clients/src/MvcJarUriJwt/ClientAssertionService.cs +++ b/identity-server/clients/src/MvcJarUriJwt/ClientAssertionService.cs @@ -11,7 +11,7 @@ public class ClientAssertionService(AssertionService assertionService) : IClient { public Task GetClientAssertionAsync(ClientCredentialsClientName? clientName = null, TokenRequestParameters parameters = null, - CT ct = new()) + Ct ct = new()) { var assertion = new ClientAssertion { diff --git a/identity-server/clients/src/Web/ClientAssertionService.cs b/identity-server/clients/src/Web/ClientAssertionService.cs index 9338732ed..7efcbfe07 100644 --- a/identity-server/clients/src/Web/ClientAssertionService.cs +++ b/identity-server/clients/src/Web/ClientAssertionService.cs @@ -10,7 +10,7 @@ namespace Web; public class ClientAssertionService(AssertionService assertionService) : IClientAssertionService { public Task GetClientAssertionAsync(ClientCredentialsClientName? clientName = null, TokenRequestParameters? parameters = null, - CT ct = new CT()) + Ct ct = new Ct()) { var assertion = new ClientAssertion { diff --git a/identity-server/clients/src/WindowsConsoleSystemBrowser/CallbackManager.cs b/identity-server/clients/src/WindowsConsoleSystemBrowser/CallbackManager.cs index 244ffd45d..df11bf1f1 100644 --- a/identity-server/clients/src/WindowsConsoleSystemBrowser/CallbackManager.cs +++ b/identity-server/clients/src/WindowsConsoleSystemBrowser/CallbackManager.cs @@ -26,9 +26,9 @@ internal class CallbackManager } } - public async Task RunServer(CT? token = null) + public async Task RunServer(Ct? token = null) { - token = CT.None; + token = Ct.None; await using var server = new NamedPipeServerStream(_name, PipeDirection.In); await server.WaitForConnectionAsync(token.Value); diff --git a/identity-server/hosts/EntityFramework10/TestOperationalStoreNotification.cs b/identity-server/hosts/EntityFramework10/TestOperationalStoreNotification.cs index 36e79cdd5..11662adde 100644 --- a/identity-server/hosts/EntityFramework10/TestOperationalStoreNotification.cs +++ b/identity-server/hosts/EntityFramework10/TestOperationalStoreNotification.cs @@ -12,7 +12,7 @@ public class TestOperationalStoreNotification : IOperationalStoreNotification { public TestOperationalStoreNotification() => Console.WriteLine("ctor"); - public Task PersistedGrantsRemovedAsync(IEnumerable persistedGrants, CT ct = default) + public Task PersistedGrantsRemovedAsync(IEnumerable persistedGrants, Ct ct) { ArgumentNullException.ThrowIfNull(persistedGrants); foreach (var grant in persistedGrants) @@ -22,7 +22,7 @@ public class TestOperationalStoreNotification : IOperationalStoreNotification return Task.CompletedTask; } - public Task DeviceCodesRemovedAsync(IEnumerable deviceCodes, CT ct = default) + public Task DeviceCodesRemovedAsync(IEnumerable deviceCodes, Ct ct) { ArgumentNullException.ThrowIfNull(deviceCodes); foreach (var deviceCode in deviceCodes) @@ -32,7 +32,7 @@ public class TestOperationalStoreNotification : IOperationalStoreNotification return Task.CompletedTask; } - public Task ServerSideSessionsRemovedAsync(IEnumerable userSessions, CT ct = default) + public Task ServerSideSessionsRemovedAsync(IEnumerable userSessions, Ct ct) { ArgumentNullException.ThrowIfNull(userSessions); foreach (var session in userSessions) diff --git a/identity-server/hosts/Shared/Customization/CustomClientRegistrationProcessor.cs b/identity-server/hosts/Shared/Customization/CustomClientRegistrationProcessor.cs index 91de8bacc..633170673 100644 --- a/identity-server/hosts/Shared/Customization/CustomClientRegistrationProcessor.cs +++ b/identity-server/hosts/Shared/Customization/CustomClientRegistrationProcessor.cs @@ -18,14 +18,14 @@ public sealed class CustomClientRegistrationProcessor( IClientStore clientStore) : DynamicClientRegistrationRequestProcessor(options, dcrStore) { - protected override async Task AddClientId(DynamicClientRegistrationContext context) + protected override async Task AddClientId(DynamicClientRegistrationContext context, Ct ct) { if (context.Request.Extensions.TryGetValue("client_id", out var clientIdParameter)) { var clientId = clientIdParameter.ToString(); if (clientId != null) { - var existingClient = await clientStore.FindClientByIdAsync(clientId); + var existingClient = await clientStore.FindClientByIdAsync(clientId, ct); if (existingClient is not null) { return new DynamicClientRegistrationError( @@ -40,7 +40,7 @@ public sealed class CustomClientRegistrationProcessor( } } } - return await base.AddClientId(context); + return await base.AddClientId(context, ct); } protected override async Task<(Secret, string)> GenerateSecret(DynamicClientRegistrationContext context) diff --git a/identity-server/hosts/Shared/Customization/DiscoveryHealthCheck.cs b/identity-server/hosts/Shared/Customization/DiscoveryHealthCheck.cs index f3acc850b..ea973bb8d 100644 --- a/identity-server/hosts/Shared/Customization/DiscoveryHealthCheck.cs +++ b/identity-server/hosts/Shared/Customization/DiscoveryHealthCheck.cs @@ -18,7 +18,7 @@ public class DiscoveryHealthCheck : IHealthCheck _httpContextAccessor = httpContextAccessor; } - public async Task CheckHealthAsync(HealthCheckContext context, CT ct = default) + public async Task CheckHealthAsync(HealthCheckContext context, Ct ct = default) { ArgumentNullException.ThrowIfNull(context); try @@ -55,7 +55,7 @@ public class DiscoveryKeysHealthCheck : IHealthCheck _httpContextAccessor = httpContextAccessor; } - public async Task CheckHealthAsync(HealthCheckContext context, CT ct = default) + public async Task CheckHealthAsync(HealthCheckContext context, Ct ct = default) { ArgumentNullException.ThrowIfNull(context); try diff --git a/identity-server/hosts/Shared/Customization/ExtensionGrantValidator.cs b/identity-server/hosts/Shared/Customization/ExtensionGrantValidator.cs index 6a5b40c98..b3f818737 100644 --- a/identity-server/hosts/Shared/Customization/ExtensionGrantValidator.cs +++ b/identity-server/hosts/Shared/Customization/ExtensionGrantValidator.cs @@ -8,7 +8,7 @@ namespace Duende.IdentityServer.Hosts.Shared.Customization; public class ExtensionGrantValidator : IExtensionGrantValidator { - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct ct) { ArgumentNullException.ThrowIfNull(context); var credential = context.Request.Raw.Get("custom_credential"); diff --git a/identity-server/hosts/Shared/Customization/HostProfileService.cs b/identity-server/hosts/Shared/Customization/HostProfileService.cs index ddc29152a..1508e0761 100644 --- a/identity-server/hosts/Shared/Customization/HostProfileService.cs +++ b/identity-server/hosts/Shared/Customization/HostProfileService.cs @@ -9,10 +9,10 @@ namespace Duende.IdentityServer.Hosts.Shared.Customization; public class HostProfileService(TestUserStore users, ILogger logger) : TestUserProfileService(users, logger) { - public override async Task GetProfileDataAsync(ProfileDataRequestContext context) + public override async Task GetProfileDataAsync(ProfileDataRequestContext context, Ct ct) { ArgumentNullException.ThrowIfNull(context); - await base.GetProfileDataAsync(context); + await base.GetProfileDataAsync(context, ct); var transaction = context.RequestedResources.ParsedScopes.FirstOrDefault(x => x.ParsedName == "transaction"); if (transaction?.ParsedParameter != null) diff --git a/identity-server/hosts/Shared/Customization/NoSubjectExtensionGrantValidator.cs b/identity-server/hosts/Shared/Customization/NoSubjectExtensionGrantValidator.cs index 73ab53229..5261a641d 100644 --- a/identity-server/hosts/Shared/Customization/NoSubjectExtensionGrantValidator.cs +++ b/identity-server/hosts/Shared/Customization/NoSubjectExtensionGrantValidator.cs @@ -8,7 +8,7 @@ namespace Duende.IdentityServer.Hosts.Shared.Customization; public class NoSubjectExtensionGrantValidator : IExtensionGrantValidator { - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct ct) { ArgumentNullException.ThrowIfNull(context); var credential = context.Request.Raw.Get("custom_credential"); diff --git a/identity-server/hosts/Shared/Customization/ParameterizedScopeTokenRequestValidator.cs b/identity-server/hosts/Shared/Customization/ParameterizedScopeTokenRequestValidator.cs index 695c56a72..d10677291 100644 --- a/identity-server/hosts/Shared/Customization/ParameterizedScopeTokenRequestValidator.cs +++ b/identity-server/hosts/Shared/Customization/ParameterizedScopeTokenRequestValidator.cs @@ -8,7 +8,7 @@ namespace Duende.IdentityServer.Hosts.Shared.Customization; public class ParameterizedScopeTokenRequestValidator : ICustomTokenRequestValidator { - public Task ValidateAsync(CustomTokenRequestValidationContext context) + public Task ValidateAsync(CustomTokenRequestValidationContext context, Ct ct) { ArgumentNullException.ThrowIfNull(context); var transaction = context.Result?.ValidatedRequest.ValidatedResources.ParsedScopes.FirstOrDefault(x => x.ParsedName == "transaction"); diff --git a/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Login/Index.cshtml.cs b/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Login/Index.cshtml.cs index f8a42123a..7db379d98 100644 --- a/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Login/Index.cshtml.cs +++ b/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Login/Index.cshtml.cs @@ -50,7 +50,7 @@ public class Index : PageModel public async Task OnGet(string? returnUrl) { - await BuildModelAsync(returnUrl); + await BuildModelAsync(returnUrl, HttpContext.RequestAborted); if (View.IsExternalLoginOnly) { @@ -64,7 +64,7 @@ public class Index : PageModel public async Task OnPost() { // check if we are in the context of an authorization request - var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl); + var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl, HttpContext.RequestAborted); // the user clicked the "cancel" button if (Input.Button != "login") @@ -77,7 +77,7 @@ public class Index : PageModel // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. - await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied); + await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied, HttpContext.RequestAborted); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (context.IsNativeClient()) @@ -105,7 +105,7 @@ public class Index : PageModel if (result.Succeeded) { var user = await _userManager.FindByNameAsync(Input.Username!); - await _events.RaiseAsync(new UserLoginSuccessEvent(user!.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId)); + await _events.RaiseAsync(new UserLoginSuccessEvent(user!.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId), HttpContext.RequestAborted); Duende.IdentityServer.UI.Pages.Telemetry.Metrics.UserLogin(context?.Client.ClientId, IdentityServerConstants.LocalIdentityProvider); if (context != null) @@ -141,24 +141,24 @@ public class Index : PageModel } const string error = "invalid credentials"; - await _events.RaiseAsync(new UserLoginFailureEvent(Input.Username, error, clientId: context?.Client.ClientId)); + await _events.RaiseAsync(new UserLoginFailureEvent(Input.Username, error, clientId: context?.Client.ClientId), HttpContext.RequestAborted); Duende.IdentityServer.UI.Pages.Telemetry.Metrics.UserLoginFailure(context?.Client.ClientId, IdentityServerConstants.LocalIdentityProvider, error); ModelState.AddModelError(string.Empty, LoginOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error - await BuildModelAsync(Input.ReturnUrl); + await BuildModelAsync(Input.ReturnUrl, HttpContext.RequestAborted); return Page(); } - private async Task BuildModelAsync(string? returnUrl) + private async Task BuildModelAsync(string? returnUrl, Ct ct) { Input = new InputModel { ReturnUrl = returnUrl }; - var context = await _interaction.GetAuthorizationContextAsync(returnUrl); + var context = await _interaction.GetAuthorizationContextAsync(returnUrl, HttpContext.RequestAborted); if (context?.IdP != null) { var scheme = await _schemeProvider.GetSchemeAsync(context.IdP); @@ -193,7 +193,7 @@ public class Index : PageModel displayName: x.DisplayName ?? x.Name )).ToList(); - var dynamicSchemes = (await _identityProviderStore.GetAllSchemeNamesAsync()) + var dynamicSchemes = (await _identityProviderStore.GetAllSchemeNamesAsync(ct)) .Where(x => x.Enabled) .Select(x => new ViewModel.ExternalProvider ( diff --git a/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Logout/Index.cshtml.cs b/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Logout/Index.cshtml.cs index e1da4efda..01f147b4b 100644 --- a/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Logout/Index.cshtml.cs +++ b/identity-server/hosts/UI/AspNetIdentity/Pages/Account/Logout/Index.cshtml.cs @@ -47,7 +47,7 @@ public class Index : PageModel } else { - var context = await _interaction.GetLogoutContextAsync(LogoutId); + var context = await _interaction.GetLogoutContextAsync(LogoutId, HttpContext.RequestAborted); if (context?.ShowSignoutPrompt == false) { // it's safe to automatically sign-out @@ -72,7 +72,7 @@ public class Index : PageModel // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // this can still return null if there is no context needed - LogoutId ??= await _interaction.CreateLogoutContextAsync(); + LogoutId ??= await _interaction.CreateLogoutContextAsync(HttpContext.RequestAborted); // delete local authentication cookie await _signInManager.SignOutAsync(); @@ -81,7 +81,7 @@ public class Index : PageModel var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; // raise the logout event - await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); + await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()), HttpContext.RequestAborted); Duende.IdentityServer.UI.Pages.Telemetry.Metrics.UserLogout(idp); // if it's a local login we can ignore this workflow diff --git a/identity-server/hosts/UI/AspNetIdentity/Pages/ExternalLogin/Callback.cshtml.cs b/identity-server/hosts/UI/AspNetIdentity/Pages/ExternalLogin/Callback.cshtml.cs index fc5fda88b..532bbe71c 100644 --- a/identity-server/hosts/UI/AspNetIdentity/Pages/ExternalLogin/Callback.cshtml.cs +++ b/identity-server/hosts/UI/AspNetIdentity/Pages/ExternalLogin/Callback.cshtml.cs @@ -100,8 +100,8 @@ public class Callback : PageModel var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request - var context = await _interaction.GetAuthorizationContextAsync(returnUrl); - await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, user.UserName, true, context?.Client.ClientId)); + var context = await _interaction.GetAuthorizationContextAsync(returnUrl, HttpContext.RequestAborted); + await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, user.UserName, true, context?.Client.ClientId), HttpContext.RequestAborted); Duende.IdentityServer.UI.Pages.Telemetry.Metrics.UserLogin(context?.Client.ClientId, provider!); if (context != null) diff --git a/identity-server/hosts/UI/Main/Pages/Account/Create/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Account/Create/Index.cshtml.cs index bb3def5cf..02dfebe02 100644 --- a/identity-server/hosts/UI/Main/Pages/Account/Create/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Account/Create/Index.cshtml.cs @@ -39,7 +39,7 @@ public class Index : PageModel public async Task OnPost() { // check if we are in the context of an authorization request - var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl); + var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl, HttpContext.RequestAborted); // the user clicked the "cancel" button if (Input.Button != "create") @@ -49,7 +49,7 @@ public class Index : PageModel // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. - await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied); + await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied, HttpContext.RequestAborted); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (context.IsNativeClient()) diff --git a/identity-server/hosts/UI/Main/Pages/Account/Login/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Account/Login/Index.cshtml.cs index c0359e32e..e104d71a6 100644 --- a/identity-server/hosts/UI/Main/Pages/Account/Login/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Account/Login/Index.cshtml.cs @@ -46,7 +46,7 @@ public class Index : PageModel public async Task OnGet(string? returnUrl) { - await BuildModelAsync(returnUrl); + await BuildModelAsync(returnUrl, HttpContext.RequestAborted); if (View.IsExternalLoginOnly) { @@ -60,7 +60,7 @@ public class Index : PageModel public async Task OnPost() { // check if we are in the context of an authorization request - var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl); + var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl, HttpContext.RequestAborted); // the user clicked the "cancel" button if (Input.Button != "login") @@ -73,7 +73,7 @@ public class Index : PageModel // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. - await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied); + await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied, HttpContext.RequestAborted); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (context.IsNativeClient()) @@ -98,7 +98,7 @@ public class Index : PageModel if (_users.ValidateCredentials(Input.Username, Input.Password)) { var user = _users.FindByUsername(Input.Username); - await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId: context?.Client.ClientId)); + await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId: context?.Client.ClientId), HttpContext.RequestAborted); Telemetry.Metrics.UserLogin(context?.Client.ClientId, IdentityServerConstants.LocalIdentityProvider); // only set explicit expiration here if user chooses "remember me". @@ -151,24 +151,24 @@ public class Index : PageModel } const string error = "invalid credentials"; - await _events.RaiseAsync(new UserLoginFailureEvent(Input.Username, error, clientId: context?.Client.ClientId)); + await _events.RaiseAsync(new UserLoginFailureEvent(Input.Username, error, clientId: context?.Client.ClientId), HttpContext.RequestAborted); Telemetry.Metrics.UserLoginFailure(context?.Client.ClientId, IdentityServerConstants.LocalIdentityProvider, error); ModelState.AddModelError(string.Empty, LoginOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error - await BuildModelAsync(Input.ReturnUrl); + await BuildModelAsync(Input.ReturnUrl, HttpContext.RequestAborted); return Page(); } - private async Task BuildModelAsync(string? returnUrl) + private async Task BuildModelAsync(string? returnUrl, Ct ct) { Input = new InputModel { ReturnUrl = returnUrl }; - var context = await _interaction.GetAuthorizationContextAsync(returnUrl); + var context = await _interaction.GetAuthorizationContextAsync(returnUrl, HttpContext.RequestAborted); if (context?.IdP != null) { var scheme = await _schemeProvider.GetSchemeAsync(context.IdP); @@ -203,7 +203,7 @@ public class Index : PageModel displayName: x.DisplayName ?? x.Name )).ToList(); - var dynamicSchemes = (await _identityProviderStore.GetAllSchemeNamesAsync()) + var dynamicSchemes = (await _identityProviderStore.GetAllSchemeNamesAsync(ct)) .Where(x => x.Enabled) .Select(x => new ViewModel.ExternalProvider ( diff --git a/identity-server/hosts/UI/Main/Pages/Account/Logout/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Account/Logout/Index.cshtml.cs index c4c228f90..69ffbb118 100644 --- a/identity-server/hosts/UI/Main/Pages/Account/Logout/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Account/Logout/Index.cshtml.cs @@ -41,7 +41,7 @@ public class Index : PageModel } else { - var context = await _interaction.GetLogoutContextAsync(LogoutId); + var context = await _interaction.GetLogoutContextAsync(LogoutId, HttpContext.RequestAborted); if (context?.ShowSignoutPrompt == false) { // it's safe to automatically sign-out @@ -66,7 +66,7 @@ public class Index : PageModel // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // this can still return null if there is no context needed - LogoutId ??= await _interaction.CreateLogoutContextAsync(); + LogoutId ??= await _interaction.CreateLogoutContextAsync(HttpContext.RequestAborted); // delete local authentication cookie await HttpContext.SignOutAsync(); @@ -75,7 +75,7 @@ public class Index : PageModel var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; // raise the logout event - await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); + await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()), HttpContext.RequestAborted); Telemetry.Metrics.UserLogout(idp); // if it's a local login we can ignore this workflow diff --git a/identity-server/hosts/UI/Main/Pages/Account/Logout/LoggedOut.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Account/Logout/LoggedOut.cshtml.cs index 8b88394d8..deee46f99 100644 --- a/identity-server/hosts/UI/Main/Pages/Account/Logout/LoggedOut.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Account/Logout/LoggedOut.cshtml.cs @@ -20,7 +20,7 @@ public class LoggedOut : PageModel public async Task OnGet(string? logoutId) { // get context information (client name, post logout redirect URI and iframe for federated signout) - var logout = await _interactionService.GetLogoutContextAsync(logoutId); + var logout = await _interactionService.GetLogoutContextAsync(logoutId, HttpContext.RequestAborted); View = new LoggedOutViewModel { diff --git a/identity-server/hosts/UI/Main/Pages/Ciba/All.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Ciba/All.cshtml.cs index bda76398a..f9a31d189 100644 --- a/identity-server/hosts/UI/Main/Pages/Ciba/All.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Ciba/All.cshtml.cs @@ -18,5 +18,5 @@ public class AllModel : PageModel public AllModel(IBackchannelAuthenticationInteractionService backchannelAuthenticationInteractionService) => _backchannelAuthenticationInteraction = backchannelAuthenticationInteractionService; - public async Task OnGet() => Logins = await _backchannelAuthenticationInteraction.GetPendingLoginRequestsForCurrentUserAsync(); + public async Task OnGet() => Logins = await _backchannelAuthenticationInteraction.GetPendingLoginRequestsForCurrentUserAsync(HttpContext.RequestAborted); } diff --git a/identity-server/hosts/UI/Main/Pages/Ciba/Consent.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Ciba/Consent.cshtml.cs index 04978b327..a065336ac 100644 --- a/identity-server/hosts/UI/Main/Pages/Ciba/Consent.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Ciba/Consent.cshtml.cs @@ -53,7 +53,7 @@ public class Consent : PageModel public async Task OnPost() { // validate return url is still valid - var request = await _interaction.GetLoginRequestByInternalIdAsync(Input.Id ?? throw new ArgumentNullException(nameof(Input.Id))); + var request = await _interaction.GetLoginRequestByInternalIdAsync(Input.Id ?? throw new ArgumentNullException(nameof(Input.Id)), HttpContext.RequestAborted); if (request == null || request.Subject.GetSubjectId() != User.GetSubjectId()) { _logger.InvalidId(Input.Id); @@ -68,7 +68,7 @@ public class Consent : PageModel result = new CompleteBackchannelLoginRequest(Input.Id); // emit event - await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues)); + await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues), HttpContext.RequestAborted); Telemetry.Metrics.ConsentDenied(request.Client.ClientId, request.ValidatedResources.ParsedScopes.Select(s => s.ParsedName)); } // user clicked 'yes' - validate the data @@ -90,7 +90,7 @@ public class Consent : PageModel }; // emit event - await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, result.ScopesValuesConsented, false)); + await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, result.ScopesValuesConsented, false), HttpContext.RequestAborted); Telemetry.Metrics.ConsentGranted(request.Client.ClientId, result.ScopesValuesConsented, false); var denied = request.ValidatedResources.ParsedScopes.Select(s => s.ParsedName).Except(result.ScopesValuesConsented); Telemetry.Metrics.ConsentDenied(request.Client.ClientId, denied); @@ -108,7 +108,7 @@ public class Consent : PageModel if (result != null) { // communicate outcome of consent back to identityserver - await _interaction.CompleteLoginRequestAsync(result); + await _interaction.CompleteLoginRequestAsync(result, HttpContext.RequestAborted); return RedirectToPage("/Ciba/All"); } @@ -125,7 +125,7 @@ public class Consent : PageModel { ArgumentNullException.ThrowIfNull(id); - var request = await _interaction.GetLoginRequestByInternalIdAsync(id); + var request = await _interaction.GetLoginRequestByInternalIdAsync(id, HttpContext.RequestAborted); if (request != null && request.Subject.GetSubjectId() == User.GetSubjectId()) { View = CreateConsentViewModel(request); diff --git a/identity-server/hosts/UI/Main/Pages/Ciba/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Ciba/Index.cshtml.cs index c178dbf1d..91d3bde03 100644 --- a/identity-server/hosts/UI/Main/Pages/Ciba/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Ciba/Index.cshtml.cs @@ -26,7 +26,7 @@ public class IndexModel : PageModel public async Task OnGet(string id) { - var result = await _backchannelAuthenticationInteraction.GetLoginRequestByInternalIdAsync(id); + var result = await _backchannelAuthenticationInteraction.GetLoginRequestByInternalIdAsync(id, HttpContext.RequestAborted); if (result == null) { _logger.InvalidBackchannelLoginId(id); diff --git a/identity-server/hosts/UI/Main/Pages/Consent/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Consent/Index.cshtml.cs index f18aee4f1..9691ca3d9 100644 --- a/identity-server/hosts/UI/Main/Pages/Consent/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Consent/Index.cshtml.cs @@ -54,7 +54,7 @@ public class Index : PageModel public async Task OnPost() { // validate return url is still valid - var request = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl); + var request = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl, HttpContext.RequestAborted); if (request == null) { return RedirectToPage("/Home/Error/Index"); @@ -68,7 +68,7 @@ public class Index : PageModel grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied }; // emit event - await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues)); + await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues), HttpContext.RequestAborted); Telemetry.Metrics.ConsentDenied(request.Client.ClientId, request.ValidatedResources.ParsedScopes.Select(s => s.ParsedName)); } // user clicked 'yes' - validate the data @@ -91,7 +91,7 @@ public class Index : PageModel }; // emit event - await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent)); + await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent), HttpContext.RequestAborted); Telemetry.Metrics.ConsentGranted(request.Client.ClientId, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent); var denied = request.ValidatedResources.ParsedScopes.Select(s => s.ParsedName).Except(grantedConsent.ScopesValuesConsented); Telemetry.Metrics.ConsentDenied(request.Client.ClientId, denied); @@ -111,7 +111,7 @@ public class Index : PageModel ArgumentNullException.ThrowIfNull(Input.ReturnUrl, nameof(Input.ReturnUrl)); // communicate outcome of consent back to identityserver - await _interaction.GrantConsentAsync(request, grantedConsent); + await _interaction.GrantConsentAsync(request, grantedConsent, HttpContext.RequestAborted); // redirect back to authorization endpoint if (request.IsNativeClient() == true) @@ -136,7 +136,7 @@ public class Index : PageModel { ArgumentNullException.ThrowIfNull(returnUrl); - var request = await _interaction.GetAuthorizationContextAsync(returnUrl); + var request = await _interaction.GetAuthorizationContextAsync(returnUrl, HttpContext.RequestAborted); if (request != null) { View = CreateConsentViewModel(request); diff --git a/identity-server/hosts/UI/Main/Pages/Device/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Device/Index.cshtml.cs index c87c5713d..1ba384965 100644 --- a/identity-server/hosts/UI/Main/Pages/Device/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Device/Index.cshtml.cs @@ -61,7 +61,7 @@ public class Index : PageModel public async Task OnPost() { - var request = await _interaction.GetAuthorizationContextAsync(Input.UserCode ?? throw new ArgumentNullException(nameof(Input.UserCode))); + var request = await _interaction.GetAuthorizationContextAsync(Input.UserCode ?? throw new ArgumentNullException(nameof(Input.UserCode)), HttpContext.RequestAborted); if (request == null) { return RedirectToPage("/Home/Error/Index"); @@ -78,7 +78,7 @@ public class Index : PageModel }; // emit event - await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues)); + await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues), HttpContext.RequestAborted); Telemetry.Metrics.ConsentDenied(request.Client.ClientId, request.ValidatedResources.ParsedScopes.Select(s => s.ParsedName)); } // user clicked 'yes' - validate the data @@ -101,7 +101,7 @@ public class Index : PageModel }; // emit event - await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent)); + await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent), HttpContext.RequestAborted); Telemetry.Metrics.ConsentGranted(request.Client.ClientId, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent); var denied = request.ValidatedResources.ParsedScopes.Select(s => s.ParsedName).Except(grantedConsent.ScopesValuesConsented); Telemetry.Metrics.ConsentDenied(request.Client.ClientId, denied); @@ -119,7 +119,7 @@ public class Index : PageModel if (grantedConsent != null) { // communicate outcome of consent back to identityserver - await _interaction.HandleRequestAsync(Input.UserCode, grantedConsent); + await _interaction.HandleRequestAsync(Input.UserCode, grantedConsent, HttpContext.RequestAborted); // indicate that's it ok to redirect back to authorization endpoint return RedirectToPage("/Device/Success"); @@ -136,7 +136,7 @@ public class Index : PageModel private async Task SetViewModelAsync(string userCode) { - var request = await _interaction.GetAuthorizationContextAsync(userCode); + var request = await _interaction.GetAuthorizationContextAsync(userCode, HttpContext.RequestAborted); if (request != null) { View = CreateConsentViewModel(request); diff --git a/identity-server/hosts/UI/Main/Pages/ExternalLogin/Callback.cshtml.cs b/identity-server/hosts/UI/Main/Pages/ExternalLogin/Callback.cshtml.cs index 11120fe19..1495be559 100644 --- a/identity-server/hosts/UI/Main/Pages/ExternalLogin/Callback.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/ExternalLogin/Callback.cshtml.cs @@ -103,8 +103,8 @@ public class Callback : PageModel var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request - var context = await _interaction.GetAuthorizationContextAsync(returnUrl); - await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username, true, context?.Client.ClientId)); + var context = await _interaction.GetAuthorizationContextAsync(returnUrl, HttpContext.RequestAborted); + await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username, true, context?.Client.ClientId), HttpContext.RequestAborted); Telemetry.Metrics.UserLogin(context?.Client.ClientId, provider!); if (context != null) diff --git a/identity-server/hosts/UI/Main/Pages/Grants/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Grants/Index.cshtml.cs index 58e782144..ddc704220 100644 --- a/identity-server/hosts/UI/Main/Pages/Grants/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Grants/Index.cshtml.cs @@ -35,15 +35,15 @@ public class Index : PageModel public async Task OnGet() { - var grants = await _interaction.GetAllUserGrantsAsync(); + var grants = await _interaction.GetAllUserGrantsAsync(HttpContext.RequestAborted); var list = new List(); foreach (var grant in grants) { - var client = await _clients.FindClientByIdAsync(grant.ClientId); + var client = await _clients.FindClientByIdAsync(grant.ClientId, HttpContext.RequestAborted); if (client != null) { - var resources = await _resources.FindResourcesByScopeAsync(grant.Scopes); + var resources = await _resources.FindResourcesByScopeAsync(grant.Scopes, HttpContext.RequestAborted); var item = new GrantViewModel() { @@ -73,8 +73,8 @@ public class Index : PageModel public async Task OnPost() { - await _interaction.RevokeUserConsentAsync(ClientId); - await _events.RaiseAsync(new GrantsRevokedEvent(User.GetSubjectId(), ClientId)); + await _interaction.RevokeUserConsentAsync(ClientId, HttpContext.RequestAborted); + await _events.RaiseAsync(new GrantsRevokedEvent(User.GetSubjectId(), ClientId), HttpContext.RequestAborted); Telemetry.Metrics.GrantsRevoked(ClientId); return RedirectToPage("/Grants/Index"); diff --git a/identity-server/hosts/UI/Main/Pages/Home/Error/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/Home/Error/Index.cshtml.cs index 592ab5216..21324614f 100644 --- a/identity-server/hosts/UI/Main/Pages/Home/Error/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/Home/Error/Index.cshtml.cs @@ -25,7 +25,7 @@ public class Index : PageModel public async Task OnGet(string? errorId) { // retrieve error details from identityserver - var message = await _interaction.GetErrorContextAsync(errorId); + var message = await _interaction.GetErrorContextAsync(errorId, HttpContext.RequestAborted); if (message != null) { View.Error = message; diff --git a/identity-server/hosts/UI/Main/Pages/ServerSideSessions/Index.cshtml.cs b/identity-server/hosts/UI/Main/Pages/ServerSideSessions/Index.cshtml.cs index 54793b242..ef0025370 100644 --- a/identity-server/hosts/UI/Main/Pages/ServerSideSessions/Index.cshtml.cs +++ b/identity-server/hosts/UI/Main/Pages/ServerSideSessions/Index.cshtml.cs @@ -49,7 +49,7 @@ public class IndexModel : PageModel DisplayName = DisplayNameFilter, SessionId = SessionIdFilter, SubjectId = SubjectIdFilter - }); + }, HttpContext.RequestAborted); } return Page(); @@ -71,7 +71,7 @@ public class IndexModel : PageModel await _sessionManagementService.RemoveSessionsAsync(new RemoveSessionsContext { SessionId = SessionId, - }); + }, HttpContext.RequestAborted); return RedirectToPage("/ServerSideSessions/Index", new { Token, DisplayNameFilter, SessionIdFilter, SubjectIdFilter, Prev }); } diff --git a/identity-server/perf/IdentityServer.PerfTests/Services/DefaultTokenServiceTest.cs b/identity-server/perf/IdentityServer.PerfTests/Services/DefaultTokenServiceTest.cs index ceda0f167..dfaad3882 100644 --- a/identity-server/perf/IdentityServer.PerfTests/Services/DefaultTokenServiceTest.cs +++ b/identity-server/perf/IdentityServer.PerfTests/Services/DefaultTokenServiceTest.cs @@ -60,8 +60,8 @@ public class DefaultTokenServiceTest : TestBase Client = _client, }, ValidatedResources = new ResourceValidationResult(new Resources() { ApiScopes = new[] { _scope } }), - }); - var jwt = await _subject.CreateSecurityTokenAsync(token); + }, default); + var jwt = await _subject.CreateSecurityTokenAsync(token, default); //System.Console.WriteLine(jwt); } } diff --git a/identity-server/src/AspNetIdentity/ConfigureSecurityStampValidatorOptions.cs b/identity-server/src/AspNetIdentity/ConfigureSecurityStampValidatorOptions.cs index a400ca7f6..1051855f4 100644 --- a/identity-server/src/AspNetIdentity/ConfigureSecurityStampValidatorOptions.cs +++ b/identity-server/src/AspNetIdentity/ConfigureSecurityStampValidatorOptions.cs @@ -1,12 +1,14 @@ // Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; namespace Duende.IdentityServer.AspNetIdentity; -public class ConfigureSecurityStampValidatorOptions(ISessionClaimsFilter sessionClaimsFilter) : IConfigureOptions +public class ConfigureSecurityStampValidatorOptions(ISessionClaimsFilter sessionClaimsFilter, IHttpContextAccessor httpContextAccessor) : IConfigureOptions { - public void Configure(SecurityStampValidatorOptions options) => options.OnRefreshingPrincipal = async context => await SecurityStampValidatorCallback.UpdatePrincipal(context, sessionClaimsFilter); + public void Configure(SecurityStampValidatorOptions options) => options.OnRefreshingPrincipal = async context => + await SecurityStampValidatorCallback.UpdatePrincipal(context, sessionClaimsFilter, httpContextAccessor.HttpContext?.RequestAborted ?? default); } diff --git a/identity-server/src/AspNetIdentity/DefaultSessionClaimsFilter.cs b/identity-server/src/AspNetIdentity/DefaultSessionClaimsFilter.cs index 0845f2e23..43a0d3424 100644 --- a/identity-server/src/AspNetIdentity/DefaultSessionClaimsFilter.cs +++ b/identity-server/src/AspNetIdentity/DefaultSessionClaimsFilter.cs @@ -9,7 +9,7 @@ namespace Duende.IdentityServer.AspNetIdentity; public class DefaultSessionClaimsFilter : ISessionClaimsFilter { /// - public Task> FilterToSessionClaimsAsync(SecurityStampRefreshingPrincipalContext context) + public Task> FilterToSessionClaimsAsync(SecurityStampRefreshingPrincipalContext context, Ct _) { var newClaimTypes = context.NewPrincipal.Claims.Select(x => x.Type).ToArray(); var currentClaimsToKeep = context.CurrentPrincipal.Claims.Where(x => !newClaimTypes.Contains(x.Type)).ToArray(); diff --git a/identity-server/src/AspNetIdentity/ISessionClaimsFilter.cs b/identity-server/src/AspNetIdentity/ISessionClaimsFilter.cs index 898871a0a..b2fa59acf 100644 --- a/identity-server/src/AspNetIdentity/ISessionClaimsFilter.cs +++ b/identity-server/src/AspNetIdentity/ISessionClaimsFilter.cs @@ -16,6 +16,7 @@ public interface ISessionClaimsFilter /// /// The SecurityStampRefreshingPrincipalContext /// in the call to . + /// The cancellation token. /// The claims of the ClaimsPrincipal which should be persisted for the session. - public Task> FilterToSessionClaimsAsync(SecurityStampRefreshingPrincipalContext context); + public Task> FilterToSessionClaimsAsync(SecurityStampRefreshingPrincipalContext context, Ct ct); } diff --git a/identity-server/src/AspNetIdentity/ProfileService.cs b/identity-server/src/AspNetIdentity/ProfileService.cs index b8dc6638a..834f28650 100644 --- a/identity-server/src/AspNetIdentity/ProfileService.cs +++ b/identity-server/src/AspNetIdentity/ProfileService.cs @@ -65,8 +65,9 @@ public class ProfileService : IProfileService /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint) /// /// The context. + /// The cancellation token. /// - public virtual async Task GetProfileDataAsync(ProfileDataRequestContext context) + public virtual async Task GetProfileDataAsync(ProfileDataRequestContext context, Ct ct) { var sub = context.Subject?.GetSubjectId(); if (sub == null) @@ -125,8 +126,9 @@ public class ProfileService : IProfileService /// (e.g. during token issuance or validation). /// /// The context. + /// The cancellation token. /// - public virtual async Task IsActiveAsync(IsActiveContext context) + public virtual async Task IsActiveAsync(IsActiveContext context, Ct ct) { var sub = context.Subject?.GetSubjectId(); if (sub == null) diff --git a/identity-server/src/AspNetIdentity/ResourceOwnerPasswordValidator.cs b/identity-server/src/AspNetIdentity/ResourceOwnerPasswordValidator.cs index e79c01f96..6d686f11d 100644 --- a/identity-server/src/AspNetIdentity/ResourceOwnerPasswordValidator.cs +++ b/identity-server/src/AspNetIdentity/ResourceOwnerPasswordValidator.cs @@ -38,12 +38,8 @@ public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValid _logger = logger; } - /// - /// Validates the resource owner password credential - /// - /// The context. - /// - public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) + /// + public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context, Ct ct) { var user = await _userManager.FindByNameAsync(context.UserName); if (user != null) diff --git a/identity-server/src/AspNetIdentity/SecurityStampValidatorCallback.cs b/identity-server/src/AspNetIdentity/SecurityStampValidatorCallback.cs index aeb823bc3..be581ce78 100644 --- a/identity-server/src/AspNetIdentity/SecurityStampValidatorCallback.cs +++ b/identity-server/src/AspNetIdentity/SecurityStampValidatorCallback.cs @@ -18,15 +18,16 @@ public static class SecurityStampValidatorCallback /// Instance of session claims filter used to filter the claims from the ClaimsPrincipal to /// those that are session claims which are not persisted by ASP.NET Identity and would otherwise bee lost when the principal /// is updated. + /// The cancellation token. /// - public static async Task UpdatePrincipal(SecurityStampRefreshingPrincipalContext context, ISessionClaimsFilter sessionClaimsFilter) + public static async Task UpdatePrincipal(SecurityStampRefreshingPrincipalContext context, ISessionClaimsFilter sessionClaimsFilter, Ct ct) { if (context.NewPrincipal == null || !context.NewPrincipal.Identities.Any()) { return; } - var currentClaimsToKeep = await sessionClaimsFilter.FilterToSessionClaimsAsync(context); + var currentClaimsToKeep = await sessionClaimsFilter.FilterToSessionClaimsAsync(context, ct); var id = context.NewPrincipal.Identities.First(); id.AddClaims(currentClaimsToKeep); diff --git a/identity-server/src/Configuration.EntityFramework/ClientConfigurationStore.cs b/identity-server/src/Configuration.EntityFramework/ClientConfigurationStore.cs index fd733c96d..0319cdd61 100644 --- a/identity-server/src/Configuration.EntityFramework/ClientConfigurationStore.cs +++ b/identity-server/src/Configuration.EntityFramework/ClientConfigurationStore.cs @@ -5,7 +5,6 @@ using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Microsoft.Extensions.Logging; namespace Duende.IdentityServer.Configuration; @@ -21,11 +20,6 @@ public class ClientConfigurationStore : IClientConfigurationStore /// protected readonly IConfigurationDbContext DbContext; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -37,19 +31,17 @@ public class ClientConfigurationStore : IClientConfigurationStore /// public ClientConfigurationStore( IConfigurationDbContext dbContext, - ICancellationTokenProvider cancellationTokenProvider, ILogger logger) { DbContext = dbContext; - CancellationTokenProvider = cancellationTokenProvider; Logger = logger; } /// - public async Task AddAsync(Client client) + public async Task AddAsync(Client client, Ct ct) { Logger.LogDebug("Adding client {ClientId} to configuration store", client.ClientId); DbContext.Clients.Add(client.ToEntity()); - await DbContext.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await DbContext.SaveChangesAsync(ct); } } diff --git a/identity-server/src/Configuration.EntityFramework/DefaultCancellationTokenProvider.cs b/identity-server/src/Configuration.EntityFramework/DefaultCancellationTokenProvider.cs deleted file mode 100644 index 582bf8c3a..000000000 --- a/identity-server/src/Configuration.EntityFramework/DefaultCancellationTokenProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Duende Software. All rights reserved. -// See LICENSE in the project root for license information. - - -using Duende.IdentityServer.Services; -using Microsoft.AspNetCore.Http; - -namespace Duende.IdentityServer.Configuration.EntityFramework; - -/// -/// Provides cancellation tokens based on the incoming http request -/// -#pragma warning disable CA1812 // This class is not instantiated directly, but rather used by the DI container -internal sealed class DefaultCancellationTokenProvider : ICancellationTokenProvider -#pragma warning restore CA1812 -{ - private readonly IHttpContextAccessor _httpContextAccessor; - - /// - /// Constructor - /// - /// - public DefaultCancellationTokenProvider(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; - - /// - /// Provides access to the cancellation token from the http context - /// - public CancellationToken CancellationToken => _httpContextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None; -} diff --git a/identity-server/src/Configuration.EntityFramework/ServiceCollectionExtensions.cs b/identity-server/src/Configuration.EntityFramework/ServiceCollectionExtensions.cs index 61c9089a4..36d826fb0 100644 --- a/identity-server/src/Configuration.EntityFramework/ServiceCollectionExtensions.cs +++ b/identity-server/src/Configuration.EntityFramework/ServiceCollectionExtensions.cs @@ -2,7 +2,6 @@ // See LICENSE in the project root for license information. -using Duende.IdentityServer.Services; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -22,7 +21,6 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddClientConfigurationStore(this IdentityServerConfigurationBuilder builder) { - builder.Services.TryAddTransient(); builder.Services.TryAddSingleton(); return builder.Services.AddTransient(); } diff --git a/identity-server/src/Configuration/Endpoints/DynamicClientRegistrationEndpoint.cs b/identity-server/src/Configuration/Endpoints/DynamicClientRegistrationEndpoint.cs index fb22c894f..1da4ab7b2 100644 --- a/identity-server/src/Configuration/Endpoints/DynamicClientRegistrationEndpoint.cs +++ b/identity-server/src/Configuration/Endpoints/DynamicClientRegistrationEndpoint.cs @@ -47,7 +47,7 @@ public class DynamicClientRegistrationEndpoint // Check content type if (!HasCorrectContentType(httpContext.Request)) { - await _responseGenerator.WriteContentTypeError(httpContext); + await _responseGenerator.WriteContentTypeError(httpContext, httpContext.RequestAborted); return; } @@ -55,29 +55,29 @@ public class DynamicClientRegistrationEndpoint var request = await TryParseAsync(httpContext.Request); if (request == null) { - await _responseGenerator.WriteBadRequestError(httpContext); + await _responseGenerator.WriteBadRequestError(httpContext, httpContext.RequestAborted); return; } var dcrContext = new DynamicClientRegistrationContext(request, httpContext.User); // Validate request values - var validationResult = await _validator.ValidateAsync(dcrContext); + var validationResult = await _validator.ValidateAsync(dcrContext, httpContext.RequestAborted); if (validationResult is DynamicClientRegistrationError validationError) { - await _responseGenerator.WriteError(httpContext, validationError); + await _responseGenerator.WriteError(httpContext, validationError, httpContext.RequestAborted); } else { - var processingResult = await _processor.ProcessAsync(dcrContext); + var processingResult = await _processor.ProcessAsync(dcrContext, httpContext.RequestAborted); if (processingResult is DynamicClientRegistrationError processingFailure) { - await _responseGenerator.WriteError(httpContext, processingFailure); + await _responseGenerator.WriteError(httpContext, processingFailure, httpContext.RequestAborted); } else if (processingResult is DynamicClientRegistrationResponse success) { - await _responseGenerator.WriteSuccessResponse(httpContext, success); + await _responseGenerator.WriteSuccessResponse(httpContext, success, httpContext.RequestAborted); } else { diff --git a/identity-server/src/Configuration/RequestProcessing/DynamicClientRegistrationRequestProcessor.cs b/identity-server/src/Configuration/RequestProcessing/DynamicClientRegistrationRequestProcessor.cs index 55c41b4db..2371eff43 100644 --- a/identity-server/src/Configuration/RequestProcessing/DynamicClientRegistrationRequestProcessor.cs +++ b/identity-server/src/Configuration/RequestProcessing/DynamicClientRegistrationRequestProcessor.cs @@ -39,9 +39,9 @@ public class DynamicClientRegistrationRequestProcessor : IDynamicClientRegistrat /// public virtual async Task ProcessAsync( - DynamicClientRegistrationContext context) + DynamicClientRegistrationContext context, Ct ct) { - var clientIdResult = await AddClientId(context); + var clientIdResult = await AddClientId(context, ct); if (clientIdResult is DynamicClientRegistrationError clientIdFailure) { return clientIdFailure; @@ -64,7 +64,7 @@ public class DynamicClientRegistrationRequestProcessor : IDynamicClientRegistrat } } - await Store.AddAsync(context.Client); + await Store.AddAsync(context.Client, ct); return new DynamicClientRegistrationResponse(context.Request, context.Client) { @@ -133,9 +133,10 @@ public class DynamicClientRegistrationRequestProcessor : IDynamicClientRegistrat /// The dynamic client registration context, which /// includes the client model, the DCR request, and other contextual /// information. + /// The cancellation token. /// protected virtual Task AddClientId( - DynamicClientRegistrationContext context) + DynamicClientRegistrationContext context, Ct ct) { context.Client.ClientId = CryptoRandom.CreateUniqueId(); return StepResult.Success(); diff --git a/identity-server/src/Configuration/RequestProcessing/IDynamicClientRegistrationRequestProcessor.cs b/identity-server/src/Configuration/RequestProcessing/IDynamicClientRegistrationRequestProcessor.cs index c05bd12be..ed92d50d4 100644 --- a/identity-server/src/Configuration/RequestProcessing/IDynamicClientRegistrationRequestProcessor.cs +++ b/identity-server/src/Configuration/RequestProcessing/IDynamicClientRegistrationRequestProcessor.cs @@ -22,5 +22,5 @@ public interface IDynamicClientRegistrationRequestProcessor /// properties of the client that are not specified in the request, and /// storing the new client in the . /// - Task ProcessAsync(DynamicClientRegistrationContext validatedRequest); + Task ProcessAsync(DynamicClientRegistrationContext validatedRequest, Ct ct); } diff --git a/identity-server/src/Configuration/ResponseGeneration/DynamicClientRegistrationResponseGenerator.cs b/identity-server/src/Configuration/ResponseGeneration/DynamicClientRegistrationResponseGenerator.cs index 96840b064..dfe62d035 100644 --- a/identity-server/src/Configuration/ResponseGeneration/DynamicClientRegistrationResponseGenerator.cs +++ b/identity-server/src/Configuration/ResponseGeneration/DynamicClientRegistrationResponseGenerator.cs @@ -31,15 +31,15 @@ public class DynamicClientRegistrationResponseGenerator : IDynamicClientRegistra public DynamicClientRegistrationResponseGenerator(ILogger logger) => Logger = logger; /// - public virtual async Task WriteResponse(HttpContext context, int statusCode, T response) + public virtual async Task WriteResponse(HttpContext context, int statusCode, T response, Ct ct) where T : IDynamicClientRegistrationResponse { context.Response.StatusCode = statusCode; - await context.Response.WriteAsJsonAsync(response, SerializerOptions); + await context.Response.WriteAsJsonAsync(response, SerializerOptions, ct); } /// - public virtual Task WriteContentTypeError(HttpContext context) + public virtual Task WriteContentTypeError(HttpContext context, Ct ct) { Logger.LogDebug("Invalid content type in dynamic client registration request"); context.Response.StatusCode = StatusCodes.Status415UnsupportedMediaType; @@ -47,19 +47,20 @@ public class DynamicClientRegistrationResponseGenerator : IDynamicClientRegistra } /// - public virtual async Task WriteBadRequestError(HttpContext context) => + public virtual async Task WriteBadRequestError(HttpContext context, Ct ct) => await WriteResponse(context, StatusCodes.Status400BadRequest, new DynamicClientRegistrationError( DynamicClientRegistrationErrors.InvalidClientMetadata, - "malformed metadata document") + "malformed metadata document"), + ct ); /// - public virtual async Task WriteError(HttpContext context, DynamicClientRegistrationError error) => - await WriteResponse(context, StatusCodes.Status400BadRequest, error); + public virtual async Task WriteError(HttpContext context, DynamicClientRegistrationError error, Ct ct) => + await WriteResponse(context, StatusCodes.Status400BadRequest, error, ct); /// - public virtual async Task WriteSuccessResponse(HttpContext context, DynamicClientRegistrationResponse response) => - await WriteResponse(context, StatusCodes.Status201Created, response); + public virtual async Task WriteSuccessResponse(HttpContext context, DynamicClientRegistrationResponse response, Ct ct) => + await WriteResponse(context, StatusCodes.Status201Created, response, ct); } diff --git a/identity-server/src/Configuration/ResponseGeneration/IDynamicClientRegistrationResponseGenerator.cs b/identity-server/src/Configuration/ResponseGeneration/IDynamicClientRegistrationResponseGenerator.cs index 9ff850264..5b1e6b3b9 100644 --- a/identity-server/src/Configuration/ResponseGeneration/IDynamicClientRegistrationResponseGenerator.cs +++ b/identity-server/src/Configuration/ResponseGeneration/IDynamicClientRegistrationResponseGenerator.cs @@ -20,32 +20,37 @@ public interface IDynamicClientRegistrationResponseGenerator /// The HTTP context to write the response to. /// The status code to set in the response. /// The response object to write to the response. - Task WriteResponse(HttpContext context, int statusCode, T response) + /// The cancellation token. + Task WriteResponse(HttpContext context, int statusCode, T response, Ct ct) where T : IDynamicClientRegistrationResponse; /// /// Writes a content type error to the HTTP response. /// /// The HTTP context to write the error to. - Task WriteContentTypeError(HttpContext response); + /// The cancellation token. + Task WriteContentTypeError(HttpContext response, Ct ct); /// /// Writes a bad request error to the HTTP context. /// /// The HTTP context to write the error to. - Task WriteBadRequestError(HttpContext context); + /// The cancellation token. + Task WriteBadRequestError(HttpContext context, Ct ct); /// /// Writes a success response to the HTTP context. /// /// The HTTP context to write the response to. /// The dynamic client registration response. - Task WriteSuccessResponse(HttpContext context, DynamicClientRegistrationResponse response); + /// The cancellation token. + Task WriteSuccessResponse(HttpContext context, DynamicClientRegistrationResponse response, Ct ct); /// /// Writes a validation or processing step's error to the HTTP context. /// /// The HTTP context to write the error to. /// The dynamic client registration validation error. - Task WriteError(HttpContext context, DynamicClientRegistrationError error); + /// The cancellation token. + Task WriteError(HttpContext context, DynamicClientRegistrationError error, Ct ct); } diff --git a/identity-server/src/Configuration/Stores/IClientConfigurationStore.cs b/identity-server/src/Configuration/Stores/IClientConfigurationStore.cs index 38eb66768..5d8bc9839 100644 --- a/identity-server/src/Configuration/Stores/IClientConfigurationStore.cs +++ b/identity-server/src/Configuration/Stores/IClientConfigurationStore.cs @@ -15,5 +15,6 @@ public interface IClientConfigurationStore /// Adds a client to the configuration store. /// /// The client to add to the store - Task AddAsync(Client client); + /// The cancellation token. + Task AddAsync(Client client, Ct ct); } diff --git a/identity-server/src/Configuration/Stores/InMemoryClientConfigurationStore.cs b/identity-server/src/Configuration/Stores/InMemoryClientConfigurationStore.cs index f1d6b0704..2fbf14575 100644 --- a/identity-server/src/Configuration/Stores/InMemoryClientConfigurationStore.cs +++ b/identity-server/src/Configuration/Stores/InMemoryClientConfigurationStore.cs @@ -24,7 +24,7 @@ public class InMemoryClientConfigurationStore : IClientConfigurationStore /// registered in the DI system as an ICollection. public InMemoryClientConfigurationStore(ICollection clients) => _clients = clients; /// - public Task AddAsync(Client client) + public Task AddAsync(Client client, Ct _) { if (_clients.Select(c => c.ClientId).Contains(client.ClientId)) { diff --git a/identity-server/src/Configuration/Validation/DynamicClientRegistration/DynamicClientRegistrationValidator.cs b/identity-server/src/Configuration/Validation/DynamicClientRegistration/DynamicClientRegistrationValidator.cs index 3e38f8238..0f69ddf21 100644 --- a/identity-server/src/Configuration/Validation/DynamicClientRegistration/DynamicClientRegistrationValidator.cs +++ b/identity-server/src/Configuration/Validation/DynamicClientRegistration/DynamicClientRegistrationValidator.cs @@ -27,81 +27,81 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali ILogger logger) => Logger = logger; /// - public async Task ValidateAsync(DynamicClientRegistrationContext context) + public async Task ValidateAsync(DynamicClientRegistrationContext context, Ct ct) { - var result = await ValidateSoftwareStatementAsync(context); + var result = await ValidateSoftwareStatementAsync(context, ct); if (result is DynamicClientRegistrationError softwareStatementValidation) { return softwareStatementValidation; } - result = await SetGrantTypesAsync(context); + result = await SetGrantTypesAsync(context, ct); if (result is DynamicClientRegistrationError grantTypeValidation) { return grantTypeValidation; } - result = await SetRedirectUrisAsync(context); + result = await SetRedirectUrisAsync(context, ct); if (result is DynamicClientRegistrationError redirectUrisValidation) { return redirectUrisValidation; } - result = await SetScopesAsync(context); + result = await SetScopesAsync(context, ct); if (result is DynamicClientRegistrationError scopeValidation) { return scopeValidation; } - result = await SetSecretsAsync(context); + result = await SetSecretsAsync(context, ct); if (result is DynamicClientRegistrationError keySetValidation) { return keySetValidation; } - result = await SetClientNameAsync(context); + result = await SetClientNameAsync(context, ct); if (result is DynamicClientRegistrationError nameValidation) { return nameValidation; } - result = await SetLogoutParametersAsync(context); + result = await SetLogoutParametersAsync(context, ct); if (result is DynamicClientRegistrationError logoutValidation) { return logoutValidation; } - result = await SetMaxAgeAsync(context); + result = await SetMaxAgeAsync(context, ct); if (result is DynamicClientRegistrationError maxAgeValidation) { return maxAgeValidation; } - result = await SetUserInterfaceProperties(context); + result = await SetUserInterfaceProperties(context, ct); if (result is DynamicClientRegistrationError miscValidation) { return miscValidation; } - result = await SetPublicClientProperties(context); + result = await SetPublicClientProperties(context, ct); if (result is DynamicClientRegistrationError publicClientValidation) { return publicClientValidation; } - result = await SetAccessTokenProperties(context); + result = await SetAccessTokenProperties(context, ct); if (result is DynamicClientRegistrationError accessTokenValidation) { return accessTokenValidation; } - result = await SetIdTokenProperties(context); + result = await SetIdTokenProperties(context, ct); if (result is DynamicClientRegistrationError idTokenValidation) { return idTokenValidation; } - result = await SetServerSideSessionProperties(context); + result = await SetServerSideSessionProperties(context, ct); if (result is DynamicClientRegistrationError serverSideSessionValidation) { return serverSideSessionValidation; @@ -118,9 +118,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its allowed grant types set, /// the DCR request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetGrantTypesAsync(DynamicClientRegistrationContext context) + protected virtual Task SetGrantTypesAsync(DynamicClientRegistrationContext context, Ct ct) { if (context.Request.GrantTypes.Count == 0) { @@ -218,9 +219,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its redirect uri set, the DCR /// request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetRedirectUrisAsync(DynamicClientRegistrationContext context) + protected virtual Task SetRedirectUrisAsync(DynamicClientRegistrationContext context, Ct ct) { if (context.Client.AllowedGrantTypes.Contains(GrantType.AuthorizationCode)) { @@ -265,13 +267,14 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its scopes set, the DCR /// request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetScopesAsync(DynamicClientRegistrationContext context) + protected virtual Task SetScopesAsync(DynamicClientRegistrationContext context, Ct ct) { if (string.IsNullOrEmpty(context.Request.Scope)) { - return SetDefaultScopes(context); + return SetDefaultScopes(context, ct); } else { @@ -299,9 +302,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its scopes set, the DCR /// request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetDefaultScopes(DynamicClientRegistrationContext context) + protected virtual Task SetDefaultScopes(DynamicClientRegistrationContext context, Ct ct) { Logger.LogDebug("No scopes requested for dynamic client registration, and no default scope behavior implemented. To set default scopes, extend the DynamicClientRegistrationValidator and override the SetDefaultScopes method."); return StepResult.Success(); @@ -314,9 +318,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its secrets set, the DCR /// request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetSecretsAsync(DynamicClientRegistrationContext context) + protected virtual Task SetSecretsAsync(DynamicClientRegistrationContext context, Ct ct) { if (context.Request.JwksUri is not null && context.Request.Jwks is not null) { @@ -398,9 +403,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its name set, the DCR request, /// and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetClientNameAsync(DynamicClientRegistrationContext context) + protected virtual Task SetClientNameAsync(DynamicClientRegistrationContext context, Ct ct) { context.Client.ClientName = context.Request?.ClientName; return StepResult.Success(); @@ -417,9 +423,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its logout parameters set, the /// DCR request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetLogoutParametersAsync(DynamicClientRegistrationContext context) + protected virtual Task SetLogoutParametersAsync(DynamicClientRegistrationContext context, Ct ct) { context.Client.PostLogoutRedirectUris = context.Request.PostLogoutRedirectUris?.Select(uri => uri.ToString()).ToList() ?? new List(); context.Client.FrontChannelLogoutUri = context.Request.FrontChannelLogoutUri?.AbsoluteUri; @@ -438,9 +445,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its max age set, the DCR /// request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetMaxAgeAsync(DynamicClientRegistrationContext context) + protected virtual Task SetMaxAgeAsync(DynamicClientRegistrationContext context, Ct ct) { if (context.Request.DefaultMaxAge.HasValue) { @@ -465,9 +473,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// The dynamic client registration context, which /// includes the client model that is being built up, the DCR request, and /// other contextual information. + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task ValidateSoftwareStatementAsync(DynamicClientRegistrationContext context) => StepResult.Success(); + protected virtual Task ValidateSoftwareStatementAsync(DynamicClientRegistrationContext context, Ct ct) => StepResult.Success(); /// /// Validates the requested client parameters related to public clients and @@ -479,9 +488,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its public client properties /// set, the DCR request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetPublicClientProperties(DynamicClientRegistrationContext context) + protected virtual Task SetPublicClientProperties(DynamicClientRegistrationContext context, Ct ct) { context.Client.AllowedCorsOrigins = context.Request.AllowedCorsOrigins ?? new(); if (context.Request.RequireClientSecret.HasValue) @@ -506,9 +516,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its access token properties /// set, the DCR request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetAccessTokenProperties(DynamicClientRegistrationContext context) + protected virtual Task SetAccessTokenProperties(DynamicClientRegistrationContext context, Ct ct) { if (context.Request.AccessTokenType != null) { @@ -540,9 +551,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its id token properties set, /// the DCR request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetIdTokenProperties(DynamicClientRegistrationContext context) + protected virtual Task SetIdTokenProperties(DynamicClientRegistrationContext context, Ct ct) { if (context.Request.IdentityTokenLifetime.HasValue) { @@ -567,9 +579,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// includes the client model that will have its server side session /// properties set, the DCR request, and other contextual information. /// + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - protected virtual Task SetServerSideSessionProperties(DynamicClientRegistrationContext context) + protected virtual Task SetServerSideSessionProperties(DynamicClientRegistrationContext context, Ct ct) { if (context.Request.CoordinateLifetimeWithUserSession.HasValue) { @@ -587,11 +600,10 @@ public class DynamicClientRegistrationValidator : IDynamicClientRegistrationVali /// The dynamic client registration context, which /// includes the client model that will have miscellaneous properties set, /// the DCR request, and other contextual information. + /// The cancellation token. /// A task that returns an , which either /// represents that this step succeeded or failed. - /// A task that returns an , which either - /// represents that this step succeeded or failed. - protected virtual Task SetUserInterfaceProperties(DynamicClientRegistrationContext context) + protected virtual Task SetUserInterfaceProperties(DynamicClientRegistrationContext context, Ct ct) { // Misc Uris context.Client.LogoUri = context.Request.LogoUri?.ToString(); diff --git a/identity-server/src/Configuration/Validation/DynamicClientRegistration/IDynamicClientRegistrationValidator.cs b/identity-server/src/Configuration/Validation/DynamicClientRegistration/IDynamicClientRegistrationValidator.cs index 3ac77dbe1..cf8ae04c6 100644 --- a/identity-server/src/Configuration/Validation/DynamicClientRegistration/IDynamicClientRegistrationValidator.cs +++ b/identity-server/src/Configuration/Validation/DynamicClientRegistration/IDynamicClientRegistrationValidator.cs @@ -16,8 +16,9 @@ public interface IDynamicClientRegistrationValidator /// /// Contextual information about the DCR /// request. + /// The cancellation token. /// A task that returns an , which either /// indicates success or failure. - Task ValidateAsync(DynamicClientRegistrationContext context); + Task ValidateAsync(DynamicClientRegistrationContext context, Ct ct); } diff --git a/identity-server/src/EntityFramework.Storage/Extensions/DbContextExtensions.cs b/identity-server/src/EntityFramework.Storage/Extensions/DbContextExtensions.cs index e88dceb6f..c3cc37209 100644 --- a/identity-server/src/EntityFramework.Storage/Extensions/DbContextExtensions.cs +++ b/identity-server/src/EntityFramework.Storage/Extensions/DbContextExtensions.cs @@ -18,7 +18,7 @@ public static class DbContextExtensions /// /// Saves changes and handles concurrency exceptions. /// - public static async Task> SaveChangesWithConcurrencyCheckAsync(this IPersistedGrantDbContext context, ILogger logger, CT ct = default) + public static async Task> SaveChangesWithConcurrencyCheckAsync(this IPersistedGrantDbContext context, ILogger logger, Ct ct) where T : class { var list = new List(); diff --git a/identity-server/src/EntityFramework.Storage/Interfaces/IConfigurationDbContext.cs b/identity-server/src/EntityFramework.Storage/Interfaces/IConfigurationDbContext.cs index e4efd57fc..710f39681 100644 --- a/identity-server/src/EntityFramework.Storage/Interfaces/IConfigurationDbContext.cs +++ b/identity-server/src/EntityFramework.Storage/Interfaces/IConfigurationDbContext.cs @@ -67,7 +67,7 @@ public interface IConfigurationDbContext : IDisposable /// Saves the changes. /// /// - Task SaveChangesAsync(CT ct); + Task SaveChangesAsync(Ct ct); // this is here only because of this: https://github.com/DuendeSoftware/IdentityServer/issues/472 // and because Microsoft implements the old API explicitly: https://github.com/dotnet/aspnetcore/blob/v6.0.0-rc.2.21480.10/src/Identity/ApiAuthorization.IdentityServer/src/Data/ApiAuthorizationDbContext.cs @@ -76,5 +76,5 @@ public interface IConfigurationDbContext : IDisposable /// Saves the changes. /// /// - Task SaveChangesAsync() => SaveChangesAsync(CT.None); + Task SaveChangesAsync() => SaveChangesAsync(Ct.None); } diff --git a/identity-server/src/EntityFramework.Storage/Interfaces/IPersistedGrantDbContext.cs b/identity-server/src/EntityFramework.Storage/Interfaces/IPersistedGrantDbContext.cs index 9a530e666..7c4d2c51a 100644 --- a/identity-server/src/EntityFramework.Storage/Interfaces/IPersistedGrantDbContext.cs +++ b/identity-server/src/EntityFramework.Storage/Interfaces/IPersistedGrantDbContext.cs @@ -59,7 +59,7 @@ public interface IPersistedGrantDbContext : IDisposable /// Saves the changes. /// /// - Task SaveChangesAsync(CT ct); + Task SaveChangesAsync(Ct ct); // this is here only because of this: https://github.com/DuendeSoftware/IdentityServer/issues/472 // and because Microsoft implements the old API explicitly: https://github.com/dotnet/aspnetcore/blob/v6.0.0-rc.2.21480.10/src/Identity/ApiAuthorization.IdentityServer/src/Data/ApiAuthorizationDbContext.cs @@ -68,5 +68,5 @@ public interface IPersistedGrantDbContext : IDisposable /// Saves the changes. /// /// - Task SaveChangesAsync() => SaveChangesAsync(CT.None); + Task SaveChangesAsync() => SaveChangesAsync(Ct.None); } diff --git a/identity-server/src/EntityFramework.Storage/Stores/ClientStore.cs b/identity-server/src/EntityFramework.Storage/Stores/ClientStore.cs index e392ea216..316a62821 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/ClientStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/ClientStore.cs @@ -2,9 +2,9 @@ // See LICENSE in the project root for license information. +using System.Runtime.CompilerServices; using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.EntityFramework.Mappers; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -22,11 +22,6 @@ public class ClientStore : IClientStore /// protected readonly IConfigurationDbContext Context; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -37,23 +32,22 @@ public class ClientStore : IClientStore /// /// The context. /// The logger. - /// /// context - public ClientStore(IConfigurationDbContext context, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public ClientStore(IConfigurationDbContext context, ILogger logger) { Context = context ?? throw new ArgumentNullException(nameof(context)); Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } /// /// Finds a client by id /// /// The client id + /// The cancellation token. /// /// The client /// - public virtual async Task FindClientByIdAsync(string clientId) + public virtual async Task FindClientByIdAsync(string clientId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ClientStore.FindClientById"); activity?.SetTag(Tracing.Properties.ClientId, clientId); @@ -72,7 +66,7 @@ public class ClientStore : IClientStore .AsNoTracking() .AsSplitQuery(); - var client = (await query.ToArrayAsync(CancellationTokenProvider.CancellationToken)). + var client = (await query.ToArrayAsync(ct)). SingleOrDefault(x => x.ClientId == clientId); if (client == null) { @@ -87,7 +81,7 @@ public class ClientStore : IClientStore } /// - public virtual async IAsyncEnumerable GetAllClientsAsync() + public virtual async IAsyncEnumerable GetAllClientsAsync([EnumeratorCancellation] Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ClientStore.GetAllClients"); @@ -105,7 +99,7 @@ public class ClientStore : IClientStore .AsSplitQuery(); var clientCount = 0; - await foreach (var client in query.AsAsyncEnumerable().WithCancellation(CancellationTokenProvider.CancellationToken)) + await foreach (var client in query.AsAsyncEnumerable().WithCancellation(ct)) { clientCount++; yield return client.ToModel(); diff --git a/identity-server/src/EntityFramework.Storage/Stores/DeviceFlowStore.cs b/identity-server/src/EntityFramework.Storage/Stores/DeviceFlowStore.cs index 5da088a3b..f5718288f 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/DeviceFlowStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/DeviceFlowStore.cs @@ -6,7 +6,6 @@ using Duende.IdentityModel; using Duende.IdentityServer.EntityFramework.Entities; using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Stores.Serialization; using Microsoft.EntityFrameworkCore; @@ -30,11 +29,6 @@ public class DeviceFlowStore : IDeviceFlowStore /// protected readonly IPersistentGrantSerializer Serializer; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -46,46 +40,33 @@ public class DeviceFlowStore : IDeviceFlowStore /// The context. /// The serializer /// The logger. - /// public DeviceFlowStore( IPersistedGrantDbContext context, IPersistentGrantSerializer serializer, - ILogger logger, - ICancellationTokenProvider cancellationTokenProvider) + ILogger logger) { Context = context; Serializer = serializer; Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } - /// - /// Stores the device authorization request. - /// - /// The device code. - /// The user code. - /// The data. - /// - public virtual async Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data) + /// + public virtual async Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DeviceFlowStore.StoreDeviceAuthorization"); Context.DeviceFlowCodes.Add(ToEntity(data, deviceCode, userCode)); - await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await Context.SaveChangesAsync(ct); } - /// - /// Finds device authorization by user code. - /// - /// The user code. - /// - public virtual async Task FindByUserCodeAsync(string userCode) + /// + public virtual async Task FindByUserCodeAsync(string userCode, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DeviceFlowStore.FindByUserCode"); var deviceFlowCodes = (await Context.DeviceFlowCodes.AsNoTracking().Where(x => x.UserCode == userCode) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.UserCode == userCode); var model = ToModel(deviceFlowCodes?.Data); @@ -94,17 +75,13 @@ public class DeviceFlowStore : IDeviceFlowStore return model; } - /// - /// Finds device authorization by device code. - /// - /// The device code. - /// - public virtual async Task FindByDeviceCodeAsync(string deviceCode) + /// + public virtual async Task FindByDeviceCodeAsync(string deviceCode, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DeviceFlowStore.FindByDeviceCode"); var deviceFlowCodes = (await Context.DeviceFlowCodes.AsNoTracking().Where(x => x.DeviceCode == deviceCode) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.DeviceCode == deviceCode); var model = ToModel(deviceFlowCodes?.Data); @@ -113,18 +90,13 @@ public class DeviceFlowStore : IDeviceFlowStore return model; } - /// - /// Updates device authorization, searching by user code. - /// - /// The user code. - /// The data. - /// - public virtual async Task UpdateByUserCodeAsync(string userCode, DeviceCode data) + /// + public virtual async Task UpdateByUserCodeAsync(string userCode, DeviceCode data, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DeviceFlowStore.UpdateByUserCode"); var existing = (await Context.DeviceFlowCodes.Where(x => x.UserCode == userCode) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.UserCode == userCode); if (existing == null) { @@ -141,7 +113,7 @@ public class DeviceFlowStore : IDeviceFlowStore try { - await Context.SaveChangesAsync(); + await Context.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException ex) { @@ -149,17 +121,13 @@ public class DeviceFlowStore : IDeviceFlowStore } } - /// - /// Removes the device authorization, searching by device code. - /// - /// The device code. - /// - public virtual async Task RemoveByDeviceCodeAsync(string deviceCode) + /// + public virtual async Task RemoveByDeviceCodeAsync(string deviceCode, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DeviceFlowStore.RemoveByDeviceCode"); var deviceFlowCodes = (await Context.DeviceFlowCodes.Where(x => x.DeviceCode == deviceCode) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.DeviceCode == deviceCode); if (deviceFlowCodes != null) @@ -170,7 +138,7 @@ public class DeviceFlowStore : IDeviceFlowStore try { - await Context.SaveChangesAsync(); + await Context.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException ex) { diff --git a/identity-server/src/EntityFramework.Storage/Stores/IdentityProviderStore.cs b/identity-server/src/EntityFramework.Storage/Stores/IdentityProviderStore.cs index 4560b2d61..79f44d2a7 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/IdentityProviderStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/IdentityProviderStore.cs @@ -5,7 +5,6 @@ using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -23,11 +22,6 @@ public class IdentityProviderStore : IIdentityProviderStore /// protected readonly IConfigurationDbContext Context; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -38,17 +32,15 @@ public class IdentityProviderStore : IIdentityProviderStore /// /// The context. /// The logger. - /// /// context - public IdentityProviderStore(IConfigurationDbContext context, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public IdentityProviderStore(IConfigurationDbContext context, ILogger logger) { Context = context ?? throw new ArgumentNullException(nameof(context)); Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } /// - public async Task> GetAllSchemeNamesAsync() + public async Task> GetAllSchemeNamesAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("IdentityProviderStore.GetAllSchemeNames"); @@ -59,17 +51,17 @@ public class IdentityProviderStore : IIdentityProviderStore DisplayName = x.DisplayName }); - return await query.ToArrayAsync(CancellationTokenProvider.CancellationToken); + return await query.ToArrayAsync(ct); } /// - public async Task GetBySchemeAsync(string scheme) + public async Task GetBySchemeAsync(string scheme, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("IdentityProviderStore.GetByScheme"); activity?.SetTag(Tracing.Properties.Scheme, scheme); var idp = (await Context.IdentityProviders.AsNoTracking().Where(x => x.Scheme == scheme) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.Scheme == scheme); if (idp == null) { diff --git a/identity-server/src/EntityFramework.Storage/Stores/PersistedGrantStore.cs b/identity-server/src/EntityFramework.Storage/Stores/PersistedGrantStore.cs index bf6757357..91f9ad22f 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/PersistedGrantStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/PersistedGrantStore.cs @@ -6,7 +6,6 @@ using Duende.IdentityServer.EntityFramework.Entities; using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.Extensions; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -24,11 +23,6 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS /// protected readonly IPersistedGrantDbContext Context; - /// - /// The CancellationToken service. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -39,21 +33,19 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS /// /// The context. /// The logger. - /// - public PersistedGrantStore(IPersistedGrantDbContext context, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public PersistedGrantStore(IPersistedGrantDbContext context, ILogger logger) { Context = context; Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } /// - public virtual async Task StoreAsync(Duende.IdentityServer.Models.PersistedGrant token) + public virtual async Task StoreAsync(Duende.IdentityServer.Models.PersistedGrant token, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PersistedGrantStore.Store"); var existing = (await Context.PersistedGrants.Where(x => x.Key == token.Key) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.Key == token.Key); if (existing == null) { @@ -71,7 +63,7 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS try { - await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await Context.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException ex) { @@ -80,12 +72,12 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS } /// - public virtual async Task GetAsync(string key) + public virtual async Task GetAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PersistedGrantStore.Get"); var persistedGrant = (await Context.PersistedGrants.AsNoTracking().Where(x => x.Key == key) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.Key == key); var model = persistedGrant?.ToModel(); @@ -95,14 +87,14 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS } /// - public virtual async Task> GetAllAsync(PersistedGrantFilter filter) + public virtual async Task> GetAllAsync(PersistedGrantFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PersistedGrantStore.GetAll"); filter.Validate(); var persistedGrants = await Filter(Context.PersistedGrants.AsQueryable(), filter) - .ToArrayAsync(CancellationTokenProvider.CancellationToken); + .ToArrayAsync(ct); persistedGrants = Filter(persistedGrants.AsQueryable(), filter).ToArray(); var model = persistedGrants.Select(x => x.ToModel()); @@ -113,12 +105,12 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS } /// - public virtual async Task RemoveAsync(string key) + public virtual async Task RemoveAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PersistedGrantStore.Remove"); var persistedGrant = (await Context.PersistedGrants.Where(x => x.Key == key) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.Key == key); if (persistedGrant != null) { @@ -128,7 +120,7 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS try { - await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await Context.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException ex) { @@ -142,14 +134,14 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS } /// - public virtual async Task RemoveAllAsync(PersistedGrantFilter filter) + public virtual async Task RemoveAllAsync(PersistedGrantFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PersistedGrantStore.RemoveAll"); filter.Validate(); var persistedGrants = await Filter(Context.PersistedGrants.AsQueryable(), filter) - .ToArrayAsync(CancellationTokenProvider.CancellationToken); + .ToArrayAsync(ct); persistedGrants = Filter(persistedGrants.AsQueryable(), filter).ToArray(); Logger.LogDebug("removing {persistedGrantCount} persisted grants from database for {@filter}", persistedGrants.Length, filter); @@ -158,7 +150,7 @@ public class PersistedGrantStore : Duende.IdentityServer.Stores.IPersistedGrantS try { - await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await Context.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException ex) { diff --git a/identity-server/src/EntityFramework.Storage/Stores/PushedAuthorizationRequestStore.cs b/identity-server/src/EntityFramework.Storage/Stores/PushedAuthorizationRequestStore.cs index 47e21b14b..ea1172067 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/PushedAuthorizationRequestStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/PushedAuthorizationRequestStore.cs @@ -4,7 +4,6 @@ using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.EntityFramework.Mappers; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -19,11 +18,6 @@ public class PushedAuthorizationRequestStore : IPushedAuthorizationRequestStore /// protected readonly IPersistedGrantDbContext Context; - /// - /// The CancellationToken service. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -34,22 +28,20 @@ public class PushedAuthorizationRequestStore : IPushedAuthorizationRequestStore /// /// The context. /// The logger. - /// - public PushedAuthorizationRequestStore(IPersistedGrantDbContext context, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public PushedAuthorizationRequestStore(IPersistedGrantDbContext context, ILogger logger) { Context = context; Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } /// - public async Task ConsumeByHashAsync(string referenceValueHash) + public async Task ConsumeByHashAsync(string referenceValueHash, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PersistedGrantStore.Remove"); Logger.LogDebug("removing {referenceValueHash} pushed authorization from database", referenceValueHash); var numDeleted = await Context.PushedAuthorizationRequests .Where(par => par.ReferenceValueHash == referenceValueHash) - .ExecuteDeleteAsync(CancellationTokenProvider.CancellationToken); + .ExecuteDeleteAsync(ct); if (numDeleted != 1) { Logger.LogWarning("attempted to remove {referenceValueHash} pushed authorization request because it was consumed, but no records were actually deleted.", referenceValueHash); @@ -57,13 +49,13 @@ public class PushedAuthorizationRequestStore : IPushedAuthorizationRequestStore } /// - public virtual async Task GetByHashAsync(string referenceValueHash) + public virtual async Task GetByHashAsync(string referenceValueHash, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PushedAuthorizationRequestStore.Get"); var par = (await Context.PushedAuthorizationRequests .AsNoTracking().Where(x => x.ReferenceValueHash == referenceValueHash) - .ToArrayAsync(CancellationTokenProvider.CancellationToken)) + .ToArrayAsync(ct)) .SingleOrDefault(x => x.ReferenceValueHash == referenceValueHash); var model = par?.ToModel(); @@ -74,14 +66,14 @@ public class PushedAuthorizationRequestStore : IPushedAuthorizationRequestStore /// - public virtual async Task StoreAsync(Models.PushedAuthorizationRequest par) + public virtual async Task StoreAsync(Models.PushedAuthorizationRequest par, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("PushedAuthorizationStore.Store"); Context.PushedAuthorizationRequests.Add(par.ToEntity()); try { - await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await Context.SaveChangesAsync(ct); } // REVIEW - Is this exception possible, since we don't try to load (and then update) an existing entity? // I think it isn't, but what happens if we somehow two calls to StoreAsync with the same PAR are made? diff --git a/identity-server/src/EntityFramework.Storage/Stores/ResourceStore.cs b/identity-server/src/EntityFramework.Storage/Stores/ResourceStore.cs index c1b0012f4..be024e192 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/ResourceStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/ResourceStore.cs @@ -6,7 +6,6 @@ using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -24,11 +23,6 @@ public class ResourceStore : IResourceStore /// protected readonly IConfigurationDbContext Context; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -39,21 +33,20 @@ public class ResourceStore : IResourceStore /// /// The context. /// The logger. - /// /// context - public ResourceStore(IConfigurationDbContext context, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public ResourceStore(IConfigurationDbContext context, ILogger logger) { Context = context ?? throw new ArgumentNullException(nameof(context)); Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } /// /// Finds the API resources by name. /// /// The names. + /// The cancellation token. /// - public virtual async Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames) + public virtual async Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ResourceStore.FindApiResourcesByName"); activity?.SetTag(Tracing.Properties.ApiResourceNames, apiResourceNames.ToSpaceSeparatedString()); @@ -72,7 +65,7 @@ public class ResourceStore : IResourceStore .Include(x => x.Properties) .AsNoTracking(); - var result = (await apis.ToArrayAsync(CancellationTokenProvider.CancellationToken)) + var result = (await apis.ToArrayAsync(ct)) .Where(x => apiResourceNames.Contains(x.Name)) .Select(x => x.ToModel()).ToArray(); @@ -92,8 +85,9 @@ public class ResourceStore : IResourceStore /// Gets API resources by scope name. /// /// + /// The cancellation token. /// - public virtual async Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames) + public virtual async Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ResourceStore.FindApiResourcesByScopeName"); activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString()); @@ -112,7 +106,7 @@ public class ResourceStore : IResourceStore .Include(x => x.Properties) .AsNoTracking(); - var results = (await apis.ToArrayAsync(CancellationTokenProvider.CancellationToken)) + var results = (await apis.ToArrayAsync(ct)) .Where(api => api.Scopes.Any(x => names.Contains(x.Scope))); var models = results.Select(x => x.ToModel()).ToArray(); @@ -125,8 +119,9 @@ public class ResourceStore : IResourceStore /// Gets identity resources by scope name. /// /// + /// The cancellation token. /// - public virtual async Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames) + public virtual async Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ResourceStore.FindIdentityResourcesByScopeName"); activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString()); @@ -143,7 +138,7 @@ public class ResourceStore : IResourceStore .Include(x => x.Properties) .AsNoTracking(); - var results = (await resources.ToArrayAsync(CancellationTokenProvider.CancellationToken)) + var results = (await resources.ToArrayAsync(ct)) .Where(x => scopes.Contains(x.Name)); Logger.LogDebug("Found {scopes} identity scopes in database", results.Select(x => x.Name)); @@ -155,8 +150,9 @@ public class ResourceStore : IResourceStore /// Gets scopes by scope name. /// /// + /// The cancellation token. /// - public virtual async Task> FindApiScopesByNameAsync(IEnumerable scopeNames) + public virtual async Task> FindApiScopesByNameAsync(IEnumerable scopeNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ResourceStore.FindApiScopesByName"); activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString()); @@ -173,7 +169,7 @@ public class ResourceStore : IResourceStore .Include(x => x.Properties) .AsNoTracking(); - var results = (await resources.ToArrayAsync(CancellationTokenProvider.CancellationToken)) + var results = (await resources.ToArrayAsync(ct)) .Where(x => scopes.Contains(x.Name)); Logger.LogDebug("Found {scopes} scopes in database", results.Select(x => x.Name)); @@ -185,7 +181,7 @@ public class ResourceStore : IResourceStore /// Gets all resources. /// /// - public virtual async Task GetAllResourcesAsync() + public virtual async Task GetAllResourcesAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ResourceStore.GetAllResources"); @@ -207,9 +203,9 @@ public class ResourceStore : IResourceStore .AsNoTracking(); var result = new Resources( - (await identity.ToArrayAsync(CancellationTokenProvider.CancellationToken)).Select(x => x.ToModel()), - (await apis.ToArrayAsync(CancellationTokenProvider.CancellationToken)).Select(x => x.ToModel()), - (await scopes.ToArrayAsync(CancellationTokenProvider.CancellationToken)).Select(x => x.ToModel()) + (await identity.ToArrayAsync(ct)).Select(x => x.ToModel()), + (await apis.ToArrayAsync(ct)).Select(x => x.ToModel()), + (await scopes.ToArrayAsync(ct)).Select(x => x.ToModel()) ); Logger.LogDebug("Found {scopes} as all scopes, and {apis} as API resources", diff --git a/identity-server/src/EntityFramework.Storage/Stores/ServerSideSessionStore.cs b/identity-server/src/EntityFramework.Storage/Stores/ServerSideSessionStore.cs index 872439991..d0ba58394 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/ServerSideSessionStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/ServerSideSessionStore.cs @@ -5,7 +5,6 @@ using Duende.IdentityServer.EntityFramework.Extensions; using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -23,11 +22,6 @@ public class ServerSideSessionStore : IServerSideSessionStore /// protected readonly IPersistedGrantDbContext Context; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -38,24 +32,20 @@ public class ServerSideSessionStore : IServerSideSessionStore /// /// The context. /// The logger. - /// /// context - public ServerSideSessionStore(IPersistedGrantDbContext context, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public ServerSideSessionStore(IPersistedGrantDbContext context, ILogger logger) { Context = context ?? throw new ArgumentNullException(nameof(context)); Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } /// - public virtual async Task CreateSessionAsync(ServerSideSession session, CT ct = default) + public virtual async Task CreateSessionAsync(ServerSideSession session, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.CreateSession"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - var entity = new Entities.ServerSideSession { Key = session.Key, @@ -82,12 +72,10 @@ public class ServerSideSessionStore : IServerSideSessionStore } /// - public virtual async Task GetSessionAsync(string key, CT ct = default) + public virtual async Task GetSessionAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.GetSession"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - var entity = (await Context.ServerSideSessions.AsNoTracking().Where(x => x.Key == key) .ToArrayAsync(ct)) .SingleOrDefault(x => x.Key == key); @@ -115,12 +103,10 @@ public class ServerSideSessionStore : IServerSideSessionStore } /// - public virtual async Task UpdateSessionAsync(ServerSideSession session, CT ct = default) + public virtual async Task UpdateSessionAsync(ServerSideSession session, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.UpdateSession"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - var entity = (await Context.ServerSideSessions.Where(x => x.Key == session.Key) .ToArrayAsync(ct)) .SingleOrDefault(x => x.Key == session.Key); @@ -152,12 +138,10 @@ public class ServerSideSessionStore : IServerSideSessionStore } /// - public virtual async Task DeleteSessionAsync(string key, CT ct = default) + public virtual async Task DeleteSessionAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.DeleteSession"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - var entity = (await Context.ServerSideSessions.Where(x => x.Key == key) .ToArrayAsync(ct)) .SingleOrDefault(x => x.Key == key); @@ -184,12 +168,10 @@ public class ServerSideSessionStore : IServerSideSessionStore /// - public virtual async Task> GetSessionsAsync(SessionFilter filter, CT ct = default) + public virtual async Task> GetSessionsAsync(SessionFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.GetSessions"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - filter.Validate(); var entities = await Filter(Context.ServerSideSessions.AsNoTracking().AsQueryable(), filter) @@ -215,12 +197,10 @@ public class ServerSideSessionStore : IServerSideSessionStore } /// - public virtual async Task DeleteSessionsAsync(SessionFilter filter, CT ct = default) + public virtual async Task DeleteSessionsAsync(SessionFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.DeleteSessions"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - filter.Validate(); var entities = await Filter(Context.ServerSideSessions.AsQueryable(), filter) @@ -256,12 +236,10 @@ public class ServerSideSessionStore : IServerSideSessionStore /// - public virtual async Task> GetAndRemoveExpiredSessionsAsync(int count, CT ct = default) + public virtual async Task> GetAndRemoveExpiredSessionsAsync(int count, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.GetAndRemoveExpiredSessions"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - var entities = await Context.ServerSideSessions .Where(x => x.Expires < DateTime.UtcNow) .OrderBy(x => x.Id) @@ -295,12 +273,10 @@ public class ServerSideSessionStore : IServerSideSessionStore } /// - public virtual async Task> QuerySessionsAsync(SessionQuery filter = null, CT ct = default) + public virtual async Task> QuerySessionsAsync(Ct ct, SessionQuery filter = null) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideSessionStore.QuerySessions"); - ct = ct == CT.None ? CancellationTokenProvider.CancellationToken : ct; - // it's possible that this implementation could have been done differently (e.g. use the page number for the token) // but it was done deliberately in such a way to allow document databases to mimic the logic // and omit features not supported (such as total count, total pages, and current page) @@ -338,7 +314,7 @@ public class ServerSideSessionStore : IServerSideSessionStore // we need to start over and re-query from the beginning. filter.ResultsToken = null; filter.RequestPriorResults = false; - return await QuerySessionsAsync(filter, ct); + return await QuerySessionsAsync(ct, filter); } } else @@ -401,7 +377,7 @@ public class ServerSideSessionStore : IServerSideSessionStore Ticket = entity.Data, }).ToArray(); - private static async Task NextPage(IQueryable query, int last, SessionPaginationContext pagination, CT ct) + private static async Task NextPage(IQueryable query, int last, SessionPaginationContext pagination, Ct ct) { pagination.Items = await query.OrderBy(x => x.Id) // if lastResultsId is zero, then this will just start at beginning @@ -429,7 +405,7 @@ public class ServerSideSessionStore : IServerSideSessionStore } } - private static async Task PreviousPage(IQueryable query, int first, SessionPaginationContext pagination, CT ct) + private static async Task PreviousPage(IQueryable query, int first, SessionPaginationContext pagination, Ct ct) { // sets query at the prior record from the last results, but in reverse order pagination.Items = await query.OrderByDescending(x => x.Id) diff --git a/identity-server/src/EntityFramework.Storage/Stores/SigningKeyStore.cs b/identity-server/src/EntityFramework.Storage/Stores/SigningKeyStore.cs index 318d7a6cd..fb574cf24 100644 --- a/identity-server/src/EntityFramework.Storage/Stores/SigningKeyStore.cs +++ b/identity-server/src/EntityFramework.Storage/Stores/SigningKeyStore.cs @@ -5,7 +5,6 @@ using Duende.IdentityServer.EntityFramework.Entities; using Duende.IdentityServer.EntityFramework.Interfaces; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -25,11 +24,6 @@ public class SigningKeyStore : ISigningKeyStore /// protected readonly IPersistedGrantDbContext Context; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -40,26 +34,25 @@ public class SigningKeyStore : ISigningKeyStore /// /// The context. /// The logger. - /// /// context - public SigningKeyStore(IPersistedGrantDbContext context, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public SigningKeyStore(IPersistedGrantDbContext context, ILogger logger) { Context = context ?? throw new ArgumentNullException(nameof(context)); Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } /// /// Loads all keys from store. /// + /// The cancellation token. /// - public async Task> LoadKeysAsync() + public async Task> LoadKeysAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("SigningKeyStore.LoadKeys"); var entities = await Context.Keys.Where(x => x.Use == Use) .AsNoTracking() - .ToArrayAsync(CancellationTokenProvider.CancellationToken); + .ToArrayAsync(ct); return entities.Select(key => new SerializedKey { Id = key.Id, @@ -76,8 +69,9 @@ public class SigningKeyStore : ISigningKeyStore /// Persists new key in store. /// /// + /// The cancellation token. /// - public async Task StoreKeyAsync(SerializedKey key) + public async Task StoreKeyAsync(SerializedKey key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("SigningKeyStore.StoreKey"); @@ -93,26 +87,27 @@ public class SigningKeyStore : ISigningKeyStore IsX509Certificate = key.IsX509Certificate }; Context.Keys.Add(entity); - await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await Context.SaveChangesAsync(ct); } /// /// Deletes key from storage. /// /// + /// The cancellation token. /// - public async Task DeleteKeyAsync(string id) + public async Task DeleteKeyAsync(string id, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("SigningKeyStore.DeleteKey"); var item = await Context.Keys.Where(x => x.Use == Use && x.Id == id) - .FirstOrDefaultAsync(CancellationTokenProvider.CancellationToken); + .FirstOrDefaultAsync(ct); if (item != null) { try { Context.Keys.Remove(item); - await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken); + await Context.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException ex) { diff --git a/identity-server/src/EntityFramework.Storage/TokenCleanup/IOperationalStoreNotification.cs b/identity-server/src/EntityFramework.Storage/TokenCleanup/IOperationalStoreNotification.cs index c8489fe3a..c14088dac 100644 --- a/identity-server/src/EntityFramework.Storage/TokenCleanup/IOperationalStoreNotification.cs +++ b/identity-server/src/EntityFramework.Storage/TokenCleanup/IOperationalStoreNotification.cs @@ -17,15 +17,15 @@ public interface IOperationalStoreNotification /// Notification for persisted grants being removed. /// /// - /// + /// The cancellation token. /// - Task PersistedGrantsRemovedAsync(IEnumerable persistedGrants, CT ct = default); + Task PersistedGrantsRemovedAsync(IEnumerable persistedGrants, Ct ct); /// /// Notification for device codes being removed. /// - /// - /// + /// The device codes being removed. + /// The cancellation token. /// - Task DeviceCodesRemovedAsync(IEnumerable deviceCodes, CT ct = default); + Task DeviceCodesRemovedAsync(IEnumerable deviceCodes, Ct ct); } diff --git a/identity-server/src/EntityFramework.Storage/TokenCleanup/ITokenCleanupService.cs b/identity-server/src/EntityFramework.Storage/TokenCleanup/ITokenCleanupService.cs index 5b5fc8a6e..f5223bcb8 100644 --- a/identity-server/src/EntityFramework.Storage/TokenCleanup/ITokenCleanupService.cs +++ b/identity-server/src/EntityFramework.Storage/TokenCleanup/ITokenCleanupService.cs @@ -16,8 +16,7 @@ public interface ITokenCleanupService /// Removes expired persisted grants, expired device codes, and optionally /// consumed persisted grants from the stores. /// - /// A token that propagates notification - /// that the cleanup operation should be canceled. + /// The cancellation token. /// - Task CleanupGrantsAsync(CT ct = default); + Task CleanupGrantsAsync(Ct ct); } diff --git a/identity-server/src/EntityFramework.Storage/TokenCleanup/TokenCleanupService.cs b/identity-server/src/EntityFramework.Storage/TokenCleanup/TokenCleanupService.cs index 0a0e0d4dc..d64acd443 100644 --- a/identity-server/src/EntityFramework.Storage/TokenCleanup/TokenCleanupService.cs +++ b/identity-server/src/EntityFramework.Storage/TokenCleanup/TokenCleanupService.cs @@ -43,7 +43,7 @@ public class TokenCleanupService : ITokenCleanupService } /// - public async Task CleanupGrantsAsync(CT ct = default) + public async Task CleanupGrantsAsync(Ct ct) { try { @@ -63,7 +63,7 @@ public class TokenCleanupService : ITokenCleanupService /// Removes the stale persisted grants. /// /// - protected virtual async Task RemoveGrantsAsync(CT ct = default) + protected virtual async Task RemoveGrantsAsync(Ct ct) { await RemoveExpiredPersistedGrantsAsync(ct); if (_options.RemoveConsumedTokens) @@ -76,7 +76,7 @@ public class TokenCleanupService : ITokenCleanupService /// Removes the expired persisted grants. /// /// - protected virtual async Task RemoveExpiredPersistedGrantsAsync(CT ct = default) + protected virtual async Task RemoveExpiredPersistedGrantsAsync(Ct ct) { var found = int.MaxValue; @@ -145,7 +145,7 @@ public class TokenCleanupService : ITokenCleanupService /// Removes the consumed persisted grants. /// /// - protected virtual async Task RemoveConsumedPersistedGrantsAsync(CT ct = default) + protected virtual async Task RemoveConsumedPersistedGrantsAsync(Ct ct) { var found = int.MaxValue; @@ -208,7 +208,7 @@ public class TokenCleanupService : ITokenCleanupService /// Removes the stale device codes. /// /// - protected virtual async Task RemoveDeviceCodesAsync(CT ct = default) + protected virtual async Task RemoveDeviceCodesAsync(Ct ct) { var found = int.MaxValue; @@ -264,7 +264,7 @@ public class TokenCleanupService : ITokenCleanupService /// /// Removes stale pushed authorization requests. /// - protected virtual async Task RemovePushedAuthorizationRequestsAsync(CT ct = default) + protected virtual async Task RemovePushedAuthorizationRequestsAsync(Ct ct) { var found = int.MaxValue; diff --git a/identity-server/src/EntityFramework/Services/CorsPolicyService.cs b/identity-server/src/EntityFramework/Services/CorsPolicyService.cs index 8df28b106..5d80c7725 100644 --- a/identity-server/src/EntityFramework/Services/CorsPolicyService.cs +++ b/identity-server/src/EntityFramework/Services/CorsPolicyService.cs @@ -20,11 +20,6 @@ public class CorsPolicyService : ICorsPolicyService /// protected readonly IConfigurationDbContext DbContext; - /// - /// The CancellationToken provider. - /// - protected readonly ICancellationTokenProvider CancellationTokenProvider; - /// /// The logger. /// @@ -36,21 +31,15 @@ public class CorsPolicyService : ICorsPolicyService /// /// The DbContext /// The logger. - /// /// context - public CorsPolicyService(IConfigurationDbContext dbContext, ILogger logger, ICancellationTokenProvider cancellationTokenProvider) + public CorsPolicyService(IConfigurationDbContext dbContext, ILogger logger) { DbContext = dbContext; Logger = logger; - CancellationTokenProvider = cancellationTokenProvider; } - /// - /// Determines whether origin is allowed. - /// - /// The origin. - /// - public async Task IsOriginAllowedAsync(string origin) + /// + public async Task IsOriginAllowedAsync(string origin, Ct ct) { #pragma warning disable CA1308 // this has historically been normalized to lower case and RFC 3986 instructs to normalize to lowercase origin = origin.ToLowerInvariant(); @@ -60,7 +49,7 @@ public class CorsPolicyService : ICorsPolicyService where o.Origin == origin select o; - var isAllowed = await query.AnyAsync(CancellationTokenProvider.CancellationToken); + var isAllowed = await query.AnyAsync(ct); Logger.LogDebug("Origin {origin} is allowed: {originAllowed}", origin, isAllowed); diff --git a/identity-server/src/EntityFramework/TokenCleanupHost.cs b/identity-server/src/EntityFramework/TokenCleanupHost.cs index 60153bb24..4431a4aca 100644 --- a/identity-server/src/EntityFramework/TokenCleanupHost.cs +++ b/identity-server/src/EntityFramework/TokenCleanupHost.cs @@ -38,7 +38,7 @@ public class TokenCleanupHost : IHostedService /// /// Starts the token cleanup polling. /// - public Task StartAsync(CT ct) + public Task StartAsync(Ct ct) { if (_options.EnableTokenCleanup) { @@ -60,7 +60,7 @@ public class TokenCleanupHost : IHostedService /// /// Stops the token cleanup polling. /// - public async Task StopAsync(CT ct) + public async Task StopAsync(Ct ct) { if (_options.EnableTokenCleanup) { @@ -76,7 +76,7 @@ public class TokenCleanupHost : IHostedService } } - private async Task StartInternalAsync(CT ct) + private async Task StartInternalAsync(Ct ct) { // Start the first run at a random interval. var delay = _options.FuzzTokenCleanupStart @@ -121,7 +121,7 @@ public class TokenCleanupHost : IHostedService } } - private async Task RemoveExpiredGrantsAsync(CT ct = default) + private async Task RemoveExpiredGrantsAsync(Ct ct) { try { diff --git a/identity-server/src/IdentityServer.ConformanceReport/IdentityServerClientStore.cs b/identity-server/src/IdentityServer.ConformanceReport/IdentityServerClientStore.cs index 15f36ea9e..b29e71015 100644 --- a/identity-server/src/IdentityServer.ConformanceReport/IdentityServerClientStore.cs +++ b/identity-server/src/IdentityServer.ConformanceReport/IdentityServerClientStore.cs @@ -14,10 +14,10 @@ internal sealed class IdentityServerClientStore(IClientStore clientStore) : ICon #pragma warning restore CA1812 { public async Task> GetAllClientsAsync( - CancellationToken ct = default) + CancellationToken ct) { var clients = new List(); - await foreach (var client in clientStore.GetAllClientsAsync().WithCancellation(ct)) + await foreach (var client in clientStore.GetAllClientsAsync(ct)) { clients.Add(client.ToConformanceReportClient()); } diff --git a/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Additional.cs b/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Additional.cs index d88e18730..265c9a373 100644 --- a/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Additional.cs +++ b/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Additional.cs @@ -454,7 +454,7 @@ public static class IdentityServerBuilderExtensionsAdditional var httpClient = httpClientFactory.CreateClient(name); var loggerFactory = s.GetRequiredService(); - return new DefaultBackChannelLogoutHttpClient(httpClient, loggerFactory, new NoneCancellationTokenProvider()); + return new DefaultBackChannelLogoutHttpClient(httpClient, loggerFactory); }); return httpBuilder; @@ -491,7 +491,7 @@ public static class IdentityServerBuilderExtensionsAdditional var loggerFactory = s.GetRequiredService(); var options = s.GetRequiredService(); - return new DefaultJwtRequestUriHttpClient(httpClient, options, loggerFactory, new NoneCancellationTokenProvider()); + return new DefaultJwtRequestUriHttpClient(httpClient, options, loggerFactory); }); return httpBuilder; diff --git a/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Core.cs b/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Core.cs index f524c677e..d595bc7fd 100644 --- a/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Core.cs +++ b/identity-server/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Core.cs @@ -252,7 +252,6 @@ public static class IdentityServerBuilderExtensionsCore /// public static IIdentityServerBuilder AddPluggableServices(this IIdentityServerBuilder builder) { - builder.Services.TryAddTransient(); builder.Services.TryAddTransient(); builder.Services.TryAddTransient(); builder.Services.TryAddTransient(); diff --git a/identity-server/src/IdentityServer/Endpoints/AuthorizeCallbackEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/AuthorizeCallbackEndpoint.cs index 51dca4cc2..1d19bfb14 100644 --- a/identity-server/src/IdentityServer/Endpoints/AuthorizeCallbackEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/AuthorizeCallbackEndpoint.cs @@ -45,9 +45,9 @@ internal class AuthorizeCallbackEndpoint : AuthorizeEndpointBase Logger.LogDebug("Start authorize callback request"); var parameters = context.Request.Query.AsNameValueCollection(); - var user = await UserSession.GetUserAsync(); + var user = await UserSession.GetUserAsync(context.RequestAborted); - var result = await ProcessAuthorizeRequestAsync(parameters, user, true); + var result = await ProcessAuthorizeRequestAsync(parameters, user, context.RequestAborted, true); Logger.LogTrace("End Authorize Request. Result type: {0}", result?.GetType().ToString() ?? "-none-"); diff --git a/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpoint.cs index 7805bb32e..6bbf817a4 100644 --- a/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpoint.cs @@ -59,8 +59,8 @@ internal class AuthorizeEndpoint : AuthorizeEndpointBase return new StatusCodeResult(HttpStatusCode.MethodNotAllowed); } - var user = await UserSession.GetUserAsync(); - var result = await ProcessAuthorizeRequestAsync(values, user); + var user = await UserSession.GetUserAsync(context.RequestAborted); + var result = await ProcessAuthorizeRequestAsync(values, user, context.RequestAborted); Logger.LogTrace("End authorize request. result type: {0}", result?.GetType().ToString() ?? "-none-"); diff --git a/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpointBase.cs b/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpointBase.cs index 7b486a998..cbffae7cb 100644 --- a/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpointBase.cs +++ b/identity-server/src/IdentityServer/Endpoints/AuthorizeEndpointBase.cs @@ -63,7 +63,7 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler public abstract Task ProcessAsync(HttpContext context); - internal async Task ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, bool checkConsentResponse = false) + internal async Task ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, Ct ct, bool checkConsentResponse = false) { if (user != null) { @@ -77,19 +77,20 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler if (checkConsentResponse && _authorizationParametersMessageStore != null) { var messageStoreId = parameters[Constants.AuthorizationParamsStore.MessageStoreIdParameterName]; - var entry = await _authorizationParametersMessageStore.ReadAsync(messageStoreId); + var entry = await _authorizationParametersMessageStore.ReadAsync(messageStoreId, ct); parameters = entry?.Data.FromFullDictionary() ?? new NameValueCollection(); - await _authorizationParametersMessageStore.DeleteAsync(messageStoreId); + await _authorizationParametersMessageStore.DeleteAsync(messageStoreId, ct); } // validate request - var result = await _validator.ValidateAsync(parameters, user); + var result = await _validator.ValidateAsync(parameters, ct, user); if (result.IsError) { return await CreateErrorResultAsync( "Request validation failed", + ct, result.ValidatedRequest, result.Error, result.ErrorDescription); @@ -105,11 +106,11 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler { var consentRequest = new ConsentRequest(result.ValidatedRequest.Raw, user?.GetSubjectId()); consentRequestId = consentRequest.Id; - consent = await _consentResponseStore.ReadAsync(consentRequestId); + consent = await _consentResponseStore.ReadAsync(consentRequestId, ct); if (consent != null && consent.Data == null) { - return await CreateErrorResultAsync("consent message is missing data", result.ValidatedRequest); + return await CreateErrorResultAsync("consent message is missing data", ct, result.ValidatedRequest); } } @@ -117,10 +118,10 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler LogRequest(request); // determine user interaction - var interactionResult = await _interactionGenerator.ProcessInteractionAsync(request, consent?.Data); + var interactionResult = await _interactionGenerator.ProcessInteractionAsync(request, consent?.Data, ct); if (interactionResult.ResponseType == InteractionResponseType.Error) { - return await CreateErrorResultAsync("Interaction generator error", request, interactionResult.Error, interactionResult.ErrorDescription, false); + return await CreateErrorResultAsync("Interaction generator error", ct, request, interactionResult.Error, interactionResult.ErrorDescription, false); } if (interactionResult.ResponseType == InteractionResponseType.UserInteraction) @@ -143,9 +144,9 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler } } - var response = await _authorizeResponseGenerator.CreateResponseAsync(request); + var response = await _authorizeResponseGenerator.CreateResponseAsync(request, ct); - await RaiseResponseEventAsync(response); + await RaiseResponseEventAsync(response, ct); LogResponse(response); @@ -155,13 +156,14 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler { if (consentRequestId != null) { - await _consentResponseStore.DeleteAsync(consentRequestId); + await _consentResponseStore.DeleteAsync(consentRequestId, ct); } } } protected async Task CreateErrorResultAsync( string logMessage, + Ct ct, ValidatedAuthorizeRequest request = null, string error = OidcConstants.AuthorizeErrors.ServerError, string errorDescription = null, @@ -181,7 +183,7 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler } // TODO: should we raise a token failure event for all errors to the authorize endpoint? - await RaiseFailureEventAsync(request, error, errorDescription); + await RaiseFailureEventAsync(request, error, errorDescription, ct); return new AuthorizeResult(new AuthorizeResponse { @@ -223,17 +225,17 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler } } - private Task RaiseFailureEventAsync(ValidatedAuthorizeRequest request, string error, string errorDescription) + private Task RaiseFailureEventAsync(ValidatedAuthorizeRequest request, string error, string errorDescription, Ct ct) { Telemetry.Metrics.TokenIssuedFailure( request.ClientId, request.GrantType, request.AuthorizeRequestType, error); - return _events.RaiseAsync(new TokenIssuedFailureEvent(request, error, errorDescription)); + return _events.RaiseAsync(new TokenIssuedFailureEvent(request, error, errorDescription), ct); } - private Task RaiseResponseEventAsync(AuthorizeResponse response) + private Task RaiseResponseEventAsync(AuthorizeResponse response, Ct ct) { if (!response.IsError) { @@ -247,9 +249,9 @@ internal abstract class AuthorizeEndpointBase : IEndpointHandler false, ProofType.None, response.IdentityToken.IsPresent()); - return _events.RaiseAsync(new TokenIssuedSuccessEvent(response)); + return _events.RaiseAsync(new TokenIssuedSuccessEvent(response), ct); } - return RaiseFailureEventAsync(response.Request, response.Error, response.ErrorDescription); + return RaiseFailureEventAsync(response.Request, response.Error, response.ErrorDescription, ct); } } diff --git a/identity-server/src/IdentityServer/Endpoints/BackchannelAuthenticationEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/BackchannelAuthenticationEndpoint.cs index aea0cc79b..0ddfe604c 100644 --- a/identity-server/src/IdentityServer/Endpoints/BackchannelAuthenticationEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/BackchannelAuthenticationEndpoint.cs @@ -70,7 +70,7 @@ internal class BackchannelAuthenticationEndpoint : IEndpointHandler _logger.LogDebug("Start backchannel authentication request."); // validate client - var clientResult = await _clientValidator.ValidateAsync(context); + var clientResult = await _clientValidator.ValidateAsync(context, context.RequestAborted); if (clientResult.IsError) { var error = clientResult.Error ?? OidcConstants.BackchannelAuthenticationRequestErrors.InvalidClient; @@ -80,22 +80,22 @@ internal class BackchannelAuthenticationEndpoint : IEndpointHandler } // validate request - var form = (await context.Request.ReadFormAsync()).AsNameValueCollection(); + var form = (await context.Request.ReadFormAsync(context.RequestAborted)).AsNameValueCollection(); _logger.LogTrace("Calling into backchannel authentication request validator: {type}", _requestValidator.GetType().FullName); - var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult); + var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult, context.RequestAborted); if (requestResult.IsError) { - await _events.RaiseAsync(new BackchannelAuthenticationFailureEvent(requestResult)); + await _events.RaiseAsync(new BackchannelAuthenticationFailureEvent(requestResult), context.RequestAborted); Telemetry.Metrics.BackChannelAuthenticationFailure(clientResult.Client?.ClientId, requestResult.Error); return Error(requestResult.Error, requestResult.ErrorDescription); } // create response _logger.LogTrace("Calling into backchannel authentication request response generator: {type}", _responseGenerator.GetType().FullName); - var response = await _responseGenerator.ProcessAsync(requestResult); + var response = await _responseGenerator.ProcessAsync(requestResult, context.RequestAborted); - await _events.RaiseAsync(new BackchannelAuthenticationSuccessEvent(requestResult)); + await _events.RaiseAsync(new BackchannelAuthenticationSuccessEvent(requestResult), context.RequestAborted); Telemetry.Metrics.BackChannelAuthentication(clientResult.Client.ClientId); LogResponse(response, requestResult); diff --git a/identity-server/src/IdentityServer/Endpoints/BaseDiscoveryEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/BaseDiscoveryEndpoint.cs index db79e5fe1..d44a39d71 100644 --- a/identity-server/src/IdentityServer/Endpoints/BaseDiscoveryEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/BaseDiscoveryEndpoint.cs @@ -25,20 +25,20 @@ internal abstract class BaseDiscoveryEndpoint( var distributedCache = context.RequestServices.GetRequiredService(); if (distributedCache is not null) { - return await GetCachedDiscoveryDocument(distributedCache, baseUrl, issuerUri); + return await GetCachedDiscoveryDocument(distributedCache, baseUrl, issuerUri, context.RequestAborted); } // fall through to default implementation if there is no cache provider registered } - var response = await ResponseGenerator.CreateDiscoveryDocumentAsync(baseUrl, issuerUri); + var response = await ResponseGenerator.CreateDiscoveryDocumentAsync(baseUrl, issuerUri, context.RequestAborted); return new DiscoveryDocumentResult(response, Options.Discovery.ResponseCacheInterval); } private async Task GetCachedDiscoveryDocument(IDistributedCache cache, string baseUrl, - string issuerUri) + string issuerUri, Ct ct) { var key = $"discoveryDocument/{baseUrl}/{issuerUri}"; - var json = await cache.GetStringAsync(key); + var json = await cache.GetStringAsync(key, ct); if (json is not null) { @@ -49,7 +49,7 @@ internal abstract class BaseDiscoveryEndpoint( } var entries = - await ResponseGenerator.CreateDiscoveryDocumentAsync(baseUrl, issuerUri); + await ResponseGenerator.CreateDiscoveryDocumentAsync(baseUrl, issuerUri, ct); var expirationFromNow = Options.Preview.DiscoveryDocumentCacheDuration; @@ -62,7 +62,7 @@ internal abstract class BaseDiscoveryEndpoint( await cache.SetStringAsync(key, result.Json, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = expirationFromNow, - }); + }, ct); return result; } diff --git a/identity-server/src/IdentityServer/Endpoints/DeviceAuthorizationEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/DeviceAuthorizationEndpoint.cs index b9a417819..a92cc3b83 100644 --- a/identity-server/src/IdentityServer/Endpoints/DeviceAuthorizationEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/DeviceAuthorizationEndpoint.cs @@ -79,7 +79,7 @@ internal class DeviceAuthorizationEndpoint : IEndpointHandler _logger.LogDebug("Start device authorize request."); // validate client - var clientResult = await _clientValidator.ValidateAsync(context); + var clientResult = await _clientValidator.ValidateAsync(context, context.RequestAborted); if (clientResult.IsError) { var error = clientResult.Error ?? OidcConstants.TokenErrors.InvalidClient; @@ -88,21 +88,21 @@ internal class DeviceAuthorizationEndpoint : IEndpointHandler } // validate request - var form = (await context.Request.ReadFormAsync()).AsNameValueCollection(); - var requestResult = await _requestValidator.ValidateAsync(form, clientResult); + var form = (await context.Request.ReadFormAsync(context.RequestAborted)).AsNameValueCollection(); + var requestResult = await _requestValidator.ValidateAsync(form, clientResult, context.RequestAborted); if (requestResult.IsError) { - await _events.RaiseAsync(new DeviceAuthorizationFailureEvent(requestResult)); + await _events.RaiseAsync(new DeviceAuthorizationFailureEvent(requestResult), context.RequestAborted); Telemetry.Metrics.DeviceAuthenticationFailure(clientResult.Client.ClientId, requestResult.Error); return Error(requestResult.Error, requestResult.ErrorDescription); } // create response _logger.LogTrace("Calling into device authorize response generator: {type}", _responseGenerator.GetType().FullName); - var response = await _responseGenerator.ProcessAsync(requestResult, _urls.BaseUrl); + var response = await _responseGenerator.ProcessAsync(requestResult, _urls.BaseUrl, context.RequestAborted); - await _events.RaiseAsync(new DeviceAuthorizationSuccessEvent(response, requestResult)); + await _events.RaiseAsync(new DeviceAuthorizationSuccessEvent(response, requestResult), context.RequestAborted); Telemetry.Metrics.DeviceAuthentication(clientResult.Client.ClientId); // return result diff --git a/identity-server/src/IdentityServer/Endpoints/DiscoveryEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/DiscoveryEndpoint.cs index a44a9bbee..1941aaf64 100644 --- a/identity-server/src/IdentityServer/Endpoints/DiscoveryEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/DiscoveryEndpoint.cs @@ -56,7 +56,7 @@ internal class DiscoveryEndpoint : BaseDiscoveryEndpoint, IEndpointHandler } var baseUrl = _urls.BaseUrl; - var issuerUri = await _issuerNameService.GetCurrentAsync(); + var issuerUri = await _issuerNameService.GetCurrentAsync(context.RequestAborted); // generate response _logger.LogTrace("Calling into discovery response generator: {type}", ResponseGenerator.GetType().FullName); diff --git a/identity-server/src/IdentityServer/Endpoints/DiscoveryKeyEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/DiscoveryKeyEndpoint.cs index 9a2cfc1be..143030e6d 100644 --- a/identity-server/src/IdentityServer/Endpoints/DiscoveryKeyEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/DiscoveryKeyEndpoint.cs @@ -53,7 +53,7 @@ internal class DiscoveryKeyEndpoint : IEndpointHandler // generate response _logger.LogTrace("Calling into discovery response generator: {type}", _responseGenerator.GetType().FullName); - var response = await _responseGenerator.CreateJwkDocumentAsync(); + var response = await _responseGenerator.CreateJwkDocumentAsync(context.RequestAborted); return new JsonWebKeysResult(response, _options.Discovery.ResponseCacheInterval); } diff --git a/identity-server/src/IdentityServer/Endpoints/EndSessionCallbackEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/EndSessionCallbackEndpoint.cs index 5dbff422f..524ebf613 100644 --- a/identity-server/src/IdentityServer/Endpoints/EndSessionCallbackEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/EndSessionCallbackEndpoint.cs @@ -38,7 +38,7 @@ internal class EndSessionCallbackEndpoint : IEndpointHandler _logger.LogDebug("Processing signout callback request"); var parameters = context.Request.Query.AsNameValueCollection(); - var result = await _endSessionRequestValidator.ValidateCallbackAsync(parameters); + var result = await _endSessionRequestValidator.ValidateCallbackAsync(parameters, context.RequestAborted); if (!result.IsError) { diff --git a/identity-server/src/IdentityServer/Endpoints/EndSessionEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/EndSessionEndpoint.cs index efc8900ec..fa0a569cd 100644 --- a/identity-server/src/IdentityServer/Endpoints/EndSessionEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/EndSessionEndpoint.cs @@ -59,7 +59,7 @@ internal class EndSessionEndpoint : IEndpointHandler } else if (HttpMethods.IsPost(context.Request.Method)) { - parameters = (await context.Request.ReadFormAsync()).AsNameValueCollection(); + parameters = (await context.Request.ReadFormAsync(context.RequestAborted)).AsNameValueCollection(); } else { @@ -67,11 +67,11 @@ internal class EndSessionEndpoint : IEndpointHandler return new StatusCodeResult(HttpStatusCode.MethodNotAllowed); } - var user = await _userSession.GetUserAsync(); + var user = await _userSession.GetUserAsync(context.RequestAborted); _logger.LogDebug("Processing signout request for {subjectId}", user?.GetSubjectId() ?? "anonymous"); - var result = await _endSessionRequestValidator.ValidateAsync(parameters, user); + var result = await _endSessionRequestValidator.ValidateAsync(parameters, user, context.RequestAborted); if (result.IsError) { diff --git a/identity-server/src/IdentityServer/Endpoints/IntrospectionEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/IntrospectionEndpoint.cs index a5923fa3c..f4de469ab 100644 --- a/identity-server/src/IdentityServer/Endpoints/IntrospectionEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/IntrospectionEndpoint.cs @@ -100,10 +100,10 @@ internal class IntrospectionEndpoint : IEndpointHandler ApiResource api = null; Client client = null; - var apiResult = await _apiSecretValidator.ValidateAsync(context); + var apiResult = await _apiSecretValidator.ValidateAsync(context, context.RequestAborted); if (apiResult.IsError) { - clientResult = await _clientValidator.ValidateAsync(context); + clientResult = await _clientValidator.ValidateAsync(context, context.RequestAborted); if (clientResult.IsError) { _logger.LogError("Unauthorized call introspection endpoint. aborting."); @@ -123,12 +123,12 @@ internal class IntrospectionEndpoint : IEndpointHandler var callerName = api?.Name ?? client.ClientId; - var body = await context.Request.ReadFormAsync(); + var body = await context.Request.ReadFormAsync(context.RequestAborted); if (body == null) { _logger.LogError("Malformed request body. aborting."); const string error = "Malformed request body"; - await _events.RaiseAsync(new TokenIntrospectionFailureEvent(callerName, error)); + await _events.RaiseAsync(new TokenIntrospectionFailureEvent(callerName, error), context.RequestAborted); Telemetry.Metrics.IntrospectionFailure(callerName, error); return new StatusCodeResult(HttpStatusCode.BadRequest); } @@ -141,18 +141,18 @@ internal class IntrospectionEndpoint : IEndpointHandler Api = api, Client = client, }; - var validationResult = await _requestValidator.ValidateAsync(validationRequest); + var validationResult = await _requestValidator.ValidateAsync(validationRequest, context.RequestAborted); if (validationResult.IsError) { LogFailure(validationResult.Error, callerName); - await _events.RaiseAsync(new TokenIntrospectionFailureEvent(callerName, validationResult.Error)); + await _events.RaiseAsync(new TokenIntrospectionFailureEvent(callerName, validationResult.Error), context.RequestAborted); Telemetry.Metrics.IntrospectionFailure(callerName, validationResult.Error); return new BadRequestResult(validationResult.Error); } // response generation _logger.LogTrace("Calling into introspection response generator: {type}", _responseGenerator.GetType().FullName); - var response = await _responseGenerator.ProcessAsync(validationResult); + var response = await _responseGenerator.ProcessAsync(validationResult, context.RequestAborted); // render result LogSuccess(validationResult.IsActive, callerName); diff --git a/identity-server/src/IdentityServer/Endpoints/OAuthMetadataEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/OAuthMetadataEndpoint.cs index f00fd120a..8db1fb715 100644 --- a/identity-server/src/IdentityServer/Endpoints/OAuthMetadataEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/OAuthMetadataEndpoint.cs @@ -51,7 +51,7 @@ internal class OAuthMetadataEndpoint( } context.Request.Path.StartsWithSegments("/.well-known/oauth-authorization-server", StringComparison.OrdinalIgnoreCase, out var issuerSubPath); - if (!await issuerPathValidator.ValidateAsync(issuerSubPath)) + if (!await issuerPathValidator.ValidateAsync(issuerSubPath, context.RequestAborted)) { logger.LogDebug("Request for OAuth discovery document contains invalid sub-path. Returning 404"); return new StatusCodeResult(HttpStatusCode.NotFound); @@ -62,7 +62,7 @@ internal class OAuthMetadataEndpoint( serverUrls.BasePath = issuerSubPath; } - var issuerUri = await issuerNameService.GetCurrentAsync(); + var issuerUri = await issuerNameService.GetCurrentAsync(context.RequestAborted); var baseUrl = serverUrls.BaseUrl; if (!issuerUri.Equals($"{context.Request.Scheme}://{context.Request.Host}{issuerSubPath}", StringComparison.Ordinal)) diff --git a/identity-server/src/IdentityServer/Endpoints/PushedAuthorizationEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/PushedAuthorizationEndpoint.cs index 32a198982..fb0d22e92 100644 --- a/identity-server/src/IdentityServer/Endpoints/PushedAuthorizationEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/PushedAuthorizationEndpoint.cs @@ -56,7 +56,7 @@ internal class PushedAuthorizationEndpoint : IEndpointHandler NameValueCollection values; if (HttpMethods.IsPost(context.Request.Method)) { - var form = await context.Request.ReadFormAsync(); + var form = await context.Request.ReadFormAsync(context.RequestAborted); values = form.AsNameValueCollection(); } else @@ -65,7 +65,7 @@ internal class PushedAuthorizationEndpoint : IEndpointHandler } // Authenticate Client - var client = await _clientValidator.ValidateAsync(context); + var client = await _clientValidator.ValidateAsync(context, context.RequestAborted); if (client.IsError) { return CreateErrorResult( @@ -87,11 +87,11 @@ internal class PushedAuthorizationEndpoint : IEndpointHandler validationContext.DPoPProofToken = dpopHeader.First(); //Note: if the client authenticated with mTLS, we need to know to properly validate the htu of the DPoP proof token - validationContext.ClientCertificate = await context.Connection.GetClientCertificateAsync(); + validationContext.ClientCertificate = await context.Connection.GetClientCertificateAsync(context.RequestAborted); } // Perform validations specific to PAR, as well as validation of the pushed parameters - var parValidationResult = await _parValidator.ValidateAsync(validationContext); + var parValidationResult = await _parValidator.ValidateAsync(validationContext, context.RequestAborted); if (parValidationResult.IsError) { return CreateErrorResult( @@ -110,7 +110,7 @@ internal class PushedAuthorizationEndpoint : IEndpointHandler throw new InvalidOperationException("Invalid PAR validation result: success without a validated request"); } - var response = await _responseGenerator.CreateResponseAsync(parValidationResult.ValidatedRequest); + var response = await _responseGenerator.CreateResponseAsync(parValidationResult.ValidatedRequest, context.RequestAborted); switch (response) { diff --git a/identity-server/src/IdentityServer/Endpoints/Results/AuthorizeInteractionPageResult.cs b/identity-server/src/IdentityServer/Endpoints/Results/AuthorizeInteractionPageResult.cs index 4b3757250..fd7cfcced 100644 --- a/identity-server/src/IdentityServer/Endpoints/Results/AuthorizeInteractionPageResult.cs +++ b/identity-server/src/IdentityServer/Endpoints/Results/AuthorizeInteractionPageResult.cs @@ -84,7 +84,7 @@ internal class AuthorizeInteractionPageHttpWriter : IHttpResponseWriter>(result.Request.ToOptimizedFullDictionary()); #pragma warning restore CS0618 // Type or member is obsolete - var id = await _authorizationParametersMessageStore.WriteAsync(msg); + var id = await _authorizationParametersMessageStore.WriteAsync(msg, context.RequestAborted); returnUrl = returnUrl.AddQueryString(Constants.AuthorizationParamsStore.MessageStoreIdParameterName, id); } else @@ -122,7 +122,7 @@ internal class AuthorizeInteractionPageHttpWriter : IHttpResponseWriter /// public async Task WriteHttpResponse(AuthorizeResult result, HttpContext context) { - await ConsumePushedAuthorizationRequest(result); + await ConsumePushedAuthorizationRequest(result, context.RequestAborted); if (result.Response.IsError) { @@ -80,12 +80,12 @@ public class AuthorizeHttpWriter : IHttpResponseWriter } } - private async Task ConsumePushedAuthorizationRequest(AuthorizeResult result) + private async Task ConsumePushedAuthorizationRequest(AuthorizeResult result, Ct ct) { var referenceValue = result.Response?.Request?.PushedAuthorizationReferenceValue; if (referenceValue.IsPresent()) { - await _pushedAuthorizationService.ConsumeAsync(referenceValue); + await _pushedAuthorizationService.ConsumeAsync(referenceValue, ct); } } @@ -119,7 +119,7 @@ public class AuthorizeHttpWriter : IHttpResponseWriter { // success response -- track client authorization for sign-out //_logger.LogDebug("Adding client {0} to client list cookie for subject {1}", request.ClientId, request.Subject.GetSubjectId()); - await _userSession.AddClientIdAsync(response.Request.ClientId); + await _userSession.AddClientIdAsync(response.Request.ClientId, context.RequestAborted); } await RenderAuthorizeResponseAsync(response, context); @@ -221,13 +221,13 @@ public class AuthorizeHttpWriter : IHttpResponseWriter var uiLocalesService = context.RequestServices.GetService(); if (uiLocalesService != null) { - await uiLocalesService.StoreUiLocalesForRedirectAsync(response.Request?.UiLocales); + await uiLocalesService.StoreUiLocalesForRedirectAsync(response.Request?.UiLocales, context.RequestAborted); } var errorModel = await CreateErrorMessage(response, context); var message = new Message(errorModel, _timeProvider.GetUtcNow().UtcDateTime); - var id = await _errorMessageStore.WriteAsync(message); + var id = await _errorMessageStore.WriteAsync(message, context.RequestAborted); var errorUrl = _options.UserInteraction.ErrorUrl; diff --git a/identity-server/src/IdentityServer/Endpoints/Results/EndSessionResult.cs b/identity-server/src/IdentityServer/Endpoints/Results/EndSessionResult.cs index 2a98f5132..e05b65d69 100644 --- a/identity-server/src/IdentityServer/Endpoints/Results/EndSessionResult.cs +++ b/identity-server/src/IdentityServer/Endpoints/Results/EndSessionResult.cs @@ -66,7 +66,7 @@ internal class EndSessionHttpWriter : IHttpResponseWriter if (logoutMessage.ContainsPayload) { var msg = new Message(logoutMessage, _timeProvider.GetUtcNow().UtcDateTime); - id = await _logoutMessageStore.WriteAsync(msg); + id = await _logoutMessageStore.WriteAsync(msg, context.RequestAborted); } } @@ -75,7 +75,7 @@ internal class EndSessionHttpWriter : IHttpResponseWriter if (redirect.IsLocalUrl()) { redirect = _urls.GetIdentityServerRelativeUrl(redirect); - await _localesService.StoreUiLocalesForRedirectAsync(result.Result.ValidatedRequest?.UiLocales); + await _localesService.StoreUiLocalesForRedirectAsync(result.Result.ValidatedRequest?.UiLocales, context.RequestAborted); } if (id != null) diff --git a/identity-server/src/IdentityServer/Endpoints/Results/IntrospectionResult.cs b/identity-server/src/IdentityServer/Endpoints/Results/IntrospectionResult.cs index 7a13027ab..77f6023c8 100644 --- a/identity-server/src/IdentityServer/Endpoints/Results/IntrospectionResult.cs +++ b/identity-server/src/IdentityServer/Endpoints/Results/IntrospectionResult.cs @@ -79,12 +79,12 @@ internal class IntrospectionHttpWriter(IIssuerNameService issuerNameService, ITo var token = new Token { Type = JwtClaimTypes.JwtTypes.IntrospectionJwtResponse, - Issuer = await issuerNameService.GetCurrentAsync(), + Issuer = await issuerNameService.GetCurrentAsync(context.RequestAborted), Audiences = [result.CallerName], CreationTime = DateTime.UtcNow, Claims = [new Claim("token_introspection", ObjectSerializer.ToString(result.Entries), IdentityServerConstants.ClaimValueTypes.Json)] }; - var jwt = await tokenCreationService.CreateTokenAsync(token); + var jwt = await tokenCreationService.CreateTokenAsync(token, context.RequestAborted); await context.Response.WriteAsync(jwt); } diff --git a/identity-server/src/IdentityServer/Endpoints/TokenEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/TokenEndpoint.cs index b64739c83..37389638d 100644 --- a/identity-server/src/IdentityServer/Endpoints/TokenEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/TokenEndpoint.cs @@ -88,7 +88,7 @@ internal class TokenEndpoint : IEndpointHandler _logger.LogDebug("Start token request."); // validate client - var clientResult = await _clientValidator.ValidateAsync(context); + var clientResult = await _clientValidator.ValidateAsync(context, context.RequestAborted); if (clientResult.IsError) { var errorMsg = clientResult.Error ?? OidcConstants.TokenErrors.InvalidClient; @@ -97,7 +97,7 @@ internal class TokenEndpoint : IEndpointHandler } // validate request - var form = (await context.Request.ReadFormAsync()).AsNameValueCollection(); + var form = (await context.Request.ReadFormAsync(context.RequestAborted)).AsNameValueCollection(); _logger.LogTrace("Calling into token request validator: {type}", _requestValidator.GetType().FullName); var requestContext = new TokenRequestValidationContext @@ -113,7 +113,7 @@ internal class TokenEndpoint : IEndpointHandler return error; } - var requestResult = await _requestValidator.ValidateRequestAsync(requestContext); + var requestResult = await _requestValidator.ValidateRequestAsync(requestContext, context.RequestAborted); if (requestResult.IsError) { // Note: this is an expected case in the normal DPoP flow and is not a real failure event. @@ -124,7 +124,7 @@ internal class TokenEndpoint : IEndpointHandler } else { - await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult)); + await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult), context.RequestAborted); } Telemetry.Metrics.TokenIssuedFailure( @@ -136,9 +136,9 @@ internal class TokenEndpoint : IEndpointHandler // create response _logger.LogTrace("Calling into token request response generator: {type}", _responseGenerator.GetType().FullName); - var response = await _responseGenerator.ProcessAsync(requestResult); + var response = await _responseGenerator.ProcessAsync(requestResult, context.RequestAborted); - await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult)); + await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult), context.RequestAborted); Telemetry.Metrics.TokenIssued(clientResult.Client.ClientId, requestResult.ValidatedRequest.GrantType, null, response.AccessToken.IsPresent(), response.AccessTokenType.IsPresent() ? requestResult.ValidatedRequest.AccessTokenType : null, response.RefreshToken.IsPresent(), @@ -153,7 +153,7 @@ internal class TokenEndpoint : IEndpointHandler private async Task TryReadProofTokens(HttpContext context, TokenRequestValidationContext tokenRequest) { // mTLS cert - tokenRequest.ClientCertificate = await context.Connection.GetClientCertificateAsync(); + tokenRequest.ClientCertificate = await context.Connection.GetClientCertificateAsync(context.RequestAborted); // DPoP header value if (context.Request.Headers.TryGetValue(OidcConstants.HttpHeaders.DPoP, out var dpopHeader)) diff --git a/identity-server/src/IdentityServer/Endpoints/TokenRevocationEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/TokenRevocationEndpoint.cs index d36073bf7..28fb6da67 100644 --- a/identity-server/src/IdentityServer/Endpoints/TokenRevocationEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/TokenRevocationEndpoint.cs @@ -89,7 +89,7 @@ internal class TokenRevocationEndpoint : IEndpointHandler _logger.LogDebug("Start revocation request."); // validate client - var clientValidationResult = await _clientValidator.ValidateAsync(context); + var clientValidationResult = await _clientValidator.ValidateAsync(context, context.RequestAborted); if (clientValidationResult.IsError) { var error = clientValidationResult.Error ?? OidcConstants.TokenErrors.InvalidClient; @@ -100,10 +100,10 @@ internal class TokenRevocationEndpoint : IEndpointHandler _logger.LogTrace("Client validation successful"); // validate the token request - var form = (await context.Request.ReadFormAsync()).AsNameValueCollection(); + var form = (await context.Request.ReadFormAsync(context.RequestAborted)).AsNameValueCollection(); _logger.LogTrace("Calling into token revocation request validator: {type}", _requestValidator.GetType().FullName); - var requestValidationResult = await _requestValidator.ValidateRequestAsync(form, clientValidationResult.Client); + var requestValidationResult = await _requestValidator.ValidateRequestAsync(form, clientValidationResult.Client, context.RequestAborted); if (requestValidationResult.IsError) { @@ -112,13 +112,13 @@ internal class TokenRevocationEndpoint : IEndpointHandler } _logger.LogTrace("Calling into token revocation response generator: {type}", _responseGenerator.GetType().FullName); - var response = await _responseGenerator.ProcessAsync(requestValidationResult); + var response = await _responseGenerator.ProcessAsync(requestValidationResult, context.RequestAborted); if (response.Success) { _logger.LogInformation("Token revocation complete"); Telemetry.Metrics.Revocation(clientValidationResult.Client.ClientId); - await _events.RaiseAsync(new TokenRevokedSuccessEvent(requestValidationResult, requestValidationResult.Client)); + await _events.RaiseAsync(new TokenRevokedSuccessEvent(requestValidationResult, requestValidationResult.Client), context.RequestAborted); } else { diff --git a/identity-server/src/IdentityServer/Endpoints/UserInfoEndpoint.cs b/identity-server/src/IdentityServer/Endpoints/UserInfoEndpoint.cs index d875b38b9..ec888f615 100644 --- a/identity-server/src/IdentityServer/Endpoints/UserInfoEndpoint.cs +++ b/identity-server/src/IdentityServer/Endpoints/UserInfoEndpoint.cs @@ -79,7 +79,7 @@ internal class UserInfoEndpoint : IEndpointHandler // validate the request _logger.LogTrace("Calling into userinfo request validator: {type}", _requestValidator.GetType().FullName); - var validationResult = await _requestValidator.ValidateRequestAsync(tokenUsageResult.Token); + var validationResult = await _requestValidator.ValidateRequestAsync(tokenUsageResult.Token, context.RequestAborted); if (validationResult.IsError) { @@ -89,7 +89,7 @@ internal class UserInfoEndpoint : IEndpointHandler // generate response _logger.LogTrace("Calling into userinfo response generator: {type}", _responseGenerator.GetType().FullName); - var response = await _responseGenerator.ProcessAsync(validationResult); + var response = await _responseGenerator.ProcessAsync(validationResult, context.RequestAborted); _logger.LogDebug("End userinfo request"); return new UserInfoResult(response); diff --git a/identity-server/src/IdentityServer/Extensions/HttpContextExtensions.cs b/identity-server/src/IdentityServer/Extensions/HttpContextExtensions.cs index 1ea488f12..235feb016 100644 --- a/identity-server/src/IdentityServer/Extensions/HttpContextExtensions.cs +++ b/identity-server/src/IdentityServer/Extensions/HttpContextExtensions.cs @@ -51,7 +51,7 @@ public static class HttpContextExtensions internal static async Task GetIdentityServerSignoutFrameCallbackUrlAsync(this HttpContext context, LogoutMessage logoutMessage = null) { var userSession = context.RequestServices.GetRequiredService(); - var user = await userSession.GetUserAsync(); + var user = await userSession.GetUserAsync(context.RequestAborted); var currentSubId = user?.GetSubjectId(); LogoutNotificationContext endSessionMsg = null; @@ -64,7 +64,7 @@ public static class HttpContextExtensions // check if current user is same, since we might have new clients (albeit unlikely) if (currentSubId == logoutMessage.SubjectId) { - clientIds = clientIds.Union(await userSession.GetClientListAsync()); + clientIds = clientIds.Union(await userSession.GetClientListAsync(context.RequestAborted)); } if (await AnyClientHasFrontChannelLogout(logoutMessage.ClientIds)) @@ -80,13 +80,13 @@ public static class HttpContextExtensions else if (currentSubId != null) { // see if current user has any clients they need to signout of - var clientIds = await userSession.GetClientListAsync(); + var clientIds = await userSession.GetClientListAsync(context.RequestAborted); if (clientIds.Any() && await AnyClientHasFrontChannelLogout(clientIds)) { endSessionMsg = new LogoutNotificationContext { SubjectId = currentSubId, - SessionId = await userSession.GetSessionIdAsync(), + SessionId = await userSession.GetSessionIdAsync(context.RequestAborted), ClientIds = clientIds }; } @@ -98,7 +98,7 @@ public static class HttpContextExtensions var msg = new Message(endSessionMsg, timeProvider.GetUtcNow().UtcDateTime); var endSessionMessageStore = context.RequestServices.GetRequiredService>(); - var id = await endSessionMessageStore.WriteAsync(msg); + var id = await endSessionMessageStore.WriteAsync(msg, context.RequestAborted); var urls = context.RequestServices.GetRequiredService(); var signoutIframeUrl = urls.BaseUrl.EnsureTrailingSlash() + ProtocolRoutePaths.EndSessionCallback; @@ -115,7 +115,7 @@ public static class HttpContextExtensions var clientStore = context.RequestServices.GetRequiredService(); foreach (var clientId in clientIds) { - var client = await clientStore.FindEnabledClientByIdAsync(clientId); + var client = await clientStore.FindEnabledClientByIdAsync(clientId, context.RequestAborted); if (client?.FrontChannelLogoutUri.IsPresent() == true) { return true; diff --git a/identity-server/src/IdentityServer/Extensions/IClientStoreExtensions.cs b/identity-server/src/IdentityServer/Extensions/IClientStoreExtensions.cs index eb161bc00..8ab4c206d 100644 --- a/identity-server/src/IdentityServer/Extensions/IClientStoreExtensions.cs +++ b/identity-server/src/IdentityServer/Extensions/IClientStoreExtensions.cs @@ -16,10 +16,11 @@ public static class IClientStoreExtensions /// /// The store. /// The client identifier. + /// The cancellation token. /// - public static async Task FindEnabledClientByIdAsync(this IClientStore store, string clientId) + public static async Task FindEnabledClientByIdAsync(this IClientStore store, string clientId, Ct ct) { - var client = await store.FindClientByIdAsync(clientId); + var client = await store.FindClientByIdAsync(clientId, ct); if (client != null && client.Enabled) { return client; diff --git a/identity-server/src/IdentityServer/Extensions/IResourceStoreExtensions.cs b/identity-server/src/IdentityServer/Extensions/IResourceStoreExtensions.cs index d658dd740..fada564ac 100644 --- a/identity-server/src/IdentityServer/Extensions/IResourceStoreExtensions.cs +++ b/identity-server/src/IdentityServer/Extensions/IResourceStoreExtensions.cs @@ -16,12 +16,13 @@ public static class IResourceStoreExtensions /// /// The store. /// The scope names. + /// The cancellation token. /// - public static async Task FindResourcesByScopeAsync(this IResourceStore store, IEnumerable scopeNames) + public static async Task FindResourcesByScopeAsync(this IResourceStore store, IEnumerable scopeNames, Ct ct) { - var identity = await store.FindIdentityResourcesByScopeNameAsync(scopeNames); - var apiResources = await store.FindApiResourcesByScopeNameAsync(scopeNames); - var scopes = await store.FindApiScopesByNameAsync(scopeNames); + var identity = await store.FindIdentityResourcesByScopeNameAsync(scopeNames, ct); + var apiResources = await store.FindApiResourcesByScopeNameAsync(scopeNames, ct); + var scopes = await store.FindApiScopesByNameAsync(scopeNames, ct); ValidateNameUniqueness(identity, apiResources, scopes); @@ -88,17 +89,19 @@ public static class IResourceStoreExtensions /// /// The store. /// The scope names. + /// The cancellation token. /// - public static async Task FindEnabledResourcesByScopeAsync(this IResourceStore store, IEnumerable scopeNames) => (await store.FindResourcesByScopeAsync(scopeNames)).FilterEnabled(); + public static async Task FindEnabledResourcesByScopeAsync(this IResourceStore store, IEnumerable scopeNames, Ct ct) => (await store.FindResourcesByScopeAsync(scopeNames, ct)).FilterEnabled(); /// /// Gets all enabled resources. /// /// The store. + /// The cancellation token. /// - public static async Task GetAllEnabledResourcesAsync(this IResourceStore store) + public static async Task GetAllEnabledResourcesAsync(this IResourceStore store, Ct ct) { - var resources = await store.GetAllResourcesAsync(); + var resources = await store.GetAllResourcesAsync(ct); ValidateNameUniqueness(resources.IdentityResources, resources.ApiResources, resources.ApiScopes); return resources.FilterEnabled(); @@ -109,11 +112,15 @@ public static class IResourceStoreExtensions /// /// The store. /// The scope names. + /// The cancellation token. /// - public static async Task> FindEnabledIdentityResourcesByScopeAsync(this IResourceStore store, IEnumerable scopeNames) => (await store.FindIdentityResourcesByScopeNameAsync(scopeNames)).Where(x => x.Enabled).ToArray(); + public static async Task> FindEnabledIdentityResourcesByScopeAsync(this IResourceStore store, IEnumerable scopeNames, Ct ct) => (await store.FindIdentityResourcesByScopeNameAsync(scopeNames, ct)).Where(x => x.Enabled).ToArray(); /// /// Finds the enabled API resources by name. /// - public static async Task> FindEnabledApiResourcesByNameAsync(this IResourceStore store, IEnumerable resourceNames) => (await store.FindApiResourcesByNameAsync(resourceNames)).Where(x => x.Enabled).ToArray(); + /// The store. + /// The resource names. + /// The cancellation token. + public static async Task> FindEnabledApiResourcesByNameAsync(this IResourceStore store, IEnumerable resourceNames, Ct ct) => (await store.FindApiResourcesByNameAsync(resourceNames, ct)).Where(x => x.Enabled).ToArray(); } diff --git a/identity-server/src/IdentityServer/Hosting/CorsPolicyProvider.cs b/identity-server/src/IdentityServer/Hosting/CorsPolicyProvider.cs index 866ee47ff..490ec5895 100644 --- a/identity-server/src/IdentityServer/Hosting/CorsPolicyProvider.cs +++ b/identity-server/src/IdentityServer/Hosting/CorsPolicyProvider.cs @@ -58,7 +58,7 @@ internal class CorsPolicyProvider : ICorsPolicyProvider // https://github.com/aspnet/CORS/issues/105 var corsPolicyService = _provider.GetRequiredService(); - if (await corsPolicyService.IsOriginAllowedAsync(origin)) + if (await corsPolicyService.IsOriginAllowedAsync(origin, context.RequestAborted)) { _sanitizedLogger.LogDebug("CorsPolicyService allowed origin: {origin}", origin); return Allow(origin); diff --git a/identity-server/src/IdentityServer/Hosting/DynamicProviders/DynamicSchemes/DynamicAuthenticationSchemeProvider.cs b/identity-server/src/IdentityServer/Hosting/DynamicProviders/DynamicSchemes/DynamicAuthenticationSchemeProvider.cs index cc1f7dc08..135ebd0f1 100644 --- a/identity-server/src/IdentityServer/Hosting/DynamicProviders/DynamicSchemes/DynamicAuthenticationSchemeProvider.cs +++ b/identity-server/src/IdentityServer/Hosting/DynamicProviders/DynamicSchemes/DynamicAuthenticationSchemeProvider.cs @@ -83,7 +83,7 @@ internal class DynamicAuthenticationSchemeProvider : IAuthenticationSchemeProvid var dynamicScheme = cache.Get(name); if (dynamicScheme == null) { - var idp = await store.GetBySchemeAsync(name); + var idp = await store.GetBySchemeAsync(name, _httpContextAccessor.HttpContext.RequestAborted); if (idp != null && idp.Enabled) { var providerType = _options.FindProviderType(idp.Type); diff --git a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/CachingIdentityProviderStore.cs b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/CachingIdentityProviderStore.cs index e995be2b1..8d4baa2a0 100644 --- a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/CachingIdentityProviderStore.cs +++ b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/CachingIdentityProviderStore.cs @@ -51,18 +51,19 @@ public class CachingIdentityProviderStore : IIdentityProviderStore } /// - public async Task> GetAllSchemeNamesAsync() + public async Task> GetAllSchemeNamesAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingIdentityProviderStore.GetAllSchemeNames"); var result = await _allCache.GetOrAddAsync("__all__", _options.Caching.IdentityProviderCacheDuration, - async () => await _inner.GetAllSchemeNamesAsync()); + async () => await _inner.GetAllSchemeNamesAsync(ct), + ct); return result; } /// - public async Task GetBySchemeAsync(string scheme) + public async Task GetBySchemeAsync(string scheme, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingIdentityProviderStore.GetByScheme"); @@ -79,10 +80,11 @@ public class CachingIdentityProviderStore : IIdentityProviderStore return null; } - var item = await _inner.GetBySchemeAsync(scheme); + var item = await _inner.GetBySchemeAsync(scheme, ct); RemoveCacheEntry(item); return item; - }); + }, + ct); return result; } diff --git a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/InMemoryIdentityProviderStore.cs b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/InMemoryIdentityProviderStore.cs index a2cb099a9..4b44a4418 100644 --- a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/InMemoryIdentityProviderStore.cs +++ b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/InMemoryIdentityProviderStore.cs @@ -13,7 +13,7 @@ internal class InMemoryIdentityProviderStore : IIdentityProviderStore public InMemoryIdentityProviderStore(IEnumerable providers) => _providers = providers; - public Task> GetAllSchemeNamesAsync() + public Task> GetAllSchemeNamesAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryOidcProviderStore.GetAllSchemeNames"); @@ -27,7 +27,7 @@ internal class InMemoryIdentityProviderStore : IIdentityProviderStore return Task.FromResult(items); } - public Task GetBySchemeAsync(string scheme) + public Task GetBySchemeAsync(string scheme, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryOidcProviderStore.GetByScheme"); diff --git a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NonCachingIdentityProviderStore.cs b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NonCachingIdentityProviderStore.cs index c00fa9900..f25f55a72 100644 --- a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NonCachingIdentityProviderStore.cs +++ b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NonCachingIdentityProviderStore.cs @@ -38,17 +38,17 @@ public class NonCachingIdentityProviderStore : IIdentityProviderStore } /// - public Task> GetAllSchemeNamesAsync() => _inner.GetAllSchemeNamesAsync(); + public Task> GetAllSchemeNamesAsync(Ct ct) => _inner.GetAllSchemeNamesAsync(ct); /// - public async Task GetBySchemeAsync(string scheme) + public async Task GetBySchemeAsync(string scheme, Ct ct) { if (_httpContextAccessor.HttpContext == null) { _logger.LogDebug("Failed to retrieve the dynamic authentication scheme \"{scheme}\" because there is no current HTTP request", scheme); return null; } - var item = await _inner.GetBySchemeAsync(scheme); + var item = await _inner.GetBySchemeAsync(scheme, ct); RemoveCacheEntry(item); return item; } diff --git a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NopIdentityProviderStore.cs b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NopIdentityProviderStore.cs index 46e8273b7..3dfc07139 100644 --- a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NopIdentityProviderStore.cs +++ b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/NopIdentityProviderStore.cs @@ -9,7 +9,7 @@ namespace Duende.IdentityServer.Hosting.DynamicProviders; internal class NopIdentityProviderStore : IIdentityProviderStore { - public Task> GetAllSchemeNamesAsync() => Task.FromResult(Enumerable.Empty()); + public Task> GetAllSchemeNamesAsync(Ct _) => Task.FromResult(Enumerable.Empty()); - public Task GetBySchemeAsync(string scheme) => Task.FromResult(null); + public Task GetBySchemeAsync(string scheme, Ct _) => Task.FromResult(null); } diff --git a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/ValidatingIdentityProviderStore.cs b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/ValidatingIdentityProviderStore.cs index 93088c395..1185ec479 100644 --- a/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/ValidatingIdentityProviderStore.cs +++ b/identity-server/src/IdentityServer/Hosting/DynamicProviders/Store/ValidatingIdentityProviderStore.cs @@ -38,19 +38,19 @@ public class ValidatingIdentityProviderStore : IIdentityProviderStore } /// - public Task> GetAllSchemeNamesAsync() => _inner.GetAllSchemeNamesAsync(); + public Task> GetAllSchemeNamesAsync(Ct ct) => _inner.GetAllSchemeNamesAsync(ct); /// - public async Task GetBySchemeAsync(string scheme) + public async Task GetBySchemeAsync(string scheme, Ct ct) { - var idp = await _inner.GetBySchemeAsync(scheme); + var idp = await _inner.GetBySchemeAsync(scheme, ct); if (idp != null) { _logger.LogTrace("Calling into identity provider configuration validator: {validatorType}", _validatorType); var context = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(context); + await _validator.ValidateAsync(context, ct); if (context.IsValid) { @@ -61,7 +61,7 @@ public class ValidatingIdentityProviderStore : IIdentityProviderStore _logger.LogError("Invalid IdentityProvider configuration for scheme {scheme}: {errorMessage}", scheme, context.ErrorMessage); Telemetry.Metrics.DynamicIdentityProviderValidationFailure(scheme, context.ErrorMessage); - await _events.RaiseAsync(new InvalidIdentityProviderConfiguration(idp, context.ErrorMessage)); + await _events.RaiseAsync(new InvalidIdentityProviderConfiguration(idp, context.ErrorMessage), ct); return null; } diff --git a/identity-server/src/IdentityServer/Hosting/IdentityServerAuthenticationService.cs b/identity-server/src/IdentityServer/Hosting/IdentityServerAuthenticationService.cs index 159060763..c2dfd87a0 100644 --- a/identity-server/src/IdentityServer/Hosting/IdentityServerAuthenticationService.cs +++ b/identity-server/src/IdentityServer/Hosting/IdentityServerAuthenticationService.cs @@ -61,7 +61,7 @@ internal class IdentityServerAuthenticationService : IAuthenticationService AugmentPrincipal(principal); properties ??= new AuthenticationProperties(); - await _session.CreateSessionIdAsync(principal, properties); + await _session.CreateSessionIdAsync(principal, properties, context.RequestAborted); } await _inner.SignInAsync(context, scheme, principal, properties); @@ -96,22 +96,22 @@ internal class IdentityServerAuthenticationService : IAuthenticationService _logger.LogDebug("SignOutCalled set; processing post-signout session cleanup."); // back channel logout - var user = await _session.GetUserAsync(); + var user = await _session.GetUserAsync(context.RequestAborted); if (user != null) { var session = new UserSession { SubjectId = user.GetSubjectId(), - SessionId = await _session.GetSessionIdAsync(), + SessionId = await _session.GetSessionIdAsync(context.RequestAborted), DisplayName = user.GetDisplayName(), - ClientIds = (await _session.GetClientListAsync()).ToList(), - Issuer = await _issuerNameService.GetCurrentAsync() + ClientIds = (await _session.GetClientListAsync(context.RequestAborted)).ToList(), + Issuer = await _issuerNameService.GetCurrentAsync(context.RequestAborted) }; - await _sessionCoordinationService.ProcessLogoutAsync(session); + await _sessionCoordinationService.ProcessLogoutAsync(session, context.RequestAborted); } // this clears our session id cookie so JS clients can detect the user has signed out - await _session.RemoveSessionIdCookieAsync(); + await _session.RemoveSessionIdCookieAsync(context.RequestAborted); }); context.SetBackChannelLogoutTriggered(); diff --git a/identity-server/src/IdentityServer/Hosting/IdentityServerMiddleware.cs b/identity-server/src/IdentityServer/Hosting/IdentityServerMiddleware.cs index 315d1e751..dd4710bdb 100644 --- a/identity-server/src/IdentityServer/Hosting/IdentityServerMiddleware.cs +++ b/identity-server/src/IdentityServer/Hosting/IdentityServerMiddleware.cs @@ -56,7 +56,7 @@ public class IdentityServerMiddleware { // this will check the authentication session and from it emit the check session // cookie needed from JS-based signout clients. - await userSession.EnsureSessionIdCookieAsync(); + await userSession.EnsureSessionIdCookieAsync(context.RequestAborted); context.Response.OnStarting(async () => { @@ -64,7 +64,7 @@ public class IdentityServerMiddleware { _sanitizedLogger.LogDebug("Detected expired session removed; processing post-expiration cleanup."); - await sessionCoordinationService.ProcessExpirationAsync(expiredUserSession); + await sessionCoordinationService.ProcessExpirationAsync(expiredUserSession, context.RequestAborted); } }); @@ -90,7 +90,7 @@ public class IdentityServerMiddleware using var activity = Tracing.BasicActivitySource.StartActivity("IdentityServerProtocolRequest"); activity?.SetTag(Tracing.Properties.EndpointType, endpointType); - var issuer = await issuerNameService.GetCurrentAsync(); + var issuer = await issuerNameService.GetCurrentAsync(context.RequestAborted); var licenseUsage = context.RequestServices.GetRequiredService(); licenseUsage.IssuerUsed(issuer); IdentityServerLicenseValidator.Instance.ValidateIssuer(issuer); @@ -115,7 +115,7 @@ public class IdentityServerMiddleware } catch (Exception ex) when (options.Logging.InvokeUnhandledExceptionLoggingFilter(context, ex) is not false) { - await events.RaiseAsync(new UnhandledExceptionEvent(ex)); + await events.RaiseAsync(new UnhandledExceptionEvent(ex), context.RequestAborted); Telemetry.Metrics.UnHandledException(ex); _sanitizedLogger.LogCritical(ex, "Unhandled exception: {exception}", ex.Message); diff --git a/identity-server/src/IdentityServer/Hosting/LocalApiAuthentication/LocalApiAuthenticationHandler.cs b/identity-server/src/IdentityServer/Hosting/LocalApiAuthentication/LocalApiAuthenticationHandler.cs index 3c1b7381d..9d8301a91 100644 --- a/identity-server/src/IdentityServer/Hosting/LocalApiAuthentication/LocalApiAuthenticationHandler.cs +++ b/identity-server/src/IdentityServer/Hosting/LocalApiAuthentication/LocalApiAuthenticationHandler.cs @@ -100,7 +100,7 @@ public class LocalApiAuthenticationHandler : AuthenticationHandler x.Type == JwtClaimTypes.ClientId)?.Value; - var client = await _clientStore.FindEnabledClientByIdAsync(clientId); + var client = await _clientStore.FindEnabledClientByIdAsync(clientId, Context.RequestAborted); if (client == null) { // invalid or missing client id @@ -131,7 +131,7 @@ public class LocalApiAuthenticationHandler : AuthenticationHandler logger) : BackgroundService { /// - public override Task StartAsync(CT ct) => + public override Task StartAsync(Ct ct) => !options.ServerSideSessions.RemoveExpiredSessions ? Task.CompletedTask : base.StartAsync(ct); /// - protected override async Task ExecuteAsync(CT stoppingToken) + protected override async Task ExecuteAsync(Ct stoppingToken) { logger.LogDebug("Starting server-side session removal"); @@ -68,7 +68,7 @@ public class ServerSideSessionCleanupHost( logger.LogDebug("Stopping server-side session removal"); } - private async Task RunAsync(CT ct = default) + private async Task RunAsync(Ct ct) { // this is here for testing if (!options.ServerSideSessions.RemoveExpiredSessions) @@ -100,7 +100,7 @@ public class ServerSideSessionCleanupHost( foreach (var session in sessions) { - await sessionCoordinationService.ProcessExpirationAsync(session); + await sessionCoordinationService.ProcessExpirationAsync(session, ct); } } } diff --git a/identity-server/src/IdentityServer/IdentityServerTools.cs b/identity-server/src/IdentityServer/IdentityServerTools.cs index 5276de7a9..9cf815b2c 100644 --- a/identity-server/src/IdentityServer/IdentityServerTools.cs +++ b/identity-server/src/IdentityServer/IdentityServerTools.cs @@ -27,6 +27,7 @@ public interface IIdentityServerTools /// the exp claim of the token. /// A collection of additional claims to include in the /// token. + /// The cancellation token. /// A JWT that expires after the specified lifetime and contains /// the given claims. /// Typical implementations depend on the @@ -34,7 +35,7 @@ public interface IIdentityServerTools /// of the token. Ensure that calls to this method will only occur if there /// is an incoming HTTP request or with the option set. /// - Task IssueJwtAsync(int lifetime, IEnumerable claims); + Task IssueJwtAsync(int lifetime, IEnumerable claims, Ct ct); /// /// Issues a JWT with a specific lifetime, issuer, and set of claims. @@ -45,9 +46,10 @@ public interface IIdentityServerTools /// claim. /// A collection of additional claims to include in the /// token. + /// The cancellation token. /// A JWT with the specified lifetime, issuer and additional /// claims. - Task IssueJwtAsync(int lifetime, string issuer, IEnumerable claims); + Task IssueJwtAsync(int lifetime, string issuer, IEnumerable claims, Ct ct); /// /// Issues a JWT with a specific lifetime, issuer, token type, and set of @@ -61,9 +63,10 @@ public interface IIdentityServerTools /// "id_token", set in the typ claim. /// A collection of additional claims to include in the /// token. + /// The cancellation token. /// A JWT with the specified lifetime, issuer, token type, and /// additional claims. - Task IssueJwtAsync(int lifetime, string issuer, string tokenType, IEnumerable claims); + Task IssueJwtAsync(int lifetime, string issuer, string tokenType, IEnumerable claims, Ct ct); /// /// Issues a JWT access token for a particular client. @@ -72,6 +75,7 @@ public interface IIdentityServerTools /// claim. /// The lifetime, in seconds, which will determine /// the exp claim of the token. + /// The cancellation token. /// A collection of scopes, which will be added to the /// token as claims with the "scope" type. /// A collection of audiences, which will be added @@ -88,6 +92,7 @@ public interface IIdentityServerTools Task IssueClientJwtAsync( string clientId, int lifetime, + Ct ct, IEnumerable? scopes = null, IEnumerable? audiences = null, IEnumerable? additionalClaims = null); @@ -113,21 +118,21 @@ public class IdentityServerTools : IIdentityServerTools } /// - public virtual async Task IssueJwtAsync(int lifetime, IEnumerable claims) + public virtual async Task IssueJwtAsync(int lifetime, IEnumerable claims, Ct ct) { - var issuer = await _issuerNameService.GetCurrentAsync(); - return await IssueJwtAsync(lifetime, issuer, claims); + var issuer = await _issuerNameService.GetCurrentAsync(ct); + return await IssueJwtAsync(lifetime, issuer, claims, ct); } /// - public virtual Task IssueJwtAsync(int lifetime, string issuer, IEnumerable claims) + public virtual Task IssueJwtAsync(int lifetime, string issuer, IEnumerable claims, Ct ct) { var tokenType = OidcConstants.TokenTypes.AccessToken; - return IssueJwtAsync(lifetime, issuer, tokenType, claims); + return IssueJwtAsync(lifetime, issuer, tokenType, claims, ct); } /// - public virtual async Task IssueJwtAsync(int lifetime, string issuer, string tokenType, IEnumerable claims) + public virtual async Task IssueJwtAsync(int lifetime, string issuer, string tokenType, IEnumerable claims, Ct ct) { ArgumentException.ThrowIfNullOrWhiteSpace(issuer); ArgumentException.ThrowIfNullOrWhiteSpace(tokenType); @@ -142,13 +147,14 @@ public class IdentityServerTools : IIdentityServerTools Claims = new HashSet(claims, new ClaimComparer()) }; - return await _tokenCreation.CreateTokenAsync(token); + return await _tokenCreation.CreateTokenAsync(token, ct); } /// public virtual async Task IssueClientJwtAsync( string clientId, int lifetime, + Ct ct, IEnumerable? scopes = null, IEnumerable? audiences = null, IEnumerable? additionalClaims = null) @@ -178,7 +184,7 @@ public class IdentityServerTools : IIdentityServerTools claims.Add(new Claim( JwtClaimTypes.Audience, #pragma warning disable CA1863 // Would require changing a public const on a public class and be a breaking change - string.Format(CultureInfo.InvariantCulture, IdentityServerConstants.AccessTokenAudience, (await _issuerNameService.GetCurrentAsync()).EnsureTrailingSlash()))); + string.Format(CultureInfo.InvariantCulture, IdentityServerConstants.AccessTokenAudience, (await _issuerNameService.GetCurrentAsync(ct)).EnsureTrailingSlash()))); #pragma warning restore CA1863 } @@ -190,6 +196,6 @@ public class IdentityServerTools : IIdentityServerTools } } - return await IssueJwtAsync(lifetime, claims); + return await IssueJwtAsync(lifetime, claims, ct); } } diff --git a/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticEntries/RegisteredImplementationsDiagnosticEntry.cs b/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticEntries/RegisteredImplementationsDiagnosticEntry.cs index c610ee524..e14422df9 100644 --- a/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticEntries/RegisteredImplementationsDiagnosticEntry.cs +++ b/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticEntries/RegisteredImplementationsDiagnosticEntry.cs @@ -61,7 +61,6 @@ internal class RegisteredImplementationsDiagnosticEntry(ServiceCollectionAccesso new(typeof(IBackChannelLogoutHttpClient), [typeof(DefaultBackChannelLogoutHttpClient)]), new(typeof(IBackChannelLogoutService), [typeof(DefaultBackChannelLogoutService)]), new(typeof(ICache<>), [typeof(DefaultCache<>)]), - new(typeof(ICancellationTokenProvider), [typeof(DefaultCancellationTokenProvider)]), new(typeof(IClaimsService), [typeof(DefaultClaimsService)]), new(typeof(IConsentService), [typeof(DefaultConsentService)]), new(typeof(ICorsPolicyService), [typeof(DefaultCorsPolicyService)]), diff --git a/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticHostedService.cs b/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticHostedService.cs index b68745268..9af32b589 100644 --- a/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticHostedService.cs +++ b/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticHostedService.cs @@ -10,7 +10,7 @@ namespace Duende.IdentityServer.Licensing.V2.Diagnostics; internal class DiagnosticHostedService(DiagnosticSummary diagnosticSummary, IOptions options, ILogger logger) : BackgroundService { - protected override async Task ExecuteAsync(CT stoppingToken) + protected override async Task ExecuteAsync(Ct stoppingToken) { using var timer = new PeriodicTimer(options.Value.Diagnostics.LogFrequency); try @@ -19,7 +19,7 @@ internal class DiagnosticHostedService(DiagnosticSummary diagnosticSummary, IOpt { try { - await diagnosticSummary.PrintSummary(); + await diagnosticSummary.PrintSummary(stoppingToken); } catch (Exception ex) { @@ -35,11 +35,11 @@ internal class DiagnosticHostedService(DiagnosticSummary diagnosticSummary, IOpt } // Added for testing purposes to be able to call ExecuteAsync directly. - internal Task ExecuteForTestOnly(CT stoppingToken) => ExecuteAsync(stoppingToken); + internal Task ExecuteForTestOnly(Ct stoppingToken) => ExecuteAsync(stoppingToken); - public override async Task StopAsync(CT ct) + public override async Task StopAsync(Ct ct) { - await diagnosticSummary.PrintSummary(); + await diagnosticSummary.PrintSummary(ct); await base.StopAsync(ct); } diff --git a/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticSummary.cs b/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticSummary.cs index c30e7fc78..cf44f96af 100644 --- a/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticSummary.cs +++ b/identity-server/src/IdentityServer/Licensing/V2/Diagnostics/DiagnosticSummary.cs @@ -12,9 +12,9 @@ internal class DiagnosticSummary(DiagnosticDataService diagnosticDataService, Id { private readonly ILogger _logger = loggerFactory.CreateLogger("Duende.IdentityServer.Diagnostics.Summary"); - public async Task PrintSummary() + public async Task PrintSummary(Ct ct) { - var jsonMemory = await diagnosticDataService.GetJsonBytesAsync(); + var jsonMemory = await diagnosticDataService.GetJsonBytesAsync(ct); var span = jsonMemory.Span; using var diagnosticActivity = Tracing.DiagnosticsActivitySource.StartActivity("DiagnosticSummary"); diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeInteractionResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeInteractionResponseGenerator.cs index ae3c2ad8c..36d7cde45 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeInteractionResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeInteractionResponseGenerator.cs @@ -70,8 +70,9 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon /// /// The request. /// The consent. + /// The cancellation token. /// - public virtual async Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null) + public virtual async Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("AuthorizeInteractionResponseGenerator.ProcessInteraction"); activity?.SetTag(Tracing.Properties.ClientId, request.Client.ClientId); @@ -103,15 +104,15 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon } // see if create account was requested - var result = await ProcessCreateAccountAsync(request); + var result = await ProcessCreateAccountAsync(request, ct); if (result.ResponseType == InteractionResponseType.None) { // see if the user needs to login - result = await ProcessLoginAsync(request); + result = await ProcessLoginAsync(request, ct); if (result.ResponseType == InteractionResponseType.None) { // see if the user needs to consent - result = await ProcessConsentAsync(request, consent); + result = await ProcessConsentAsync(request, consent, ct); } } @@ -134,8 +135,9 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon /// Processes the create account logic. /// /// The request. + /// The cancellation token. /// - protected internal virtual Task ProcessCreateAccountAsync(ValidatedAuthorizeRequest request) + protected internal virtual Task ProcessCreateAccountAsync(ValidatedAuthorizeRequest request, Ct ct) { InteractionResponse result; @@ -161,8 +163,9 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon /// Processes the login logic. /// /// The request. + /// The cancellation token. /// - protected internal virtual async Task ProcessLoginAsync(ValidatedAuthorizeRequest request) + protected internal virtual async Task ProcessLoginAsync(ValidatedAuthorizeRequest request, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("AuthorizeInteractionResponseGenerator.ProcessLogin"); @@ -205,7 +208,7 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon if (isAuthenticated) { var isActiveCtx = new IsActiveContext(request.Subject, request.Client, IdentityServerConstants.ProfileIsActiveCallers.AuthorizeEndpoint); - await Profile.IsActiveAsync(isActiveCtx); + await Profile.IsActiveAsync(isActiveCtx, ct); isActive = isActiveCtx.IsActive; } @@ -305,10 +308,11 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon /// /// The request. /// The consent. + /// The cancellation token. /// /// /// Invalid PromptMode - protected internal virtual async Task ProcessConsentAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null) + protected internal virtual async Task ProcessConsentAsync(ValidatedAuthorizeRequest request, ConsentResponse consent, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("AuthorizeInteractionResponseGenerator.ProcessConsent"); @@ -322,7 +326,7 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon throw new ArgumentException("Invalid PromptMode"); } - var consentRequired = await Consent.RequiresConsentAsync(request.Subject, request.Client, request.ValidatedResources.ParsedScopes); + var consentRequired = await Consent.RequiresConsentAsync(request.Subject, request.Client, request.ValidatedResources.ParsedScopes, ct); if (consentRequired && request.PromptModes.Contains(OidcConstants.PromptModes.None)) { @@ -399,7 +403,7 @@ public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionRespon Logger.LogDebug("User indicated to remember consent for scopes: {scopes}", request.ValidatedResources.RawScopeValues); } - await Consent.UpdateConsentAsync(request.Subject, request.Client, parsedScopes); + await Consent.UpdateConsentAsync(request.Subject, request.Client, parsedScopes, ct); } } } diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeResponseGenerator.cs index e46d634e6..9954f85d7 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/AuthorizeResponseGenerator.cs @@ -82,27 +82,22 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator Events = events; } - /// - /// Creates the response - /// - /// The request. - /// - /// invalid grant type: " + request.GrantType - public virtual async Task CreateResponseAsync(ValidatedAuthorizeRequest request) + /// + public virtual async Task CreateResponseAsync(ValidatedAuthorizeRequest request, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("AuthorizeResponseGenerator.CreateResponse"); if (request.GrantType == GrantType.AuthorizationCode) { - return await CreateCodeFlowResponseAsync(request); + return await CreateCodeFlowResponseAsync(request, ct); } if (request.GrantType == GrantType.Implicit) { - return await CreateImplicitFlowResponseAsync(request); + return await CreateImplicitFlowResponseAsync(request, ct); } if (request.GrantType == GrantType.Hybrid) { - return await CreateHybridFlowResponseAsync(request); + return await CreateHybridFlowResponseAsync(request, ct); } Logger.LogError("Unsupported grant type: {GrantType}", request.GrantType); @@ -113,15 +108,16 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator /// Creates the response for a hybrid flow request /// /// + /// The cancellation token. /// - protected virtual async Task CreateHybridFlowResponseAsync(ValidatedAuthorizeRequest request) + protected virtual async Task CreateHybridFlowResponseAsync(ValidatedAuthorizeRequest request, Ct ct) { Logger.LogDebug("Creating Hybrid Flow response."); - var code = await CreateCodeAsync(request); - var id = await AuthorizationCodeStore.StoreAuthorizationCodeAsync(code); + var code = await CreateCodeAsync(request, ct); + var id = await AuthorizationCodeStore.StoreAuthorizationCodeAsync(code, ct); - var response = await CreateImplicitFlowResponseAsync(request, id); + var response = await CreateImplicitFlowResponseAsync(request, ct, id); response.Code = id; return response; @@ -131,13 +127,14 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator /// Creates the response for a code flow request /// /// + /// The cancellation token. /// - protected virtual async Task CreateCodeFlowResponseAsync(ValidatedAuthorizeRequest request) + protected virtual async Task CreateCodeFlowResponseAsync(ValidatedAuthorizeRequest request, Ct ct) { Logger.LogDebug("Creating Authorization Code Flow response."); - var code = await CreateCodeAsync(request); - var id = await AuthorizationCodeStore.StoreAuthorizationCodeAsync(code); + var code = await CreateCodeAsync(request, ct); + var id = await AuthorizationCodeStore.StoreAuthorizationCodeAsync(code, ct); var response = new AuthorizeResponse { @@ -154,9 +151,10 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator /// Creates the response for a implicit flow request /// /// + /// The cancellation token. /// /// - protected virtual async Task CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request, string authorizationCode = null) + protected virtual async Task CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request, Ct ct, string authorizationCode = null) { Logger.LogDebug("Creating Implicit Flow response."); @@ -176,10 +174,10 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator ValidatedRequest = request }; - var accessToken = await TokenService.CreateAccessTokenAsync(tokenRequest); + var accessToken = await TokenService.CreateAccessTokenAsync(tokenRequest, ct); accessTokenLifetime = accessToken.Lifetime; - accessTokenValue = await TokenService.CreateSecurityTokenAsync(accessToken); + accessTokenValue = await TokenService.CreateSecurityTokenAsync(accessToken, ct); } string jwt = null; @@ -189,7 +187,7 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator if (Options.EmitStateHash && request.State.IsPresent()) { - var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.Client.AllowedIdentityTokenSigningAlgorithms); + var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.Client.AllowedIdentityTokenSigningAlgorithms, ct); if (credential == null) { throw new InvalidOperationException("No signing credential is configured."); @@ -211,8 +209,8 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator StateHash = stateHash }; - var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest); - jwt = await TokenService.CreateSecurityTokenAsync(idToken); + var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest, ct); + jwt = await TokenService.CreateSecurityTokenAsync(idToken, ct); } var response = new AuthorizeResponse @@ -231,13 +229,14 @@ public class AuthorizeResponseGenerator : IAuthorizeResponseGenerator /// Creates an authorization code /// /// + /// The cancellation token. /// - protected virtual async Task CreateCodeAsync(ValidatedAuthorizeRequest request) + protected virtual async Task CreateCodeAsync(ValidatedAuthorizeRequest request, Ct ct) { string stateHash = null; if (Options.EmitStateHash && request.State.IsPresent()) { - var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.Client.AllowedIdentityTokenSigningAlgorithms); + var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.Client.AllowedIdentityTokenSigningAlgorithms, ct); if (credential == null) { throw new InvalidOperationException("No signing credential is configured."); diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/BackchannelAuthenticationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/BackchannelAuthenticationResponseGenerator.cs index 27e360dd1..7bad0f2ac 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/BackchannelAuthenticationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/BackchannelAuthenticationResponseGenerator.cs @@ -64,7 +64,7 @@ public class BackchannelAuthenticationResponseGenerator : IBackchannelAuthentica } /// - public virtual async Task ProcessAsync(BackchannelAuthenticationRequestValidationResult validationResult) + public virtual async Task ProcessAsync(BackchannelAuthenticationRequestValidationResult validationResult, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("BackchannelAuthenticationResponseGenerator.Process"); @@ -96,7 +96,7 @@ public class BackchannelAuthenticationResponseGenerator : IBackchannelAuthentica Properties = validationResult.ValidatedRequest.Properties, }; - var requestId = await BackChannelAuthenticationRequestStore.CreateRequestAsync(request); + var requestId = await BackChannelAuthenticationRequestStore.CreateRequestAsync(request, ct); var interval = validationResult.ValidatedRequest.Client.PollingInterval ?? Options.Ciba.DefaultPollingInterval; var response = new BackchannelAuthenticationResponse() @@ -118,7 +118,7 @@ public class BackchannelAuthenticationResponseGenerator : IBackchannelAuthentica Tenant = validationResult.ValidatedRequest.Tenant, IdP = validationResult.ValidatedRequest.IdP, Properties = validationResult.ValidatedRequest.Properties, - }); + }, ct); return response; } diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/DeviceAuthorizationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/DeviceAuthorizationResponseGenerator.cs index ae536b52c..07f38738c 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/DeviceAuthorizationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/DeviceAuthorizationResponseGenerator.cs @@ -59,15 +59,8 @@ public class DeviceAuthorizationResponseGenerator : IDeviceAuthorizationResponse Logger = logger; } - /// - /// Processes the response. - /// - /// The validation result. - /// The base URL. - /// - /// validationResult or Client - /// Value cannot be null or whitespace. - baseUrl - public virtual async Task ProcessAsync(DeviceAuthorizationRequestValidationResult validationResult, string baseUrl) + /// + public virtual async Task ProcessAsync(DeviceAuthorizationRequestValidationResult validationResult, string baseUrl, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("DeviceAuthorizationResponseGenerator.Process"); @@ -89,15 +82,15 @@ public class DeviceAuthorizationResponseGenerator : IDeviceAuthorizationResponse // generate user_code var userCodeGenerator = await UserCodeService.GetGenerator( validationResult.ValidatedRequest.Client.UserCodeType ?? - Options.DeviceFlow.DefaultUserCodeType); + Options.DeviceFlow.DefaultUserCodeType, ct); var retryCount = 0; while (retryCount < userCodeGenerator.RetryLimit) { - var userCode = await userCodeGenerator.GenerateAsync(); + var userCode = await userCodeGenerator.GenerateAsync(ct); - var deviceCode = await DeviceFlowCodeService.FindByUserCodeAsync(userCode); + var deviceCode = await DeviceFlowCodeService.FindByUserCodeAsync(userCode, ct); if (deviceCode == null) { response.UserCode = userCode; @@ -141,7 +134,7 @@ public class DeviceAuthorizationResponseGenerator : IDeviceAuthorizationResponse Lifetime = response.DeviceCodeLifetime, CreationTime = TimeProvider.GetUtcNow().UtcDateTime, RequestedScopes = validationResult.ValidatedRequest.ValidatedResources.RawScopeValues - }); + }, ct); return response; } diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/DiscoveryResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/DiscoveryResponseGenerator.cs index c43b1a7de..4aa17934d 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/DiscoveryResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/DiscoveryResponseGenerator.cs @@ -92,7 +92,8 @@ public class DiscoveryResponseGenerator : IDiscoveryResponseGenerator /// /// The base URL. /// The issuer URI. - public virtual async Task> CreateDiscoveryDocumentAsync(string baseUrl, string issuerUri) + /// The cancellation token. + public virtual async Task> CreateDiscoveryDocumentAsync(string baseUrl, string issuerUri, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("DiscoveryResponseGenerator.CreateDiscoveryDocument"); @@ -106,7 +107,7 @@ public class DiscoveryResponseGenerator : IDiscoveryResponseGenerator // jwks if (Options.Discovery.ShowKeySet) { - if ((await Keys.GetValidationKeysAsync()).Any()) + if ((await Keys.GetValidationKeysAsync(ct)).Any()) { entries.Add(OidcConstants.Discovery.JwksUri, baseUrl + ProtocolRoutePaths.DiscoveryWebKeys); } @@ -236,7 +237,7 @@ public class DiscoveryResponseGenerator : IDiscoveryResponseGenerator Options.Discovery.ShowApiScopes || Options.Discovery.ShowClaims) { - var resources = await ResourceStore.GetAllEnabledResourcesAsync(); + var resources = await ResourceStore.GetAllEnabledResourcesAsync(ct); var scopes = new List(); // scopes @@ -342,7 +343,7 @@ public class DiscoveryResponseGenerator : IDiscoveryResponseGenerator AddSigningAlgorithmsForEndpointIfNeeded(OidcConstants.Discovery.IntrospectionEndpointAuthSigningAlgorithmsSupported, entries, supportedAuthMethods); } - var signingCredentials = await Keys.GetAllSigningCredentialsAsync(); + var signingCredentials = await Keys.GetAllSigningCredentialsAsync(ct); if (signingCredentials.Any()) { var signingAlgorithms = signingCredentials.Select(c => c.Algorithm).Distinct(); @@ -458,13 +459,14 @@ public class DiscoveryResponseGenerator : IDiscoveryResponseGenerator /// /// Creates the JWK document. /// - public virtual async Task> CreateJwkDocumentAsync() + /// The cancellation token. + public virtual async Task> CreateJwkDocumentAsync(Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("DiscoveryResponseGenerator.CreateJwkDocument"); var webKeys = new List(); - foreach (var key in await Keys.GetValidationKeysAsync()) + foreach (var key in await Keys.GetValidationKeysAsync(ct)) { if (key.Key is X509SecurityKey x509Key) { diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/IntrospectionResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/IntrospectionResponseGenerator.cs index a73ca0242..318786599 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/IntrospectionResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/IntrospectionResponseGenerator.cs @@ -45,8 +45,9 @@ public class IntrospectionResponseGenerator : IIntrospectionResponseGenerator /// Processes the response. /// /// The validation result. + /// The cancellation token. /// - public virtual async Task> ProcessAsync(IntrospectionRequestValidationResult validationResult) + public virtual async Task> ProcessAsync(IntrospectionRequestValidationResult validationResult, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("IntrospectionResponseGenerator.Process"); @@ -65,7 +66,7 @@ public class IntrospectionResponseGenerator : IIntrospectionResponseGenerator { Logger.LogDebug("Creating introspection response for inactive token."); Telemetry.Metrics.Introspection(callerName, false); - await Events.RaiseAsync(new TokenIntrospectionSuccessEvent(validationResult)); + await Events.RaiseAsync(new TokenIntrospectionSuccessEvent(validationResult), ct); return response; } @@ -76,7 +77,7 @@ public class IntrospectionResponseGenerator : IIntrospectionResponseGenerator if (validationResult.Api != null) { // expected scope not present - if (await AreExpectedScopesPresentAsync(validationResult) == false) + if (await AreExpectedScopesPresentAsync(validationResult, ct) == false) { return response; } @@ -98,7 +99,7 @@ public class IntrospectionResponseGenerator : IIntrospectionResponseGenerator response.Add("scope", scopes.ToSpaceSeparatedString()); Telemetry.Metrics.Introspection(callerName, true); - await Events.RaiseAsync(new TokenIntrospectionSuccessEvent(validationResult)); + await Events.RaiseAsync(new TokenIntrospectionSuccessEvent(validationResult), ct); return response; } @@ -106,8 +107,9 @@ public class IntrospectionResponseGenerator : IIntrospectionResponseGenerator /// Checks if the API resource is allowed to introspect the scopes. /// /// The validation result. + /// The cancellation token. /// - protected virtual async Task AreExpectedScopesPresentAsync(IntrospectionRequestValidationResult validationResult) + protected virtual async Task AreExpectedScopesPresentAsync(IntrospectionRequestValidationResult validationResult, Ct ct) { var apiScopes = validationResult.Api.Scopes; var tokenScopes = validationResult.Claims.Where(c => c.Type == JwtClaimTypes.Scope); @@ -129,7 +131,7 @@ public class IntrospectionResponseGenerator : IIntrospectionResponseGenerator const string errorMessage = "Expected scopes are missing"; var callerName = validationResult.Api?.Name ?? validationResult.Client.ClientId; Telemetry.Metrics.IntrospectionFailure(callerName, errorMessage); - await Events.RaiseAsync(new TokenIntrospectionFailureEvent(validationResult.Api.Name, errorMessage, validationResult.Token, apiScopes, tokenScopes.Select(s => s.Value))); + await Events.RaiseAsync(new TokenIntrospectionFailureEvent(validationResult.Api.Name, errorMessage, validationResult.Token, apiScopes, tokenScopes.Select(s => s.Value)), ct); } return result; diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/PushedAuthorizationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/PushedAuthorizationResponseGenerator.cs index b59349af2..72a3ddc77 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/PushedAuthorizationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/PushedAuthorizationResponseGenerator.cs @@ -37,10 +37,10 @@ public class PushedAuthorizationResponseGenerator : IPushedAuthorizationResponse } /// - public async Task CreateResponseAsync(ValidatedPushedAuthorizationRequest request) + public async Task CreateResponseAsync(ValidatedPushedAuthorizationRequest request, Ct ct) { // Create a reference value - var referenceValue = await _handleGeneration.GenerateAsync(); + var referenceValue = await _handleGeneration.GenerateAsync(ct); var requestUri = $"{IdentityServerConstants.PushedAuthorizationRequestUri}:{referenceValue}"; @@ -53,7 +53,7 @@ public class PushedAuthorizationResponseGenerator : IPushedAuthorizationResponse ReferenceValue = referenceValue, ExpiresAtUtc = expiresAt, PushedParameters = request.Raw - }); + }, ct); // Return reference and expiration return new PushedAuthorizationSuccess diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/TokenResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/TokenResponseGenerator.cs index 534f95ea4..c1d3db214 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/TokenResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/TokenResponseGenerator.cs @@ -78,8 +78,9 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// Processes the response. /// /// The request. + /// The cancellation token. /// - public virtual async Task ProcessAsync(TokenRequestValidationResult request) + public virtual async Task ProcessAsync(TokenRequestValidationResult request, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenResponseGenerator.Process"); activity?.SetTag(Tracing.Properties.GrantType, request.ValidatedRequest.GrantType); @@ -87,13 +88,13 @@ public class TokenResponseGenerator : ITokenResponseGenerator return request.ValidatedRequest.GrantType switch { - OidcConstants.GrantTypes.ClientCredentials => await ProcessClientCredentialsRequestAsync(request), - OidcConstants.GrantTypes.Password => await ProcessPasswordRequestAsync(request), - OidcConstants.GrantTypes.AuthorizationCode => await ProcessAuthorizationCodeRequestAsync(request), - OidcConstants.GrantTypes.RefreshToken => await ProcessRefreshTokenRequestAsync(request), - OidcConstants.GrantTypes.DeviceCode => await ProcessDeviceCodeRequestAsync(request), - OidcConstants.GrantTypes.Ciba => await ProcessCibaRequestAsync(request), - _ => await ProcessExtensionGrantRequestAsync(request) + OidcConstants.GrantTypes.ClientCredentials => await ProcessClientCredentialsRequestAsync(request, ct), + OidcConstants.GrantTypes.Password => await ProcessPasswordRequestAsync(request, ct), + OidcConstants.GrantTypes.AuthorizationCode => await ProcessAuthorizationCodeRequestAsync(request, ct), + OidcConstants.GrantTypes.RefreshToken => await ProcessRefreshTokenRequestAsync(request, ct), + OidcConstants.GrantTypes.DeviceCode => await ProcessDeviceCodeRequestAsync(request, ct), + OidcConstants.GrantTypes.Ciba => await ProcessCibaRequestAsync(request, ct), + _ => await ProcessExtensionGrantRequestAsync(request, ct) }; } @@ -101,37 +102,40 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// Creates the response for a client credentials request. /// /// The request. + /// The cancellation token. /// - protected virtual Task ProcessClientCredentialsRequestAsync(TokenRequestValidationResult request) + protected virtual Task ProcessClientCredentialsRequestAsync(TokenRequestValidationResult request, Ct ct) { Logger.LogTrace("Creating response for client credentials request"); - return ProcessTokenRequestAsync(request); + return ProcessTokenRequestAsync(request, ct); } /// /// Creates the response for a password request. /// /// The request. + /// The cancellation token. /// - protected virtual Task ProcessPasswordRequestAsync(TokenRequestValidationResult request) + protected virtual Task ProcessPasswordRequestAsync(TokenRequestValidationResult request, Ct ct) { Logger.LogTrace("Creating response for password request"); - return ProcessTokenRequestAsync(request); + return ProcessTokenRequestAsync(request, ct); } /// /// Creates the response for an authorization code request. /// /// The request. + /// The cancellation token. /// /// Client does not exist anymore. - protected virtual async Task ProcessAuthorizationCodeRequestAsync(TokenRequestValidationResult request) + protected virtual async Task ProcessAuthorizationCodeRequestAsync(TokenRequestValidationResult request, Ct ct) { Logger.LogTrace("Creating response for authorization code request"); - var response = await ProcessTokenRequestAsync(request); + var response = await ProcessTokenRequestAsync(request, ct); if (request.ValidatedRequest.AuthorizationCode.IsOpenId) { @@ -140,7 +144,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator if (request.ValidatedRequest.AuthorizationCode.ClientId != null) { // todo: do we need this check? - client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.AuthorizationCode.ClientId); + client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.AuthorizationCode.ClientId, ct); } if (client == null) { @@ -157,8 +161,8 @@ public class TokenResponseGenerator : ITokenResponseGenerator ValidatedRequest = request.ValidatedRequest }; - var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest); - var jwt = await TokenService.CreateSecurityTokenAsync(idToken); + var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest, ct); + var jwt = await TokenService.CreateSecurityTokenAsync(idToken, ct); response.IdentityToken = jwt; } @@ -169,8 +173,9 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// Creates the response for a refresh token request. /// /// The request. + /// The cancellation token. /// - protected virtual async Task ProcessRefreshTokenRequestAsync(TokenRequestValidationResult request) + protected virtual async Task ProcessRefreshTokenRequestAsync(TokenRequestValidationResult request, Ct ct) { Logger.LogTrace("Creating response for refresh token request"); @@ -186,7 +191,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator ValidatedRequest = request.ValidatedRequest, ValidatedResources = request.ValidatedRequest.ValidatedResources }; - accessToken = await TokenService.CreateAccessTokenAsync(creationRequest); + accessToken = await TokenService.CreateAccessTokenAsync(creationRequest, ct); } else { @@ -202,7 +207,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator } } - var accessTokenString = await TokenService.CreateSecurityTokenAsync(accessToken); + var accessTokenString = await TokenService.CreateSecurityTokenAsync(accessToken, ct); request.ValidatedRequest.RefreshToken.SetAccessToken(accessToken, request.ValidatedRequest.RequestedResourceIndicator); var handle = await RefreshTokenService.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest @@ -211,11 +216,11 @@ public class TokenResponseGenerator : ITokenResponseGenerator RefreshToken = request.ValidatedRequest.RefreshToken, Client = request.ValidatedRequest.Client, MustUpdate = mustUpdate - }); + }, ct); return new TokenResponse { - IdentityToken = await CreateIdTokenFromRefreshTokenRequestAsync(request.ValidatedRequest, accessTokenString), + IdentityToken = await CreateIdTokenFromRefreshTokenRequestAsync(request.ValidatedRequest, accessTokenString, ct), AccessToken = accessTokenString, AccessTokenType = request.ValidatedRequest.ProofType == ProofType.DPoP ? OidcConstants.TokenResponse.DPoPTokenType : OidcConstants.TokenResponse.BearerTokenType, AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime, @@ -229,12 +234,13 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// Processes the response for device code grant request. /// /// The request. + /// The cancellation token. /// - protected virtual async Task ProcessDeviceCodeRequestAsync(TokenRequestValidationResult request) + protected virtual async Task ProcessDeviceCodeRequestAsync(TokenRequestValidationResult request, Ct ct) { Logger.LogTrace("Creating response for device code request"); - var response = await ProcessTokenRequestAsync(request); + var response = await ProcessTokenRequestAsync(request, ct); if (request.ValidatedRequest.DeviceCode.IsOpenId) { @@ -243,7 +249,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator if (request.ValidatedRequest.DeviceCode.ClientId != null) { // todo: do we need this check? - client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.DeviceCode.ClientId); + client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.DeviceCode.ClientId, ct); } if (client == null) { @@ -258,8 +264,8 @@ public class TokenResponseGenerator : ITokenResponseGenerator ValidatedRequest = request.ValidatedRequest }; - var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest); - var jwt = await TokenService.CreateSecurityTokenAsync(idToken); + var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest, ct); + var jwt = await TokenService.CreateSecurityTokenAsync(idToken, ct); response.IdentityToken = jwt; } @@ -270,19 +276,20 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// Processes the response for CIBA request. /// /// The request. + /// The cancellation token. /// - protected virtual async Task ProcessCibaRequestAsync(TokenRequestValidationResult request) + protected virtual async Task ProcessCibaRequestAsync(TokenRequestValidationResult request, Ct ct) { Logger.LogTrace("Creating response for CIBA request"); - var response = await ProcessTokenRequestAsync(request); + var response = await ProcessTokenRequestAsync(request, ct); // load the client that belongs to the device code Client client = null; if (request.ValidatedRequest.BackChannelAuthenticationRequest.ClientId != null) { // todo: do we need this check? - client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.BackChannelAuthenticationRequest.ClientId); + client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.BackChannelAuthenticationRequest.ClientId, ct); } if (client == null) { @@ -297,8 +304,8 @@ public class TokenResponseGenerator : ITokenResponseGenerator ValidatedRequest = request.ValidatedRequest }; - var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest); - var jwt = await TokenService.CreateSecurityTokenAsync(idToken); + var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest, ct); + var jwt = await TokenService.CreateSecurityTokenAsync(idToken, ct); response.IdentityToken = jwt; return response; @@ -308,21 +315,22 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// Creates the response for an extension grant request. /// /// The request. + /// The cancellation token. /// - protected virtual Task ProcessExtensionGrantRequestAsync(TokenRequestValidationResult request) + protected virtual Task ProcessExtensionGrantRequestAsync(TokenRequestValidationResult request, Ct ct) { Logger.LogTrace("Creating response for extension grant request"); - return ProcessTokenRequestAsync(request); + return ProcessTokenRequestAsync(request, ct); } /// /// Creates a response for a token request containing an access token and a /// refresh token if requested. /// - protected virtual async Task ProcessTokenRequestAsync(TokenRequestValidationResult validationResult) + protected virtual async Task ProcessTokenRequestAsync(TokenRequestValidationResult validationResult, Ct ct) { - (var accessToken, var refreshToken) = await CreateAccessTokenAsync(validationResult.ValidatedRequest); + (var accessToken, var refreshToken) = await CreateAccessTokenAsync(validationResult.ValidatedRequest, ct); var response = new TokenResponse { AccessToken = accessToken, @@ -345,9 +353,10 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// Creates the access/refresh token. /// /// The request. + /// The cancellation token. /// /// Client does not exist anymore. - protected virtual async Task<(string accessToken, string refreshToken)> CreateAccessTokenAsync(ValidatedTokenRequest request) + protected virtual async Task<(string accessToken, string refreshToken)> CreateAccessTokenAsync(ValidatedTokenRequest request, Ct ct) { var tokenRequest = new TokenCreationRequest { @@ -367,7 +376,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator if (request.AuthorizationCode.ClientId != null) { // todo: do we need this check? - client = await Clients.FindEnabledClientByIdAsync(request.AuthorizationCode.ClientId); + client = await Clients.FindEnabledClientByIdAsync(request.AuthorizationCode.ClientId, ct); } if (client == null) { @@ -387,7 +396,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator if (request.BackChannelAuthenticationRequest.ClientId != null) { // todo: do we need this check? - client = await Clients.FindEnabledClientByIdAsync(request.BackChannelAuthenticationRequest.ClientId); + client = await Clients.FindEnabledClientByIdAsync(request.BackChannelAuthenticationRequest.ClientId, ct); } if (client == null) { @@ -407,7 +416,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator if (request.DeviceCode.ClientId != null) { // todo: do we need this check? - client = await Clients.FindEnabledClientByIdAsync(request.DeviceCode.ClientId); + client = await Clients.FindEnabledClientByIdAsync(request.DeviceCode.ClientId, ct); } if (client == null) { @@ -424,8 +433,8 @@ public class TokenResponseGenerator : ITokenResponseGenerator authorizedScopes = request.ValidatedResources.RawScopeValues; } - var at = await TokenService.CreateAccessTokenAsync(tokenRequest); - var accessToken = await TokenService.CreateSecurityTokenAsync(at); + var at = await TokenService.CreateAccessTokenAsync(tokenRequest, ct); + var accessToken = await TokenService.CreateSecurityTokenAsync(at, ct); if (createRefreshToken) { @@ -440,7 +449,7 @@ public class TokenResponseGenerator : ITokenResponseGenerator RequestedResourceIndicator = request.RequestedResourceIndicator, ProofType = request.ProofType }; - var refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(rtRequest); + var refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(rtRequest, ct); return (accessToken, refreshToken); } @@ -452,8 +461,9 @@ public class TokenResponseGenerator : ITokenResponseGenerator /// /// The request. /// The new access token. + /// The cancellation token. /// - protected virtual async Task CreateIdTokenFromRefreshTokenRequestAsync(ValidatedTokenRequest request, string newAccessToken) + protected virtual async Task CreateIdTokenFromRefreshTokenRequestAsync(ValidatedTokenRequest request, string newAccessToken, Ct ct) { if (request.RefreshToken.AuthorizedScopes.Contains(OidcConstants.StandardScopes.OpenId)) { @@ -465,8 +475,8 @@ public class TokenResponseGenerator : ITokenResponseGenerator AccessTokenToHash = newAccessToken }; - var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest); - return await TokenService.CreateSecurityTokenAsync(idToken); + var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest, ct); + return await TokenService.CreateSecurityTokenAsync(idToken, ct); } return null; diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/TokenRevocationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/TokenRevocationResponseGenerator.cs index faa1197da..a501875a2 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/TokenRevocationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/TokenRevocationResponseGenerator.cs @@ -51,12 +51,8 @@ public class TokenRevocationResponseGenerator : ITokenRevocationResponseGenerato Logger = logger; } - /// - /// Creates the revocation endpoint response and processes the revocation request. - /// - /// The userinfo request validation result. - /// - public virtual async Task ProcessAsync(TokenRevocationRequestValidationResult validationResult) + /// + public virtual async Task ProcessAsync(TokenRevocationRequestValidationResult validationResult, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenRevocationResponseGenerator.Process"); @@ -70,22 +66,22 @@ public class TokenRevocationResponseGenerator : ITokenRevocationResponseGenerato if (validationResult.TokenTypeHint == Constants.TokenTypeHints.AccessToken) { Logger.LogTrace("Hint was for access token"); - response.Success = await RevokeAccessTokenAsync(validationResult); + response.Success = await RevokeAccessTokenAsync(validationResult, ct); } else if (validationResult.TokenTypeHint == Constants.TokenTypeHints.RefreshToken) { Logger.LogTrace("Hint was for refresh token"); - response.Success = await RevokeRefreshTokenAsync(validationResult); + response.Success = await RevokeRefreshTokenAsync(validationResult, ct); } else { Logger.LogTrace("No hint for token type"); - response.Success = await RevokeAccessTokenAsync(validationResult); + response.Success = await RevokeAccessTokenAsync(validationResult, ct); if (!response.Success) { - response.Success = await RevokeRefreshTokenAsync(validationResult); + response.Success = await RevokeRefreshTokenAsync(validationResult, ct); response.TokenType = Constants.TokenTypeHints.RefreshToken; } else @@ -100,16 +96,16 @@ public class TokenRevocationResponseGenerator : ITokenRevocationResponseGenerato /// /// Revoke access token only if it belongs to client doing the request. /// - protected virtual async Task RevokeAccessTokenAsync(TokenRevocationRequestValidationResult validationResult) + protected virtual async Task RevokeAccessTokenAsync(TokenRevocationRequestValidationResult validationResult, Ct ct) { - var token = await ReferenceTokenStore.GetReferenceTokenAsync(validationResult.Token); + var token = await ReferenceTokenStore.GetReferenceTokenAsync(validationResult.Token, ct); if (token != null) { if (token.ClientId == validationResult.Client.ClientId) { Logger.LogDebug("Access token revoked"); - await ReferenceTokenStore.RemoveReferenceTokenAsync(validationResult.Token); + await ReferenceTokenStore.RemoveReferenceTokenAsync(validationResult.Token, ct); } else { @@ -125,17 +121,17 @@ public class TokenRevocationResponseGenerator : ITokenRevocationResponseGenerato /// /// Revoke refresh token only if it belongs to client doing the request /// - protected virtual async Task RevokeRefreshTokenAsync(TokenRevocationRequestValidationResult validationResult) + protected virtual async Task RevokeRefreshTokenAsync(TokenRevocationRequestValidationResult validationResult, Ct ct) { - var token = await RefreshTokenStore.GetRefreshTokenAsync(validationResult.Token); + var token = await RefreshTokenStore.GetRefreshTokenAsync(validationResult.Token, ct); if (token != null) { if (token.ClientId == validationResult.Client.ClientId) { Logger.LogDebug("Refresh token revoked"); - await RefreshTokenStore.RemoveRefreshTokenAsync(validationResult.Token); - await ReferenceTokenStore.RemoveReferenceTokensAsync(token.SubjectId, token.ClientId, token.SessionId); + await RefreshTokenStore.RemoveRefreshTokenAsync(validationResult.Token, ct); + await ReferenceTokenStore.RemoveReferenceTokensAsync(token.SubjectId, token.ClientId, token.SessionId, ct); } else { diff --git a/identity-server/src/IdentityServer/ResponseHandling/Default/UserInfoResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/Default/UserInfoResponseGenerator.cs index d9f2002a4..33db09f9d 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/Default/UserInfoResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/Default/UserInfoResponseGenerator.cs @@ -51,9 +51,10 @@ public class UserInfoResponseGenerator : IUserInfoResponseGenerator /// Creates the response. /// /// The userinfo request validation result. + /// The cancellation token. /// /// Profile service returned incorrect subject value - public virtual async Task> ProcessAsync(UserInfoRequestValidationResult validationResult) + public virtual async Task> ProcessAsync(UserInfoRequestValidationResult validationResult, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("UserInfoResponseGenerator.Process"); @@ -62,7 +63,7 @@ public class UserInfoResponseGenerator : IUserInfoResponseGenerator // extract scopes and turn into requested claim types var scopes = validationResult.TokenValidationResult.Claims.Where(c => c.Type == JwtClaimTypes.Scope).Select(c => c.Value); - var validatedResources = await GetRequestedResourcesAsync(scopes); + var validatedResources = await GetRequestedResourcesAsync(scopes, ct); var requestedClaimTypes = await GetRequestedClaimTypesAsync(validatedResources); Logger.LogDebug("Requested claim types: {claimTypes}", requestedClaimTypes.ToSpaceSeparatedString()); @@ -75,7 +76,7 @@ public class UserInfoResponseGenerator : IUserInfoResponseGenerator requestedClaimTypes); context.RequestedResources = validatedResources; - await Profile.GetProfileDataAsync(context); + await Profile.GetProfileDataAsync(context, ct); var profileClaims = context.IssuedClaims; // construct outgoing claims @@ -109,8 +110,9 @@ public class UserInfoResponseGenerator : IUserInfoResponseGenerator /// Gets the identity resources from the scopes. /// /// + /// The cancellation token. /// - protected internal virtual async Task GetRequestedResourcesAsync(IEnumerable scopes) + protected internal virtual async Task GetRequestedResourcesAsync(IEnumerable scopes, Ct ct) { if (scopes == null || !scopes.Any()) { @@ -121,7 +123,7 @@ public class UserInfoResponseGenerator : IUserInfoResponseGenerator Logger.LogDebug("Scopes in access token: {scopes}", scopeString); // if we ever parameterized identity scopes, then we would need to invoke the resource validator's parse API here - var identityResources = await Resources.FindEnabledIdentityResourcesByScopeAsync(scopes); + var identityResources = await Resources.FindEnabledIdentityResourcesByScopeAsync(scopes, ct); var resources = new Resources(identityResources, Enumerable.Empty(), Enumerable.Empty()); var result = new ResourceValidationResult(resources); diff --git a/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeInteractionResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeInteractionResponseGenerator.cs index 8647d1199..72c76b9f8 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeInteractionResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeInteractionResponseGenerator.cs @@ -19,6 +19,7 @@ public interface IAuthorizeInteractionResponseGenerator /// /// The request. /// The consent. + /// The cancellation token. /// - Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse? consent = null); + Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse? consent, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeResponseGenerator.cs index 342f2ff81..301abee0a 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IAuthorizeResponseGenerator.cs @@ -15,6 +15,7 @@ public interface IAuthorizeResponseGenerator /// Creates the response /// /// The request. + /// The cancellation token. /// - Task CreateResponseAsync(ValidatedAuthorizeRequest request); + Task CreateResponseAsync(ValidatedAuthorizeRequest request, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/IBackchannelAuthenticationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IBackchannelAuthenticationResponseGenerator.cs index 1a4c99249..0cd82a659 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IBackchannelAuthenticationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IBackchannelAuthenticationResponseGenerator.cs @@ -15,6 +15,7 @@ public interface IBackchannelAuthenticationResponseGenerator /// Processes the response. /// /// The validation result. + /// The cancellation token. /// - Task ProcessAsync(BackchannelAuthenticationRequestValidationResult validationResult); + Task ProcessAsync(BackchannelAuthenticationRequestValidationResult validationResult, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/IDeviceAuthorizationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IDeviceAuthorizationResponseGenerator.cs index 07a7103d4..a974b7d4f 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IDeviceAuthorizationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IDeviceAuthorizationResponseGenerator.cs @@ -16,6 +16,7 @@ public interface IDeviceAuthorizationResponseGenerator /// /// The validation result. /// The base URL. + /// The cancellation token. /// - Task ProcessAsync(DeviceAuthorizationRequestValidationResult validationResult, string baseUrl); + Task ProcessAsync(DeviceAuthorizationRequestValidationResult validationResult, string baseUrl, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/IDiscoveryResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IDiscoveryResponseGenerator.cs index c24fb45c2..365c6b5df 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IDiscoveryResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IDiscoveryResponseGenerator.cs @@ -16,10 +16,12 @@ public interface IDiscoveryResponseGenerator /// /// The base URL. /// The issuer URI. - Task> CreateDiscoveryDocumentAsync(string baseUrl, string issuerUri); + /// The cancellation token. + Task> CreateDiscoveryDocumentAsync(string baseUrl, string issuerUri, Ct ct); /// /// Creates the JWK document. /// - Task> CreateJwkDocumentAsync(); + /// The cancellation token. + Task> CreateJwkDocumentAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/IIntrospectionResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IIntrospectionResponseGenerator.cs index fc11b8651..f9cffbd08 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IIntrospectionResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IIntrospectionResponseGenerator.cs @@ -15,6 +15,7 @@ public interface IIntrospectionResponseGenerator /// Processes the response. /// /// The validation result. + /// The cancellation token. /// - Task> ProcessAsync(IntrospectionRequestValidationResult validationResult); + Task> ProcessAsync(IntrospectionRequestValidationResult validationResult, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/IPushedAuthorizationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IPushedAuthorizationResponseGenerator.cs index 02d008e46..65751683a 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IPushedAuthorizationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IPushedAuthorizationResponseGenerator.cs @@ -19,6 +19,7 @@ public interface IPushedAuthorizationResponseGenerator /// Asynchronously creates a response model from a validated pushed authorization request. /// /// The validated pushed authorization request. + /// The cancellation token. /// A task that contains response model indicating either success or failure. - Task CreateResponseAsync(ValidatedPushedAuthorizationRequest request); + Task CreateResponseAsync(ValidatedPushedAuthorizationRequest request, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/ITokenResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/ITokenResponseGenerator.cs index 0931233bb..15fe2f92d 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/ITokenResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/ITokenResponseGenerator.cs @@ -17,6 +17,7 @@ public interface ITokenResponseGenerator /// Processes the response. /// /// The validation result. + /// The cancellation token. /// - Task ProcessAsync(TokenRequestValidationResult validationResult); + Task ProcessAsync(TokenRequestValidationResult validationResult, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/ITokenRevocationResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/ITokenRevocationResponseGenerator.cs index 5f343cd0a..490fbbde4 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/ITokenRevocationResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/ITokenRevocationResponseGenerator.cs @@ -15,6 +15,7 @@ public interface ITokenRevocationResponseGenerator /// Creates the revocation endpoint response and processes the revocation request. /// /// The userinfo request validation result. + /// The cancellation token. /// - Task ProcessAsync(TokenRevocationRequestValidationResult validationResult); + Task ProcessAsync(TokenRevocationRequestValidationResult validationResult, Ct ct); } diff --git a/identity-server/src/IdentityServer/ResponseHandling/IUserInfoResponseGenerator.cs b/identity-server/src/IdentityServer/ResponseHandling/IUserInfoResponseGenerator.cs index 0b0241076..2fc211b4a 100644 --- a/identity-server/src/IdentityServer/ResponseHandling/IUserInfoResponseGenerator.cs +++ b/identity-server/src/IdentityServer/ResponseHandling/IUserInfoResponseGenerator.cs @@ -15,6 +15,7 @@ public interface IUserInfoResponseGenerator /// Creates the response. /// /// The userinfo request validation result. + /// The cancellation token. /// - Task> ProcessAsync(UserInfoRequestValidationResult validationResult); + Task> ProcessAsync(UserInfoRequestValidationResult validationResult, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/Default/BackChannelLogoutHttpClient.cs b/identity-server/src/IdentityServer/Services/Default/BackChannelLogoutHttpClient.cs index b81e0394f..4af02ec07 100644 --- a/identity-server/src/IdentityServer/Services/Default/BackChannelLogoutHttpClient.cs +++ b/identity-server/src/IdentityServer/Services/Default/BackChannelLogoutHttpClient.cs @@ -14,19 +14,16 @@ public class DefaultBackChannelLogoutHttpClient : IBackChannelLogoutHttpClient { private readonly HttpClient _client; private readonly ILogger _logger; - private readonly ICancellationTokenProvider _cancellationTokenProvider; /// /// Constructor for BackChannelLogoutHttpClient. /// /// /// - /// - public DefaultBackChannelLogoutHttpClient(HttpClient client, ILoggerFactory loggerFactory, ICancellationTokenProvider cancellationTokenProvider) + public DefaultBackChannelLogoutHttpClient(HttpClient client, ILoggerFactory loggerFactory) { _client = client; _logger = loggerFactory.CreateLogger(); - _cancellationTokenProvider = cancellationTokenProvider; } /// @@ -34,15 +31,16 @@ public class DefaultBackChannelLogoutHttpClient : IBackChannelLogoutHttpClient /// /// /// + /// The cancellation token. /// - public async Task PostAsync(string url, Dictionary payload) + public async Task PostAsync(string url, Dictionary payload, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultBackChannelLogoutHttpClient.Post"); try { using var formEncodedContent = new FormUrlEncodedContent(payload); - var response = await _client.PostAsync(url, formEncodedContent, _cancellationTokenProvider.CancellationToken); + var response = await _client.PostAsync(url, formEncodedContent, ct); if (response.IsSuccessStatusCode) { _logger.LogDebug("Response from back-channel logout endpoint: {url} status code: {status}", url, (int)response.StatusCode); @@ -51,7 +49,7 @@ public class DefaultBackChannelLogoutHttpClient : IBackChannelLogoutHttpClient { BackChannelError err = null; - var errorjson = await response.Content.ReadAsStringAsync(); + var errorjson = await response.Content.ReadAsStringAsync(ct); try { err = JsonSerializer.Deserialize(errorjson); diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultBackChannelLogoutService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultBackChannelLogoutService.cs index b396be22a..2906510cb 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultBackChannelLogoutService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultBackChannelLogoutService.cs @@ -75,14 +75,14 @@ public class DefaultBackChannelLogoutService : IBackChannelLogoutService } /// - public virtual async Task SendLogoutNotificationsAsync(LogoutNotificationContext context) + public virtual async Task SendLogoutNotificationsAsync(LogoutNotificationContext context, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultBackChannelLogoutService.SendLogoutNotifications"); - var backChannelRequests = await LogoutNotificationService.GetBackChannelLogoutNotificationsAsync(context); + var backChannelRequests = await LogoutNotificationService.GetBackChannelLogoutNotificationsAsync(context, ct); if (backChannelRequests.Any()) { - await SendLogoutNotificationsAsync(backChannelRequests); + await SendLogoutNotificationsAsync(backChannelRequests, ct); } } @@ -90,8 +90,9 @@ public class DefaultBackChannelLogoutService : IBackChannelLogoutService /// Sends the logout notifications for the collection of clients. /// /// + /// The cancellation token. /// - protected virtual async Task SendLogoutNotificationsAsync(IEnumerable requests) + protected virtual async Task SendLogoutNotificationsAsync(IEnumerable requests, Ct ct) { requests ??= []; var logoutRequestsWithPayload = new List<(BackChannelLogoutRequest, Dictionary)>(); @@ -102,11 +103,11 @@ public class DefaultBackChannelLogoutService : IBackChannelLogoutService // implementation doesn't make parallel use of a single DB context. // Since the signing key material should be cached, only the // first serial operation will call the db. - var payload = await CreateFormPostPayloadAsync(backChannelLogoutRequest); + var payload = await CreateFormPostPayloadAsync(backChannelLogoutRequest, ct); logoutRequestsWithPayload.Add((backChannelLogoutRequest, payload)); } - var logoutRequests = logoutRequestsWithPayload.Select(request => PostLogoutJwt(request.Item1, request.Item2)).ToArray(); + var logoutRequests = logoutRequestsWithPayload.Select(request => PostLogoutJwt(request.Item1, request.Item2, ct)).ToArray(); await Task.WhenAll(logoutRequests); } @@ -115,17 +116,19 @@ public class DefaultBackChannelLogoutService : IBackChannelLogoutService /// /// /// + /// The cancellation token. /// - protected virtual Task PostLogoutJwt(BackChannelLogoutRequest client, Dictionary data) => HttpClient.PostAsync(client.LogoutUri, data); + protected virtual Task PostLogoutJwt(BackChannelLogoutRequest client, Dictionary data, Ct ct) => HttpClient.PostAsync(client.LogoutUri, data, ct); /// /// Creates the form-url-encoded payload (as a dictionary) to send to the client. /// /// + /// The cancellation token. /// - protected async Task> CreateFormPostPayloadAsync(BackChannelLogoutRequest request) + protected async Task> CreateFormPostPayloadAsync(BackChannelLogoutRequest request, Ct ct) { - var token = await CreateTokenAsync(request); + var token = await CreateTokenAsync(request, ct); var data = new Dictionary { @@ -138,8 +141,9 @@ public class DefaultBackChannelLogoutService : IBackChannelLogoutService /// Creates the JWT used for the back-channel logout notification. /// /// + /// The cancellation token. /// The token. - protected virtual async Task CreateTokenAsync(BackChannelLogoutRequest request) + protected virtual async Task CreateTokenAsync(BackChannelLogoutRequest request, Ct ct) { var claims = await CreateClaimsForTokenAsync(request); if (claims.Any(x => x.Type == JwtClaimTypes.Nonce)) @@ -149,11 +153,11 @@ public class DefaultBackChannelLogoutService : IBackChannelLogoutService if (request.Issuer != null) { - return await Tools.IssueJwtAsync(DefaultLogoutTokenLifetime, request.Issuer, IdentityServerConstants.TokenTypes.LogoutToken, claims); + return await Tools.IssueJwtAsync(DefaultLogoutTokenLifetime, request.Issuer, IdentityServerConstants.TokenTypes.LogoutToken, claims, ct); } - var issuer = await IssuerNameService.GetCurrentAsync(); - return await Tools.IssueJwtAsync(DefaultLogoutTokenLifetime, issuer, IdentityServerConstants.TokenTypes.LogoutToken, claims); + var issuer = await IssuerNameService.GetCurrentAsync(ct); + return await Tools.IssueJwtAsync(DefaultLogoutTokenLifetime, issuer, IdentityServerConstants.TokenTypes.LogoutToken, claims, ct); } /// diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultBackchannelAuthenticationInteractionService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultBackchannelAuthenticationInteractionService.cs index 621e99f52..a5ef7f062 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultBackchannelAuthenticationInteractionService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultBackchannelAuthenticationInteractionService.cs @@ -45,14 +45,14 @@ public class DefaultBackchannelAuthenticationInteractionService : IBackchannelAu _logger = logger; } - private async Task CreateAsync(BackChannelAuthenticationRequest request) + private async Task CreateAsync(BackChannelAuthenticationRequest request, Ct ct) { if (request == null) { return null; } - var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId); + var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId, ct); if (client == null) { return null; @@ -63,7 +63,7 @@ public class DefaultBackchannelAuthenticationInteractionService : IBackchannelAu Client = client, Scopes = request.RequestedScopes, ResourceIndicators = request.RequestedResourceIndicators, - }); + }, ct); return new BackchannelUserLoginRequest { @@ -79,32 +79,32 @@ public class DefaultBackchannelAuthenticationInteractionService : IBackchannelAu } /// - public async Task GetLoginRequestByInternalIdAsync(string id) + public async Task GetLoginRequestByInternalIdAsync(string id, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultBackchannelAuthenticationInteractionService.GetLoginRequestByInternalId"); - var request = await _requestStore.GetByInternalIdAsync(id); - return await CreateAsync(request); + var request = await _requestStore.GetByInternalIdAsync(id, ct); + return await CreateAsync(request, ct); } /// - public async Task> GetPendingLoginRequestsForCurrentUserAsync() + public async Task> GetPendingLoginRequestsForCurrentUserAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultBackchannelAuthenticationInteractionService.GetPendingLoginRequestsForCurrentUser"); var list = new List(); - var user = await _session.GetUserAsync(); + var user = await _session.GetUserAsync(ct); if (user != null) { _logger.LogDebug("No user present"); - var items = await _requestStore.GetLoginsForUserAsync(user.GetSubjectId()); + var items = await _requestStore.GetLoginsForUserAsync(user.GetSubjectId(), ct); foreach (var item in items) { if (!item.IsComplete) { - var req = await CreateAsync(item); + var req = await CreateAsync(item, ct); if (req != null) { list.Add(req); @@ -117,19 +117,19 @@ public class DefaultBackchannelAuthenticationInteractionService : IBackchannelAu } /// - public async Task CompleteLoginRequestAsync(CompleteBackchannelLoginRequest completionRequest) + public async Task CompleteLoginRequestAsync(CompleteBackchannelLoginRequest completionRequest, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultBackchannelAuthenticationInteractionService.CompleteLoginRequest"); ArgumentNullException.ThrowIfNull(completionRequest); - var request = await _requestStore.GetByInternalIdAsync(completionRequest.InternalId); + var request = await _requestStore.GetByInternalIdAsync(completionRequest.InternalId, ct); if (request == null) { throw new InvalidOperationException("Invalid backchannel authentication request id."); } - var subject = completionRequest.Subject ?? await _session.GetUserAsync(); + var subject = completionRequest.Subject ?? await _session.GetUserAsync(ct); if (subject == null) { throw new InvalidOperationException("Invalid subject."); @@ -141,7 +141,7 @@ public class DefaultBackchannelAuthenticationInteractionService : IBackchannelAu } var sid = (completionRequest.Subject == null) ? - await _session.GetSessionIdAsync() : + await _session.GetSessionIdAsync(ct) : completionRequest.SessionId; if (completionRequest.ScopesValuesConsented != null) @@ -170,7 +170,7 @@ public class DefaultBackchannelAuthenticationInteractionService : IBackchannelAu request.AuthorizedScopes = completionRequest.ScopesValuesConsented; request.Description = completionRequest.Description; - await _requestStore.UpdateByInternalIdAsync(completionRequest.InternalId, request); + await _requestStore.UpdateByInternalIdAsync(completionRequest.InternalId, request, ct); _logger.LogDebug("Successful update for backchannel authentication request id {id}", completionRequest.InternalId); } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultCache.cs b/identity-server/src/IdentityServer/Services/Default/DefaultCache.cs index 3ab28d855..2cceecc46 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultCache.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultCache.cs @@ -62,7 +62,7 @@ public class DefaultCache : ICache protected string GetKey(string key) => typeof(T).FullName + KeySeparator + key; /// - public Task GetAsync(string key) + public Task GetAsync(string key, Ct ct) { using var activity = Tracing.CacheActivitySource.StartActivity("DefaultCache.Get"); @@ -72,7 +72,7 @@ public class DefaultCache : ICache } /// - public Task SetAsync(string key, T item, TimeSpan expiration) + public Task SetAsync(string key, T item, TimeSpan expiration, Ct ct) { using var activity = Tracing.CacheActivitySource.StartActivity("DefaultCache.Set"); @@ -82,7 +82,7 @@ public class DefaultCache : ICache } /// - public Task RemoveAsync(string key) + public Task RemoveAsync(string key, Ct ct) { using var activity = Tracing.CacheActivitySource.StartActivity("DefaultCache.Remove"); @@ -92,7 +92,7 @@ public class DefaultCache : ICache } /// - public async Task GetOrAddAsync(string key, TimeSpan duration, Func> get) + public async Task GetOrAddAsync(string key, TimeSpan duration, Func> get, Ct ct) { using var activity = Tracing.CacheActivitySource.StartActivity("DefaultCache.GetOrAdd"); @@ -102,7 +102,7 @@ public class DefaultCache : ICache return null; } - var item = await GetAsync(key); + var item = await GetAsync(key, ct); if (item == null) { @@ -114,7 +114,7 @@ public class DefaultCache : ICache try { // double check - item = await GetAsync(key); + item = await GetAsync(key, ct); if (item == null) { @@ -125,7 +125,7 @@ public class DefaultCache : ICache if (item != null) { Logger.LogTrace("Setting item in cache for {cacheKey}", key); - await SetAsync(key, item, duration); + await SetAsync(key, item, duration, ct); } } else diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultCancellationTokenProvider.cs b/identity-server/src/IdentityServer/Services/Default/DefaultCancellationTokenProvider.cs deleted file mode 100644 index 451a5e148..000000000 --- a/identity-server/src/IdentityServer/Services/Default/DefaultCancellationTokenProvider.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Duende Software. All rights reserved. -// See LICENSE in the project root for license information. - - -using Microsoft.AspNetCore.Http; - -namespace Duende.IdentityServer.Services.Default; - -/// -/// Provides cancellation tokens based on the incoming http request -/// -internal class DefaultCancellationTokenProvider : ICancellationTokenProvider -{ - private readonly IHttpContextAccessor _httpContextAccessor; - - /// - /// Constructor - /// - /// - public DefaultCancellationTokenProvider(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; - - /// - /// Provides access to the cancellation token from the http context - /// - public CT CancellationToken => _httpContextAccessor.HttpContext?.RequestAborted ?? CT.None; -} diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultClaimsService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultClaimsService.cs index 07f445e19..c19f45fd1 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultClaimsService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultClaimsService.cs @@ -38,17 +38,8 @@ public class DefaultClaimsService : IClaimsService Profile = profile; } - /// - /// Returns claims for an identity token - /// - /// The subject - /// The requested resources - /// Specifies if all claims should be included in the token, or if the userinfo endpoint can be used to retrieve them - /// The raw request - /// - /// Claims for the identity token - /// - public virtual async Task> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, bool includeAllIdentityClaims, ValidatedRequest request) + /// + public virtual async Task> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, bool includeAllIdentityClaims, ValidatedRequest request, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultClaimsService.GetIdentityTokenClaims"); @@ -85,7 +76,7 @@ public class DefaultClaimsService : IClaimsService ValidatedRequest = request }; - await Profile.GetProfileDataAsync(context); + await Profile.GetProfileDataAsync(context, ct); var claims = FilterProtocolClaims(context.IssuedClaims); if (claims != null) @@ -101,16 +92,8 @@ public class DefaultClaimsService : IClaimsService return outputClaims; } - /// - /// Returns claims for an access token. - /// - /// The subject. - /// The validated resource result - /// The raw request. - /// - /// Claims for the access token - /// - public virtual async Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resourceResult, ValidatedRequest request) + /// + public virtual async Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resourceResult, ValidatedRequest request, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultClaimsService.GetAccessTokenClaims"); @@ -206,7 +189,7 @@ public class DefaultClaimsService : IClaimsService ValidatedRequest = request }; - await Profile.GetProfileDataAsync(context); + await Profile.GetProfileDataAsync(context, ct); var claims = FilterProtocolClaims(context.IssuedClaims); if (claims != null) diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultConsentService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultConsentService.cs index ae016ad02..5f0b2f5e4 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultConsentService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultConsentService.cs @@ -51,6 +51,7 @@ public class DefaultConsentService : IConsentService /// The user. /// The client. /// The parsed scopes. + /// The cancellation token. /// /// Boolean if consent is required. /// @@ -59,7 +60,7 @@ public class DefaultConsentService : IConsentService /// or /// subject /// - public virtual async Task RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes) + public virtual async Task RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultConsentService.RequiresConsent"); @@ -100,7 +101,7 @@ public class DefaultConsentService : IConsentService return true; } - var consent = await UserConsentStore.GetUserConsentAsync(subject.GetSubjectId(), client.ClientId); + var consent = await UserConsentStore.GetUserConsentAsync(subject.GetSubjectId(), client.ClientId, ct); if (consent == null) { @@ -111,7 +112,7 @@ public class DefaultConsentService : IConsentService if (consent.Expiration.HasExpired(TimeProvider.GetUtcNow().UtcDateTime)) { Logger.LogDebug("Consent found in consent store is expired, consent is required"); - await UserConsentStore.RemoveUserConsentAsync(consent.SubjectId, consent.ClientId); + await UserConsentStore.RemoveUserConsentAsync(consent.SubjectId, consent.ClientId, ct); return true; } @@ -143,13 +144,14 @@ public class DefaultConsentService : IConsentService /// The client. /// The subject. /// The parsed scopes. + /// The cancellation token. /// /// /// client /// or /// subject /// - public virtual async Task UpdateConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes) + public virtual async Task UpdateConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultConsentService.UpdateConsent"); @@ -179,13 +181,13 @@ public class DefaultConsentService : IConsentService consent.Expiration = consent.CreationTime.AddSeconds(client.ConsentLifetime.Value); } - await UserConsentStore.StoreUserConsentAsync(consent); + await UserConsentStore.StoreUserConsentAsync(consent, ct); } else { Logger.LogDebug("Client allows remembering consent, and no scopes provided. Removing consent from consent store for subject: {subject}", subject.GetSubjectId()); - await UserConsentStore.RemoveUserConsentAsync(subjectId, clientId); + await UserConsentStore.RemoveUserConsentAsync(subjectId, clientId, ct); } } } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultCorsPolicyService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultCorsPolicyService.cs index 3f3e03332..236f911a5 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultCorsPolicyService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultCorsPolicyService.cs @@ -41,12 +41,8 @@ public class DefaultCorsPolicyService : ICorsPolicyService /// public bool AllowAll { get; set; } - /// - /// Determines whether the origin allowed. - /// - /// The origin. - /// - public virtual Task IsOriginAllowedAsync(string origin) + /// + public virtual Task IsOriginAllowedAsync(string origin, Ct _) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultCorsPolicyService.IsOriginAllowed"); diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowCodeService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowCodeService.cs index 9300a2e1b..5e62e4509 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowCodeService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowCodeService.cs @@ -28,69 +28,47 @@ public class DefaultDeviceFlowCodeService : IDeviceFlowCodeService _handleGenerationService = handleGenerationService; } - /// - /// Stores the device authorization request. - /// - /// The user code. - /// The data. - /// - public async Task StoreDeviceAuthorizationAsync(string userCode, DeviceCode data) + /// + public async Task StoreDeviceAuthorizationAsync(string userCode, DeviceCode data, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultDeviceFlowCodeService.SendLogoutNotifStoreDeviceAuthorization"); - var deviceCode = await _handleGenerationService.GenerateAsync(); + var deviceCode = await _handleGenerationService.GenerateAsync(ct); - await _store.StoreDeviceAuthorizationAsync(deviceCode.Sha256(), userCode.Sha256(), data); + await _store.StoreDeviceAuthorizationAsync(deviceCode.Sha256(), userCode.Sha256(), data, ct); return deviceCode; } - /// - /// Finds device authorization by user code. - /// - /// The user code. - /// - public Task FindByUserCodeAsync(string userCode) + /// + public Task FindByUserCodeAsync(string userCode, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultDeviceFlowCodeService.FindByUserCode"); - return _store.FindByUserCodeAsync(userCode.Sha256()); + return _store.FindByUserCodeAsync(userCode.Sha256(), ct); } - /// - /// Finds device authorization by device code. - /// - /// The device code. - /// - public Task FindByDeviceCodeAsync(string deviceCode) + /// + public Task FindByDeviceCodeAsync(string deviceCode, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultDeviceFlowCodeService.FindByDeviceCode"); - return _store.FindByDeviceCodeAsync(deviceCode.Sha256()); + return _store.FindByDeviceCodeAsync(deviceCode.Sha256(), ct); } - /// - /// Updates device authorization, searching by user code. - /// - /// The user code. - /// The data. - /// - public Task UpdateByUserCodeAsync(string userCode, DeviceCode data) + /// + public Task UpdateByUserCodeAsync(string userCode, DeviceCode data, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultDeviceFlowCodeService.UpdateByUserCode"); - return _store.UpdateByUserCodeAsync(userCode.Sha256(), data); + return _store.UpdateByUserCodeAsync(userCode.Sha256(), data, ct); } - /// - /// Removes the device authorization, searching by device code. - /// - /// The device code. - /// - public Task RemoveByDeviceCodeAsync(string deviceCode) + /// + public Task RemoveByDeviceCodeAsync(string deviceCode, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultDeviceFlowCodeService.RemoveByDeviceCode"); - return _store.RemoveByDeviceCodeAsync(deviceCode.Sha256()); + return _store.RemoveByDeviceCodeAsync(deviceCode.Sha256(), ct); } } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowInteractionService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowInteractionService.cs index 2f3ba929d..995316899 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowInteractionService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultDeviceFlowInteractionService.cs @@ -31,15 +31,15 @@ internal class DefaultDeviceFlowInteractionService : IDeviceFlowInteractionServi _logger = logger; } - public async Task GetAuthorizationContextAsync(string userCode) + public async Task GetAuthorizationContextAsync(string userCode, Ct ct) { - var deviceAuth = await _devices.FindByUserCodeAsync(userCode); + var deviceAuth = await _devices.FindByUserCodeAsync(userCode, ct); if (deviceAuth == null) { return null; } - var client = await _clients.FindEnabledClientByIdAsync(deviceAuth.ClientId); + var client = await _clients.FindEnabledClientByIdAsync(deviceAuth.ClientId, ct); if (client == null) { return null; @@ -49,7 +49,7 @@ internal class DefaultDeviceFlowInteractionService : IDeviceFlowInteractionServi { Client = client, Scopes = deviceAuth.RequestedScopes, - }); + }, ct); return new DeviceFlowAuthorizationRequest { @@ -58,30 +58,30 @@ internal class DefaultDeviceFlowInteractionService : IDeviceFlowInteractionServi }; } - public async Task HandleRequestAsync(string userCode, ConsentResponse consent) + public async Task HandleRequestAsync(string userCode, ConsentResponse consent, Ct ct) { ArgumentNullException.ThrowIfNull(userCode); ArgumentNullException.ThrowIfNull(consent); - var deviceAuth = await _devices.FindByUserCodeAsync(userCode); + var deviceAuth = await _devices.FindByUserCodeAsync(userCode, ct); if (deviceAuth == null) { return LogAndReturnError("Invalid user code", "Device authorization failure - user code is invalid"); } - var client = await _clients.FindEnabledClientByIdAsync(deviceAuth.ClientId); + var client = await _clients.FindEnabledClientByIdAsync(deviceAuth.ClientId, ct); if (client == null) { return LogAndReturnError("Invalid client", "Device authorization failure - requesting client is invalid"); } - var subject = await _session.GetUserAsync(); + var subject = await _session.GetUserAsync(ct); if (subject == null) { return LogAndReturnError("No user present in device flow request", "Device authorization failure - no user found"); } - var sid = await _session.GetSessionIdAsync(); + var sid = await _session.GetSessionIdAsync(ct); deviceAuth.IsAuthorized = true; deviceAuth.Subject = subject; @@ -96,7 +96,7 @@ internal class DefaultDeviceFlowInteractionService : IDeviceFlowInteractionServi //await _consentMessageStore.WriteAsync(consentRequest.Id, new Message(consent, _clock.UtcNow.UtcDateTime)); } - await _devices.UpdateByUserCodeAsync(userCode, deviceAuth); + await _devices.UpdateByUserCodeAsync(userCode, deviceAuth, ct); return new DeviceFlowInteractionResult(); } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultEventService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultEventService.cs index 0b4c4b68e..7b3e74a5e 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultEventService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultEventService.cs @@ -50,20 +50,15 @@ public class DefaultEventService : IEventService TimeProvider = timeProvider; } - /// - /// Raises the specified event. - /// - /// The event. - /// - /// evt - public async Task RaiseAsync(Event evt) + /// + public async Task RaiseAsync(Event evt, Ct ct) { ArgumentNullException.ThrowIfNull(evt); if (CanRaiseEvent(evt)) { - await PrepareEventAsync(evt); - await Sink.PersistAsync(evt); + await PrepareEventAsync(evt, ct); + await Sink.PersistAsync(evt, ct); } } @@ -96,8 +91,9 @@ public class DefaultEventService : IEventService /// Prepares the event. /// /// The evt. + /// The cancellation token. /// - protected virtual async Task PrepareEventAsync(Event evt) + protected virtual async Task PrepareEventAsync(Event evt, Ct ct) { evt.TimeStamp = TimeProvider.GetUtcNow().DateTime; using var process = Process.GetCurrentProcess(); diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultEventSink.cs b/identity-server/src/IdentityServer/Services/Default/DefaultEventSink.cs index ec23f2251..3fb636418 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultEventSink.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultEventSink.cs @@ -23,12 +23,8 @@ public class DefaultEventSink : IEventSink /// The logger. public DefaultEventSink(ILogger logger) => _logger = logger; - /// - /// Raises the specified event. - /// - /// The event. - /// evt - public virtual Task PersistAsync(Event evt) + /// + public virtual Task PersistAsync(Event evt, Ct _) { ArgumentNullException.ThrowIfNull(evt); diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultHandleGenerationService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultHandleGenerationService.cs index 6037340ec..82af5fc8b 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultHandleGenerationService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultHandleGenerationService.cs @@ -12,10 +12,6 @@ namespace Duende.IdentityServer.Services; /// public class DefaultHandleGenerationService : IHandleGenerationService { - /// - /// Generates a handle. - /// - /// The length. - /// - public Task GenerateAsync(int length) => Task.FromResult(CryptoRandom.CreateUniqueId(length, CryptoRandom.OutputFormat.Hex)); + /// + public Task GenerateAsync(Ct _, int length = 32) => Task.FromResult(CryptoRandom.CreateUniqueId(length, CryptoRandom.OutputFormat.Hex)); } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultIdentityServerInteractionService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultIdentityServerInteractionService.cs index c374e08f9..ccea3bdc2 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultIdentityServerInteractionService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultIdentityServerInteractionService.cs @@ -44,11 +44,12 @@ internal class DefaultIdentityServerInteractionService : IIdentityServerInteract _logger = logger; } - public async Task GetAuthorizationContextAsync(string returnUrl) + /// + public async Task GetAuthorizationContextAsync(string returnUrl, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.GetAuthorizationContext"); - var result = await _returnUrlParser.ParseAsync(returnUrl); + var result = await _returnUrlParser.ParseAsync(returnUrl, ct); if (result != null) { @@ -62,33 +63,35 @@ internal class DefaultIdentityServerInteractionService : IIdentityServerInteract return result; } - public async Task GetLogoutContextAsync(string logoutId) + /// + public async Task GetLogoutContextAsync(string logoutId, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.GetLogoutContext"); - var msg = await _logoutMessageStore.ReadAsync(logoutId); + var msg = await _logoutMessageStore.ReadAsync(logoutId, ct); var iframeUrl = await _context.HttpContext.GetIdentityServerSignoutFrameCallbackUrlAsync(msg?.Data); return new LogoutRequest(iframeUrl, msg?.Data); } - public async Task CreateLogoutContextAsync() + /// + public async Task CreateLogoutContextAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.CreateLogoutContext"); - var user = await _userSession.GetUserAsync(); + var user = await _userSession.GetUserAsync(ct); if (user != null) { - var clientIds = await _userSession.GetClientListAsync(); + var clientIds = await _userSession.GetClientListAsync(ct); if (clientIds.Any()) { - var sid = await _userSession.GetSessionIdAsync(); + var sid = await _userSession.GetSessionIdAsync(ct); var msg = new Message(new LogoutMessage { SubjectId = user.GetSubjectId(), SessionId = sid, ClientIds = clientIds }, _timeProvider.GetUtcNow().UtcDateTime); - var id = await _logoutMessageStore.WriteAsync(msg); + var id = await _logoutMessageStore.WriteAsync(msg, ct); return id; } } @@ -96,13 +99,14 @@ internal class DefaultIdentityServerInteractionService : IIdentityServerInteract return null; } - public async Task GetErrorContextAsync(string errorId) + /// + public async Task GetErrorContextAsync(string errorId, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.GetErrorContext"); if (errorId != null) { - var result = await _errorMessageStore.ReadAsync(errorId); + var result = await _errorMessageStore.ReadAsync(errorId, ct); var data = result?.Data; if (data != null) { @@ -120,13 +124,14 @@ internal class DefaultIdentityServerInteractionService : IIdentityServerInteract return null; } - public async Task GrantConsentAsync(AuthorizationRequest request, ConsentResponse consent, string subject = null) + /// + public async Task GrantConsentAsync(AuthorizationRequest request, ConsentResponse consent, Ct ct, string subject = null) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.GrantConsent"); if (subject == null) { - var user = await _userSession.GetUserAsync(); + var user = await _userSession.GetUserAsync(ct); subject = user?.GetSubjectId(); } @@ -136,10 +141,11 @@ internal class DefaultIdentityServerInteractionService : IIdentityServerInteract } var consentRequest = new ConsentRequest(request, subject); - await _consentMessageStore.WriteAsync(consentRequest.Id, new Message(consent, _timeProvider.GetUtcNow().UtcDateTime)); + await _consentMessageStore.WriteAsync(consentRequest.Id, new Message(consent, _timeProvider.GetUtcNow().UtcDateTime), ct); } - public Task DenyAuthorizationAsync(AuthorizationRequest request, AuthorizationError error, string errorDescription = null) + /// + public Task DenyAuthorizationAsync(AuthorizationRequest request, AuthorizationError error, Ct ct, string errorDescription = null) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.DenyAuthorization"); @@ -148,7 +154,7 @@ internal class DefaultIdentityServerInteractionService : IIdentityServerInteract Error = error, ErrorDescription = errorDescription }; - return GrantConsentAsync(request, response); + return GrantConsentAsync(request, response, ct); } public bool IsValidReturnUrl(string returnUrl) @@ -169,42 +175,45 @@ internal class DefaultIdentityServerInteractionService : IIdentityServerInteract return result; } - public async Task> GetAllUserGrantsAsync() + /// + public async Task> GetAllUserGrantsAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.GetAllUserGrants"); - var user = await _userSession.GetUserAsync(); + var user = await _userSession.GetUserAsync(ct); if (user != null) { var subject = user.GetSubjectId(); - return await _grants.GetAllGrantsAsync(subject); + return await _grants.GetAllGrantsAsync(subject, ct); } return Enumerable.Empty(); } - public async Task RevokeUserConsentAsync(string clientId) + /// + public async Task RevokeUserConsentAsync(string clientId, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.RevokeUserConsent"); - var user = await _userSession.GetUserAsync(); + var user = await _userSession.GetUserAsync(ct); if (user != null) { var subject = user.GetSubjectId(); - await _grants.RemoveAllGrantsAsync(subject, clientId); + await _grants.RemoveAllGrantsAsync(subject, ct, clientId); } } - public async Task RevokeTokensForCurrentSessionAsync() + /// + public async Task RevokeTokensForCurrentSessionAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.RevokeTokensForCurrentSession"); - var user = await _userSession.GetUserAsync(); + var user = await _userSession.GetUserAsync(ct); if (user != null) { var subject = user.GetSubjectId(); - var sessionId = await _userSession.GetSessionIdAsync(); - await _grants.RemoveAllGrantsAsync(subject, sessionId: sessionId); + var sessionId = await _userSession.GetSessionIdAsync(ct); + await _grants.RemoveAllGrantsAsync(subject, ct, sessionId: sessionId); } } } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultIssuerNameService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultIssuerNameService.cs index 77376910e..c5387c05e 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultIssuerNameService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultIssuerNameService.cs @@ -31,7 +31,7 @@ public class DefaultIssuerNameService : IIssuerNameService } /// - public Task GetCurrentAsync() + public Task GetCurrentAsync(Ct ct) { // if they've explicitly configured a URI then use it, // otherwise dynamically calculate it diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultJwtRequestUriHttpClient.cs b/identity-server/src/IdentityServer/Services/Default/DefaultJwtRequestUriHttpClient.cs index ffb07ba1a..a7ce1d534 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultJwtRequestUriHttpClient.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultJwtRequestUriHttpClient.cs @@ -18,7 +18,6 @@ public class DefaultJwtRequestUriHttpClient : IJwtRequestUriHttpClient private readonly HttpClient _client; private readonly IdentityServerOptions _options; private readonly SanitizedLogger _sanitizedLogger; - private readonly ICancellationTokenProvider _cancellationTokenProvider; /// /// ctor @@ -26,26 +25,24 @@ public class DefaultJwtRequestUriHttpClient : IJwtRequestUriHttpClient /// An HTTP client /// The options. /// The logger factory - /// public DefaultJwtRequestUriHttpClient(HttpClient client, IdentityServerOptions options, - ILoggerFactory loggerFactory, ICancellationTokenProvider cancellationTokenProvider) + ILoggerFactory loggerFactory) { _client = client; _options = options; _sanitizedLogger = new SanitizedLogger(loggerFactory.CreateLogger()); - _cancellationTokenProvider = cancellationTokenProvider; } /// - public async Task GetJwtAsync(string url, Client client) + public async Task GetJwtAsync(string url, Client client, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultJwtRequestUriHttpClient.GetJwt"); using var req = new HttpRequestMessage(HttpMethod.Get, url); req.Options.TryAdd(IdentityServerConstants.JwtRequestClientKey, client); - var response = await _client.SendAsync(req, _cancellationTokenProvider.CancellationToken); + var response = await _client.SendAsync(req, ct); if (response.StatusCode == System.Net.HttpStatusCode.OK) { if (_options.StrictJarValidation) @@ -61,7 +58,7 @@ public class DefaultJwtRequestUriHttpClient : IJwtRequestUriHttpClient _sanitizedLogger.LogDebug("Success http response from jwt url {url}", url); - var json = await response.Content.ReadAsStringAsync(); + var json = await response.Content.ReadAsStringAsync(ct); return json; } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultKeyMaterialService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultKeyMaterialService.cs index 29f9f940f..fd09251fa 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultKeyMaterialService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultKeyMaterialService.cs @@ -37,7 +37,7 @@ public class DefaultKeyMaterialService : IKeyMaterialService } /// - public async Task GetSigningCredentialsAsync(IEnumerable allowedAlgorithms = null) + public async Task GetSigningCredentialsAsync(IEnumerable allowedAlgorithms, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultKeyMaterialService.GetSigningCredentials"); @@ -46,14 +46,14 @@ public class DefaultKeyMaterialService : IKeyMaterialService var list = _signingCredentialStores.ToList(); for (var i = 0; i < list.Count; i++) { - var key = await list[i].GetSigningCredentialsAsync(); + var key = await list[i].GetSigningCredentialsAsync(ct); if (key != null) { return key; } } - var automaticKey = await _keyManagerKeyStore.GetSigningCredentialsAsync(); + var automaticKey = await _keyManagerKeyStore.GetSigningCredentialsAsync(ct); if (automaticKey != null) { return automaticKey; @@ -63,7 +63,7 @@ public class DefaultKeyMaterialService : IKeyMaterialService } var credential = - (await GetAllSigningCredentialsAsync()).FirstOrDefault(c => allowedAlgorithms.Contains(c.Algorithm)); + (await GetAllSigningCredentialsAsync(ct)).FirstOrDefault(c => allowedAlgorithms.Contains(c.Algorithm)); if (credential is null) { throw new InvalidOperationException( @@ -74,7 +74,7 @@ public class DefaultKeyMaterialService : IKeyMaterialService } /// - public async Task> GetAllSigningCredentialsAsync() + public async Task> GetAllSigningCredentialsAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultKeyMaterialService.GetAllSigningCredentials"); @@ -82,14 +82,14 @@ public class DefaultKeyMaterialService : IKeyMaterialService foreach (var store in _signingCredentialStores) { - var signingKey = await store.GetSigningCredentialsAsync(); + var signingKey = await store.GetSigningCredentialsAsync(ct); if (signingKey != null) { credentials.Add(signingKey); } } - var automaticSigningKeys = await _keyManagerKeyStore.GetAllSigningCredentialsAsync(); + var automaticSigningKeys = await _keyManagerKeyStore.GetAllSigningCredentialsAsync(ct); if (automaticSigningKeys != null) { credentials.AddRange(automaticSigningKeys); @@ -99,13 +99,13 @@ public class DefaultKeyMaterialService : IKeyMaterialService } /// - public async Task> GetValidationKeysAsync() + public async Task> GetValidationKeysAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultKeyMaterialService.GetValidationKeys"); var keys = new List(); - var automaticSigningKeys = await _keyManagerKeyStore.GetValidationKeysAsync(); + var automaticSigningKeys = await _keyManagerKeyStore.GetValidationKeysAsync(ct); if (automaticSigningKeys?.Any() == true) { keys.AddRange(automaticSigningKeys); @@ -113,7 +113,7 @@ public class DefaultKeyMaterialService : IKeyMaterialService foreach (var store in _validationKeysStores) { - var validationKeys = await store.GetValidationKeysAsync(); + var validationKeys = await store.GetValidationKeysAsync(ct); keys.AddRange(validationKeys); } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultPersistedGrantService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultPersistedGrantService.cs index 5a228af22..8e8e203f9 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultPersistedGrantService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultPersistedGrantService.cs @@ -34,13 +34,13 @@ public class DefaultPersistedGrantService : IPersistedGrantService } /// - public async Task> GetAllGrantsAsync(string subjectId) + public async Task> GetAllGrantsAsync(string subjectId, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultPersistedGrantService.GetAllGrants"); ArgumentException.ThrowIfNullOrWhiteSpace(subjectId); - var grants = (await _store.GetAllAsync(new PersistedGrantFilter { SubjectId = subjectId })) + var grants = (await _store.GetAllAsync(new PersistedGrantFilter { SubjectId = subjectId }, ct)) .Where(x => x.ConsumedTime == null) // filter consumed grants .ToArray(); @@ -171,7 +171,7 @@ public class DefaultPersistedGrantService : IPersistedGrantService } /// - public Task RemoveAllGrantsAsync(string subjectId, string clientId = null, string sessionId = null) + public Task RemoveAllGrantsAsync(string subjectId, Ct ct, string clientId = null, string sessionId = null) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultPersistedGrantService.RemoveAllGrants"); @@ -182,6 +182,6 @@ public class DefaultPersistedGrantService : IPersistedGrantService SubjectId = subjectId, ClientId = clientId, SessionId = sessionId - }); + }, ct); } } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultProfileService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultProfileService.cs index 6aabf62ae..53cd64e00 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultProfileService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultProfileService.cs @@ -25,12 +25,8 @@ public class DefaultProfileService : IProfileService /// The logger. public DefaultProfileService(ILogger logger) => Logger = logger; - /// - /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint) - /// - /// The context. - /// - public virtual Task GetProfileDataAsync(ProfileDataRequestContext context) + /// + public virtual Task GetProfileDataAsync(ProfileDataRequestContext context, Ct _) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultProfileService.GetProfileData"); @@ -41,13 +37,8 @@ public class DefaultProfileService : IProfileService return Task.CompletedTask; } - /// - /// This method gets called whenever identity server needs to determine if the user is valid or active (e.g. if the user's account has been deactivated since they logged in). - /// (e.g. during token issuance or validation). - /// - /// The context. - /// - public virtual Task IsActiveAsync(IsActiveContext context) + /// + public virtual Task IsActiveAsync(IsActiveContext context, Ct _) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultProfileService.IsActive"); diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultRefreshTokenService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultRefreshTokenService.cs index 6018fd290..2c06c5df9 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultRefreshTokenService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultRefreshTokenService.cs @@ -66,13 +66,8 @@ public class DefaultRefreshTokenService : IRefreshTokenService Logger = logger; } - /// - /// Validates a refresh token - /// - /// The token handle. - /// The client. - /// - public virtual async Task ValidateRefreshTokenAsync(string tokenHandle, Client client) + /// + public virtual async Task ValidateRefreshTokenAsync(string tokenHandle, Client client, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultRefreshTokenService.ValidateRefreshToken"); @@ -87,7 +82,7 @@ public class DefaultRefreshTokenService : IRefreshTokenService ///////////////////////////////////////////// // check if refresh token is valid ///////////////////////////////////////////// - var refreshToken = await RefreshTokenStore.GetRefreshTokenAsync(tokenHandle); + var refreshToken = await RefreshTokenStore.GetRefreshTokenAsync(tokenHandle, ct); if (refreshToken == null) { Logger.LogWarning("Invalid refresh token"); @@ -141,7 +136,7 @@ public class DefaultRefreshTokenService : IRefreshTokenService client, IdentityServerConstants.ProfileIsActiveCallers.RefreshTokenValidation); - await Profile.IsActiveAsync(isActiveCtx); + await Profile.IsActiveAsync(isActiveCtx, ct); if (isActiveCtx.IsActive == false) { @@ -174,7 +169,7 @@ public class DefaultRefreshTokenService : IRefreshTokenService /// /// The refresh token handle /// - public virtual async Task CreateRefreshTokenAsync(RefreshTokenCreationRequest request) + public virtual async Task CreateRefreshTokenAsync(RefreshTokenCreationRequest request, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultRefreshTokenService.CreateRefreshToken"); @@ -218,7 +213,7 @@ public class DefaultRefreshTokenService : IRefreshTokenService }; refreshToken.SetAccessToken(request.AccessToken, request.RequestedResourceIndicator); - var handle = await RefreshTokenStore.StoreRefreshTokenAsync(refreshToken); + var handle = await RefreshTokenStore.StoreRefreshTokenAsync(refreshToken, ct); return handle; } @@ -228,7 +223,7 @@ public class DefaultRefreshTokenService : IRefreshTokenService /// /// The refresh token handle /// - public virtual async Task UpdateRefreshTokenAsync(RefreshTokenUpdateRequest request) + public virtual async Task UpdateRefreshTokenAsync(RefreshTokenUpdateRequest request, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultTokenCreationService.UpdateRefreshToken"); @@ -245,7 +240,7 @@ public class DefaultRefreshTokenService : IRefreshTokenService { Logger.LogDebug("Token usage is one-time only and refresh behavior is delete. Deleting current handle, and generating new handle"); - await RefreshTokenStore.RemoveRefreshTokenAsync(handle); + await RefreshTokenStore.RemoveRefreshTokenAsync(handle, ct); } else { @@ -255,7 +250,7 @@ public class DefaultRefreshTokenService : IRefreshTokenService if (request.RefreshToken.ConsumedTime == null) { request.RefreshToken.ConsumedTime = TimeProvider.GetUtcNow().UtcDateTime; - await RefreshTokenStore.UpdateRefreshTokenAsync(handle, request.RefreshToken); + await RefreshTokenStore.UpdateRefreshTokenAsync(handle, request.RefreshToken, ct); } } @@ -292,12 +287,12 @@ public class DefaultRefreshTokenService : IRefreshTokenService { // set it to null so that we save non-consumed token request.RefreshToken.ConsumedTime = null; - handle = await RefreshTokenStore.StoreRefreshTokenAsync(request.RefreshToken); + handle = await RefreshTokenStore.StoreRefreshTokenAsync(request.RefreshToken, ct); Logger.LogDebug("Created refresh token in store"); } else if (needsUpdate) { - await RefreshTokenStore.UpdateRefreshTokenAsync(handle, request.RefreshToken); + await RefreshTokenStore.UpdateRefreshTokenAsync(handle, request.RefreshToken, ct); Logger.LogDebug("Updated refresh token in store"); } else diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultReplayCache.cs b/identity-server/src/IdentityServer/Services/Default/DefaultReplayCache.cs index 26ee20a27..8d44a49ca 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultReplayCache.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultReplayCache.cs @@ -22,7 +22,7 @@ public class DefaultReplayCache : IReplayCache public DefaultReplayCache(IDistributedCache cache) => _cache = cache; /// - public async Task AddAsync(string purpose, string handle, DateTimeOffset expiration) + public async Task AddAsync(string purpose, string handle, DateTimeOffset expiration, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultReplayCache.Add"); @@ -31,14 +31,14 @@ public class DefaultReplayCache : IReplayCache AbsoluteExpiration = expiration }; - await _cache.SetAsync(Prefix + purpose + handle, [], options); + await _cache.SetAsync(Prefix + purpose + handle, [], options, ct); } /// - public async Task ExistsAsync(string purpose, string handle) + public async Task ExistsAsync(string purpose, string handle, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultReplayCache.Exists"); - return (await _cache.GetAsync(Prefix + purpose + handle, default)) != null; + return (await _cache.GetAsync(Prefix + purpose + handle, ct)) != null; } } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultSessionCoordinationService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultSessionCoordinationService.cs index 33820f4b3..21f7409f5 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultSessionCoordinationService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultSessionCoordinationService.cs @@ -81,14 +81,14 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService }; /// - public virtual async Task ProcessLogoutAsync(UserSession session) + public virtual async Task ProcessLogoutAsync(UserSession session, Ct ct) { if (session.ClientIds.Count > 0) { var clientsToCoordinate = new List(); foreach (var clientId in session.ClientIds) { - var client = await ClientStore.FindClientByIdAsync(clientId); // i don't think we care if it's an enabled client at this point + var client = await ClientStore.FindClientByIdAsync(clientId, ct); // i don't think we care if it's an enabled client at this point if (client != null) { var shouldCoordinate = @@ -112,7 +112,7 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService SessionId = session.SessionId, ClientIds = clientsToCoordinate, Types = PersistedGrantTokenTypes - }); + }, ct); } Logger.LogDebug("Due to user logout, invoking backchannel logout for subject id {subjectId} and session id {sessionId}", session.SubjectId, session.SessionId); @@ -126,19 +126,19 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService ClientIds = session.ClientIds, Issuer = session.Issuer, LogoutReason = LogoutNotificationReason.UserLogout - }); + }, ct); } } /// - public virtual async Task ProcessExpirationAsync(UserSession session) + public virtual async Task ProcessExpirationAsync(UserSession session, Ct ct) { var clientsToCoordinate = new List(); foreach (var clientId in session.ClientIds) { - var client = await ClientStore.FindClientByIdAsync(clientId); // i don't think we care if it's an enabled client at this point + var client = await ClientStore.FindClientByIdAsync(clientId, ct); // i don't think we care if it's an enabled client at this point if (client != null) { @@ -164,7 +164,7 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService SessionId = session.SessionId, Types = PersistedGrantTokenTypes, ClientIds = clientsToCoordinate - }); + }, ct); } if (Options.ServerSideSessions.ExpiredSessionsTriggerBackchannelLogout || clientsToCoordinate.Count > 0) @@ -187,14 +187,14 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService Issuer = session.Issuer, ClientIds = clientsToContact, LogoutReason = LogoutNotificationReason.SessionExpiration, - }); + }, ct); } } } /// - public virtual async Task ValidateSessionAsync(SessionValidationRequest request) + public virtual async Task ValidateSessionAsync(SessionValidationRequest request, Ct ct) { if (ServerSideSessionStore != null) { @@ -208,7 +208,7 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService { SubjectId = request.SubjectId, SessionId = request.SessionId - }); + }, ct); var valid = sessions.Count > 0 && sessions.Any(x => x.Expires == null || DateTime.UtcNow < x.Expires.Value); @@ -238,6 +238,7 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService //result in the cookie never being renewed and expiring in a surprising way. Renewing //the ticket also updates the session, so we don't need to do both. if (Options.Authentication.CookieSlidingExpiration && +#pragma warning disable CA2016 // ITicketStore interface has no Ct parameter await ServerSideTicketStore.RetrieveAsync(session.Key) is { Properties: { IsPersistent: true, AllowRefresh: null or true } } ticket) { @@ -245,10 +246,11 @@ public class DefaultSessionCoordinationService : ISessionCoordinationService ticket.Properties.IssuedUtc = session.Renewed; ticket.Properties.ExpiresUtc = session.Expires; await ServerSideTicketStore.RenewAsync(session.Key, ticket); +#pragma warning restore CA2016 } else { - await ServerSideSessionStore.UpdateSessionAsync(session); + await ServerSideSessionStore.UpdateSessionAsync(session, ct); } } } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultSessionManagementService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultSessionManagementService.cs index 1b4d0015b..d7ac96fe7 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultSessionManagementService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultSessionManagementService.cs @@ -33,7 +33,7 @@ public class DefaultSessionManagementService : ISessionManagementService } /// - public Task> QuerySessionsAsync(SessionQuery filter = null, CT ct = default) + public Task> QuerySessionsAsync(SessionQuery filter, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultSessionManagementService.QuerySessions"); @@ -48,7 +48,7 @@ public class DefaultSessionManagementService : ISessionManagementService }; /// - public async Task RemoveSessionsAsync(RemoveSessionsContext context, CT ct = default) + public async Task RemoveSessionsAsync(RemoveSessionsContext context, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultSessionManagementService.RemoveSessions"); @@ -78,7 +78,7 @@ public class DefaultSessionManagementService : ISessionManagementService } } - await _persistedGrantStore.RemoveAllAsync(grantFilter); + await _persistedGrantStore.RemoveAllAsync(grantFilter, ct); } // send back channel SLO @@ -102,7 +102,7 @@ public class DefaultSessionManagementService : ISessionManagementService Issuer = session.Issuer, ClientIds = session.ClientIds.Where(x => context.ClientIds == null || context.ClientIds.Contains(x)), LogoutReason = LogoutNotificationReason.Terminated - }); + }, ct); } } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultTokenCreationService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultTokenCreationService.cs index 7f7671b79..f5756434e 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultTokenCreationService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultTokenCreationService.cs @@ -56,21 +56,15 @@ public class DefaultTokenCreationService : ITokenCreationService Logger = logger; } - /// - /// Creates the token. - /// - /// The token. - /// - /// A protected and serialized security token - /// - public virtual async Task CreateTokenAsync(Token token) + /// + public virtual async Task CreateTokenAsync(Token token, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultTokenCreationService.CreateToken"); var payload = await CreatePayloadAsync(token); var headerElements = await CreateHeaderElementsAsync(token); - return await CreateJwtAsync(token, payload, headerElements); + return await CreateJwtAsync(token, payload, headerElements, ct); } /// @@ -121,14 +115,15 @@ public class DefaultTokenCreationService : ITokenCreationService /// /// /// + /// The cancellation token. /// /// protected virtual async Task CreateJwtAsync(Token token, string payload, - Dictionary headerElements) + Dictionary headerElements, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultTokenCreationService.CreateJwt"); - var credential = await Keys.GetSigningCredentialsAsync(token.AllowedSigningAlgorithms); + var credential = await Keys.GetSigningCredentialsAsync(token.AllowedSigningAlgorithms, ct); if (credential == null) { diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultTokenService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultTokenService.cs index 0d7c299ae..1a56f2e36 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultTokenService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultTokenService.cs @@ -81,14 +81,8 @@ public class DefaultTokenService : ITokenService Logger = logger; } - /// - /// Creates an identity token. - /// - /// The token creation request. - /// - /// An identity token - /// - public virtual async Task CreateIdentityTokenAsync(TokenCreationRequest request) + /// + public virtual async Task CreateIdentityTokenAsync(TokenCreationRequest request, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultTokenService.CreateIdentityToken"); @@ -96,7 +90,7 @@ public class DefaultTokenService : ITokenService request.Validate(); // todo: Dom, add a test for this. validate the at and c hashes are correct for the id_token when the client's alg doesn't match the server default. - var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms); + var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms, ct); if (credential == null) { throw new InvalidOperationException("No signing credential is configured."); @@ -141,7 +135,8 @@ public class DefaultTokenService : ITokenService request.Subject, request.ValidatedResources, request.IncludeAllIdentityClaims, - request.ValidatedRequest)); + request.ValidatedRequest, + ct)); var issuer = request.ValidatedRequest.IssuerName; var token = new Token(OidcConstants.TokenTypes.IdentityToken) @@ -159,14 +154,8 @@ public class DefaultTokenService : ITokenService return token; } - /// - /// Creates an access token. - /// - /// The token creation request. - /// - /// An access token - /// - public virtual async Task CreateAccessTokenAsync(TokenCreationRequest request) + /// + public virtual async Task CreateAccessTokenAsync(TokenCreationRequest request, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultTokenService.CreateAccessToken"); @@ -177,7 +166,8 @@ public class DefaultTokenService : ITokenService claims.AddRange(await ClaimsProvider.GetAccessTokenClaimsAsync( request.Subject, request.ValidatedResources, - request.ValidatedRequest)); + request.ValidatedRequest, + ct)); if (request.ValidatedRequest.SessionId.IsPresent()) { @@ -220,15 +210,8 @@ public class DefaultTokenService : ITokenService return token; } - /// - /// Creates a serialized and protected security token. - /// - /// The token. - /// - /// A security token in serialized form - /// - /// Invalid token type. - public virtual async Task CreateSecurityTokenAsync(Token token) + /// + public virtual async Task CreateSecurityTokenAsync(Token token, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultTokenService.CreateSecurityToken"); @@ -250,13 +233,13 @@ public class DefaultTokenService : ITokenService { Logger.LogTrace("Creating JWT access token"); - tokenResult = await CreationService.CreateTokenAsync(token); + tokenResult = await CreationService.CreateTokenAsync(token, ct); } else { Logger.LogTrace("Creating reference access token"); - var handle = await ReferenceTokenStore.StoreReferenceTokenAsync(token); + var handle = await ReferenceTokenStore.StoreReferenceTokenAsync(token, ct); tokenResult = handle; } @@ -265,7 +248,7 @@ public class DefaultTokenService : ITokenService { Logger.LogTrace("Creating JWT identity token"); - tokenResult = await CreationService.CreateTokenAsync(token); + tokenResult = await CreationService.CreateTokenAsync(token, ct); } else { diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultUiLocalesService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultUiLocalesService.cs index d395bf97e..930534255 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultUiLocalesService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultUiLocalesService.cs @@ -13,7 +13,7 @@ namespace Duende.IdentityServer.Services.Default; public class DefaultUiLocalesService(IHttpContextAccessor httpContextAccessor, IOptions requestLocalizationOptions, ILogger logger) : IUiLocalesService { - public virtual Task StoreUiLocalesForRedirectAsync(string? uiLocales) + public virtual Task StoreUiLocalesForRedirectAsync(string? uiLocales, Ct _) { if (httpContextAccessor.HttpContext is null) { diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultUserCodeService.cs b/identity-server/src/IdentityServer/Services/Default/DefaultUserCodeService.cs index 69ea36274..a906b02ff 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultUserCodeService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultUserCodeService.cs @@ -23,7 +23,8 @@ public class DefaultUserCodeService : IUserCodeService /// Gets the user code generator. /// /// Type of user code. + /// The cancellation token. /// - public Task GetGenerator(string userCodeType) => + public Task GetGenerator(string userCodeType, Ct ct) => Task.FromResult(_generators.FirstOrDefault(x => x.UserCodeType == userCodeType)); } diff --git a/identity-server/src/IdentityServer/Services/Default/DefaultUserSession.cs b/identity-server/src/IdentityServer/Services/Default/DefaultUserSession.cs index 32a18c427..e57e1b81a 100644 --- a/identity-server/src/IdentityServer/Services/Default/DefaultUserSession.cs +++ b/identity-server/src/IdentityServer/Services/Default/DefaultUserSession.cs @@ -154,23 +154,24 @@ public class DefaultUserSession : IUserSession /// /// /// + /// The cancellation token. /// /// /// principal /// or /// properties /// - public virtual async Task CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties) + public virtual async Task CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties, Ct ct) { ArgumentNullException.ThrowIfNull(principal); ArgumentNullException.ThrowIfNull(properties); - var currentSubjectId = (await GetUserAsync())?.GetSubjectId(); + var currentSubjectId = (await GetUserAsync(ct))?.GetSubjectId(); var newSubjectId = principal.GetSubjectId(); if (properties.GetSessionId() == null) { - var currSid = await GetSessionIdAsync(); + var currSid = await GetSessionIdAsync(ct); if (newSubjectId == currentSubjectId && currSid != null) { properties.SetSessionId(currSid); @@ -198,8 +199,9 @@ public class DefaultUserSession : IUserSession /// /// Gets the current authenticated user. /// + /// The cancellation token. /// - public virtual async Task GetUserAsync() + public virtual async Task GetUserAsync(Ct ct) { await AuthenticateAsync(); @@ -209,8 +211,9 @@ public class DefaultUserSession : IUserSession /// /// Gets the current session identifier. /// + /// The cancellation token. /// - public virtual async Task GetSessionIdAsync() + public virtual async Task GetSessionIdAsync(Ct ct) { await AuthenticateAsync(); @@ -222,25 +225,27 @@ public class DefaultUserSession : IUserSession /// session identifier. If there is no sid, the cookie is removed. If there /// is a sid, and the session identifier cookie is missing, it is issued. /// + /// The cancellation token. /// - public virtual async Task EnsureSessionIdCookieAsync() + public virtual async Task EnsureSessionIdCookieAsync(Ct ct) { - var sid = await GetSessionIdAsync(); + var sid = await GetSessionIdAsync(ct); if (sid != null) { IssueSessionIdCookie(sid); } else { - await RemoveSessionIdCookieAsync(); + await RemoveSessionIdCookieAsync(ct); } } /// /// Removes the session identifier cookie. /// + /// The cancellation token. /// - public virtual Task RemoveSessionIdCookieAsync() + public virtual Task RemoveSessionIdCookieAsync(Ct ct) { if (HttpContext.Request.Cookies.ContainsKey(CheckSessionCookieName)) { @@ -297,9 +302,10 @@ public class DefaultUserSession : IUserSession /// Adds a client to the list of clients the user has signed into during their session. /// /// The client identifier. + /// The cancellation token. /// /// clientId - public virtual async Task AddClientIdAsync(string clientId) + public virtual async Task AddClientIdAsync(string clientId, Ct ct) { ArgumentNullException.ThrowIfNull(clientId); @@ -318,8 +324,9 @@ public class DefaultUserSession : IUserSession /// /// Gets the list of clients the user has signed into during their session. /// + /// The cancellation token. /// - public virtual async Task> GetClientListAsync() + public virtual async Task> GetClientListAsync(Ct ct) { await AuthenticateAsync(); diff --git a/identity-server/src/IdentityServer/Services/Default/DistributedBackchannelAuthenticationThrottlingService.cs b/identity-server/src/IdentityServer/Services/Default/DistributedBackchannelAuthenticationThrottlingService.cs index 01ab02744..59c272824 100644 --- a/identity-server/src/IdentityServer/Services/Default/DistributedBackchannelAuthenticationThrottlingService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DistributedBackchannelAuthenticationThrottlingService.cs @@ -37,7 +37,7 @@ public class DistributedBackchannelAuthenticationThrottlingService : IBackchanne } /// - public async Task ShouldSlowDown(string requestId, BackChannelAuthenticationRequest details) + public async Task ShouldSlowDown(string requestId, BackChannelAuthenticationRequest details, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DistributedBackchannelAuthenticationThrottlingService.ShouldSlowDown"); @@ -46,12 +46,12 @@ public class DistributedBackchannelAuthenticationThrottlingService : IBackchanne var key = KeyPrefix + requestId; var options = new DistributedCacheEntryOptions { AbsoluteExpiration = _timeProvider.GetUtcNow().AddSeconds(details.Lifetime) }; - var lastSeenAsString = await _cache.GetStringAsync(key); + var lastSeenAsString = await _cache.GetStringAsync(key, ct); // record new if (lastSeenAsString == null) { - await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options); + await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options, ct); return false; } @@ -60,17 +60,17 @@ public class DistributedBackchannelAuthenticationThrottlingService : IBackchanne { lastSeen = lastSeen.ToUniversalTime(); - var client = await _clientStore.FindEnabledClientByIdAsync(details.ClientId); + var client = await _clientStore.FindEnabledClientByIdAsync(details.ClientId, ct); var interval = client?.PollingInterval ?? _options.Ciba.DefaultPollingInterval; if (_timeProvider.GetUtcNow().UtcDateTime < lastSeen.AddSeconds(interval)) { - await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options); + await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options, ct); return true; } } // store current and continue - await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options); + await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options, ct); return false; } diff --git a/identity-server/src/IdentityServer/Services/Default/DistributedDeviceFlowThrottlingService.cs b/identity-server/src/IdentityServer/Services/Default/DistributedDeviceFlowThrottlingService.cs index 20b38964f..310654e22 100644 --- a/identity-server/src/IdentityServer/Services/Default/DistributedDeviceFlowThrottlingService.cs +++ b/identity-server/src/IdentityServer/Services/Default/DistributedDeviceFlowThrottlingService.cs @@ -46,9 +46,10 @@ public class DistributedDeviceFlowThrottlingService : IDeviceFlowThrottlingServi /// /// The device code. /// The device code details. + /// The cancellation token. /// /// deviceCode - public async Task ShouldSlowDown(string deviceCode, DeviceCode details) + public async Task ShouldSlowDown(string deviceCode, DeviceCode details, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("DistributedDeviceFlowThrottlingService.ShouldSlowDown"); @@ -57,12 +58,12 @@ public class DistributedDeviceFlowThrottlingService : IDeviceFlowThrottlingServi var key = KeyPrefix + deviceCode; var options = new DistributedCacheEntryOptions { AbsoluteExpiration = _timeProvider.GetUtcNow().AddSeconds(details.Lifetime) }; - var lastSeenAsString = await _cache.GetStringAsync(key); + var lastSeenAsString = await _cache.GetStringAsync(key, ct); // record new if (lastSeenAsString == null) { - await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options); + await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options, ct); return false; } @@ -71,17 +72,17 @@ public class DistributedDeviceFlowThrottlingService : IDeviceFlowThrottlingServi { lastSeen = lastSeen.ToUniversalTime(); - var client = await _clientStore.FindEnabledClientByIdAsync(details.ClientId); + var client = await _clientStore.FindEnabledClientByIdAsync(details.ClientId, ct); var interval = client?.PollingInterval ?? _options.DeviceFlow.Interval; if (_timeProvider.GetUtcNow().UtcDateTime < lastSeen.AddSeconds(interval)) { - await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options); + await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options, ct); return true; } } // store current and continue - await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options); + await _cache.SetStringAsync(key, _timeProvider.GetUtcNow().ToString("O"), options, ct); return false; } } diff --git a/identity-server/src/IdentityServer/Services/Default/KeyManagement/AutomaticKeyManagerKeyStore.cs b/identity-server/src/IdentityServer/Services/Default/KeyManagement/AutomaticKeyManagerKeyStore.cs index 539f4e6b8..5115e65aa 100644 --- a/identity-server/src/IdentityServer/Services/Default/KeyManagement/AutomaticKeyManagerKeyStore.cs +++ b/identity-server/src/IdentityServer/Services/Default/KeyManagement/AutomaticKeyManagerKeyStore.cs @@ -17,8 +17,9 @@ public interface IAutomaticKeyManagerKeyStore : IValidationKeysStore, ISigningCr /// /// Gets all the signing credentials. /// + /// The cancellation token. /// - Task> GetAllSigningCredentialsAsync(); + Task> GetAllSigningCredentialsAsync(Ct ct); } /// @@ -27,13 +28,13 @@ public interface IAutomaticKeyManagerKeyStore : IValidationKeysStore, ISigningCr internal class NopAutomaticKeyManagerKeyStore : IAutomaticKeyManagerKeyStore { /// - public Task GetSigningCredentialsAsync() => Task.FromResult(null); + public Task GetSigningCredentialsAsync(Ct _) => Task.FromResult(null); /// - public Task> GetAllSigningCredentialsAsync() => Task.FromResult(Enumerable.Empty()); + public Task> GetAllSigningCredentialsAsync(Ct _) => Task.FromResult(Enumerable.Empty()); /// - public Task> GetValidationKeysAsync() => Task.FromResult(Enumerable.Empty()); + public Task> GetValidationKeysAsync(Ct _) => Task.FromResult(Enumerable.Empty()); } /// @@ -56,41 +57,41 @@ public class AutomaticKeyManagerKeyStore : IAutomaticKeyManagerKeyStore } /// - public async Task GetSigningCredentialsAsync() + public async Task GetSigningCredentialsAsync(Ct ct) { if (!_options.Enabled) { return null; } - var credentials = await GetAllSigningCredentialsAsync(); + var credentials = await GetAllSigningCredentialsAsync(ct); var alg = _options.DefaultSigningAlgorithm; var credential = credentials.FirstOrDefault(x => alg == x.Algorithm); return credential; } /// - public async Task> GetAllSigningCredentialsAsync() + public async Task> GetAllSigningCredentialsAsync(Ct ct) { if (!_options.Enabled) { return Enumerable.Empty(); } - var keyContainers = await _keyManager.GetCurrentKeysAsync(); + var keyContainers = await _keyManager.GetCurrentKeysAsync(ct); var credentials = keyContainers.Select(x => new SigningCredentials(x.ToSecurityKey(), x.Algorithm)); return credentials; } /// - public async Task> GetValidationKeysAsync() + public async Task> GetValidationKeysAsync(Ct ct) { if (!_options.Enabled) { return Enumerable.Empty(); } - var containers = await _keyManager.GetAllKeysAsync(); + var containers = await _keyManager.GetAllKeysAsync(ct); var keys = containers.Select(x => new SecurityKeyInfo { Key = x.ToSecurityKey(), diff --git a/identity-server/src/IdentityServer/Services/Default/KeyManagement/FileSystemKeyStore.cs b/identity-server/src/IdentityServer/Services/Default/KeyManagement/FileSystemKeyStore.cs index 3aff2c332..506fad503 100644 --- a/identity-server/src/IdentityServer/Services/Default/KeyManagement/FileSystemKeyStore.cs +++ b/identity-server/src/IdentityServer/Services/Default/KeyManagement/FileSystemKeyStore.cs @@ -44,8 +44,9 @@ public class FileSystemKeyStore : ISigningKeyStore /// /// Returns all the keys in storage. /// + /// The cancellation token. /// - public async Task> LoadKeysAsync() + public async Task> LoadKeysAsync(Ct ct) { var list = new List(); @@ -62,7 +63,7 @@ public class FileSystemKeyStore : ISigningKeyStore { using (var reader = new StreamReader(file.OpenRead())) { - var json = await reader.ReadToEndAsync(); + var json = await reader.ReadToEndAsync(ct); var item = KeySerializer.Deserialize(json); list.Add(item); } @@ -80,8 +81,9 @@ public class FileSystemKeyStore : ISigningKeyStore /// Persists new key in storage. /// /// + /// The cancellation token. /// - public async Task StoreKeyAsync(SerializedKey key) + public async Task StoreKeyAsync(SerializedKey key, Ct ct) { if (!_directory.Exists) { @@ -91,15 +93,16 @@ public class FileSystemKeyStore : ISigningKeyStore var json = KeySerializer.Serialize(key); var path = Path.Combine(_directory.FullName, KeyFilePrefix + key.Id + KeyFileExtension); - await File.WriteAllTextAsync(path, json, Encoding.UTF8); + await File.WriteAllTextAsync(path, json, Encoding.UTF8, ct); } /// /// Deletes key from storage. /// /// + /// The cancellation token. /// - public Task DeleteKeyAsync(string id) + public Task DeleteKeyAsync(string id, Ct ct) { var path = Path.Combine(_directory.FullName, KeyFilePrefix + id + KeyFileExtension); try diff --git a/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyManager.cs b/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyManager.cs index af880dcb5..787da7dd2 100644 --- a/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyManager.cs +++ b/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyManager.cs @@ -12,12 +12,14 @@ public interface IKeyManager /// /// Returns the current signing keys. /// + /// The cancellation token. /// - Task> GetCurrentKeysAsync(); + Task> GetCurrentKeysAsync(Ct ct); /// /// Returns all the validation keys. /// + /// The cancellation token. /// - Task> GetAllKeysAsync(); + Task> GetAllKeysAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyStoreCache.cs b/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyStoreCache.cs index 577be305a..60b561c1b 100644 --- a/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyStoreCache.cs +++ b/identity-server/src/IdentityServer/Services/Default/KeyManagement/IKeyStoreCache.cs @@ -12,14 +12,16 @@ public interface ISigningKeyStoreCache /// /// Returns cached keys. /// + /// The cancellation token. /// - Task> GetKeysAsync(); + Task> GetKeysAsync(Ct ct); /// /// Caches keys for duration. /// /// /// + /// The cancellation token. /// - Task StoreKeysAsync(IEnumerable keys, TimeSpan duration); + Task StoreKeysAsync(IEnumerable keys, TimeSpan duration, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/Default/KeyManagement/InMemoryKeyStoreCache.cs b/identity-server/src/IdentityServer/Services/Default/KeyManagement/InMemoryKeyStoreCache.cs index 30df29eee..42c24f9e7 100644 --- a/identity-server/src/IdentityServer/Services/Default/KeyManagement/InMemoryKeyStoreCache.cs +++ b/identity-server/src/IdentityServer/Services/Default/KeyManagement/InMemoryKeyStoreCache.cs @@ -26,7 +26,7 @@ internal class InMemoryKeyStoreCache : ISigningKeyStoreCache /// Returns cached keys. /// /// - public Task> GetKeysAsync() + public Task> GetKeysAsync(Ct ct) { DateTime expires; IEnumerable keys; @@ -50,8 +50,9 @@ internal class InMemoryKeyStoreCache : ISigningKeyStoreCache /// /// /// + /// The cancellation token. /// - public Task StoreKeysAsync(IEnumerable keys, TimeSpan duration) + public Task StoreKeysAsync(IEnumerable keys, TimeSpan duration, Ct ct) { lock (_lock) { diff --git a/identity-server/src/IdentityServer/Services/Default/KeyManagement/KeyManager.cs b/identity-server/src/IdentityServer/Services/Default/KeyManagement/KeyManager.cs index 85afdc91c..60e40efdd 100644 --- a/identity-server/src/IdentityServer/Services/Default/KeyManagement/KeyManager.cs +++ b/identity-server/src/IdentityServer/Services/Default/KeyManagement/KeyManager.cs @@ -60,13 +60,13 @@ public class KeyManager : IKeyManager } /// - public async Task> GetCurrentKeysAsync() + public async Task> GetCurrentKeysAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("KeyManager.GetCurrentKeys"); _logger.LogTrace("Getting the current key."); - var (_, currentKeys) = await GetAllKeysInternalAsync(); + var (_, currentKeys) = await GetAllKeysInternalAsync(ct); if (_logger.IsEnabled(LogLevel.Debug)) { @@ -83,26 +83,26 @@ public class KeyManager : IKeyManager } /// - public async Task> GetAllKeysAsync() + public async Task> GetAllKeysAsync(Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("KeyManager.GetAllKeys"); _logger.LogTrace("Getting all the keys."); - var (keys, _) = await GetAllKeysInternalAsync(); + var (keys, _) = await GetAllKeysInternalAsync(ct); return keys; } - internal async Task<(IEnumerable allKeys, IEnumerable signingKeys)> GetAllKeysInternalAsync() + internal async Task<(IEnumerable allKeys, IEnumerable signingKeys)> GetAllKeysInternalAsync(Ct ct) { var cached = true; - var keys = await GetAllKeysFromCacheAsync(); + var keys = await GetAllKeysFromCacheAsync(ct); if (!keys.Any()) { cached = false; - keys = await GetAllKeysFromStoreAsync(); + keys = await GetAllKeysFromStoreAsync(ct); } // ensure we have all of our active signing keys @@ -140,7 +140,7 @@ public class KeyManager : IKeyManager try { // check if another thread did the work already - keys = await GetAllKeysFromCacheAsync(); + keys = await GetAllKeysFromCacheAsync(ct); if (!signingKeysSuccess) { @@ -154,7 +154,7 @@ public class KeyManager : IKeyManager if (!signingKeysSuccess || rotationRequired) { // still need to do the work, but check if another server did the work already - keys = await GetAllKeysFromStoreAsync(); + keys = await GetAllKeysFromStoreAsync(ct); if (!signingKeysSuccess) { @@ -177,7 +177,7 @@ public class KeyManager : IKeyManager } // now we know we need to create new keys - (keys, signingKeys) = await CreateNewKeysAndAddToCacheAsync(); + (keys, signingKeys) = await CreateNewKeysAndAddToCacheAsync(ct); } else { @@ -265,7 +265,7 @@ public class KeyManager : IKeyManager return false; } - internal async Task CreateAndStoreNewKeyAsync(SigningAlgorithmOptions alg) + internal async Task CreateAndStoreNewKeyAsync(SigningAlgorithmOptions alg, Ct ct) { _logger.LogTrace("Creating new key."); @@ -279,7 +279,7 @@ public class KeyManager : IKeyManager if (alg.UseX509Certificate) { - var iss = await _issuerNameService.GetCurrentAsync(); + var iss = await _issuerNameService.GetCurrentAsync(ct); container = new X509KeyContainer(rsa, alg.Name, now, _options.KeyManagement.KeyRetirementAge, iss); } else @@ -300,16 +300,16 @@ public class KeyManager : IKeyManager } var key = _protector.Protect(container); - await _store.StoreKeyAsync(key); + await _store.StoreKeyAsync(key, ct); _logger.LogDebug("Created and stored new key with kid {kid}.", container.Id); return container; } - internal async Task> GetAllKeysFromCacheAsync() + internal async Task> GetAllKeysFromCacheAsync(Ct ct) { - var cachedKeys = await _cache.GetKeysAsync(); + var cachedKeys = await _cache.GetKeysAsync(ct); if (cachedKeys != null) { _logger.LogTrace("Cache hit when loading all keys."); @@ -340,7 +340,7 @@ public class KeyManager : IKeyManager return result; } - internal async Task> FilterAndDeleteRetiredKeysAsync(IEnumerable keys) + internal async Task> FilterAndDeleteRetiredKeysAsync(IEnumerable keys, Ct ct) { var retired = keys .Where(x => @@ -365,7 +365,7 @@ public class KeyManager : IKeyManager { _logger.LogDebug("Deleting retired keys from store: {kids}", ids.Aggregate((x, y) => $"{x},{y}")); } - await DeleteKeysAsync(ids); + await DeleteKeysAsync(ids, ct); } } @@ -373,7 +373,7 @@ public class KeyManager : IKeyManager return result; } - internal async Task DeleteKeysAsync(IEnumerable keys) + internal async Task DeleteKeysAsync(IEnumerable keys, Ct ct) { if (keys == null || !keys.Any()) { @@ -382,7 +382,7 @@ public class KeyManager : IKeyManager foreach (var key in keys) { - await _store.DeleteKeyAsync(key); + await _store.DeleteKeyAsync(key, ct); } } @@ -399,7 +399,7 @@ public class KeyManager : IKeyManager return result; } - internal async Task CacheKeysAsync(IEnumerable keys) + internal async Task CacheKeysAsync(IEnumerable keys, Ct ct) { if (keys?.Any() == true) { @@ -423,20 +423,20 @@ public class KeyManager : IKeyManager if (duration > TimeSpan.Zero) { - await _cache.StoreKeysAsync(keys, duration); + await _cache.StoreKeysAsync(keys, duration, ct); } } } - internal async Task> GetAllKeysFromStoreAsync(bool cache = true) + internal async Task> GetAllKeysFromStoreAsync(Ct ct, bool cache = true) { _logger.LogTrace("Loading keys from store."); - var protectedKeys = await _store.LoadKeysAsync(); + var protectedKeys = await _store.LoadKeysAsync(ct); if (protectedKeys != null && protectedKeys.Any()) { // retired keys are those that are beyond inclusion, thus we act as if they don't exist. - protectedKeys = await FilterAndDeleteRetiredKeysAsync(protectedKeys); + protectedKeys = await FilterAndDeleteRetiredKeysAsync(protectedKeys, ct); var keys = protectedKeys.Select(x => { @@ -490,7 +490,7 @@ public class KeyManager : IKeyManager if (cache) { - await CacheKeysAsync(keys); + await CacheKeysAsync(keys, ct); } return keys; @@ -505,14 +505,14 @@ public class KeyManager : IKeyManager - internal async Task<(IEnumerable allKeys, IEnumerable activeKeys)> CreateNewKeysAndAddToCacheAsync() + internal async Task<(IEnumerable allKeys, IEnumerable activeKeys)> CreateNewKeysAndAddToCacheAsync(Ct ct) { var keys = new List(); - keys.AddRange(await _cache.GetKeysAsync() ?? Enumerable.Empty()); + keys.AddRange(await _cache.GetKeysAsync(ct) ?? Enumerable.Empty()); foreach (var alg in _options.KeyManagement.SigningAlgorithms) { - var newKey = await CreateAndStoreNewKeyAsync(alg); + var newKey = await CreateAndStoreNewKeyAsync(alg, ct); keys.Add(newKey); } @@ -527,7 +527,7 @@ public class KeyManager : IKeyManager if (_options.KeyManagement.InitializationSynchronizationDelay > TimeSpan.Zero) { _logger.LogTrace("All keys are new; delaying before reloading keys from store by InitializationSynchronizationDelay for {InitializationSynchronizationDelay}.", _options.KeyManagement.InitializationSynchronizationDelay); - await Task.Delay(_options.KeyManagement.InitializationSynchronizationDelay); + await Task.Delay(_options.KeyManagement.InitializationSynchronizationDelay, ct); } else { @@ -535,11 +535,11 @@ public class KeyManager : IKeyManager } // reload in case other new keys were recently created - keys = new List(await GetAllKeysFromStoreAsync(false)); + keys = new List(await GetAllKeysFromStoreAsync(ct, false)); } // explicitly cache here since we didn't when we loaded above - await CacheKeysAsync(keys); + await CacheKeysAsync(keys, ct); var activeKeys = GetAllCurrentSigningKeys(keys); diff --git a/identity-server/src/IdentityServer/Services/Default/KeyManagement/NopKeyStoreCache.cs b/identity-server/src/IdentityServer/Services/Default/KeyManagement/NopKeyStoreCache.cs index 026ca61b1..f75a7eac8 100644 --- a/identity-server/src/IdentityServer/Services/Default/KeyManagement/NopKeyStoreCache.cs +++ b/identity-server/src/IdentityServer/Services/Default/KeyManagement/NopKeyStoreCache.cs @@ -13,13 +13,8 @@ internal class NopKeyStoreCache : ISigningKeyStoreCache /// Returns null. /// /// - public Task> GetKeysAsync() => Task.FromResult>(null); + public Task> GetKeysAsync(Ct _) => Task.FromResult>(null); - /// - /// Does not cache keys. - /// - /// - /// - /// - public Task StoreKeysAsync(IEnumerable keys, TimeSpan duration) => Task.CompletedTask; + /// + public Task StoreKeysAsync(IEnumerable keys, TimeSpan duration, Ct _) => Task.CompletedTask; } diff --git a/identity-server/src/IdentityServer/Services/Default/LogoutNotificationService.cs b/identity-server/src/IdentityServer/Services/Default/LogoutNotificationService.cs index 30370cc45..7523fd34c 100644 --- a/identity-server/src/IdentityServer/Services/Default/LogoutNotificationService.cs +++ b/identity-server/src/IdentityServer/Services/Default/LogoutNotificationService.cs @@ -35,14 +35,14 @@ public class LogoutNotificationService : ILogoutNotificationService } /// - public async Task> GetFrontChannelLogoutNotificationsUrlsAsync(LogoutNotificationContext context) + public async Task> GetFrontChannelLogoutNotificationsUrlsAsync(LogoutNotificationContext context, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("LogoutNotificationService.GetFrontChannelLogoutNotificationsUrls"); var frontChannelUrls = new List(); foreach (var clientId in context.ClientIds) { - var client = await _clientStore.FindEnabledClientByIdAsync(clientId); + var client = await _clientStore.FindEnabledClientByIdAsync(clientId, ct); if (client != null) { if (client.FrontChannelLogoutUri.IsPresent()) @@ -55,7 +55,7 @@ public class LogoutNotificationService : ILogoutNotificationService if (client.FrontChannelLogoutSessionRequired) { url = url.AddQueryString(OidcConstants.EndSessionRequest.Sid, context.SessionId); - url = url.AddQueryString(OidcConstants.EndSessionRequest.Issuer, await _issuerNameService.GetCurrentAsync()); + url = url.AddQueryString(OidcConstants.EndSessionRequest.Issuer, await _issuerNameService.GetCurrentAsync(ct)); } } else if (client.ProtocolType == IdentityServerConstants.ProtocolTypes.WsFederation) @@ -82,14 +82,14 @@ public class LogoutNotificationService : ILogoutNotificationService } /// - public async Task> GetBackChannelLogoutNotificationsAsync(LogoutNotificationContext context) + public async Task> GetBackChannelLogoutNotificationsAsync(LogoutNotificationContext context, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("LogoutNotificationService.GetBackChannelLogoutNotifications"); var backChannelLogouts = new List(); foreach (var clientId in context.ClientIds) { - var client = await _clientStore.FindEnabledClientByIdAsync(clientId); + var client = await _clientStore.FindEnabledClientByIdAsync(clientId, ct); if (client != null) { if (client.BackChannelLogoutUri.IsPresent()) diff --git a/identity-server/src/IdentityServer/Services/Default/NopBackchannelAuthenticationUserNotificationService.cs b/identity-server/src/IdentityServer/Services/Default/NopBackchannelAuthenticationUserNotificationService.cs index b56fb2e2d..cb8154778 100644 --- a/identity-server/src/IdentityServer/Services/Default/NopBackchannelAuthenticationUserNotificationService.cs +++ b/identity-server/src/IdentityServer/Services/Default/NopBackchannelAuthenticationUserNotificationService.cs @@ -26,9 +26,9 @@ public class NopBackchannelAuthenticationUserNotificationService : IBackchannelA } /// - public async Task SendLoginRequestAsync(BackchannelUserLoginRequest request) + public async Task SendLoginRequestAsync(BackchannelUserLoginRequest request, Ct ct) { - var url = await _issuerNameService.GetCurrentAsync(); + var url = await _issuerNameService.GetCurrentAsync(ct); url += "/ciba?id=" + request.InternalId; _sanitizedLogger.LogWarning("IBackchannelAuthenticationUserNotificationService not implemented. But for testing, visit {url} to simulate what a user might need to do to complete the request.", url); } diff --git a/identity-server/src/IdentityServer/Services/Default/NumericUserCodeGenerator.cs b/identity-server/src/IdentityServer/Services/Default/NumericUserCodeGenerator.cs index a9dc8b835..aad9ba925 100644 --- a/identity-server/src/IdentityServer/Services/Default/NumericUserCodeGenerator.cs +++ b/identity-server/src/IdentityServer/Services/Default/NumericUserCodeGenerator.cs @@ -29,11 +29,8 @@ public class NumericUserCodeGenerator : IUserCodeGenerator /// public int RetryLimit => 5; - /// - /// Generates the user code. - /// - /// - public Task GenerateAsync() + /// + public Task GenerateAsync(Ct _) { var next = RandomNumberGenerator.GetInt32(100000000, 1000000000); return Task.FromResult(next.ToString(CultureInfo.InvariantCulture)); diff --git a/identity-server/src/IdentityServer/Services/Default/OidcReturnUrlParser.cs b/identity-server/src/IdentityServer/Services/Default/OidcReturnUrlParser.cs index f888aeba3..36c20d28a 100644 --- a/identity-server/src/IdentityServer/Services/Default/OidcReturnUrlParser.cs +++ b/identity-server/src/IdentityServer/Services/Default/OidcReturnUrlParser.cs @@ -38,7 +38,7 @@ internal class OidcReturnUrlParser : IReturnUrlParser _authorizationParametersMessageStore = authorizationParametersMessageStore; } - public async Task ParseAsync(string returnUrl) + public async Task ParseAsync(string returnUrl, Ct ct) { using var activity = Tracing.ValidationActivitySource.StartActivity("OidcReturnUrlParser.Parse"); @@ -48,12 +48,12 @@ internal class OidcReturnUrlParser : IReturnUrlParser if (_authorizationParametersMessageStore != null) { var messageStoreId = parameters[Constants.AuthorizationParamsStore.MessageStoreIdParameterName]; - var entry = await _authorizationParametersMessageStore.ReadAsync(messageStoreId); + var entry = await _authorizationParametersMessageStore.ReadAsync(messageStoreId, ct); parameters = entry?.Data.FromFullDictionary() ?? new NameValueCollection(); } - var user = await _userSession.GetUserAsync(); - var result = await _validator.ValidateAsync(parameters, user); + var user = await _userSession.GetUserAsync(ct); + var result = await _validator.ValidateAsync(parameters, ct, user); if (!result.IsError) { _logger.LogTrace("AuthorizationRequest being returned"); diff --git a/identity-server/src/IdentityServer/Services/Default/PushedAuthorizationService.cs b/identity-server/src/IdentityServer/Services/Default/PushedAuthorizationService.cs index b2a6a14e6..3b806deb7 100644 --- a/identity-server/src/IdentityServer/Services/Default/PushedAuthorizationService.cs +++ b/identity-server/src/IdentityServer/Services/Default/PushedAuthorizationService.cs @@ -29,12 +29,12 @@ public class PushedAuthorizationService : IPushedAuthorizationService } /// - public Task ConsumeAsync(string referenceValue) => _store.ConsumeByHashAsync(referenceValue.ToSha256()); + public Task ConsumeAsync(string referenceValue, Ct ct) => _store.ConsumeByHashAsync(referenceValue.ToSha256(), ct); /// - public async Task GetPushedAuthorizationRequestAsync(string referenceValue) + public async Task GetPushedAuthorizationRequestAsync(string referenceValue, Ct ct) { - var par = await _store.GetByHashAsync(referenceValue.ToSha256()); + var par = await _store.GetByHashAsync(referenceValue.ToSha256(), ct); if (par == null) { return null; @@ -49,7 +49,7 @@ public class PushedAuthorizationService : IPushedAuthorizationService } /// - public async Task StoreAsync(DeserializedPushedAuthorizationRequest request) + public async Task StoreAsync(DeserializedPushedAuthorizationRequest request, Ct ct) { var protectedData = _serializer.Serialize(request.PushedParameters); await _store.StoreAsync(new Models.PushedAuthorizationRequest @@ -57,6 +57,6 @@ public class PushedAuthorizationService : IPushedAuthorizationService ReferenceValueHash = request.ReferenceValue.ToSha256(), ExpiresAtUtc = request.ExpiresAtUtc, Parameters = protectedData - }); + }, ct); } } diff --git a/identity-server/src/IdentityServer/Services/Default/ReturnUrlParser.cs b/identity-server/src/IdentityServer/Services/Default/ReturnUrlParser.cs index 6ffafecdd..3c1a63b1b 100644 --- a/identity-server/src/IdentityServer/Services/Default/ReturnUrlParser.cs +++ b/identity-server/src/IdentityServer/Services/Default/ReturnUrlParser.cs @@ -23,14 +23,15 @@ public class ReturnUrlParser /// Parses the return URL. /// /// The return URL. + /// The cancellation token. /// - public virtual async Task ParseAsync(string returnUrl) + public virtual async Task ParseAsync(string returnUrl, Ct ct) { using var activity = Tracing.ValidationActivitySource.StartActivity("ReturnUrlParser.Parse"); foreach (var parser in _parsers) { - var result = await parser.ParseAsync(returnUrl); + var result = await parser.ParseAsync(returnUrl, ct); if (result != null) { return result; diff --git a/identity-server/src/IdentityServer/Services/Default/ServerSideSessionRefreshTokenService.cs b/identity-server/src/IdentityServer/Services/Default/ServerSideSessionRefreshTokenService.cs index f323cd464..c648d5473 100644 --- a/identity-server/src/IdentityServer/Services/Default/ServerSideSessionRefreshTokenService.cs +++ b/identity-server/src/IdentityServer/Services/Default/ServerSideSessionRefreshTokenService.cs @@ -43,9 +43,9 @@ internal class ServerSideSessionRefreshTokenService : IRefreshTokenService /// - public virtual async Task ValidateRefreshTokenAsync(string tokenHandle, Client client) + public virtual async Task ValidateRefreshTokenAsync(string tokenHandle, Client client, Ct ct) { - var result = await Inner.ValidateRefreshTokenAsync(tokenHandle, client); + var result = await Inner.ValidateRefreshTokenAsync(tokenHandle, client, ct); using var activity = Tracing.ServiceActivitySource.StartActivity("ServerSideSessionRefreshTokenService.ValidateRefreshToken"); @@ -57,7 +57,7 @@ internal class ServerSideSessionRefreshTokenService : IRefreshTokenService SessionId = result.RefreshToken.SessionId, Client = result.Client, Type = SessionValidationType.RefreshToken - }); + }, ct); if (!valid) { @@ -69,8 +69,8 @@ internal class ServerSideSessionRefreshTokenService : IRefreshTokenService } /// - public Task CreateRefreshTokenAsync(RefreshTokenCreationRequest request) => Inner.CreateRefreshTokenAsync(request); + public Task CreateRefreshTokenAsync(RefreshTokenCreationRequest request, Ct ct) => Inner.CreateRefreshTokenAsync(request, ct); /// - public Task UpdateRefreshTokenAsync(RefreshTokenUpdateRequest request) => Inner.UpdateRefreshTokenAsync(request); + public Task UpdateRefreshTokenAsync(RefreshTokenUpdateRequest request, Ct ct) => Inner.UpdateRefreshTokenAsync(request, ct); } diff --git a/identity-server/src/IdentityServer/Services/DiagnosticDataService.cs b/identity-server/src/IdentityServer/Services/DiagnosticDataService.cs index 590e4725f..29078da60 100644 --- a/identity-server/src/IdentityServer/Services/DiagnosticDataService.cs +++ b/identity-server/src/IdentityServer/Services/DiagnosticDataService.cs @@ -22,7 +22,7 @@ public class DiagnosticDataService _entries = entries; } - public async Task> GetJsonBytesAsync(CT ct = default) + public async Task> GetJsonBytesAsync(Ct ct) { var bufferWriter = new ArrayBufferWriter(); await using var writer = new Utf8JsonWriter(bufferWriter, new JsonWriterOptions { Indented = false }); @@ -42,7 +42,7 @@ public class DiagnosticDataService return bufferWriter.WrittenMemory; } - public async Task GetJsonStringAsync(CT ct = default) + public async Task GetJsonStringAsync(Ct ct) { var bytes = await GetJsonBytesAsync(ct); return Encoding.UTF8.GetString(bytes.Span); diff --git a/identity-server/src/IdentityServer/Services/IBackChannelLogoutHttpClient.cs b/identity-server/src/IdentityServer/Services/IBackChannelLogoutHttpClient.cs index 3cd09583f..2e307d90e 100644 --- a/identity-server/src/IdentityServer/Services/IBackChannelLogoutHttpClient.cs +++ b/identity-server/src/IdentityServer/Services/IBackChannelLogoutHttpClient.cs @@ -16,6 +16,7 @@ public interface IBackChannelLogoutHttpClient /// /// /// + /// The cancellation token. /// - Task PostAsync(string url, Dictionary payload); + Task PostAsync(string url, Dictionary payload, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IBackChannelLogoutService.cs b/identity-server/src/IdentityServer/Services/IBackChannelLogoutService.cs index 65440b9e0..0283fa4fe 100644 --- a/identity-server/src/IdentityServer/Services/IBackChannelLogoutService.cs +++ b/identity-server/src/IdentityServer/Services/IBackChannelLogoutService.cs @@ -17,5 +17,6 @@ public interface IBackChannelLogoutService /// Performs http back-channel logout notification. /// /// The context of the back channel logout notification. - Task SendLogoutNotificationsAsync(LogoutNotificationContext context); + /// The cancellation token. + Task SendLogoutNotificationsAsync(LogoutNotificationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationInteractionService.cs b/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationInteractionService.cs index 261fb33a2..b895454f0 100644 --- a/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationInteractionService.cs +++ b/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationInteractionService.cs @@ -17,17 +17,19 @@ public interface IBackchannelAuthenticationInteractionService /// /// Returns the pending login requests for the current user. /// - Task> GetPendingLoginRequestsForCurrentUserAsync(); + Task> GetPendingLoginRequestsForCurrentUserAsync(Ct ct); /// /// Returns the login request for the id. /// - Task GetLoginRequestByInternalIdAsync(string id); + Task GetLoginRequestByInternalIdAsync(string id, Ct ct); /// /// Completes the login request with the provided response for the current user or the subject passed. /// - Task CompleteLoginRequestAsync(CompleteBackchannelLoginRequest completionRequest); + /// The completion request. + /// The cancellation token. + Task CompleteLoginRequestAsync(CompleteBackchannelLoginRequest completionRequest, Ct ct); } /// diff --git a/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationThrottlingService.cs b/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationThrottlingService.cs index 738d7f8f8..0784376cb 100644 --- a/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationThrottlingService.cs +++ b/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationThrottlingService.cs @@ -16,5 +16,5 @@ public interface IBackchannelAuthenticationThrottlingService /// /// Decides if the requesting client and request needs to slow down. /// - Task ShouldSlowDown(string requestId, BackChannelAuthenticationRequest details); + Task ShouldSlowDown(string requestId, BackChannelAuthenticationRequest details, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationUserNotificationService.cs b/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationUserNotificationService.cs index 5d8ba7108..d542c2fe0 100644 --- a/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationUserNotificationService.cs +++ b/identity-server/src/IdentityServer/Services/IBackchannelAuthenticationUserNotificationService.cs @@ -16,5 +16,7 @@ public interface IBackchannelAuthenticationUserNotificationService /// /// Sends a notification for the user to login. /// - Task SendLoginRequestAsync(BackchannelUserLoginRequest request); + /// + /// The cancellation token. + Task SendLoginRequestAsync(BackchannelUserLoginRequest request, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/ICache.cs b/identity-server/src/IdentityServer/Services/ICache.cs index dd92c1cf9..c61e9461f 100644 --- a/identity-server/src/IdentityServer/Services/ICache.cs +++ b/identity-server/src/IdentityServer/Services/ICache.cs @@ -17,8 +17,9 @@ public interface ICache /// Gets the cached data based upon a key index. /// /// The key. + /// The cancellation token. /// The cached item, or null if no item matches the key. - Task GetAsync(string key); + Task GetAsync(string key, Ct ct); /// /// Gets the cached data based upon a key index. @@ -27,8 +28,9 @@ public interface ICache /// The key. /// The duration. /// The function to obtain the item. + /// The cancellation token. /// The cached item. - Task GetOrAddAsync(string key, TimeSpan duration, Func> get); + Task GetOrAddAsync(string key, TimeSpan duration, Func> get, Ct ct); /// /// Caches the data based upon a key @@ -36,12 +38,14 @@ public interface ICache /// The key. /// The item. /// The expiration. + /// The cancellation token. /// - Task SetAsync(string key, T item, TimeSpan expiration); + Task SetAsync(string key, T item, TimeSpan expiration, Ct ct); /// /// Removes the cached data based upon a key index. /// /// The key. - Task RemoveAsync(string key); + /// The cancellation token. + Task RemoveAsync(string key, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IClaimsService.cs b/identity-server/src/IdentityServer/Services/IClaimsService.cs index 553bbb655..8741aa0dc 100644 --- a/identity-server/src/IdentityServer/Services/IClaimsService.cs +++ b/identity-server/src/IdentityServer/Services/IClaimsService.cs @@ -21,10 +21,11 @@ public interface IClaimsService /// The resources. /// Specifies if all claims should be included in the token, or if the userinfo endpoint can be used to retrieve them /// The raw request + /// The cancellation token. /// /// Claims for the identity token /// - Task> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, bool includeAllIdentityClaims, ValidatedRequest request); + Task> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, bool includeAllIdentityClaims, ValidatedRequest request, Ct ct); /// /// Returns claims for an access token. @@ -32,8 +33,9 @@ public interface IClaimsService /// The subject. /// The resources. /// The raw request. + /// The cancellation token. /// /// Claims for the access token /// - Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, ValidatedRequest request); + Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, ValidatedRequest request, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IConsentService.cs b/identity-server/src/IdentityServer/Services/IConsentService.cs index b01057fe2..1d6534f5e 100644 --- a/identity-server/src/IdentityServer/Services/IConsentService.cs +++ b/identity-server/src/IdentityServer/Services/IConsentService.cs @@ -21,10 +21,11 @@ public interface IConsentService /// The user. /// The client. /// The parsed scopes. + /// The cancellation token. /// /// Boolean if consent is required. /// - Task RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes); + Task RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes, Ct ct); /// /// Updates the consent. @@ -32,6 +33,7 @@ public interface IConsentService /// The subject. /// The client. /// The parsed scopes. + /// The cancellation token. /// - Task UpdateConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes); + Task UpdateConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IDeviceFlowCodeService.cs b/identity-server/src/IdentityServer/Services/IDeviceFlowCodeService.cs index dc2110823..1d5ee1b42 100644 --- a/identity-server/src/IdentityServer/Services/IDeviceFlowCodeService.cs +++ b/identity-server/src/IdentityServer/Services/IDeviceFlowCodeService.cs @@ -18,31 +18,36 @@ public interface IDeviceFlowCodeService /// /// The user code. /// The data. - Task StoreDeviceAuthorizationAsync(string userCode, DeviceCode data); + /// The cancellation token. + Task StoreDeviceAuthorizationAsync(string userCode, DeviceCode data, Ct ct); /// /// Finds device authorization by user code. /// /// The user code. + /// The cancellation token. /// - Task FindByUserCodeAsync(string userCode); + Task FindByUserCodeAsync(string userCode, Ct ct); /// /// Finds device authorization by device code. /// /// The device code. - Task FindByDeviceCodeAsync(string deviceCode); + /// The cancellation token. + Task FindByDeviceCodeAsync(string deviceCode, Ct ct); /// /// Updates device authorization, searching by user code. /// /// The user code. /// The data. - Task UpdateByUserCodeAsync(string userCode, DeviceCode data); + /// The cancellation token. + Task UpdateByUserCodeAsync(string userCode, DeviceCode data, Ct ct); /// /// Removes the device authorization, searching by device code. /// /// The device code. - Task RemoveByDeviceCodeAsync(string deviceCode); + /// The cancellation token. + Task RemoveByDeviceCodeAsync(string deviceCode, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IDeviceFlowInteractionService.cs b/identity-server/src/IdentityServer/Services/IDeviceFlowInteractionService.cs index 5c6c87cf6..677120b5e 100644 --- a/identity-server/src/IdentityServer/Services/IDeviceFlowInteractionService.cs +++ b/identity-server/src/IdentityServer/Services/IDeviceFlowInteractionService.cs @@ -17,14 +17,16 @@ public interface IDeviceFlowInteractionService /// Gets the authorization context asynchronously. /// /// The user code. + /// The cancellation token. /// - Task GetAuthorizationContextAsync(string userCode); + Task GetAuthorizationContextAsync(string userCode, Ct ct); /// /// Handles the request asynchronously. /// /// The user code. /// The consent. + /// The cancellation token. /// - Task HandleRequestAsync(string userCode, ConsentResponse consent); + Task HandleRequestAsync(string userCode, ConsentResponse consent, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IDeviceFlowThrottlingService.cs b/identity-server/src/IdentityServer/Services/IDeviceFlowThrottlingService.cs index 3361a71e8..a8e8e66d2 100644 --- a/identity-server/src/IdentityServer/Services/IDeviceFlowThrottlingService.cs +++ b/identity-server/src/IdentityServer/Services/IDeviceFlowThrottlingService.cs @@ -18,6 +18,7 @@ public interface IDeviceFlowThrottlingService /// /// The device code. /// The device code details. + /// The cancellation token. /// - Task ShouldSlowDown(string deviceCode, DeviceCode details); + Task ShouldSlowDown(string deviceCode, DeviceCode details, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IEventService.cs b/identity-server/src/IdentityServer/Services/IEventService.cs index 38fdd27b3..86468cca2 100644 --- a/identity-server/src/IdentityServer/Services/IEventService.cs +++ b/identity-server/src/IdentityServer/Services/IEventService.cs @@ -17,8 +17,9 @@ public interface IEventService /// Raises the specified event. /// /// The event. + /// The cancellation token. #pragma warning disable CA1030 // This is our own eventing and this name is appropriate here - Task RaiseAsync(Event evt); + Task RaiseAsync(Event evt, Ct ct); #pragma warning restore CA1030 /// diff --git a/identity-server/src/IdentityServer/Services/IEventSink.cs b/identity-server/src/IdentityServer/Services/IEventSink.cs index 80ae5dcd2..d1d815cb4 100644 --- a/identity-server/src/IdentityServer/Services/IEventSink.cs +++ b/identity-server/src/IdentityServer/Services/IEventSink.cs @@ -17,5 +17,6 @@ public interface IEventSink /// Raises the specified event. /// /// The event. - Task PersistAsync(Event evt); + /// The cancellation token. + Task PersistAsync(Event evt, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IHandleGenerationService.cs b/identity-server/src/IdentityServer/Services/IHandleGenerationService.cs index 93d2ce852..2c4ba56c0 100644 --- a/identity-server/src/IdentityServer/Services/IHandleGenerationService.cs +++ b/identity-server/src/IdentityServer/Services/IHandleGenerationService.cs @@ -14,7 +14,8 @@ public interface IHandleGenerationService /// /// Generates a handle. /// + /// The cancellation token. /// The length. /// - Task GenerateAsync(int length = 32); + Task GenerateAsync(Ct ct, int length = 32); } diff --git a/identity-server/src/IdentityServer/Services/IIdentityServerInteractionService.cs b/identity-server/src/IdentityServer/Services/IIdentityServerInteractionService.cs index 12b3fc2da..2b34a3b7d 100644 --- a/identity-server/src/IdentityServer/Services/IIdentityServerInteractionService.cs +++ b/identity-server/src/IdentityServer/Services/IIdentityServerInteractionService.cs @@ -17,7 +17,8 @@ public interface IIdentityServerInteractionService /// Gets the authorization context. /// /// The return URL. - Task GetAuthorizationContextAsync(string? returnUrl); + /// The cancellation token. + Task GetAuthorizationContextAsync(string? returnUrl, Ct ct); /// /// Indicates if the returnUrl is a valid URL for redirect after login or consent. @@ -29,27 +30,31 @@ public interface IIdentityServerInteractionService /// Gets the error context. /// /// The error identifier. - Task GetErrorContextAsync(string? errorId); + /// The cancellation token. + Task GetErrorContextAsync(string? errorId, Ct ct); /// /// Gets the logout context. /// /// The logout identifier. - Task GetLogoutContextAsync(string? logoutId); + /// The cancellation token. + Task GetLogoutContextAsync(string? logoutId, Ct ct); /// /// Used to create a logoutId if there is not one presently. /// + /// The cancellation token. /// - Task CreateLogoutContextAsync(); + Task CreateLogoutContextAsync(Ct ct); /// /// Informs IdentityServer of the user's consent. /// /// The request. /// The consent. + /// The cancellation token. /// The subject. - Task GrantConsentAsync(AuthorizationRequest request, ConsentResponse consent, string? subject = null); + Task GrantConsentAsync(AuthorizationRequest request, ConsentResponse consent, Ct ct, string? subject = null); /// /// Triggers error back to the client for the authorization request. @@ -57,22 +62,26 @@ public interface IIdentityServerInteractionService /// /// The request. /// + /// The cancellation token. /// - Task DenyAuthorizationAsync(AuthorizationRequest request, AuthorizationError error, string? errorDescription = null); + Task DenyAuthorizationAsync(AuthorizationRequest request, AuthorizationError error, Ct ct, string? errorDescription = null); /// /// Returns a collection representing all of the user's consents and grants. /// - Task> GetAllUserGrantsAsync(); + /// The cancellation token. + Task> GetAllUserGrantsAsync(Ct ct); /// /// Revokes all a user's consents and grants for a given client, or for all clients if clientId is null. /// /// The client identifier. - Task RevokeUserConsentAsync(string? clientId); + /// The cancellation token. + Task RevokeUserConsentAsync(string? clientId, Ct ct); /// /// Revokes all of a user's consents and grants for clients the user has signed into during their current session. /// - Task RevokeTokensForCurrentSessionAsync(); + /// The cancellation token. + Task RevokeTokensForCurrentSessionAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IIssuerNameService.cs b/identity-server/src/IdentityServer/Services/IIssuerNameService.cs index 0670402f1..7b2c9f463 100644 --- a/identity-server/src/IdentityServer/Services/IIssuerNameService.cs +++ b/identity-server/src/IdentityServer/Services/IIssuerNameService.cs @@ -14,6 +14,7 @@ public interface IIssuerNameService /// /// Returns the issuer name for the current request /// + /// The cancellation token. /// - Task GetCurrentAsync(); + Task GetCurrentAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IJwtRequestUriHttpClient.cs b/identity-server/src/IdentityServer/Services/IJwtRequestUriHttpClient.cs index 16377cd4d..8a56fa295 100644 --- a/identity-server/src/IdentityServer/Services/IJwtRequestUriHttpClient.cs +++ b/identity-server/src/IdentityServer/Services/IJwtRequestUriHttpClient.cs @@ -18,6 +18,7 @@ public interface IJwtRequestUriHttpClient /// /// /// + /// The cancellation token. /// - Task GetJwtAsync(string url, Client client); + Task GetJwtAsync(string url, Client client, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IKeyMaterialService.cs b/identity-server/src/IdentityServer/Services/IKeyMaterialService.cs index 198aa9b38..57be8ff07 100644 --- a/identity-server/src/IdentityServer/Services/IKeyMaterialService.cs +++ b/identity-server/src/IdentityServer/Services/IKeyMaterialService.cs @@ -17,20 +17,23 @@ public interface IKeyMaterialService /// /// Gets all validation keys. /// + /// The cancellation token. /// - Task> GetValidationKeysAsync(); + Task> GetValidationKeysAsync(Ct ct); /// /// Gets the signing credentials. /// /// Collection of algorithms used to filter the server supported algorithms. /// A value of null or empty indicates that the server default should be returned. + /// The cancellation token. /// - Task GetSigningCredentialsAsync(IEnumerable? allowedAlgorithms = null); + Task GetSigningCredentialsAsync(IEnumerable? allowedAlgorithms, Ct ct); /// /// Gets all signing credentials. /// + /// The cancellation token. /// - Task> GetAllSigningCredentialsAsync(); + Task> GetAllSigningCredentialsAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/ILogoutNotificationService.cs b/identity-server/src/IdentityServer/Services/ILogoutNotificationService.cs index 1e7c68496..568756274 100644 --- a/identity-server/src/IdentityServer/Services/ILogoutNotificationService.cs +++ b/identity-server/src/IdentityServer/Services/ILogoutNotificationService.cs @@ -17,13 +17,15 @@ public interface ILogoutNotificationService /// Builds the URLs needed for front-channel logout notification. /// /// The context for the logout notification. - Task> GetFrontChannelLogoutNotificationsUrlsAsync(LogoutNotificationContext context); + /// The cancellation token. + Task> GetFrontChannelLogoutNotificationsUrlsAsync(LogoutNotificationContext context, Ct ct); /// /// Builds the http back-channel logout request data for the collection of clients. /// /// The context for the logout notification. - Task> GetBackChannelLogoutNotificationsAsync(LogoutNotificationContext context); + /// The cancellation token. + Task> GetBackChannelLogoutNotificationsAsync(LogoutNotificationContext context, Ct ct); } /// diff --git a/identity-server/src/IdentityServer/Services/IPersistedGrantService.cs b/identity-server/src/IdentityServer/Services/IPersistedGrantService.cs index 03417eaf7..cf423617e 100644 --- a/identity-server/src/IdentityServer/Services/IPersistedGrantService.cs +++ b/identity-server/src/IdentityServer/Services/IPersistedGrantService.cs @@ -17,15 +17,17 @@ public interface IPersistedGrantService /// Gets all grants for a given subject ID. /// /// The subject identifier. + /// The cancellation token. /// - Task> GetAllGrantsAsync(string subjectId); + Task> GetAllGrantsAsync(string subjectId, Ct ct); /// /// Removes all grants for a given subject id, and optionally client id and session id combination. /// /// The subject identifier. + /// The cancellation token. /// The client identifier (optional). /// The session id (optional). /// - Task RemoveAllGrantsAsync(string subjectId, string? clientId = null, string? sessionId = null); + Task RemoveAllGrantsAsync(string subjectId, Ct ct, string? clientId = null, string? sessionId = null); } diff --git a/identity-server/src/IdentityServer/Services/IProfileService.cs b/identity-server/src/IdentityServer/Services/IProfileService.cs index 1b614e70b..0caf0adbd 100644 --- a/identity-server/src/IdentityServer/Services/IProfileService.cs +++ b/identity-server/src/IdentityServer/Services/IProfileService.cs @@ -17,14 +17,16 @@ public interface IProfileService /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint) /// /// The context. + /// The cancellation token. /// - Task GetProfileDataAsync(ProfileDataRequestContext context); + Task GetProfileDataAsync(ProfileDataRequestContext context, Ct ct); /// /// This method gets called whenever identity server needs to determine if the user is valid or active (e.g. if the user's account has been deactivated since they logged in). /// (e.g. during token issuance or validation). /// /// The context. + /// The cancellation token. /// - Task IsActiveAsync(IsActiveContext context); + Task IsActiveAsync(IsActiveContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IPushedAuthorizationService.cs b/identity-server/src/IdentityServer/Services/IPushedAuthorizationService.cs index 302663ecd..986b2dd3c 100644 --- a/identity-server/src/IdentityServer/Services/IPushedAuthorizationService.cs +++ b/identity-server/src/IdentityServer/Services/IPushedAuthorizationService.cs @@ -17,8 +17,9 @@ public interface IPushedAuthorizationService /// /// The pushed authorization /// request without serialization or data protection applied + /// The cancellation token. /// - Task StoreAsync(DeserializedPushedAuthorizationRequest pushedAuthorizationRequest); + Task StoreAsync(DeserializedPushedAuthorizationRequest pushedAuthorizationRequest, Ct ct); /// /// Consumes the pushed authorization request, indicating that it should not @@ -30,7 +31,8 @@ public interface IPushedAuthorizationService /// The reference value of the pushed /// authorization request. The reference value is the identifier within the /// request_uri parameter. - Task ConsumeAsync(string referenceValue); + /// The cancellation token. + Task ConsumeAsync(string referenceValue, Ct ct); /// /// Gets the raw pushed authorization parameters. @@ -38,8 +40,9 @@ public interface IPushedAuthorizationService /// The reference value of the pushed /// authorization request. The reference value is the identifier within the /// request_uri parameter. + /// The cancellation token. /// The deserialized pushed authorization request, or null if the /// request does not exist or was previously consumed. /// - Task GetPushedAuthorizationRequestAsync(string referenceValue); + Task GetPushedAuthorizationRequestAsync(string referenceValue, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IRefreshTokenService.cs b/identity-server/src/IdentityServer/Services/IRefreshTokenService.cs index cc313ca90..737b4dd35 100644 --- a/identity-server/src/IdentityServer/Services/IRefreshTokenService.cs +++ b/identity-server/src/IdentityServer/Services/IRefreshTokenService.cs @@ -19,22 +19,27 @@ public interface IRefreshTokenService /// /// The refresh token. /// The client. + /// The cancellation token. /// - Task ValidateRefreshTokenAsync(string token, Client client); + Task ValidateRefreshTokenAsync(string token, Client client, Ct ct); /// /// Creates the refresh token. /// + /// The refresh token creation request. + /// The cancellation token. /// /// The refresh token handle /// - Task CreateRefreshTokenAsync(RefreshTokenCreationRequest request); + Task CreateRefreshTokenAsync(RefreshTokenCreationRequest request, Ct ct); /// /// Updates the refresh token. /// + /// The refresh token update request. + /// The cancellation token. /// /// The refresh token handle /// - Task UpdateRefreshTokenAsync(RefreshTokenUpdateRequest request); + Task UpdateRefreshTokenAsync(RefreshTokenUpdateRequest request, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IReplayCache.cs b/identity-server/src/IdentityServer/Services/IReplayCache.cs index 89b0b17e3..3461f624a 100644 --- a/identity-server/src/IdentityServer/Services/IReplayCache.cs +++ b/identity-server/src/IdentityServer/Services/IReplayCache.cs @@ -17,8 +17,9 @@ public interface IReplayCache /// /// /// + /// The cancellation token. /// - Task AddAsync(string purpose, string handle, DateTimeOffset expiration); + Task AddAsync(string purpose, string handle, DateTimeOffset expiration, Ct ct); /// @@ -26,6 +27,7 @@ public interface IReplayCache /// /// /// + /// The cancellation token. /// - Task ExistsAsync(string purpose, string handle); + Task ExistsAsync(string purpose, string handle, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IReturnUrlParser.cs b/identity-server/src/IdentityServer/Services/IReturnUrlParser.cs index 23a0b73b1..8dfcaaa86 100644 --- a/identity-server/src/IdentityServer/Services/IReturnUrlParser.cs +++ b/identity-server/src/IdentityServer/Services/IReturnUrlParser.cs @@ -17,8 +17,9 @@ public interface IReturnUrlParser /// Parses a return URL. /// /// The return URL. + /// The cancellation token. /// - Task ParseAsync(string returnUrl); + Task ParseAsync(string returnUrl, Ct ct); /// /// Determines whether the return URL is valid. diff --git a/identity-server/src/IdentityServer/Services/ISessionCoordinationService.cs b/identity-server/src/IdentityServer/Services/ISessionCoordinationService.cs index ec00d0d2e..5de585565 100644 --- a/identity-server/src/IdentityServer/Services/ISessionCoordinationService.cs +++ b/identity-server/src/IdentityServer/Services/ISessionCoordinationService.cs @@ -16,18 +16,20 @@ public interface ISessionCoordinationService /// /// Coordinates when a user logs out. /// - Task ProcessLogoutAsync(UserSession session); + Task ProcessLogoutAsync(UserSession session, Ct ct); /// /// Coordinates when a user session has expired. /// - Task ProcessExpirationAsync(UserSession session); + Task ProcessExpirationAsync(UserSession session, Ct ct); /// /// Validates client request, and if valid extends server-side session. /// Returns false if the session is invalid, true otherwise. /// - Task ValidateSessionAsync(SessionValidationRequest request); + /// The session validation request. + /// The cancellation token. + Task ValidateSessionAsync(SessionValidationRequest request, Ct ct); } /// diff --git a/identity-server/src/IdentityServer/Services/ISessionManagementService.cs b/identity-server/src/IdentityServer/Services/ISessionManagementService.cs index 92484cce6..20fb8bc51 100644 --- a/identity-server/src/IdentityServer/Services/ISessionManagementService.cs +++ b/identity-server/src/IdentityServer/Services/ISessionManagementService.cs @@ -17,12 +17,16 @@ public interface ISessionManagementService /// /// Queries all the session related data for a user. /// - Task> QuerySessionsAsync(SessionQuery? filter = null, CT ct = default); + /// The session query filter. + /// The cancellation token. + Task> QuerySessionsAsync(SessionQuery? filter, Ct ct); /// /// Removes all the session related data for a user. /// - Task RemoveSessionsAsync(RemoveSessionsContext context, CT ct = default); + /// The context describing what to remove. + /// The cancellation token. + Task RemoveSessionsAsync(RemoveSessionsContext context, Ct ct); } /// diff --git a/identity-server/src/IdentityServer/Services/ITokenCreationService.cs b/identity-server/src/IdentityServer/Services/ITokenCreationService.cs index 7ff182d15..def2c5f30 100644 --- a/identity-server/src/IdentityServer/Services/ITokenCreationService.cs +++ b/identity-server/src/IdentityServer/Services/ITokenCreationService.cs @@ -17,6 +17,7 @@ public interface ITokenCreationService /// Creates a token. /// /// The token description. + /// The cancellation token. /// A protected and serialized security token - Task CreateTokenAsync(Token token); + Task CreateTokenAsync(Token token, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/ITokenService.cs b/identity-server/src/IdentityServer/Services/ITokenService.cs index aba1959b2..6d2dd7937 100644 --- a/identity-server/src/IdentityServer/Services/ITokenService.cs +++ b/identity-server/src/IdentityServer/Services/ITokenService.cs @@ -17,20 +17,23 @@ public interface ITokenService /// Creates an identity token. /// /// The token creation request. + /// The cancellation token. /// An identity token - Task CreateIdentityTokenAsync(TokenCreationRequest request); + Task CreateIdentityTokenAsync(TokenCreationRequest request, Ct ct); /// /// Creates an access token. /// /// The token creation request. + /// The cancellation token. /// An access token - Task CreateAccessTokenAsync(TokenCreationRequest request); + Task CreateAccessTokenAsync(TokenCreationRequest request, Ct ct); /// /// Creates a serialized and protected security token. /// /// The token. + /// The cancellation token. /// A security token in serialized form - Task CreateSecurityTokenAsync(Token token); + Task CreateSecurityTokenAsync(Token token, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IUiLocalesService.cs b/identity-server/src/IdentityServer/Services/IUiLocalesService.cs index bcba0d8a6..6cfcf925f 100644 --- a/identity-server/src/IdentityServer/Services/IUiLocalesService.cs +++ b/identity-server/src/IdentityServer/Services/IUiLocalesService.cs @@ -6,5 +6,10 @@ namespace Duende.IdentityServer.Services; public interface IUiLocalesService { - Task StoreUiLocalesForRedirectAsync(string? uiLocales); + /// + /// Stores the UI locales for redirect. + /// + /// + /// The cancellation token. + Task StoreUiLocalesForRedirectAsync(string? uiLocales, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IUserCodeGenerator.cs b/identity-server/src/IdentityServer/Services/IUserCodeGenerator.cs index 7d0f13144..090caa45d 100644 --- a/identity-server/src/IdentityServer/Services/IUserCodeGenerator.cs +++ b/identity-server/src/IdentityServer/Services/IUserCodeGenerator.cs @@ -30,6 +30,7 @@ public interface IUserCodeGenerator /// /// Generates the user code. /// + /// The cancellation token. /// - Task GenerateAsync(); + Task GenerateAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IUserCodeService.cs b/identity-server/src/IdentityServer/Services/IUserCodeService.cs index 91fba912e..c106b99ed 100644 --- a/identity-server/src/IdentityServer/Services/IUserCodeService.cs +++ b/identity-server/src/IdentityServer/Services/IUserCodeService.cs @@ -15,6 +15,7 @@ public interface IUserCodeService /// Gets the user code generator. /// /// Type of user code. + /// The cancellation token. /// - Task GetGenerator(string userCodeType); + Task GetGenerator(string userCodeType, Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/IUserSession.cs b/identity-server/src/IdentityServer/Services/IUserSession.cs index ceafe2d6e..ad88e4877 100644 --- a/identity-server/src/IdentityServer/Services/IUserSession.cs +++ b/identity-server/src/IdentityServer/Services/IUserSession.cs @@ -17,40 +17,49 @@ public interface IUserSession /// /// Creates a session identifier for the signin context and issues the session id cookie. /// - Task CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties); + /// + /// + /// The cancellation token. + Task CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties, Ct ct); /// /// Gets the current authenticated user. /// - Task GetUserAsync(); + /// The cancellation token. + Task GetUserAsync(Ct ct); /// /// Gets the current session identifier. /// + /// The cancellation token. /// - Task GetSessionIdAsync(); + Task GetSessionIdAsync(Ct ct); /// /// Ensures the session identifier cookie asynchronously. /// + /// The cancellation token. /// - Task EnsureSessionIdCookieAsync(); + Task EnsureSessionIdCookieAsync(Ct ct); /// /// Removes the session identifier cookie. /// - Task RemoveSessionIdCookieAsync(); + /// The cancellation token. + Task RemoveSessionIdCookieAsync(Ct ct); /// /// Adds a client to the list of clients the user has signed into during their session. /// /// The client identifier. + /// The cancellation token. /// - Task AddClientIdAsync(string clientId); + Task AddClientIdAsync(string clientId, Ct ct); /// /// Gets the list of clients the user has signed into during their session. /// + /// The cancellation token. /// - Task> GetClientListAsync(); + Task> GetClientListAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Services/InMemory/InMemoryCorsPolicyService.cs b/identity-server/src/IdentityServer/Services/InMemory/InMemoryCorsPolicyService.cs index 0e43414c6..cdae13db0 100644 --- a/identity-server/src/IdentityServer/Services/InMemory/InMemoryCorsPolicyService.cs +++ b/identity-server/src/IdentityServer/Services/InMemory/InMemoryCorsPolicyService.cs @@ -34,12 +34,8 @@ public class InMemoryCorsPolicyService : ICorsPolicyService Clients = clients ?? Enumerable.Empty(); } - /// - /// Determines whether origin is allowed. - /// - /// The origin. - /// - public virtual Task IsOriginAllowedAsync(string origin) + /// + public virtual Task IsOriginAllowedAsync(string origin, Ct ct) { using var activity = Tracing.ServiceActivitySource.StartActivity("InMemoryCorsPolicyService.IsOriginAllowedAsync"); diff --git a/identity-server/src/IdentityServer/Stores/Caching/CachingClientStore.cs b/identity-server/src/IdentityServer/Stores/Caching/CachingClientStore.cs index bc9f583b0..118a50e85 100644 --- a/identity-server/src/IdentityServer/Stores/Caching/CachingClientStore.cs +++ b/identity-server/src/IdentityServer/Stores/Caching/CachingClientStore.cs @@ -37,27 +37,29 @@ public class CachingClientStore : IClientStore /// Finds a client by id /// /// The client id + /// The cancellation token. /// /// The client /// - public async Task FindClientByIdAsync(string clientId) + public async Task FindClientByIdAsync(string clientId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingClientStore.FindClientById"); activity?.SetTag(Tracing.Properties.ClientId, clientId); var client = await _cache.GetOrAddAsync(clientId, _options.Caching.ClientStoreExpiration, - async () => await _inner.FindClientByIdAsync(clientId)); + async () => await _inner.FindClientByIdAsync(clientId, ct), + ct); return client; } #if NET10_0_OR_GREATER /// - public IAsyncEnumerable GetAllClientsAsync() + public IAsyncEnumerable GetAllClientsAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingClientStore.GetAllClients"); - return _inner.GetAllClientsAsync(); + return _inner.GetAllClientsAsync(ct); } #endif } diff --git a/identity-server/src/IdentityServer/Stores/Caching/CachingCorsPolicyService.cs b/identity-server/src/IdentityServer/Stores/Caching/CachingCorsPolicyService.cs index 58af4290c..4079db8ca 100644 --- a/identity-server/src/IdentityServer/Stores/Caching/CachingCorsPolicyService.cs +++ b/identity-server/src/IdentityServer/Stores/Caching/CachingCorsPolicyService.cs @@ -49,19 +49,16 @@ public class CachingCorsPolicyService : ICorsPolicyService CorsCache = corsCache; } - /// - /// Determines whether origin is allowed. - /// - /// The origin. - /// - public virtual async Task IsOriginAllowedAsync(string origin) + /// + public virtual async Task IsOriginAllowedAsync(string origin, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingCorsPolicyService.IsOriginAllowed"); activity?.SetTag(Tracing.Properties.Origin, origin); var entry = await CorsCache.GetOrAddAsync(origin, Options.Caching.CorsExpiration, - async () => new CorsCacheEntry(await Inner.IsOriginAllowedAsync(origin))); + async () => new CorsCacheEntry(await Inner.IsOriginAllowedAsync(origin, ct)), + ct); return entry.Allowed; } diff --git a/identity-server/src/IdentityServer/Stores/Caching/CachingResourceStore.cs b/identity-server/src/IdentityServer/Stores/Caching/CachingResourceStore.cs index bcfa37e7e..2eee090c6 100644 --- a/identity-server/src/IdentityServer/Stores/Caching/CachingResourceStore.cs +++ b/identity-server/src/IdentityServer/Stores/Caching/CachingResourceStore.cs @@ -80,7 +80,7 @@ public class CachingResourceStore : IResourceStore } /// - public async Task GetAllResourcesAsync() + public async Task GetAllResourcesAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingResourceStore.GetAllResources"); @@ -88,13 +88,14 @@ public class CachingResourceStore : IResourceStore var all = await _allCache.GetOrAddAsync(key, _options.Caching.ResourceStoreExpiration, - async () => await _inner.GetAllResourcesAsync()); + async () => await _inner.GetAllResourcesAsync(ct), + ct); return all; } /// - public async Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames) + public async Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingResourceStore.FindApiResourcesByScopeName"); activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString()); @@ -103,7 +104,7 @@ public class CachingResourceStore : IResourceStore var uncachedScopes = new List(); foreach (var scope in scopeNames) { - var apiResourceName = await _apiResourceNames.GetAsync(scope); + var apiResourceName = await _apiResourceNames.GetAsync(scope, ct); if (apiResourceName != null) { foreach (var name in apiResourceName.Names) @@ -133,9 +134,9 @@ public class CachingResourceStore : IResourceStore // do the cache/DB lookup var resources = await _allCache.GetOrAddAsync(allCacheItemsKey, itemsDuration, async () => { - var results = await _inner.FindApiResourcesByScopeNameAsync(uncachedScopes); + var results = await _inner.FindApiResourcesByScopeNameAsync(uncachedScopes, ct); return new Resources(null, results, null); - }); + }, ct); // get the specific items from the Resources object var uncachedItems = resources.ApiResources; @@ -145,14 +146,14 @@ public class CachingResourceStore : IResourceStore { var names = uncachedItems.Where(x => x.Scopes.Contains(scope)).Select(x => x.Name).ToArray(); var apiResourceNamesCacheItem = new ApiResourceNames { Names = names }; - await _apiResourceNames.SetAsync(scope, apiResourceNamesCacheItem, _options.Caching.ResourceStoreExpiration); + await _apiResourceNames.SetAsync(scope, apiResourceNamesCacheItem, _options.Caching.ResourceStoreExpiration, ct); } // add each one to the specific cache foreach (var item in uncachedItems) { // this adds to the ApiResource cache in the same way when FindApiResourcesByNameAsync is used - await _apiResourceCache.SetAsync(item.Name, item, _options.Caching.ResourceStoreExpiration); + await _apiResourceCache.SetAsync(item.Name, item, _options.Caching.ResourceStoreExpiration, ct); // add this name apiResourceNames.Add(item.Name); @@ -160,51 +161,52 @@ public class CachingResourceStore : IResourceStore } // now that we have all the ApiResource names, just use our other API (that should find the cacted items) - return await FindApiResourcesByNameAsync(apiResourceNames); + return await FindApiResourcesByNameAsync(apiResourceNames, ct); } /// - public async Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames) + public async Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingResourceStore.FindApiResourcesByName"); activity?.SetTag(Tracing.Properties.ApiResourceNames, apiResourceNames.ToSpaceSeparatedString()); return await FindItemsAsync(apiResourceNames, _apiResourceCache, - async names => new Resources(null, await _inner.FindApiResourcesByNameAsync(names), null), - x => x.ApiResources, x => x.Name, "ApiResources-"); + async (names, innerCt) => new Resources(null, await _inner.FindApiResourcesByNameAsync(names, innerCt), null), + x => x.ApiResources, x => x.Name, "ApiResources-", ct); } /// - public async Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames) + public async Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingResourceStore.FindIdentityResourcesByScopeName"); activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString()); return await FindItemsAsync(scopeNames, _identityCache, - async names => new Resources(await _inner.FindIdentityResourcesByScopeNameAsync(names), null, null), - x => x.IdentityResources, x => x.Name, "IdentityResources-"); + async (names, innerCt) => new Resources(await _inner.FindIdentityResourcesByScopeNameAsync(names, innerCt), null, null), + x => x.IdentityResources, x => x.Name, "IdentityResources-", ct); } /// - public async Task> FindApiScopesByNameAsync(IEnumerable scopeNames) + public async Task> FindApiScopesByNameAsync(IEnumerable scopeNames, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("CachingResourceStore.FindApiScopesByName"); activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString()); return await FindItemsAsync(scopeNames, _apiScopeCache, - async names => new Resources(null, null, await _inner.FindApiScopesByNameAsync(names)), - x => x.ApiScopes, x => x.Name, "ApiScopes-"); + async (names, innerCt) => new Resources(null, null, await _inner.FindApiScopesByNameAsync(names, innerCt)), + x => x.ApiScopes, x => x.Name, "ApiScopes-", ct); } private async Task> FindItemsAsync( IEnumerable names, ICache cache, - Func, Task> getResourcesFunc, + Func, Ct, Task> getResourcesFunc, Func> getFromResourcesFunc, Func getNameFunc, - string allCachePrefix + string allCachePrefix, + Ct ct ) where TItem : class { @@ -212,7 +214,7 @@ public class CachingResourceStore : IResourceStore var cachedItems = new List(); foreach (var name in names) { - var item = await cache.GetAsync(name); + var item = await cache.GetAsync(name, ct); if (item != null) { cachedItems.Add(item); @@ -237,14 +239,14 @@ public class CachingResourceStore : IResourceStore // expire this entry much faster than the normal items var itemsDuration = _options.Caching.ResourceStoreExpiration / 20; // do the cache/DB lookup - var resources = await _allCache.GetOrAddAsync(allCacheItemsKey, itemsDuration, async () => await getResourcesFunc(uncachedNames)); + var resources = await _allCache.GetOrAddAsync(allCacheItemsKey, itemsDuration, async () => await getResourcesFunc(uncachedNames, ct), ct); // get the specific items from the Resources object var uncachedItems = getFromResourcesFunc(resources); // add each one to the specific cache foreach (var item in uncachedItems) { - await cache.SetAsync(getNameFunc(item), item, _options.Caching.ResourceStoreExpiration); + await cache.SetAsync(getNameFunc(item), item, _options.Caching.ResourceStoreExpiration, ct); } // add these to our result diff --git a/identity-server/src/IdentityServer/Stores/Default/ConsentMessageStore.cs b/identity-server/src/IdentityServer/Stores/Default/ConsentMessageStore.cs index f8b840e6b..de9d4bf97 100644 --- a/identity-server/src/IdentityServer/Stores/Default/ConsentMessageStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/ConsentMessageStore.cs @@ -12,7 +12,7 @@ internal class ConsentMessageStore : IConsentMessageStore public ConsentMessageStore(MessageCookie cookie) => Cookie = cookie; - public virtual Task DeleteAsync(string id) + public virtual Task DeleteAsync(string id, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ConsentMessageStore.Delete"); @@ -20,14 +20,14 @@ internal class ConsentMessageStore : IConsentMessageStore return Task.CompletedTask; } - public virtual Task> ReadAsync(string id) + public virtual Task> ReadAsync(string id, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ConsentMessageStore.Read"); return Task.FromResult(Cookie.Read(id)); } - public virtual Task WriteAsync(string id, Message message) + public virtual Task WriteAsync(string id, Message message, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ConsentMessageStore.Write"); diff --git a/identity-server/src/IdentityServer/Stores/Default/DefaultAuthorizationCodeStore.cs b/identity-server/src/IdentityServer/Stores/Default/DefaultAuthorizationCodeStore.cs index 01dc2cc7e..7a68856c9 100644 --- a/identity-server/src/IdentityServer/Stores/Default/DefaultAuthorizationCodeStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/DefaultAuthorizationCodeStore.cs @@ -31,39 +31,27 @@ public class DefaultAuthorizationCodeStore : DefaultGrantStore - /// Stores the authorization code asynchronously. - /// - /// The code. - /// - public Task StoreAuthorizationCodeAsync(AuthorizationCode code) + /// + public Task StoreAuthorizationCodeAsync(AuthorizationCode code, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultAuthorizationCodeStore.StoreAuthorizationCode"); - return CreateItemAsync(code, code.ClientId, code.Subject.GetSubjectId(), code.SessionId, code.Description, code.CreationTime, code.Lifetime); + return CreateItemAsync(code, code.ClientId, code.Subject.GetSubjectId(), code.SessionId, code.Description, code.CreationTime, code.Lifetime, ct); } - /// - /// Gets the authorization code asynchronously. - /// - /// The code. - /// - public Task GetAuthorizationCodeAsync(string code) + /// + public Task GetAuthorizationCodeAsync(string code, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultAuthorizationCodeStore.GetAuthorizationCode"); - return GetItemAsync(code); + return GetItemAsync(code, ct); } - /// - /// Removes the authorization code asynchronously. - /// - /// The code. - /// - public Task RemoveAuthorizationCodeAsync(string code) + /// + public Task RemoveAuthorizationCodeAsync(string code, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultAuthorizationCodeStore.RemoveAuthorizationCode"); - return RemoveItemAsync(code); + return RemoveItemAsync(code, ct); } } diff --git a/identity-server/src/IdentityServer/Stores/Default/DefaultBackChannelAuthenticationRequestStore.cs b/identity-server/src/IdentityServer/Stores/Default/DefaultBackChannelAuthenticationRequestStore.cs index 5e7615038..e28e55dbc 100644 --- a/identity-server/src/IdentityServer/Stores/Default/DefaultBackChannelAuthenticationRequestStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/DefaultBackChannelAuthenticationRequestStore.cs @@ -32,42 +32,42 @@ public class DefaultBackChannelAuthenticationRequestStore : DefaultGrantStore - public async Task CreateRequestAsync(BackChannelAuthenticationRequest request) + public async Task CreateRequestAsync(BackChannelAuthenticationRequest request, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultBackChannelAuthenticationRequestStore.CreateRequest"); - var handle = await CreateHandleAsync(); + var handle = await CreateHandleAsync(ct); request.InternalId = GetHashedKey(handle); - await StoreItemByHashedKeyAsync(request.InternalId, request, request.ClientId, request.Subject.GetSubjectId(), null, null, request.CreationTime, request.CreationTime.AddSeconds(request.Lifetime)); + await StoreItemByHashedKeyAsync(request.InternalId, request, request.ClientId, request.Subject.GetSubjectId(), null, null, request.CreationTime, request.CreationTime.AddSeconds(request.Lifetime), ct); return handle; } /// - public Task GetByInternalIdAsync(string id) + public Task GetByInternalIdAsync(string id, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultBackChannelAuthenticationRequestStore.GetByInternalId"); - return GetItemByHashedKeyAsync(id); + return GetItemByHashedKeyAsync(id, ct); } /// - public Task GetByAuthenticationRequestIdAsync(string requestId) + public Task GetByAuthenticationRequestIdAsync(string requestId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultBackChannelAuthenticationRequestStore.GetByAuthenticationRequestId"); - return GetItemAsync(requestId); + return GetItemAsync(requestId, ct); } /// - public Task RemoveByInternalIdAsync(string requestId) + public Task RemoveByInternalIdAsync(string requestId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultBackChannelAuthenticationRequestStore.RemoveByInternalId"); - return RemoveItemByHashedKeyAsync(requestId); + return RemoveItemByHashedKeyAsync(requestId, ct); } /// - public Task> GetLoginsForUserAsync(string subjectId, string clientId = null) + public Task> GetLoginsForUserAsync(string subjectId, Ct ct, string clientId = null) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultBackChannelAuthenticationRequestStore.GetLoginsForUser"); @@ -75,14 +75,14 @@ public class DefaultBackChannelAuthenticationRequestStore : DefaultGrantStore - public Task UpdateByInternalIdAsync(string id, BackChannelAuthenticationRequest request) + public Task UpdateByInternalIdAsync(string id, BackChannelAuthenticationRequest request, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultBackChannelAuthenticationRequestStore.UpdateByInternalId"); - return StoreItemByHashedKeyAsync(id, request, request.ClientId, request.Subject.GetSubjectId(), request.SessionId, request.Description, request.CreationTime, request.CreationTime.AddSeconds(request.Lifetime)); + return StoreItemByHashedKeyAsync(id, request, request.ClientId, request.Subject.GetSubjectId(), request.SessionId, request.Description, request.CreationTime, request.CreationTime.AddSeconds(request.Lifetime), ct); } } diff --git a/identity-server/src/IdentityServer/Stores/Default/DefaultGrantStore.cs b/identity-server/src/IdentityServer/Stores/Default/DefaultGrantStore.cs index 6cdede84e..390252a79 100644 --- a/identity-server/src/IdentityServer/Stores/Default/DefaultGrantStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/DefaultGrantStore.cs @@ -80,7 +80,7 @@ public class DefaultGrantStore /// /// Creates a handle. /// - protected async Task CreateHandleAsync() => await HandleGenerationService.GenerateAsync() + HexEncodingFormatSuffix; + protected async Task CreateHandleAsync(Ct ct) => await HandleGenerationService.GenerateAsync(ct) + HexEncodingFormatSuffix; /// /// Gets the hashed key. @@ -107,11 +107,12 @@ public class DefaultGrantStore /// Gets the item. /// /// The key. + /// The cancellation token. /// - protected virtual async Task GetItemAsync(string key) + protected virtual async Task GetItemAsync(string key, Ct ct) { var hashedKey = GetHashedKey(key); - var item = await GetItemByHashedKeyAsync(hashedKey); + var item = await GetItemByHashedKeyAsync(hashedKey, ct); if (item == null) { Logger.LogDebug("{grantType} grant with value: {key} not found in store.", GrantType, key.SanitizeLogParameter()); @@ -123,10 +124,11 @@ public class DefaultGrantStore /// Gets the item by the hashed key. /// /// + /// The cancellation token. /// - protected virtual async Task GetItemByHashedKeyAsync(string hashedKey) + protected virtual async Task GetItemByHashedKeyAsync(string hashedKey, Ct ct) { - var grant = await Store.GetAsync(hashedKey); + var grant = await Store.GetAsync(hashedKey, ct); if (grant != null && grant.Type == GrantType) { try @@ -145,10 +147,12 @@ public class DefaultGrantStore /// /// Gets the items. /// - protected virtual async Task> GetAllAsync(PersistedGrantFilter filter) + /// The filter. + /// The cancellation token. + protected virtual async Task> GetAllAsync(PersistedGrantFilter filter, Ct ct) { filter.Type = GrantType; - var items = await Store.GetAllAsync(filter); + var items = await Store.GetAllAsync(filter, ct); var result = items.Select(x => Serializer.Deserialize(x.Data)).ToArray(); return result; } @@ -163,11 +167,12 @@ public class DefaultGrantStore /// The description. /// The created. /// The lifetime. + /// The cancellation token. /// - protected virtual async Task CreateItemAsync(T item, string clientId, string subjectId, string sessionId, string description, DateTime created, int lifetime) + protected virtual async Task CreateItemAsync(T item, string clientId, string subjectId, string sessionId, string description, DateTime created, int lifetime, Ct ct) { - var handle = await CreateHandleAsync(); - await StoreItemAsync(handle, item, clientId, subjectId, sessionId, description, created, created.AddSeconds(lifetime)); + var handle = await CreateHandleAsync(ct); + await StoreItemAsync(handle, item, clientId, subjectId, sessionId, description, created, created.AddSeconds(lifetime), ct); return handle; } @@ -182,12 +187,13 @@ public class DefaultGrantStore /// The description. /// The created time. /// The expiration. + /// The cancellation token. /// The consumed time. /// - protected virtual Task StoreItemAsync(string key, T item, string clientId, string subjectId, string sessionId, string description, DateTime created, DateTime? expiration, DateTime? consumedTime = null) + protected virtual Task StoreItemAsync(string key, T item, string clientId, string subjectId, string sessionId, string description, DateTime created, DateTime? expiration, Ct ct, DateTime? consumedTime = null) { key = GetHashedKey(key); - return StoreItemByHashedKeyAsync(key, item, clientId, subjectId, sessionId, description, created, expiration, consumedTime); + return StoreItemByHashedKeyAsync(key, item, clientId, subjectId, sessionId, description, created, expiration, ct, consumedTime); } /// @@ -201,9 +207,10 @@ public class DefaultGrantStore /// The description. /// The created time. /// The expiration. + /// The cancellation token. /// The consumed time. /// - protected virtual async Task StoreItemByHashedKeyAsync(string hashedKey, T item, string clientId, string subjectId, string sessionId, string description, DateTime created, DateTime? expiration, DateTime? consumedTime = null) + protected virtual async Task StoreItemByHashedKeyAsync(string hashedKey, T item, string clientId, string subjectId, string sessionId, string description, DateTime created, DateTime? expiration, Ct ct, DateTime? consumedTime = null) { var json = Serializer.Serialize(item); @@ -221,39 +228,42 @@ public class DefaultGrantStore Data = json }; - await Store.StoreAsync(grant); + await Store.StoreAsync(grant, ct); } /// /// Removes the item. /// /// The key. + /// The cancellation token. /// - protected virtual Task RemoveItemAsync(string key) + protected virtual Task RemoveItemAsync(string key, Ct ct) { key = GetHashedKey(key); - return RemoveItemByHashedKeyAsync(key); + return RemoveItemByHashedKeyAsync(key, ct); } /// /// Removes the item. /// /// The key. + /// The cancellation token. /// - protected virtual async Task RemoveItemByHashedKeyAsync(string key) => await Store.RemoveAsync(key); + protected virtual async Task RemoveItemByHashedKeyAsync(string key, Ct ct) => await Store.RemoveAsync(key, ct); /// /// Removes all items for a subject id / client id combination. /// /// The subject identifier. /// The client identifier. + /// The cancellation token. /// The optional session identifier. /// - protected virtual async Task RemoveAllAsync(string subjectId, string clientId, string sessionId = null) => await Store.RemoveAllAsync(new PersistedGrantFilter + protected virtual async Task RemoveAllAsync(string subjectId, string clientId, Ct ct, string sessionId = null) => await Store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = subjectId, ClientId = clientId, SessionId = sessionId, Type = GrantType - }); + }, ct); } diff --git a/identity-server/src/IdentityServer/Stores/Default/DefaultReferenceTokenStore.cs b/identity-server/src/IdentityServer/Stores/Default/DefaultReferenceTokenStore.cs index e6048c138..8e0913c52 100644 --- a/identity-server/src/IdentityServer/Stores/Default/DefaultReferenceTokenStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/DefaultReferenceTokenStore.cs @@ -31,34 +31,34 @@ public class DefaultReferenceTokenStore : DefaultGrantStore, IReferenceTo } /// - public Task StoreReferenceTokenAsync(Token token) + public Task StoreReferenceTokenAsync(Token token, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultReferenceTokenStore.StoreReferenceToken"); - return CreateItemAsync(token, token.ClientId, token.SubjectId, token.SessionId, token.Description, token.CreationTime, token.Lifetime); + return CreateItemAsync(token, token.ClientId, token.SubjectId, token.SessionId, token.Description, token.CreationTime, token.Lifetime, ct); } /// - public Task GetReferenceTokenAsync(string handle) + public Task GetReferenceTokenAsync(string handle, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultReferenceTokenStore.GetReferenceToken"); - return GetItemAsync(handle); + return GetItemAsync(handle, ct); } /// - public Task RemoveReferenceTokenAsync(string handle) + public Task RemoveReferenceTokenAsync(string handle, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultReferenceTokenStore.RemoveReferenceToken"); - return RemoveItemAsync(handle); + return RemoveItemAsync(handle, ct); } /// - public Task RemoveReferenceTokensAsync(string subjectId, string clientId, string sessionId = null) + public Task RemoveReferenceTokensAsync(string subjectId, string clientId, string sessionId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultReferenceTokenStore.RemoveReferenceTokens"); - return RemoveAllAsync(subjectId, clientId, sessionId); + return RemoveAllAsync(subjectId, clientId, ct, sessionId); } } diff --git a/identity-server/src/IdentityServer/Stores/Default/DefaultRefreshTokenStore.cs b/identity-server/src/IdentityServer/Stores/Default/DefaultRefreshTokenStore.cs index 11d7c0bf1..93ebcb822 100644 --- a/identity-server/src/IdentityServer/Stores/Default/DefaultRefreshTokenStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/DefaultRefreshTokenStore.cs @@ -30,65 +30,43 @@ public class DefaultRefreshTokenStore : DefaultGrantStore, IRefres { } - /// - /// Stores the refresh token. - /// - /// The refresh token. - /// - public async Task StoreRefreshTokenAsync(RefreshToken refreshToken) + /// + public async Task StoreRefreshTokenAsync(RefreshToken refreshToken, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultRefreshTokenStore.StoreRefreshTokenAsync"); - return await CreateItemAsync(refreshToken, refreshToken.ClientId, refreshToken.SubjectId, refreshToken.SessionId, refreshToken.Description, refreshToken.CreationTime, refreshToken.Lifetime); + return await CreateItemAsync(refreshToken, refreshToken.ClientId, refreshToken.SubjectId, refreshToken.SessionId, refreshToken.Description, refreshToken.CreationTime, refreshToken.Lifetime, ct); } - /// - /// Updates the refresh token. - /// - /// The handle. - /// The refresh token. - /// - public Task UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken) + /// + public Task UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultRefreshTokenStore.UpdateRefreshToken"); - return StoreItemAsync(handle, refreshToken, refreshToken.ClientId, refreshToken.SubjectId, refreshToken.SessionId, refreshToken.Description, refreshToken.CreationTime, refreshToken.CreationTime.AddSeconds(refreshToken.Lifetime), refreshToken.ConsumedTime); + return StoreItemAsync(handle, refreshToken, refreshToken.ClientId, refreshToken.SubjectId, refreshToken.SessionId, refreshToken.Description, refreshToken.CreationTime, refreshToken.CreationTime.AddSeconds(refreshToken.Lifetime), ct, refreshToken.ConsumedTime); } - /// - /// Gets the refresh token. - /// - /// The refresh token handle. - /// - public Task GetRefreshTokenAsync(string refreshTokenHandle) + /// + public Task GetRefreshTokenAsync(string refreshTokenHandle, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultRefreshTokenStore.GetRefreshToken"); - return GetItemAsync(refreshTokenHandle); + return GetItemAsync(refreshTokenHandle, ct); } - /// - /// Removes the refresh token. - /// - /// The refresh token handle. - /// - public Task RemoveRefreshTokenAsync(string refreshTokenHandle) + /// + public Task RemoveRefreshTokenAsync(string refreshTokenHandle, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultRefreshTokenStore.RemoveRefreshToken"); - return RemoveItemAsync(refreshTokenHandle); + return RemoveItemAsync(refreshTokenHandle, ct); } - /// - /// Removes the refresh tokens. - /// - /// The subject identifier. - /// The client identifier. - /// - public Task RemoveRefreshTokensAsync(string subjectId, string clientId) + /// + public Task RemoveRefreshTokensAsync(string subjectId, string clientId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultRefreshTokenStore.RemoveRefreshTokens"); - return RemoveAllAsync(subjectId, clientId); + return RemoveAllAsync(subjectId, clientId, ct); } } diff --git a/identity-server/src/IdentityServer/Stores/Default/DefaultUserConsentStore.cs b/identity-server/src/IdentityServer/Stores/Default/DefaultUserConsentStore.cs index 9552c63b8..daf63a2e8 100644 --- a/identity-server/src/IdentityServer/Stores/Default/DefaultUserConsentStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/DefaultUserConsentStore.cs @@ -42,56 +42,42 @@ public class DefaultUserConsentStore : DefaultGrantStore, IUserConsentS } } - /// - /// Stores the user consent asynchronously. - /// - /// The consent. - /// - public Task StoreUserConsentAsync(Consent consent) + /// + public Task StoreUserConsentAsync(Consent consent, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultUserConsentStore.StoreUserConsent"); var key = GetConsentKey(consent.SubjectId, consent.ClientId); - return StoreItemAsync(key, consent, consent.ClientId, consent.SubjectId, null, null, consent.CreationTime, consent.Expiration); + return StoreItemAsync(key, consent, consent.ClientId, consent.SubjectId, null, null, consent.CreationTime, consent.Expiration, ct); } - /// - /// Gets the user consent asynchronously. - /// - /// The subject identifier. - /// The client identifier. - /// - public async Task GetUserConsentAsync(string subjectId, string clientId) + /// + public async Task GetUserConsentAsync(string subjectId, string clientId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultUserConsentStore.GetUserConsent"); var key = GetConsentKey(subjectId, clientId); - var consent = await GetItemAsync(key); + var consent = await GetItemAsync(key, ct); if (consent == null) { var legacyKey = GetConsentKey(subjectId, clientId, useHexEncoding: false); - consent = await GetItemAsync(legacyKey); + consent = await GetItemAsync(legacyKey, ct); if (consent != null) { - await StoreUserConsentAsync(consent); // Write back the consent record to update its key - await RemoveItemAsync(legacyKey); + await StoreUserConsentAsync(consent, ct); // Write back the consent record to update its key + await RemoveItemAsync(legacyKey, ct); } } return consent; } - /// - /// Removes the user consent asynchronously. - /// - /// The subject identifier. - /// The client identifier. - /// - public Task RemoveUserConsentAsync(string subjectId, string clientId) + /// + public Task RemoveUserConsentAsync(string subjectId, string clientId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultUserConsentStore.RemoveUserConsent"); var key = GetConsentKey(subjectId, clientId); - return RemoveItemAsync(key); + return RemoveItemAsync(key, ct); } } diff --git a/identity-server/src/IdentityServer/Stores/Default/DistributedCacheAuthorizationParametersMessageStore.cs b/identity-server/src/IdentityServer/Stores/Default/DistributedCacheAuthorizationParametersMessageStore.cs index ca90eaeef..dc578a8f8 100644 --- a/identity-server/src/IdentityServer/Stores/Default/DistributedCacheAuthorizationParametersMessageStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/DistributedCacheAuthorizationParametersMessageStore.cs @@ -31,7 +31,7 @@ public class DistributedCacheAuthorizationParametersMessageStore : IAuthorizatio private static string CacheKeyPrefix => "DistributedCacheAuthorizationParametersMessageStore"; /// - public virtual async Task WriteAsync(Message> message) + public virtual async Task WriteAsync(Message> message, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DistributedCacheAuthorizationParametersMessageStore.Write"); @@ -41,7 +41,7 @@ public class DistributedCacheAuthorizationParametersMessageStore : IAuthorizatio // same for the "request" param, but it's less of a concern (as it's just a signature check). message.Data.Remove(OidcConstants.AuthorizeRequest.RequestUri); - var key = await _handleGenerationService.GenerateAsync(); + var key = await _handleGenerationService.GenerateAsync(ct); var cacheKey = $"{CacheKeyPrefix}-{key}"; var json = ObjectSerializer.ToString(message); @@ -49,18 +49,18 @@ public class DistributedCacheAuthorizationParametersMessageStore : IAuthorizatio var options = new DistributedCacheEntryOptions(); options.SetSlidingExpiration(Constants.DefaultCacheDuration); - await _distributedCache.SetStringAsync(cacheKey, json, options); + await _distributedCache.SetStringAsync(cacheKey, json, options, ct); return key; } /// - public virtual async Task>> ReadAsync(string id) + public virtual async Task>> ReadAsync(string id, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DistributedCacheAuthorizationParametersMessageStore.Read"); var cacheKey = $"{CacheKeyPrefix}-{id}"; - var json = await _distributedCache.GetStringAsync(cacheKey); + var json = await _distributedCache.GetStringAsync(cacheKey, ct); if (json == null) { @@ -71,11 +71,11 @@ public class DistributedCacheAuthorizationParametersMessageStore : IAuthorizatio } /// - public virtual Task DeleteAsync(string id) + public virtual Task DeleteAsync(string id, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("DistributedCacheAuthorizationParametersMessageStore.Delete"); var cacheKey = $"{CacheKeyPrefix}-{id}"; - return _distributedCache.RemoveAsync(cacheKey); + return _distributedCache.RemoveAsync(cacheKey, ct); } } diff --git a/identity-server/src/IdentityServer/Stores/Default/ProtectedDataMessageStore.cs b/identity-server/src/IdentityServer/Stores/Default/ProtectedDataMessageStore.cs index 86e73b3b3..79394d5f9 100644 --- a/identity-server/src/IdentityServer/Stores/Default/ProtectedDataMessageStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/ProtectedDataMessageStore.cs @@ -40,7 +40,7 @@ public class ProtectedDataMessageStore : IMessageStore } /// - public virtual Task> ReadAsync(string value) + public virtual Task> ReadAsync(string value, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("ProtectedDataMessageStore.Read"); @@ -65,7 +65,7 @@ public class ProtectedDataMessageStore : IMessageStore } /// - public virtual Task WriteAsync(Message message) + public virtual Task WriteAsync(Message message, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("ProtectedDataMessageStore.Write"); diff --git a/identity-server/src/IdentityServer/Stores/Default/QueryStringAuthorizationParametersMessageStore.cs b/identity-server/src/IdentityServer/Stores/Default/QueryStringAuthorizationParametersMessageStore.cs index 9178b759e..ac76df041 100644 --- a/identity-server/src/IdentityServer/Stores/Default/QueryStringAuthorizationParametersMessageStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/QueryStringAuthorizationParametersMessageStore.cs @@ -10,18 +10,18 @@ namespace Duende.IdentityServer.Stores; // internal just for testing internal class QueryStringAuthorizationParametersMessageStore : IAuthorizationParametersMessageStore { - public Task WriteAsync(Message> message) + public Task WriteAsync(Message> message, Ct _) { var queryString = message.Data.FromFullDictionary().ToQueryString(); return Task.FromResult(queryString); } - public Task>> ReadAsync(string id) + public Task>> ReadAsync(string id, Ct _) { var values = id.ReadQueryStringAsNameValueCollection(); var msg = new Message>(values.ToFullDictionary()); return Task.FromResult(msg); } - public Task DeleteAsync(string id) => Task.CompletedTask; + public Task DeleteAsync(string id, Ct _) => Task.CompletedTask; } diff --git a/identity-server/src/IdentityServer/Stores/Default/ServerSideTicketStore.cs b/identity-server/src/IdentityServer/Stores/Default/ServerSideTicketStore.cs index 115bb27cb..790335886 100644 --- a/identity-server/src/IdentityServer/Stores/Default/ServerSideTicketStore.cs +++ b/identity-server/src/IdentityServer/Stores/Default/ServerSideTicketStore.cs @@ -58,7 +58,7 @@ public class ServerSideTicketStore : IServerSideTicketStore ArgumentNullException.ThrowIfNull(ticket); - ticket.SetIssuer(await _issuerNameService.GetCurrentAsync()); + ticket.SetIssuer(await _issuerNameService.GetCurrentAsync(_httpContextAccessor.HttpContext?.RequestAborted ?? default)); var key = CryptoRandom.CreateUniqueId(format: CryptoRandom.OutputFormat.Hex); @@ -84,7 +84,7 @@ public class ServerSideTicketStore : IServerSideTicketStore Ticket = ticket.Serialize(_protector) }; - await _store.CreateSessionAsync(session); + await _store.CreateSessionAsync(session, _httpContextAccessor.HttpContext?.RequestAborted ?? default); } /// @@ -96,7 +96,7 @@ public class ServerSideTicketStore : IServerSideTicketStore _logger.LogDebug("Retrieve AuthenticationTicket for key {key}", key); - var session = await _store.GetSessionAsync(key); + var session = await _store.GetSessionAsync(key, _httpContextAccessor.HttpContext?.RequestAborted ?? default); if (session == null) { _logger.LogDebug("No ticket found in store for {key}", key); @@ -124,7 +124,7 @@ public class ServerSideTicketStore : IServerSideTicketStore ArgumentNullException.ThrowIfNull(ticket); - var session = await _store.GetSessionAsync(key); + var session = await _store.GetSessionAsync(key, _httpContextAccessor.HttpContext?.RequestAborted ?? default); if (session == null) { // https://github.com/dotnet/aspnetcore/issues/41516#issuecomment-1178076544 @@ -149,14 +149,14 @@ public class ServerSideTicketStore : IServerSideTicketStore if (ticket.GetIssuer() == null) { // when issuing a new cookie on top of an existing cookie, the AuthenticationTicket passed above is new (and not the prior one loaded from the ticket store) - ticket.SetIssuer(await _issuerNameService.GetCurrentAsync()); + ticket.SetIssuer(await _issuerNameService.GetCurrentAsync(_httpContextAccessor.HttpContext?.RequestAborted ?? default)); } session.Renewed = ticket.GetIssued(); session.Expires = ticket.GetExpiration(); session.DisplayName = name; session.Ticket = ticket.Serialize(_protector); - await _store.UpdateSessionAsync(session); + await _store.UpdateSessionAsync(session, _httpContextAccessor.HttpContext?.RequestAborted ?? default); } /// @@ -171,7 +171,7 @@ public class ServerSideTicketStore : IServerSideTicketStore // There is a somewhat rare scenario where a session has expired and a request to IdentityServer happens prior // to the cleanup job running. When that happens, the session is removed but none of the processing to trigger // backchannel logouts, etc. happens so we need a way to kick that off and are doing so here. - var session = await _store.GetSessionAsync(key); + var session = await _store.GetSessionAsync(key, _httpContextAccessor.HttpContext?.RequestAborted ?? default); if (session != null) { var userSession = AsUserSessions([session]).SingleOrDefault(); @@ -181,11 +181,11 @@ public class ServerSideTicketStore : IServerSideTicketStore } } - await _store.DeleteSessionAsync(key); + await _store.DeleteSessionAsync(key, _httpContextAccessor.HttpContext?.RequestAborted ?? default); } /// - public async Task> GetSessionsAsync(SessionFilter filter, CT ct = default) + public async Task> GetSessionsAsync(SessionFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideTicketStore.GetSessions"); @@ -196,11 +196,11 @@ public class ServerSideTicketStore : IServerSideTicketStore } /// - public async Task> QuerySessionsAsync(SessionQuery filter = null, CT ct = default) + public async Task> QuerySessionsAsync(SessionQuery filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideTicketStore.QuerySessions"); - var results = await _store.QuerySessionsAsync(filter, ct); + var results = await _store.QuerySessionsAsync(ct, filter); var tickets = AsUserSessions(results.Results); @@ -219,7 +219,7 @@ public class ServerSideTicketStore : IServerSideTicketStore } /// - public async Task> GetAndRemoveExpiredSessionsAsync(int count, CT ct = default) + public async Task> GetAndRemoveExpiredSessionsAsync(int count, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ServerSideTicketStore.GetAndRemoveExpiredSessions"); diff --git a/identity-server/src/IdentityServer/Stores/Empty/EmptyClientStore.cs b/identity-server/src/IdentityServer/Stores/Empty/EmptyClientStore.cs index 8524f0568..68c3cd2ce 100644 --- a/identity-server/src/IdentityServer/Stores/Empty/EmptyClientStore.cs +++ b/identity-server/src/IdentityServer/Stores/Empty/EmptyClientStore.cs @@ -2,16 +2,17 @@ // See LICENSE in the project root for license information. +using System.Runtime.CompilerServices; using Duende.IdentityServer.Models; namespace Duende.IdentityServer.Stores.Empty; internal class EmptyClientStore : IClientStore { - public Task FindClientByIdAsync(string clientId) => Task.FromResult(null); + public Task FindClientByIdAsync(string clientId, Ct _) => Task.FromResult(null); #if NET10_0_OR_GREATER - public async IAsyncEnumerable GetAllClientsAsync() + public async IAsyncEnumerable GetAllClientsAsync([EnumeratorCancellation] Ct _) { await Task.CompletedTask; yield break; diff --git a/identity-server/src/IdentityServer/Stores/Empty/EmptyResourceStore.cs b/identity-server/src/IdentityServer/Stores/Empty/EmptyResourceStore.cs index 236c73572..9cb6d820c 100644 --- a/identity-server/src/IdentityServer/Stores/Empty/EmptyResourceStore.cs +++ b/identity-server/src/IdentityServer/Stores/Empty/EmptyResourceStore.cs @@ -8,13 +8,13 @@ namespace Duende.IdentityServer.Stores.Empty; internal class EmptyResourceStore : IResourceStore { - public Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames) => Task.FromResult(Enumerable.Empty()); + public Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames, Ct _) => Task.FromResult(Enumerable.Empty()); - public Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames) => Task.FromResult(Enumerable.Empty()); + public Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames, Ct _) => Task.FromResult(Enumerable.Empty()); - public Task> FindApiScopesByNameAsync(IEnumerable scopeNames) => Task.FromResult(Enumerable.Empty()); + public Task> FindApiScopesByNameAsync(IEnumerable scopeNames, Ct _) => Task.FromResult(Enumerable.Empty()); - public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames) => Task.FromResult(Enumerable.Empty()); + public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames, Ct _) => Task.FromResult(Enumerable.Empty()); - public Task GetAllResourcesAsync() => Task.FromResult(new Resources() { OfflineAccess = true }); + public Task GetAllResourcesAsync(Ct _) => Task.FromResult(new Resources() { OfflineAccess = true }); } diff --git a/identity-server/src/IdentityServer/Stores/IAuthorizationParametersMessageStore.cs b/identity-server/src/IdentityServer/Stores/IAuthorizationParametersMessageStore.cs index 8147ccdc7..fef9af6c4 100644 --- a/identity-server/src/IdentityServer/Stores/IAuthorizationParametersMessageStore.cs +++ b/identity-server/src/IdentityServer/Stores/IAuthorizationParametersMessageStore.cs @@ -15,20 +15,23 @@ public interface IAuthorizationParametersMessageStore /// Writes the authorization parameters. /// /// The message. + /// The cancellation token. /// The identifier for the stored message. - Task WriteAsync(Message> message); + Task WriteAsync(Message> message, Ct ct); /// /// Reads the authorization parameters. /// /// The identifier. + /// The cancellation token. /// - Task>> ReadAsync(string id); + Task>> ReadAsync(string id, Ct ct); /// /// Deletes the authorization parameters. /// /// The identifier. + /// The cancellation token. /// - Task DeleteAsync(string id); + Task DeleteAsync(string id, Ct ct); } diff --git a/identity-server/src/IdentityServer/Stores/IConsentMessageStore.cs b/identity-server/src/IdentityServer/Stores/IConsentMessageStore.cs index 56050967a..a9f0a493e 100644 --- a/identity-server/src/IdentityServer/Stores/IConsentMessageStore.cs +++ b/identity-server/src/IdentityServer/Stores/IConsentMessageStore.cs @@ -16,19 +16,22 @@ public interface IConsentMessageStore /// /// The id for the message. /// The message. - Task WriteAsync(string id, Message message); + /// The cancellation token. + Task WriteAsync(string id, Message message, Ct ct); /// /// Reads the consent response message. /// /// The identifier. + /// The cancellation token. /// - Task> ReadAsync(string id); + Task> ReadAsync(string id, Ct ct); /// /// Deletes the consent response message. /// /// The identifier. + /// The cancellation token. /// - Task DeleteAsync(string id); + Task DeleteAsync(string id, Ct ct); } diff --git a/identity-server/src/IdentityServer/Stores/IMessageStore.cs b/identity-server/src/IdentityServer/Stores/IMessageStore.cs index bc93974f4..6501e5ea5 100644 --- a/identity-server/src/IdentityServer/Stores/IMessageStore.cs +++ b/identity-server/src/IdentityServer/Stores/IMessageStore.cs @@ -16,13 +16,15 @@ public interface IMessageStore /// Writes the message. /// /// The message. + /// The cancellation token. /// An identifier for the message - Task WriteAsync(Message message); + Task WriteAsync(Message message, Ct ct); /// /// Reads the message. /// /// The identifier. + /// The cancellation token. /// - Task> ReadAsync(string id); + Task> ReadAsync(string id, Ct ct); } diff --git a/identity-server/src/IdentityServer/Stores/IServerSideTicketStore.cs b/identity-server/src/IdentityServer/Stores/IServerSideTicketStore.cs index dc5b1982f..ae8665227 100644 --- a/identity-server/src/IdentityServer/Stores/IServerSideTicketStore.cs +++ b/identity-server/src/IdentityServer/Stores/IServerSideTicketStore.cs @@ -17,15 +17,21 @@ public interface IServerSideTicketStore : ITicketStore /// /// Gets sessions for a specific subject id and/or session id /// - Task> GetSessionsAsync(SessionFilter filter, CT ct = default); + /// The session filter. + /// The cancellation token. + Task> GetSessionsAsync(SessionFilter filter, Ct ct); /// /// Queries user sessions based on filter /// - Task> QuerySessionsAsync(SessionQuery filter, CT ct = default); + /// The session query filter. + /// The cancellation token. + Task> QuerySessionsAsync(SessionQuery filter, Ct ct); /// /// Removes and returns expired sessions /// - Task> GetAndRemoveExpiredSessionsAsync(int count, CT ct = default); + /// The maximum number of sessions to return. + /// The cancellation token. + Task> GetAndRemoveExpiredSessionsAsync(int count, Ct ct); } diff --git a/identity-server/src/IdentityServer/Stores/ISigningCredentialStore.cs b/identity-server/src/IdentityServer/Stores/ISigningCredentialStore.cs index 4ab3ad833..ca75885f6 100644 --- a/identity-server/src/IdentityServer/Stores/ISigningCredentialStore.cs +++ b/identity-server/src/IdentityServer/Stores/ISigningCredentialStore.cs @@ -14,6 +14,7 @@ public interface ISigningCredentialStore /// /// Gets the signing credentials. /// + /// The cancellation token. /// - Task GetSigningCredentialsAsync(); + Task GetSigningCredentialsAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Stores/IValidationKeysStore.cs b/identity-server/src/IdentityServer/Stores/IValidationKeysStore.cs index dbe523da7..5e591823d 100644 --- a/identity-server/src/IdentityServer/Stores/IValidationKeysStore.cs +++ b/identity-server/src/IdentityServer/Stores/IValidationKeysStore.cs @@ -14,6 +14,7 @@ public interface IValidationKeysStore /// /// Gets all validation keys. /// + /// The cancellation token. /// - Task> GetValidationKeysAsync(); + Task> GetValidationKeysAsync(Ct ct); } diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryClientStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryClientStore.cs index dfbc364a5..f0e9d681d 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryClientStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryClientStore.cs @@ -1,6 +1,7 @@ // Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. +using System.Runtime.CompilerServices; using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; @@ -30,10 +31,11 @@ public class InMemoryClientStore : IClientStore /// Finds a client by id /// /// The client id + /// The cancellation token (unused). /// /// The client /// - public Task FindClientByIdAsync(string clientId) + public Task FindClientByIdAsync(string clientId, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryClientStore.FindClientById"); activity?.SetTag(Tracing.Properties.ClientId, clientId); @@ -47,7 +49,7 @@ public class InMemoryClientStore : IClientStore } /// - public async IAsyncEnumerable GetAllClientsAsync() + public async IAsyncEnumerable GetAllClientsAsync([EnumeratorCancellation] Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryClientStore.GetAllClients"); diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryDeviceFlowStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryDeviceFlowStore.cs index 02c366a4d..b904fbef5 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryDeviceFlowStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryDeviceFlowStore.cs @@ -14,14 +14,8 @@ public class InMemoryDeviceFlowStore : IDeviceFlowStore { private readonly List _repository = new List(); - /// - /// Stores the device authorization request. - /// - /// The device code. - /// The user code. - /// The data. - /// - public Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data) + /// + public Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryDeviceFlowStore.StoreDeviceAuthorization"); @@ -33,11 +27,8 @@ public class InMemoryDeviceFlowStore : IDeviceFlowStore return Task.CompletedTask; } - /// - /// Finds device authorization by user code. - /// - /// The user code. - public Task FindByUserCodeAsync(string userCode) + /// + public Task FindByUserCodeAsync(string userCode, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryDeviceFlowStore.FindByUserCode"); @@ -51,11 +42,8 @@ public class InMemoryDeviceFlowStore : IDeviceFlowStore return Task.FromResult(foundDeviceCode); } - /// - /// Finds device authorization by device code. - /// - /// The device code. - public Task FindByDeviceCodeAsync(string deviceCode) + /// + public Task FindByDeviceCodeAsync(string deviceCode, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryDeviceFlowStore.FindByDeviceCode"); @@ -69,12 +57,8 @@ public class InMemoryDeviceFlowStore : IDeviceFlowStore return Task.FromResult(foundDeviceCode); } - /// - /// Updates device authorization, searching by user code. - /// - /// The user code. - /// The data. - public Task UpdateByUserCodeAsync(string userCode, DeviceCode data) + /// + public Task UpdateByUserCodeAsync(string userCode, DeviceCode data, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryDeviceFlowStore.UpdateByUserCode"); @@ -91,12 +75,8 @@ public class InMemoryDeviceFlowStore : IDeviceFlowStore return Task.CompletedTask; } - /// - /// Removes the device authorization, searching by device code. - /// - /// The device code. - /// - public Task RemoveByDeviceCodeAsync(string deviceCode) + /// + public Task RemoveByDeviceCodeAsync(string deviceCode, Ct _) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryDeviceFlowStore.RemoveByDeviceCode"); diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPersistedGrantStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPersistedGrantStore.cs index bc36f2602..21b92349f 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPersistedGrantStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPersistedGrantStore.cs @@ -16,7 +16,7 @@ public class InMemoryPersistedGrantStore : IPersistedGrantStore private readonly ConcurrentDictionary _repository = new ConcurrentDictionary(); /// - public Task StoreAsync(PersistedGrant grant) + public Task StoreAsync(PersistedGrant grant, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPersistedGrantStoreResponseGenerator.Store"); @@ -26,7 +26,7 @@ public class InMemoryPersistedGrantStore : IPersistedGrantStore } /// - public Task GetAsync(string key) + public Task GetAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPersistedGrantStoreResponseGenerator.Get"); @@ -39,7 +39,7 @@ public class InMemoryPersistedGrantStore : IPersistedGrantStore } /// - public Task> GetAllAsync(PersistedGrantFilter filter) + public Task> GetAllAsync(PersistedGrantFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPersistedGrantStoreResponseGenerator.GetAll"); @@ -51,7 +51,7 @@ public class InMemoryPersistedGrantStore : IPersistedGrantStore } /// - public Task RemoveAsync(string key) + public Task RemoveAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPersistedGrantStoreResponseGenerator.Remove"); @@ -61,7 +61,7 @@ public class InMemoryPersistedGrantStore : IPersistedGrantStore } /// - public Task RemoveAllAsync(PersistedGrantFilter filter) + public Task RemoveAllAsync(PersistedGrantFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPersistedGrantStoreResponseGenerator.RemoveAll"); diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPushedAuthorizationRequestStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPushedAuthorizationRequestStore.cs index ebc057829..97062a127 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPushedAuthorizationRequestStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryPushedAuthorizationRequestStore.cs @@ -17,7 +17,7 @@ public class InMemoryPushedAuthorizationRequestStore : IPushedAuthorizationReque private readonly ConcurrentDictionary _repository = new ConcurrentDictionary(); /// - public Task StoreAsync(PushedAuthorizationRequest pushedAuthorizationRequest) + public Task StoreAsync(PushedAuthorizationRequest pushedAuthorizationRequest, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPushedAuthorizationRequestStore.Store"); @@ -27,7 +27,7 @@ public class InMemoryPushedAuthorizationRequestStore : IPushedAuthorizationReque } /// - public Task GetByHashAsync(string referenceValueHash) + public Task GetByHashAsync(string referenceValueHash, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPushedAuthorizationRequestStore.Get"); _repository.TryGetValue(referenceValueHash, out var request); @@ -36,7 +36,7 @@ public class InMemoryPushedAuthorizationRequestStore : IPushedAuthorizationReque } /// - public Task ConsumeByHashAsync(string referenceValueHash) + public Task ConsumeByHashAsync(string referenceValueHash, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryPushedAuthorizationRequestStore.Remove"); _repository.TryRemove(referenceValueHash, out _); diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryResourcesStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryResourcesStore.cs index ec45ec19a..c85e1df27 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryResourcesStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryResourcesStore.cs @@ -45,7 +45,7 @@ public class InMemoryResourcesStore : IResourceStore } /// - public Task GetAllResourcesAsync() + public Task GetAllResourcesAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.GetAllResources"); @@ -54,7 +54,7 @@ public class InMemoryResourcesStore : IResourceStore } /// - public Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames) + public Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames, Ct ct) { ArgumentNullException.ThrowIfNull(apiResourceNames); using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindApiResourcesByName"); @@ -67,7 +67,7 @@ public class InMemoryResourcesStore : IResourceStore } /// - public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames) + public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct) { ArgumentNullException.ThrowIfNull(scopeNames); using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindIdentityResourcesByScopeName"); @@ -81,7 +81,7 @@ public class InMemoryResourcesStore : IResourceStore } /// - public Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames) + public Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct) { ArgumentNullException.ThrowIfNull(scopeNames); using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindApiResourcesByScopeName"); @@ -95,7 +95,7 @@ public class InMemoryResourcesStore : IResourceStore } /// - public Task> FindApiScopesByNameAsync(IEnumerable scopeNames) + public Task> FindApiScopesByNameAsync(IEnumerable scopeNames, Ct ct) { ArgumentNullException.ThrowIfNull(scopeNames); using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindApiScopesByName"); diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryServerSideSessionStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryServerSideSessionStore.cs index f5bd14def..f217424a3 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryServerSideSessionStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryServerSideSessionStore.cs @@ -18,7 +18,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore /// - public Task CreateSessionAsync(ServerSideSession session, CT ct = default) + public Task CreateSessionAsync(ServerSideSession session, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.CreateSession"); @@ -30,7 +30,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore } /// - public Task GetSessionAsync(string key, CT ct = default) + public Task GetSessionAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.GetSession"); @@ -39,7 +39,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore } /// - public Task UpdateSessionAsync(ServerSideSession session, CT ct = default) + public Task UpdateSessionAsync(ServerSideSession session, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.UpdateSession"); @@ -48,7 +48,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore } /// - public Task DeleteSessionAsync(string key, CT ct = default) + public Task DeleteSessionAsync(string key, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.DeleteSession"); @@ -59,7 +59,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore /// - public Task> GetSessionsAsync(SessionFilter filter, CT ct = default) + public Task> GetSessionsAsync(SessionFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.GetSessions"); @@ -80,7 +80,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore } /// - public Task DeleteSessionsAsync(SessionFilter filter, CT ct = default) + public Task DeleteSessionsAsync(SessionFilter filter, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.DeleteSessions"); @@ -108,7 +108,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore /// - public Task> GetAndRemoveExpiredSessionsAsync(int count, CT ct = default) + public Task> GetAndRemoveExpiredSessionsAsync(int count, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.GetAndRemoveExpiredSession"); @@ -129,7 +129,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore /// - public Task> QuerySessionsAsync(SessionQuery filter = null, CT ct = default) + public Task> QuerySessionsAsync(Ct ct, SessionQuery filter = null) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryServerSideSessionStore.QuerySessions"); @@ -219,7 +219,7 @@ public class InMemoryServerSideSessionStore : IServerSideSessionStore // we need to start over and re-query from the beginning. filter.ResultsToken = null; filter.RequestPriorResults = false; - return QuerySessionsAsync(filter, ct); + return QuerySessionsAsync(ct, filter); } } else diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemorySigningCredentialsStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemorySigningCredentialsStore.cs index 5bec161f6..6c6cba8d7 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemorySigningCredentialsStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemorySigningCredentialsStore.cs @@ -24,7 +24,7 @@ public class InMemorySigningCredentialsStore : ISigningCredentialStore /// Gets the signing credentials. /// /// - public Task GetSigningCredentialsAsync() + public Task GetSigningCredentialsAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemorySigningCredentialsStore.GetSigningCredentials"); diff --git a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryValidationKeysStore.cs b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryValidationKeysStore.cs index 8d4c9fd51..e015a60cf 100644 --- a/identity-server/src/IdentityServer/Stores/InMemory/InMemoryValidationKeysStore.cs +++ b/identity-server/src/IdentityServer/Stores/InMemory/InMemoryValidationKeysStore.cs @@ -25,7 +25,7 @@ public class InMemoryValidationKeysStore : IValidationKeysStore /// Gets all validation keys. /// /// - public Task> GetValidationKeysAsync() + public Task> GetValidationKeysAsync(Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryValidationKeysStore.GetValidationKeys"); diff --git a/identity-server/src/IdentityServer/Stores/ValidatingClientStore.cs b/identity-server/src/IdentityServer/Stores/ValidatingClientStore.cs index 9c92414d6..a3099fa11 100644 --- a/identity-server/src/IdentityServer/Stores/ValidatingClientStore.cs +++ b/identity-server/src/IdentityServer/Stores/ValidatingClientStore.cs @@ -2,6 +2,7 @@ // See LICENSE in the project root for license information. +using System.Runtime.CompilerServices; using Duende.IdentityServer.Events; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; @@ -43,21 +44,22 @@ public class ValidatingClientStore : IClientStore /// Finds a client by id (and runs the validation logic) /// /// The client id + /// The cancellation token. /// /// The client or an InvalidOperationException /// - public async Task FindClientByIdAsync(string clientId) + public async Task FindClientByIdAsync(string clientId, Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ValidatingClientStore.FindClientById"); - var client = await _inner.FindClientByIdAsync(clientId); + var client = await _inner.FindClientByIdAsync(clientId, ct); if (client != null) { _logger.LogTrace("Calling into client configuration validator: {validatorType}", _validatorType); var context = new ClientConfigurationValidationContext(client); - await _validator.ValidateAsync(context); + await _validator.ValidateAsync(context, ct); if (context.IsValid) { @@ -68,7 +70,7 @@ public class ValidatingClientStore : IClientStore _logger.LogError("Invalid client configuration for client {clientId}: {errorMessage}", client.ClientId, context.ErrorMessage); Telemetry.Metrics.ClientValidationFailure(clientId, context.ErrorMessage); - await _events.RaiseAsync(new InvalidClientConfigurationEvent(client, context.ErrorMessage)); + await _events.RaiseAsync(new InvalidClientConfigurationEvent(client, context.ErrorMessage), ct); return null; } @@ -79,14 +81,14 @@ public class ValidatingClientStore : IClientStore } /// - public async IAsyncEnumerable GetAllClientsAsync() + public async IAsyncEnumerable GetAllClientsAsync([EnumeratorCancellation] Ct ct) { using var activity = Tracing.StoreActivitySource.StartActivity("ValidatingClientStore.GetAllClients"); - await foreach (var client in _inner.GetAllClientsAsync()) + await foreach (var client in _inner.GetAllClientsAsync(ct)) { _logger.LogTrace("Calling into client configuration validator: {validatorType}", _validatorType); var context = new ClientConfigurationValidationContext(client); - await _validator.ValidateAsync(context); + await _validator.ValidateAsync(context, ct); if (context.IsValid) { _logger.LogDebug("client configuration validation for client {clientId} succeeded.", client.ClientId); @@ -97,7 +99,7 @@ public class ValidatingClientStore : IClientStore { _logger.LogError("Invalid client configuration for client {clientId}: {errorMessage}", client.ClientId, context.ErrorMessage); Telemetry.Metrics.ClientValidationFailure(client.ClientId, context.ErrorMessage); - await _events.RaiseAsync(new InvalidClientConfigurationEvent(client, context.ErrorMessage)); + await _events.RaiseAsync(new InvalidClientConfigurationEvent(client, context.ErrorMessage), ct); // Skip invalid clients - do not yield } } diff --git a/identity-server/src/IdentityServer/Test/TestBackchannelLoginUserValidator.cs b/identity-server/src/IdentityServer/Test/TestBackchannelLoginUserValidator.cs index fee8f7be9..049e4ddd7 100644 --- a/identity-server/src/IdentityServer/Test/TestBackchannelLoginUserValidator.cs +++ b/identity-server/src/IdentityServer/Test/TestBackchannelLoginUserValidator.cs @@ -22,7 +22,7 @@ public class TestBackchannelLoginUserValidator : IBackchannelAuthenticationUserV public TestBackchannelLoginUserValidator(TestUserStore testUserStore) => _testUserStore = testUserStore; /// - public Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext) + public Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext, Ct ct) { var result = new BackchannelAuthenticationUserValidationResult(); diff --git a/identity-server/src/IdentityServer/Test/TestUserProfileService.cs b/identity-server/src/IdentityServer/Test/TestUserProfileService.cs index 03419f328..8eeca1a1f 100644 --- a/identity-server/src/IdentityServer/Test/TestUserProfileService.cs +++ b/identity-server/src/IdentityServer/Test/TestUserProfileService.cs @@ -40,8 +40,9 @@ public class TestUserProfileService : IProfileService /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint) /// /// The context. + /// The cancellation token. /// - public virtual Task GetProfileDataAsync(ProfileDataRequestContext context) + public virtual Task GetProfileDataAsync(ProfileDataRequestContext context, Ct ct) { context.LogProfileRequest(Logger); @@ -64,8 +65,9 @@ public class TestUserProfileService : IProfileService /// (e.g. during token issuance or validation). /// /// The context. + /// The cancellation token. /// - public virtual Task IsActiveAsync(IsActiveContext context) + public virtual Task IsActiveAsync(IsActiveContext context, Ct ct) { Logger.LogDebug("IsActive called from: {caller}", context.Caller); diff --git a/identity-server/src/IdentityServer/Test/TestUserResourceOwnerPasswordValidator.cs b/identity-server/src/IdentityServer/Test/TestUserResourceOwnerPasswordValidator.cs index 2e729b302..1f7c985b9 100644 --- a/identity-server/src/IdentityServer/Test/TestUserResourceOwnerPasswordValidator.cs +++ b/identity-server/src/IdentityServer/Test/TestUserResourceOwnerPasswordValidator.cs @@ -27,12 +27,8 @@ public class TestUserResourceOwnerPasswordValidator : IResourceOwnerPasswordVali _timeProvider = timeProvider; } - /// - /// Validates the resource owner password credential - /// - /// The context. - /// - public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) + /// + public Task ValidateAsync(ResourceOwnerPasswordValidationContext context, Ct ct) { if (_users.ValidateCredentials(context.UserName, context.Password)) { diff --git a/identity-server/src/IdentityServer/Validation/Contexts/IntrospectionRequestValidationContext.cs b/identity-server/src/IdentityServer/Validation/Contexts/IntrospectionRequestValidationContext.cs index cc6c133dc..3fbfd80f3 100644 --- a/identity-server/src/IdentityServer/Validation/Contexts/IntrospectionRequestValidationContext.cs +++ b/identity-server/src/IdentityServer/Validation/Contexts/IntrospectionRequestValidationContext.cs @@ -29,4 +29,5 @@ public class IntrospectionRequestValidationContext /// The Client that is making the request /// public Client? Client { get; set; } + } diff --git a/identity-server/src/IdentityServer/Validation/Default/ApiSecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/ApiSecretValidator.cs index 459fd3b8f..14ac2c949 100644 --- a/identity-server/src/IdentityServer/Validation/Default/ApiSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/ApiSecretValidator.cs @@ -42,8 +42,10 @@ public class ApiSecretValidator : IApiSecretValidator /// Validates the secret on the current request. /// /// The context. + /// The cancellation token. /// - public async Task ValidateAsync(HttpContext context) + /// + public async Task ValidateAsync(HttpContext context, Ct ct) { using var activity = Tracing.ValidationActivitySource.StartActivity("ApiSecretValidator.Validate"); @@ -54,20 +56,20 @@ public class ApiSecretValidator : IApiSecretValidator IsError = true }; - var parsedSecret = await _parser.ParseAsync(context); + var parsedSecret = await _parser.ParseAsync(context, ct); if (parsedSecret == null) { - await RaiseFailureEventAsync("unknown", "No API id or secret found"); + await RaiseFailureEventAsync("unknown", "No API id or secret found", ct); _logger.LogError("No API secret found"); return fail; } // load API resource - var apis = await _resources.FindApiResourcesByNameAsync(new[] { parsedSecret.Id }); + var apis = await _resources.FindApiResourcesByNameAsync(new[] { parsedSecret.Id }, ct); if (apis == null || !apis.Any()) { - await RaiseFailureEventAsync(parsedSecret.Id, "Unknown API resource"); + await RaiseFailureEventAsync(parsedSecret.Id, "Unknown API resource", ct); _logger.LogError("No API resource with that name found. aborting"); return fail; @@ -75,7 +77,7 @@ public class ApiSecretValidator : IApiSecretValidator if (apis.Count() > 1) { - await RaiseFailureEventAsync(parsedSecret.Id, "Invalid API resource"); + await RaiseFailureEventAsync(parsedSecret.Id, "Invalid API resource", ct); _logger.LogError("More than one API resource with that name found. aborting"); return fail; @@ -85,13 +87,13 @@ public class ApiSecretValidator : IApiSecretValidator if (api.Enabled == false) { - await RaiseFailureEventAsync(parsedSecret.Id, "API resource not enabled"); + await RaiseFailureEventAsync(parsedSecret.Id, "API resource not enabled", ct); _logger.LogError("API resource not enabled. aborting."); return fail; } - var result = await _validator.ValidateAsync(api.ApiSecrets, parsedSecret); + var result = await _validator.ValidateAsync(api.ApiSecrets, parsedSecret, ct); if (result.Success) { _logger.LogDebug("API resource validation success"); @@ -102,25 +104,25 @@ public class ApiSecretValidator : IApiSecretValidator Resource = api }; - await RaiseSuccessEventAsync(api.Name, parsedSecret.Type); + await RaiseSuccessEventAsync(api.Name, parsedSecret.Type, ct); return success; } - await RaiseFailureEventAsync(api.Name, "Invalid API secret"); + await RaiseFailureEventAsync(api.Name, "Invalid API secret", ct); _logger.LogError("API validation failed."); return fail; } - private Task RaiseSuccessEventAsync(string clientId, string authMethod) + private Task RaiseSuccessEventAsync(string clientId, string authMethod, Ct ct) { Telemetry.Metrics.ApiSecretValidation(clientId, authMethod); - return _events.RaiseAsync(new ApiAuthenticationSuccessEvent(clientId, authMethod)); + return _events.RaiseAsync(new ApiAuthenticationSuccessEvent(clientId, authMethod), ct); } - private Task RaiseFailureEventAsync(string clientId, string message) + private Task RaiseFailureEventAsync(string clientId, string message, Ct ct) { Telemetry.Metrics.ApiSecretValidationFailure(clientId, message); - return _events.RaiseAsync(new ApiAuthenticationFailureEvent(clientId, message)); + return _events.RaiseAsync(new ApiAuthenticationFailureEvent(clientId, message), ct); } } diff --git a/identity-server/src/IdentityServer/Validation/Default/AuthorizeRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/AuthorizeRequestValidator.cs index feec8794e..1dff3cd32 100644 --- a/identity-server/src/IdentityServer/Validation/Default/AuthorizeRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/AuthorizeRequestValidator.cs @@ -1,6 +1,7 @@ // Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. +#nullable enable using System.Collections.Specialized; using System.Security.Claims; @@ -67,7 +68,8 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator public async Task ValidateAsync( NameValueCollection parameters, - ClaimsPrincipal subject = null, + Ct ct, + ClaimsPrincipal? subject = null, AuthorizeRequestType authorizeRequestType = AuthorizeRequestType.Authorize) { using var activity = Tracing.BasicActivitySource.StartActivity("AuthorizeRequestValidator.Validate"); @@ -77,7 +79,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator var request = new ValidatedAuthorizeRequest { Options = _options, - IssuerName = await _issuerNameService.GetCurrentAsync(), + IssuerName = await _issuerNameService.GetCurrentAsync(ct), Subject = subject ?? Principal.Anonymous, Raw = parameters ?? throw new ArgumentNullException(nameof(parameters)), AuthorizeRequestType = authorizeRequestType @@ -92,21 +94,21 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator // load client_id // client_id must always be present on the request - var loadClientResult = await LoadClientAsync(request); + var loadClientResult = await LoadClientAsync(request, ct); if (loadClientResult.IsError) { return loadClientResult; } // load request object - var roLoadResult = await _requestObjectValidator.LoadRequestObjectAsync(request); + var roLoadResult = await _requestObjectValidator.LoadRequestObjectAsync(request, ct); if (roLoadResult.IsError) { return roLoadResult; } // validate request object - var roValidationResult = await _requestObjectValidator.ValidateRequestObjectAsync(request); + var roValidationResult = await _requestObjectValidator.ValidateRequestObjectAsync(request, ct); if (roValidationResult.IsError) { return roValidationResult; @@ -120,7 +122,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator } // validate client_id and redirect_uri - var clientResult = await ValidateClientAsync(request); + var clientResult = await ValidateClientAsync(request, ct); if (clientResult.IsError) { return clientResult; @@ -134,14 +136,14 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator } // scope, scope restrictions and plausibility, and resource indicators - var scopeResult = await ValidateScopeAndResourceAsync(request); + var scopeResult = await ValidateScopeAndResourceAsync(request, ct); if (scopeResult.IsError) { return scopeResult; } // nonce, prompt, acr_values, login_hint etc. - var optionalResult = await ValidateOptionalParametersAsync(request); + var optionalResult = await ValidateOptionalParametersAsync(request, ct); if (optionalResult.IsError) { return optionalResult; @@ -153,13 +155,13 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator { Result = new AuthorizeRequestValidationResult(request) }; - await _customValidator.ValidateAsync(context); + await _customValidator.ValidateAsync(context, ct); var customResult = context.Result; if (customResult.IsError) { LogError("Error in custom validation", customResult.Error, request); - return Invalid(request, customResult.Error, customResult.ErrorDescription); + return Invalid(request, customResult.Error ?? OidcConstants.AuthorizeErrors.InvalidRequest, customResult.ErrorDescription); } _sanitizedLogger.LogTrace("Authorize request protocol validation successful"); @@ -194,7 +196,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator return Valid(request); } - private async Task LoadClientAsync(ValidatedAuthorizeRequest request) + private async Task LoadClientAsync(ValidatedAuthorizeRequest request, Ct ct) { ////////////////////////////////////////////////////////// // client_id must be present @@ -207,12 +209,12 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator return Invalid(request, description: "Invalid client_id"); } - request.ClientId = clientId; + request.ClientId = clientId!; ////////////////////////////////////////////////////////// // check for valid client ////////////////////////////////////////////////////////// - var client = await _clients.FindEnabledClientByIdAsync(request.ClientId); + var client = await _clients.FindEnabledClientByIdAsync(request.ClientId, ct); if (client == null) { LogError("Unknown client or not enabled", request.ClientId, request); @@ -224,7 +226,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator return Valid(request); } - private async Task ValidateClientAsync(ValidatedAuthorizeRequest request) + private async Task ValidateClientAsync(ValidatedAuthorizeRequest request, Ct ct) { ////////////////////////////////////////////////////////// // check request object requirement @@ -248,7 +250,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator return Invalid(request, description: "Invalid redirect_uri"); } - if (!redirectUri.IsUri()) + if (!redirectUri!.IsUri()) { LogError("malformed redirect_uri", redirectUri, request); return Invalid(request, description: "Invalid redirect_uri"); @@ -266,14 +268,14 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator ////////////////////////////////////////////////////////// // check if redirect_uri is valid ////////////////////////////////////////////////////////// - var uriContext = new RedirectUriValidationContext(redirectUri, request); - if (await _uriValidator.IsRedirectUriValidAsync(uriContext) == false) + var uriContext = new RedirectUriValidationContext(redirectUri!, request); + if (await _uriValidator.IsRedirectUriValidAsync(uriContext, ct) == false) { LogError("Invalid redirect_uri", redirectUri, request); return Invalid(request, OidcConstants.AuthorizeErrors.InvalidRequest, "Invalid redirect_uri"); } - request.RedirectUri = redirectUri; + request.RedirectUri = redirectUri!; return Valid(request); } @@ -473,7 +475,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator return Valid(request); } - private async Task ValidateScopeAndResourceAsync(ValidatedAuthorizeRequest request) + private async Task ValidateScopeAndResourceAsync(ValidatedAuthorizeRequest request, Ct ct) { ////////////////////////////////////////////////////////// // scope must be present @@ -547,7 +549,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator Client = request.Client, Scopes = request.RequestedScopes, ResourceIndicators = resourceIndicators, - }); + }, ct); if (!validatedResources.Succeeded) { @@ -562,7 +564,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator } } - _licenseUsage.ResourceIndicatorsUsed(resourceIndicators); + _licenseUsage.ResourceIndicatorsUsed(resourceIndicators!); IdentityServerLicenseValidator.Instance.ValidateResourceIndicators(resourceIndicators); if (validatedResources.Resources.IdentityResources.Count > 0 && !request.IsOpenIdRequest) @@ -615,7 +617,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator return Valid(request); } - private async Task ValidateOptionalParametersAsync(ValidatedAuthorizeRequest request) + private async Task ValidateOptionalParametersAsync(ValidatedAuthorizeRequest request, Ct ct) { ////////////////////////////////////////////////////////// // check nonce @@ -796,7 +798,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator ////////////////////////////////////////////////////////// if (request.Subject.IsAuthenticated()) { - var sessionId = await _userSession.GetSessionIdAsync(); + var sessionId = await _userSession.GetSessionIdAsync(ct); if (sessionId.IsPresent()) { request.SessionId = sessionId; @@ -840,7 +842,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator return true; } - private static AuthorizeRequestValidationResult Invalid(ValidatedAuthorizeRequest request, string error = OidcConstants.AuthorizeErrors.InvalidRequest, string description = null) => new AuthorizeRequestValidationResult(request, error, description); + private static AuthorizeRequestValidationResult Invalid(ValidatedAuthorizeRequest request, string error = OidcConstants.AuthorizeErrors.InvalidRequest, string? description = null) => new AuthorizeRequestValidationResult(request, error, description); private static AuthorizeRequestValidationResult Valid(ValidatedAuthorizeRequest request) => new AuthorizeRequestValidationResult(request); @@ -850,7 +852,7 @@ internal class AuthorizeRequestValidator : IAuthorizeRequestValidator _sanitizedLogger.LogError(message + "\n{@requestDetails}", requestDetails); } - private void LogError(string message, string detail, ValidatedAuthorizeRequest request) + private void LogError(string message, string? detail, ValidatedAuthorizeRequest request) { var requestDetails = new AuthorizeRequestValidationLog(request, _options.Logging.AuthorizeRequestSensitiveValuesFilter); _sanitizedLogger.LogError(message + ": {detail}\n{@requestDetails}", detail, requestDetails); diff --git a/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestIdValidator.cs b/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestIdValidator.cs index f4746ac8d..620a39616 100644 --- a/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestIdValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestIdValidator.cs @@ -37,11 +37,11 @@ internal class BackchannelAuthenticationRequestIdValidator : IBackchannelAuthent } /// - public async Task ValidateAsync(BackchannelAuthenticationRequestIdValidationContext context) + public async Task ValidateAsync(BackchannelAuthenticationRequestIdValidationContext context, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("BackchannelAuthenticationRequestIdValidator.Validate"); - var request = await _backchannelAuthenticationStore.GetByAuthenticationRequestIdAsync(context.AuthenticationRequestId); + var request = await _backchannelAuthenticationStore.GetByAuthenticationRequestIdAsync(context.AuthenticationRequestId, ct); if (request == null) { @@ -58,7 +58,7 @@ internal class BackchannelAuthenticationRequestIdValidator : IBackchannelAuthent return; } - if (await _throttlingService.ShouldSlowDown(context.AuthenticationRequestId, request)) + if (await _throttlingService.ShouldSlowDown(context.AuthenticationRequestId, request, ct)) { _logger.LogError("Client {ClientId} is polling too fast", request.ClientId); context.Result = new TokenRequestValidationResult(context.Request, OidcConstants.TokenErrors.SlowDown); @@ -79,7 +79,7 @@ internal class BackchannelAuthenticationRequestIdValidator : IBackchannelAuthent { _logger.LogError("No scopes authorized for backchannel authentication request. Access denied"); context.Result = new TokenRequestValidationResult(context.Request, OidcConstants.TokenErrors.AccessDenied); - await _backchannelAuthenticationStore.RemoveByInternalIdAsync(request.InternalId); + await _backchannelAuthenticationStore.RemoveByInternalIdAsync(request.InternalId, ct); return; } @@ -92,7 +92,7 @@ internal class BackchannelAuthenticationRequestIdValidator : IBackchannelAuthent // make sure user is enabled var isActiveCtx = new IsActiveContext(request.Subject, context.Request.Client, IdentityServerConstants.ProfileIsActiveCallers.BackchannelAuthenticationRequestIdValidation); - await _profile.IsActiveAsync(isActiveCtx); + await _profile.IsActiveAsync(isActiveCtx, ct); if (isActiveCtx.IsActive == false) { @@ -107,7 +107,7 @@ internal class BackchannelAuthenticationRequestIdValidator : IBackchannelAuthent context.Result = new TokenRequestValidationResult(context.Request); - await _backchannelAuthenticationStore.RemoveByInternalIdAsync(request.InternalId); + await _backchannelAuthenticationStore.RemoveByInternalIdAsync(request.InternalId, ct); _logger.LogDebug("Success validating backchannel authentication request id."); } diff --git a/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestValidator.cs index 0ba14ee04..9e9620293 100644 --- a/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/BackchannelAuthenticationRequestValidator.cs @@ -47,7 +47,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic _licenseUsage = licenseUsage; } - public async Task ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult) + public async Task ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("BackchannelAuthenticationRequestValidator.ValidateRequest"); @@ -94,7 +94,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic ////////////////////////////////////////////////////////// // validate request object ////////////////////////////////////////////////////////// - var roValidationResult = await TryValidateRequestObjectAsync(); + var roValidationResult = await TryValidateRequestObjectAsync(ct); if (!roValidationResult.Success) { return roValidationResult.ErrorResult; @@ -165,7 +165,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic Client = _validatedRequest.Client, Scopes = _validatedRequest.RequestedScopes, ResourceIndicators = resourceIndicators, - }); + }, ct); if (!validatedResources.Succeeded) { @@ -338,7 +338,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic return Invalid(OidcConstants.BackchannelAuthenticationRequestErrors.InvalidRequest, "Invalid id_token_hint"); } - var idTokenHintValidationResult = await _tokenValidator.ValidateIdentityTokenAsync(idTokenHint, _validatedRequest.ClientId, false); + var idTokenHintValidationResult = await _tokenValidator.ValidateIdentityTokenAsync(idTokenHint, _validatedRequest.ClientId, false, ct); if (idTokenHintValidationResult.IsError) { LogError("id token hint failed to validate: " + idTokenHintValidationResult.Error, idTokenHintValidationResult.ErrorDescription); @@ -391,7 +391,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic IdTokenHintClaims = _validatedRequest.IdTokenHintClaims, UserCode = _validatedRequest.UserCode, BindingMessage = _validatedRequest.BindingMessage - }); + }, ct); if (userResult.IsError) { @@ -440,7 +440,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic var result = new BackchannelAuthenticationRequestValidationResult(_validatedRequest); var customValidationContext = new CustomBackchannelAuthenticationRequestValidationContext(result); - await _customValidator.ValidateAsync(customValidationContext); + await _customValidator.ValidateAsync(customValidationContext, ct); if (customValidationContext.ValidationResult.IsError) { LogError("Custom validation of backchannel authorize request failed"); @@ -451,7 +451,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic return result; } - private async Task<(bool Success, BackchannelAuthenticationRequestValidationResult ErrorResult)> TryValidateRequestObjectAsync() + private async Task<(bool Success, BackchannelAuthenticationRequestValidationResult ErrorResult)> TryValidateRequestObjectAsync(Ct ct) { ////////////////////////////////////////////////////////// // validate request object @@ -465,7 +465,7 @@ internal class BackchannelAuthenticationRequestValidator : IBackchannelAuthentic JwtTokenString = _validatedRequest.RequestObject, StrictJarValidation = false, IncludeJti = true - }); + }, ct); if (jwtRequestValidationResult.IsError) { LogError("request JWT validation failure", jwtRequestValidationResult.Error); diff --git a/identity-server/src/IdentityServer/Validation/Default/BasicAuthenticationSecretParser.cs b/identity-server/src/IdentityServer/Validation/Default/BasicAuthenticationSecretParser.cs index f94013834..aa2166c10 100644 --- a/identity-server/src/IdentityServer/Validation/Default/BasicAuthenticationSecretParser.cs +++ b/identity-server/src/IdentityServer/Validation/Default/BasicAuthenticationSecretParser.cs @@ -45,7 +45,8 @@ public class BasicAuthenticationSecretParser : ISecretParser /// /// A parsed secret /// - public Task ParseAsync(HttpContext context) + /// + public Task ParseAsync(HttpContext context, Ct ct) { _logger.LogDebug("Start parsing Basic Authentication secret"); diff --git a/identity-server/src/IdentityServer/Validation/Default/BearerTokenUsageValidator.cs b/identity-server/src/IdentityServer/Validation/Default/BearerTokenUsageValidator.cs index 37919f8ad..157a42a7b 100644 --- a/identity-server/src/IdentityServer/Validation/Default/BearerTokenUsageValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/BearerTokenUsageValidator.cs @@ -38,7 +38,7 @@ internal class BearerTokenUsageValidator if (context.Request.HasApplicationFormContentType()) { - result = await ValidatePostBodyAsync(context); + result = await ValidatePostBodyAsync(context, context.RequestAborted); if (result.TokenFound) { _logger.LogDebug("Bearer token found in body"); @@ -87,10 +87,11 @@ internal class BearerTokenUsageValidator /// Validates the post body. /// /// The context. + /// The cancellation token. /// - public static async Task ValidatePostBodyAsync(HttpContext context) + public static async Task ValidatePostBodyAsync(HttpContext context, Ct ct) { - var token = (await context.Request.ReadFormAsync())["access_token"].FirstOrDefault(); + var token = (await context.Request.ReadFormAsync(ct))["access_token"].FirstOrDefault(); if (token.IsPresent()) { return new BearerTokenUsageValidationResult diff --git a/identity-server/src/IdentityServer/Validation/Default/ClientSecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/ClientSecretValidator.cs index 342140917..79ef0105f 100644 --- a/identity-server/src/IdentityServer/Validation/Default/ClientSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/ClientSecretValidator.cs @@ -39,12 +39,8 @@ public class ClientSecretValidator : IClientSecretValidator _logger = logger; } - /// - /// Validates the current request. - /// - /// The context. - /// - public async Task ValidateAsync(HttpContext context) + /// + public async Task ValidateAsync(HttpContext context, Ct ct) { using var activity = Tracing.ValidationActivitySource.StartActivity("ClientSecretValidator.Validate"); @@ -56,10 +52,10 @@ public class ClientSecretValidator : IClientSecretValidator Error = IdentityModel.OidcConstants.TokenErrors.InvalidClient }; - var parsedSecret = await _parser.ParseAsync(context); + var parsedSecret = await _parser.ParseAsync(context, ct); if (parsedSecret == null) { - await RaiseFailureEventAsync("unknown", "No client id found"); + await RaiseFailureEventAsync("unknown", "No client id found", ct); _logger.LogError("No client identifier found"); @@ -68,10 +64,10 @@ public class ClientSecretValidator : IClientSecretValidator } // load client - var client = await _clients.FindEnabledClientByIdAsync(parsedSecret.Id); + var client = await _clients.FindEnabledClientByIdAsync(parsedSecret.Id, ct); if (client == null) { - await RaiseFailureEventAsync(parsedSecret.Id, "Unknown client"); + await RaiseFailureEventAsync(parsedSecret.Id, "Unknown client", ct); _logger.LogError("No client with id '{clientId}' found. aborting", parsedSecret.Id); return fail; @@ -84,10 +80,10 @@ public class ClientSecretValidator : IClientSecretValidator } else { - secretValidationResult = await _validator.ValidateAsync(client.ClientSecrets, parsedSecret); + secretValidationResult = await _validator.ValidateAsync(client.ClientSecrets, parsedSecret, ct); if (secretValidationResult.Success == false) { - await RaiseFailureEventAsync(client.ClientId, "Invalid client secret"); + await RaiseFailureEventAsync(client.ClientId, "Invalid client secret", ct); _logger.LogError("Client secret validation failed for client: {clientId}.", client.ClientId); return fail; @@ -104,19 +100,19 @@ public class ClientSecretValidator : IClientSecretValidator Confirmation = secretValidationResult?.Confirmation }; - await RaiseSuccessEventAsync(client.ClientId, parsedSecret.Type); + await RaiseSuccessEventAsync(client.ClientId, parsedSecret.Type, ct); return success; } - private Task RaiseSuccessEventAsync(string clientId, string authMethod) + private Task RaiseSuccessEventAsync(string clientId, string authMethod, Ct ct) { Telemetry.Metrics.ClientSecretValidation(clientId, authMethod); - return _events.RaiseAsync(new ClientAuthenticationSuccessEvent(clientId, authMethod)); + return _events.RaiseAsync(new ClientAuthenticationSuccessEvent(clientId, authMethod), ct); } - private Task RaiseFailureEventAsync(string clientId, string message) + private Task RaiseFailureEventAsync(string clientId, string message, Ct ct) { Telemetry.Metrics.ClientSecretValidationFailure(clientId, message); - return _events.RaiseAsync(new ClientAuthenticationFailureEvent(clientId, message)); + return _events.RaiseAsync(new ClientAuthenticationFailureEvent(clientId, message), ct); } } diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultClientConfigurationValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultClientConfigurationValidator.cs index 8a2a0e215..339ea7d70 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultClientConfigurationValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultClientConfigurationValidator.cs @@ -25,8 +25,9 @@ public class DefaultClientConfigurationValidator : IClientConfigurationValidator /// Determines whether the configuration of a client is valid. /// /// The context. + /// The cancellation token. /// - public async Task ValidateAsync(ClientConfigurationValidationContext context) + public async Task ValidateAsync(ClientConfigurationValidationContext context, Ct ct) { using var activity = Tracing.ValidationActivitySource.StartActivity("DefaultClientConfigurationValidator.Validate"); diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomAuthorizeRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomAuthorizeRequestValidator.cs index 74a3e5f1f..936eef2f0 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomAuthorizeRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomAuthorizeRequestValidator.cs @@ -9,9 +9,6 @@ namespace Duende.IdentityServer.Validation; /// internal class DefaultCustomAuthorizeRequestValidator : ICustomAuthorizeRequestValidator { - /// - /// Custom validation logic for the authorize request. - /// - /// The context. - public Task ValidateAsync(CustomAuthorizeRequestValidationContext context) => Task.CompletedTask; + /// + public Task ValidateAsync(CustomAuthorizeRequestValidationContext context, Ct _) => Task.CompletedTask; } diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomBackchannelAuthenticationValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomBackchannelAuthenticationValidator.cs index b597659ee..cb62e0153 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomBackchannelAuthenticationValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomBackchannelAuthenticationValidator.cs @@ -11,5 +11,6 @@ namespace Duende.IdentityServer.Validation; public class DefaultCustomBackchannelAuthenticationValidator : ICustomBackchannelAuthenticationValidator { /// - public Task ValidateAsync(CustomBackchannelAuthenticationRequestValidationContext customValidationContext) => Task.CompletedTask; + /// + public Task ValidateAsync(CustomBackchannelAuthenticationRequestValidationContext customValidationContext, Ct _) => Task.CompletedTask; } diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenRequestValidator.cs index 46ce763d1..7fea9ac00 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenRequestValidator.cs @@ -9,12 +9,6 @@ namespace Duende.IdentityServer.Validation; /// internal class DefaultCustomTokenRequestValidator : ICustomTokenRequestValidator { - /// - /// Custom validation logic for a token request. - /// - /// The context. - /// - /// The validation result - /// - public Task ValidateAsync(CustomTokenRequestValidationContext context) => Task.CompletedTask; + /// + public Task ValidateAsync(CustomTokenRequestValidationContext context, Ct _) => Task.CompletedTask; } diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenValidator.cs index b62a3855f..8b38e7843 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultCustomTokenValidator.cs @@ -28,21 +28,9 @@ public class DefaultCustomTokenValidator : ICustomTokenValidator /// protected readonly IClientStore Clients; - /// - /// Custom validation logic for access tokens. - /// - /// The validation result so far. - /// - /// The validation result - /// - public virtual Task ValidateAccessTokenAsync(TokenValidationResult result) => Task.FromResult(result); + /// + public virtual Task ValidateAccessTokenAsync(TokenValidationResult result, Ct _) => Task.FromResult(result); - /// - /// Custom validation logic for identity tokens. - /// - /// The validation result so far. - /// - /// The validation result - /// - public virtual Task ValidateIdentityTokenAsync(TokenValidationResult result) => Task.FromResult(result); + /// + public virtual Task ValidateIdentityTokenAsync(TokenValidationResult result, Ct _) => Task.FromResult(result); } diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultDPoPProofValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultDPoPProofValidator.cs index 77cde6c4c..c5eac04d0 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultDPoPProofValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultDPoPProofValidator.cs @@ -69,7 +69,7 @@ public class DefaultDPoPProofValidator : IDPoPProofValidator } /// - public async Task ValidateAsync(DPoPProofValidatonContext context) + public async Task ValidateAsync(DPoPProofValidatonContext context, Ct ct) { var result = new DPoPProofValidatonResult() { IsError = false }; @@ -96,7 +96,7 @@ public class DefaultDPoPProofValidator : IDPoPProofValidator return result; } - await ValidatePayloadAsync(context, result); + await ValidatePayloadAsync(context, result, ct); if (result.IsError) { Logger.LogDebug("Failed to validate DPoP payload"); @@ -284,7 +284,7 @@ public class DefaultDPoPProofValidator : IDPoPProofValidator /// /// Validates the payload. /// - protected virtual async Task ValidatePayloadAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result) + protected virtual async Task ValidatePayloadAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result, Ct ct) { if (context.ValidateAccessToken) { @@ -370,7 +370,7 @@ public class DefaultDPoPProofValidator : IDPoPProofValidator } // we do replay at the end so we only add to the reply cache if everything else is ok - await ValidateReplayAsync(context, result); + await ValidateReplayAsync(context, result, ct); if (result.IsError) { result.ErrorDescription = "Detected replay of DPoP proof token."; @@ -381,9 +381,9 @@ public class DefaultDPoPProofValidator : IDPoPProofValidator /// /// Validates is the token has been replayed. /// - protected virtual async Task ValidateReplayAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result) + protected virtual async Task ValidateReplayAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result, Ct ct) { - if (await ReplayCache.ExistsAsync(ReplayCachePurpose, result.TokenId)) + if (await ReplayCache.ExistsAsync(ReplayCachePurpose, result.TokenId, ct)) { Logger.LogDebug("Detected DPoP proof token replay for jti {jti}", result.TokenId); result.IsError = true; @@ -410,7 +410,7 @@ public class DefaultDPoPProofValidator : IDPoPProofValidator Logger.LogDebug("Adding proof token with jti {jti} to replay cache for duration {cacheDuration}", result.TokenId, cacheDuration); - await ReplayCache.AddAsync(ReplayCachePurpose, result.TokenId, TimeProvider.GetUtcNow().Add(cacheDuration)); + await ReplayCache.AddAsync(ReplayCachePurpose, result.TokenId, TimeProvider.GetUtcNow().Add(cacheDuration), ct); } /// diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultIdentityProviderConfigurationValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultIdentityProviderConfigurationValidator.cs index 348b6a6f7..87c8e658f 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultIdentityProviderConfigurationValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultIdentityProviderConfigurationValidator.cs @@ -21,7 +21,7 @@ public class DefaultIdentityProviderConfigurationValidator : IIdentityProviderCo public DefaultIdentityProviderConfigurationValidator(IdentityServerOptions options) => _options = options; /// - public virtual async Task ValidateAsync(IdentityProviderConfigurationValidationContext context) + public virtual async Task ValidateAsync(IdentityProviderConfigurationValidationContext context, Ct ct) { using var activity = Tracing.ValidationActivitySource.StartActivity("DefaultIdentityProviderConfigurationValidator.Validate"); diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultIssuerPathValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultIssuerPathValidator.cs index f386ec511..03afbea36 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultIssuerPathValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultIssuerPathValidator.cs @@ -9,7 +9,7 @@ namespace Duende.IdentityServer.Validation; public class DefaultIssuerPathValidator(IIssuerNameService issuerNameService, ILogger logger) : IIssuerPathValidator { - public async Task ValidateAsync(string path) + public async Task ValidateAsync(string path, Ct ct) { //if there is no path, this is fine since the default issuer is probably being used if (path.IsMissing()) @@ -18,7 +18,7 @@ public class DefaultIssuerPathValidator(IIssuerNameService issuerNameService, IL } //if there is a path, then we should be matching against an explicitly configured issuer - var currentIssuer = await issuerNameService.GetCurrentAsync(); + var currentIssuer = await issuerNameService.GetCurrentAsync(ct); if (!Uri.TryCreate(currentIssuer, UriKind.Absolute, out var uri)) { logger.LogDebug("Current issuer is not a valid absolute URI: {Issuer}", currentIssuer.SanitizeLogParameter()); diff --git a/identity-server/src/IdentityServer/Validation/Default/DefaultResourceValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DefaultResourceValidator.cs index ccd146123..87edd408a 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DefaultResourceValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DefaultResourceValidator.cs @@ -32,7 +32,7 @@ public class DefaultResourceValidator : IResourceValidator } /// - public virtual async Task ValidateRequestedResourcesAsync(ResourceValidationRequest request) + public virtual async Task ValidateRequestedResourcesAsync(ResourceValidationRequest request, Ct ct) { ArgumentNullException.ThrowIfNull(request); using var activity = Tracing.ValidationActivitySource.StartActivity("DefaultResourceValidator.ValidateRequestedResources"); @@ -55,7 +55,7 @@ public class DefaultResourceValidator : IResourceValidator var scopeNames = parsedScopesResult.ParsedScopes.Select(x => x.ParsedName).Distinct().ToArray(); // todo: this API might want to pass resource indicators to better filter - var scopeResourcesFromStore = await _store.FindEnabledResourcesByScopeAsync(scopeNames); + var scopeResourcesFromStore = await _store.FindEnabledResourcesByScopeAsync(scopeNames, ct); if (request.ResourceIndicators?.Any() == true) { diff --git a/identity-server/src/IdentityServer/Validation/Default/DeviceAuthorizationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DeviceAuthorizationRequestValidator.cs index 0fa05e93e..f3a470d7b 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DeviceAuthorizationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DeviceAuthorizationRequestValidator.cs @@ -28,7 +28,7 @@ internal class DeviceAuthorizationRequestValidator : IDeviceAuthorizationRequest _logger = logger; } - public async Task ValidateAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult) + public async Task ValidateAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("DeviceAuthorizationRequestValidator.Validate"); @@ -46,7 +46,7 @@ internal class DeviceAuthorizationRequestValidator : IDeviceAuthorizationRequest return clientResult; } - var scopeResult = await ValidateScopeAsync(request); + var scopeResult = await ValidateScopeAsync(request, ct); if (scopeResult.IsError) { return scopeResult; @@ -101,7 +101,7 @@ internal class DeviceAuthorizationRequestValidator : IDeviceAuthorizationRequest return Valid(request); } - private async Task ValidateScopeAsync(ValidatedDeviceAuthorizationRequest request) + private async Task ValidateScopeAsync(ValidatedDeviceAuthorizationRequest request, Ct ct) { ////////////////////////////////////////////////////////// // scope must be present @@ -148,7 +148,7 @@ internal class DeviceAuthorizationRequestValidator : IDeviceAuthorizationRequest { Client = request.Client, Scopes = request.RequestedScopes - }); + }, ct); if (!validatedResources.Succeeded) { diff --git a/identity-server/src/IdentityServer/Validation/Default/DeviceCodeValidator.cs b/identity-server/src/IdentityServer/Validation/Default/DeviceCodeValidator.cs index de01c124d..b435b4af5 100644 --- a/identity-server/src/IdentityServer/Validation/Default/DeviceCodeValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/DeviceCodeValidator.cs @@ -47,12 +47,13 @@ internal class DeviceCodeValidator : IDeviceCodeValidator /// Validates the device code. /// /// The context. + /// The cancellation token. /// - public async Task ValidateAsync(DeviceCodeValidationContext context) + public async Task ValidateAsync(DeviceCodeValidationContext context, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("DeviceCodeValidator.Validate"); - var deviceCode = await _devices.FindByDeviceCodeAsync(context.DeviceCode); + var deviceCode = await _devices.FindByDeviceCodeAsync(context.DeviceCode, ct); if (deviceCode == null) { @@ -69,7 +70,7 @@ internal class DeviceCodeValidator : IDeviceCodeValidator return; } - if (await _throttlingService.ShouldSlowDown(context.DeviceCode, deviceCode)) + if (await _throttlingService.ShouldSlowDown(context.DeviceCode, deviceCode, ct)) { _logger.LogError("Client {ClientId} is polling too fast", deviceCode.ClientId); context.Result = new TokenRequestValidationResult(context.Request, OidcConstants.TokenErrors.SlowDown); @@ -102,7 +103,7 @@ internal class DeviceCodeValidator : IDeviceCodeValidator // make sure user is enabled var isActiveCtx = new IsActiveContext(deviceCode.Subject, context.Request.Client, IdentityServerConstants.ProfileIsActiveCallers.DeviceCodeValidation); - await _profile.IsActiveAsync(isActiveCtx); + await _profile.IsActiveAsync(isActiveCtx, ct); if (isActiveCtx.IsActive == false) { @@ -115,6 +116,6 @@ internal class DeviceCodeValidator : IDeviceCodeValidator context.Request.SessionId = deviceCode.SessionId; context.Result = new TokenRequestValidationResult(context.Request); - await _devices.RemoveByDeviceCodeAsync(context.DeviceCode); + await _devices.RemoveByDeviceCodeAsync(context.DeviceCode, ct); } } diff --git a/identity-server/src/IdentityServer/Validation/Default/EndSessionRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/EndSessionRequestValidator.cs index 335819379..6b8e10e06 100644 --- a/identity-server/src/IdentityServer/Validation/Default/EndSessionRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/EndSessionRequestValidator.cs @@ -84,7 +84,7 @@ public class EndSessionRequestValidator : IEndSessionRequestValidator } /// - public async Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject) + public async Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("EndSessionRequestValidator.Validate"); @@ -120,7 +120,7 @@ public class EndSessionRequestValidator : IEndSessionRequestValidator if (idTokenHint.IsPresent()) { // validate id_token - no need to validate token life time - var tokenValidationResult = await TokenValidator.ValidateIdentityTokenAsync(idTokenHint, null, false); + var tokenValidationResult = await TokenValidator.ValidateIdentityTokenAsync(idTokenHint, null, false, ct); if (tokenValidationResult.IsError) { return Invalid("Error validating id token hint", validatedRequest); @@ -138,14 +138,14 @@ public class EndSessionRequestValidator : IEndSessionRequestValidator } validatedRequest.Subject = subject; - validatedRequest.SessionId = await UserSession.GetSessionIdAsync(); - validatedRequest.ClientIds = await UserSession.GetClientListAsync(); + validatedRequest.SessionId = await UserSession.GetSessionIdAsync(ct); + validatedRequest.ClientIds = await UserSession.GetClientListAsync(ct); } var redirectUri = parameters.Get(OidcConstants.EndSessionRequest.PostLogoutRedirectUri); if (redirectUri.IsPresent()) { - if (await UriValidator.IsPostLogoutRedirectUriValidAsync(redirectUri, validatedRequest.Client)) + if (await UriValidator.IsPostLogoutRedirectUriValidAsync(redirectUri, validatedRequest.Client, ct)) { validatedRequest.PostLogOutUri = redirectUri; } @@ -168,8 +168,8 @@ public class EndSessionRequestValidator : IEndSessionRequestValidator { // no id_token to authenticate the client, but we do have a user and a user session validatedRequest.Subject = subject; - validatedRequest.SessionId = await UserSession.GetSessionIdAsync(); - validatedRequest.ClientIds = await UserSession.GetClientListAsync(); + validatedRequest.SessionId = await UserSession.GetSessionIdAsync(ct); + validatedRequest.ClientIds = await UserSession.GetClientListAsync(ct); } LogSuccess(validatedRequest); @@ -222,7 +222,7 @@ public class EndSessionRequestValidator : IEndSessionRequestValidator } /// - public async Task ValidateCallbackAsync(NameValueCollection parameters) + public async Task ValidateCallbackAsync(NameValueCollection parameters, Ct ct) { var result = new EndSessionCallbackValidationResult { @@ -230,11 +230,11 @@ public class EndSessionRequestValidator : IEndSessionRequestValidator }; var endSessionId = parameters[Constants.UIConstants.DefaultRoutePathParams.EndSessionCallback]; - var endSessionMessage = await EndSessionMessageStore.ReadAsync(endSessionId); + var endSessionMessage = await EndSessionMessageStore.ReadAsync(endSessionId, ct); if (endSessionMessage?.Data?.ClientIds?.Any() == true) { result.IsError = false; - result.FrontChannelLogoutUrls = await LogoutNotificationService.GetFrontChannelLogoutNotificationsUrlsAsync(endSessionMessage.Data); + result.FrontChannelLogoutUrls = await LogoutNotificationService.GetFrontChannelLogoutNotificationsUrlsAsync(endSessionMessage.Data, ct); } else { diff --git a/identity-server/src/IdentityServer/Validation/Default/ExtensionGrantValidator.cs b/identity-server/src/IdentityServer/Validation/Default/ExtensionGrantValidator.cs index 25e1bfa05..7c59b39c4 100644 --- a/identity-server/src/IdentityServer/Validation/Default/ExtensionGrantValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/ExtensionGrantValidator.cs @@ -44,8 +44,9 @@ public class ExtensionGrantValidator /// Validates the request. /// /// The request. + /// The cancellation token. /// - public async Task ValidateAsync(ValidatedTokenRequest request) + public async Task ValidateAsync(ValidatedTokenRequest request, Ct ct) { var validator = _validators.FirstOrDefault(v => v.GrantType.Equals(request.GrantType, StringComparison.Ordinal)); @@ -64,7 +65,7 @@ public class ExtensionGrantValidator Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, ct); return context.Result; } catch (Exception e) diff --git a/identity-server/src/IdentityServer/Validation/Default/HashedSharedSecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/HashedSharedSecretValidator.cs index 52060fcb5..516936770 100644 --- a/identity-server/src/IdentityServer/Validation/Default/HashedSharedSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/HashedSharedSecretValidator.cs @@ -27,11 +27,13 @@ public class HashedSharedSecretValidator : ISecretValidator /// /// The stored secrets. /// The received secret. + /// The cancellation token. /// /// A validation result /// /// Id or credential - public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret) + /// + public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct) { var fail = Task.FromResult(new SecretValidationResult { Success = false }); var success = Task.FromResult(new SecretValidationResult { Success = true }); diff --git a/identity-server/src/IdentityServer/Validation/Default/IntrospectionRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/IntrospectionRequestValidator.cs index 9d1f611d9..6ff85be09 100644 --- a/identity-server/src/IdentityServer/Validation/Default/IntrospectionRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/IntrospectionRequestValidator.cs @@ -37,7 +37,7 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator } /// - public async Task ValidateAsync(IntrospectionRequestValidationContext context) + public async Task ValidateAsync(IntrospectionRequestValidationContext context, Ct ct) { var parameters = context.Parameters; var api = context.Api; @@ -102,7 +102,7 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator // APIs can only introspect access tokens. We ignore the hint and just immediately try to // validate the token as an access token. If that fails, claims will be null and // we'll return { "isActive": false }. - claims = await GetAccessTokenClaimsAsync(token); + claims = await GetAccessTokenClaimsAsync(token, ct); } else { @@ -120,7 +120,7 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator if (hint.IsMissing() || hint == TokenTypeHints.AccessToken) { // try access token - claims = await GetAccessTokenClaimsAsync(token, client); + claims = await GetAccessTokenClaimsAsync(token, client, ct); if (claims == null) { // fall back to refresh token @@ -128,13 +128,13 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator { _logger.LogDebug("Failed to validate token as access token. Possible incorrect token_type_hint parameter."); } - claims = await GetRefreshTokenClaimsAsync(token, client); + claims = await GetRefreshTokenClaimsAsync(token, client, ct); } } else { // try refresh token - claims = await GetRefreshTokenClaimsAsync(token, client); + claims = await GetRefreshTokenClaimsAsync(token, client, ct); if (claims == null) { // fall back to access token @@ -142,7 +142,7 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator { _logger.LogDebug("Failed to validate token as refresh token. Possible incorrect token_type_hint parameter."); } - claims = await GetAccessTokenClaimsAsync(token, client); + claims = await GetAccessTokenClaimsAsync(token, client, ct); } } } @@ -181,9 +181,9 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator /// /// Attempt to obtain the claims for a token as a refresh token for a client. /// - private async Task> GetRefreshTokenClaimsAsync(string token, Client client) + private async Task> GetRefreshTokenClaimsAsync(string token, Client client, Ct ct) { - var refreshValidationResult = await _refreshTokenService.ValidateRefreshTokenAsync(token, client); + var refreshValidationResult = await _refreshTokenService.ValidateRefreshTokenAsync(token, client, ct); if (!refreshValidationResult.IsError) { var iat = ((DateTimeOffset)refreshValidationResult.RefreshToken.CreationTime).ToUnixTimeSeconds(); @@ -210,9 +210,9 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator /// /// Attempt to obtain the claims for a token as an access token, and validate that it belongs to the client. /// - private async Task> GetAccessTokenClaimsAsync(string token, Client client) + private async Task> GetAccessTokenClaimsAsync(string token, Client client, Ct ct) { - var tokenValidationResult = await _tokenValidator.ValidateAccessTokenAsync(token); + var tokenValidationResult = await _tokenValidator.ValidateAccessTokenAsync(token, null, ct); if (!tokenValidationResult.IsError) { var claims = tokenValidationResult.Claims.ToList(); @@ -234,9 +234,9 @@ internal class IntrospectionRequestValidator : IIntrospectionRequestValidator /// token belongs to a particular client, and is intended for use when we have an API caller (any API can /// introspect a token). /// - private async Task> GetAccessTokenClaimsAsync(string token) + private async Task> GetAccessTokenClaimsAsync(string token, Ct ct) { - var tokenValidationResult = await _tokenValidator.ValidateAccessTokenAsync(token); + var tokenValidationResult = await _tokenValidator.ValidateAccessTokenAsync(token, null, ct); if (!tokenValidationResult.IsError) { _logger.LogDebug("Validated access token"); diff --git a/identity-server/src/IdentityServer/Validation/Default/JwtBearerClientAssertionSecretParser.cs b/identity-server/src/IdentityServer/Validation/Default/JwtBearerClientAssertionSecretParser.cs index c9c3d6deb..85519abef 100644 --- a/identity-server/src/IdentityServer/Validation/Default/JwtBearerClientAssertionSecretParser.cs +++ b/identity-server/src/IdentityServer/Validation/Default/JwtBearerClientAssertionSecretParser.cs @@ -44,10 +44,12 @@ public class JwtBearerClientAssertionSecretParser : ISecretParser /// Used for "private_key_jwt" client authentication method as defined in http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication /// /// The HTTP context + /// The cancellation token. /// /// A parsed secret /// - public async Task ParseAsync(HttpContext context) + /// + public async Task ParseAsync(HttpContext context, Ct ct) { _logger.LogDebug("Start parsing for JWT client assertion in post body"); @@ -57,7 +59,7 @@ public class JwtBearerClientAssertionSecretParser : ISecretParser return null; } - var body = await context.Request.ReadFormAsync(); + var body = await context.Request.ReadFormAsync(ct); if (body != null) { diff --git a/identity-server/src/IdentityServer/Validation/Default/JwtRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/JwtRequestValidator.cs index 53056388b..c66c79c47 100644 --- a/identity-server/src/IdentityServer/Validation/Default/JwtRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/JwtRequestValidator.cs @@ -29,14 +29,14 @@ public class JwtRequestValidator : IJwtRequestValidator /// /// The audience URI to use /// - protected async Task GetAudienceUri() + protected async Task GetAudienceUri(Ct ct) { if (_audienceUri.IsPresent()) { return _audienceUri; } - return await IssuerNameService.GetCurrentAsync(); + return await IssuerNameService.GetCurrentAsync(ct); } /// @@ -82,7 +82,7 @@ public class JwtRequestValidator : IJwtRequestValidator } /// - public virtual async Task ValidateAsync(JwtRequestValidationContext context) + public virtual async Task ValidateAsync(JwtRequestValidationContext context, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("JwtRequestValidator.Validate"); @@ -119,7 +119,7 @@ public class JwtRequestValidator : IJwtRequestValidator JsonWebToken jwtSecurityToken; try { - jwtSecurityToken = await ValidateJwtAsync(context, trustedKeys); + jwtSecurityToken = await ValidateJwtAsync(context, trustedKeys, ct); } catch (Exception e) { @@ -156,7 +156,7 @@ public class JwtRequestValidator : IJwtRequestValidator /// /// Validates the JWT token /// - protected virtual async Task ValidateJwtAsync(JwtRequestValidationContext context, IEnumerable keys) + protected virtual async Task ValidateJwtAsync(JwtRequestValidationContext context, IEnumerable keys, Ct ct) { var tokenValidationParameters = new TokenValidationParameters { @@ -166,7 +166,7 @@ public class JwtRequestValidator : IJwtRequestValidator ValidIssuer = context.Client.ClientId, ValidateIssuer = true, - ValidAudience = await GetAudienceUri(), + ValidAudience = await GetAudienceUri(ct), ValidateAudience = true, RequireSignedTokens = true, diff --git a/identity-server/src/IdentityServer/Validation/Default/MutualTlsSecretParser.cs b/identity-server/src/IdentityServer/Validation/Default/MutualTlsSecretParser.cs index 2f1e3eb41..116a81fb9 100644 --- a/identity-server/src/IdentityServer/Validation/Default/MutualTlsSecretParser.cs +++ b/identity-server/src/IdentityServer/Validation/Default/MutualTlsSecretParser.cs @@ -38,8 +38,10 @@ public class MutualTlsSecretParser : ISecretParser /// Parses the HTTP context /// /// + /// The cancellation token. /// - public async Task ParseAsync(HttpContext context) + /// + public async Task ParseAsync(HttpContext context, Ct ct) { _logger.LogDebug("Start parsing for client id in post body"); @@ -49,7 +51,7 @@ public class MutualTlsSecretParser : ISecretParser return null; } - var body = await context.Request.ReadFormAsync(); + var body = await context.Request.ReadFormAsync(ct); if (body != null) { @@ -64,7 +66,7 @@ public class MutualTlsSecretParser : ISecretParser return null; } - var clientCertificate = await context.Connection.GetClientCertificateAsync(); + var clientCertificate = await context.Connection.GetClientCertificateAsync(ct); if (clientCertificate is null) { diff --git a/identity-server/src/IdentityServer/Validation/Default/NopBackchannelAuthenticationUserValidator.cs b/identity-server/src/IdentityServer/Validation/Default/NopBackchannelAuthenticationUserValidator.cs index 85c72039b..8d8bd00ff 100644 --- a/identity-server/src/IdentityServer/Validation/Default/NopBackchannelAuthenticationUserValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/NopBackchannelAuthenticationUserValidator.cs @@ -12,7 +12,7 @@ namespace Duende.IdentityServer.Validation; public class NopBackchannelAuthenticationUserValidator : IBackchannelAuthenticationUserValidator { /// - public Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext) + public Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext, Ct _) { var result = new BackchannelAuthenticationUserValidationResult { diff --git a/identity-server/src/IdentityServer/Validation/Default/NopClientConfigurationValidator.cs b/identity-server/src/IdentityServer/Validation/Default/NopClientConfigurationValidator.cs index a02edfa2a..a53c5436d 100644 --- a/identity-server/src/IdentityServer/Validation/Default/NopClientConfigurationValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/NopClientConfigurationValidator.cs @@ -10,12 +10,8 @@ namespace Duende.IdentityServer.Validation; /// public class NopClientConfigurationValidator : IClientConfigurationValidator { - /// - /// Determines whether the configuration of a client is valid. - /// - /// The context. - /// - public Task ValidateAsync(ClientConfigurationValidationContext context) + /// + public Task ValidateAsync(ClientConfigurationValidationContext context, Ct _) { context.IsValid = true; return Task.CompletedTask; diff --git a/identity-server/src/IdentityServer/Validation/Default/NotSupportedResouceOwnerCredentialValidator.cs b/identity-server/src/IdentityServer/Validation/Default/NotSupportedResouceOwnerCredentialValidator.cs index fac26c1de..e6bc3719e 100644 --- a/identity-server/src/IdentityServer/Validation/Default/NotSupportedResouceOwnerCredentialValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/NotSupportedResouceOwnerCredentialValidator.cs @@ -21,12 +21,8 @@ public class NotSupportedResourceOwnerPasswordValidator : IResourceOwnerPassword /// The logger. public NotSupportedResourceOwnerPasswordValidator(ILogger logger) => _logger = logger; - /// - /// Validates the resource owner password credential - /// - /// The context. - /// - public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) + /// + public Task ValidateAsync(ResourceOwnerPasswordValidationContext context, Ct _) { context.Result = new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType); diff --git a/identity-server/src/IdentityServer/Validation/Default/PlainTextSharedSecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/PlainTextSharedSecretValidator.cs index 1099c1fbe..9f1a73b68 100644 --- a/identity-server/src/IdentityServer/Validation/Default/PlainTextSharedSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/PlainTextSharedSecretValidator.cs @@ -27,11 +27,13 @@ public class PlainTextSharedSecretValidator : ISecretValidator /// /// The stored secrets. /// The received secret. + /// The cancellation token. /// /// A validation result /// /// id or credential is missing. - public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret) + /// + public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct) { var fail = Task.FromResult(new SecretValidationResult { Success = false }); var success = Task.FromResult(new SecretValidationResult { Success = true }); diff --git a/identity-server/src/IdentityServer/Validation/Default/PostBodySecretParser.cs b/identity-server/src/IdentityServer/Validation/Default/PostBodySecretParser.cs index 799227fbb..ab4326c4b 100644 --- a/identity-server/src/IdentityServer/Validation/Default/PostBodySecretParser.cs +++ b/identity-server/src/IdentityServer/Validation/Default/PostBodySecretParser.cs @@ -42,10 +42,12 @@ public class PostBodySecretParser : ISecretParser /// Tries to find a secret on the context that can be used for authentication /// /// The HTTP context. + /// The cancellation token. /// /// A parsed secret /// - public async Task ParseAsync(HttpContext context) + /// + public async Task ParseAsync(HttpContext context, Ct ct) { _logger.LogDebug("Start parsing for secret in post body"); @@ -55,7 +57,7 @@ public class PostBodySecretParser : ISecretParser return null; } - var body = await context.Request.ReadFormAsync(); + var body = await context.Request.ReadFormAsync(ct); if (body != null) { diff --git a/identity-server/src/IdentityServer/Validation/Default/PrivateKeyJwtSecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/PrivateKeyJwtSecretValidator.cs index a4ffcfa10..cb43cdfe2 100644 --- a/identity-server/src/IdentityServer/Validation/Default/PrivateKeyJwtSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/PrivateKeyJwtSecretValidator.cs @@ -48,11 +48,13 @@ public class PrivateKeyJwtSecretValidator : ISecretValidator /// /// The stored secrets. /// The received secret. + /// The cancellation token. /// /// A validation result /// /// ParsedSecret.Credential is not a JWT token - public async Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret) + /// + public async Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct) { var fail = new SecretValidationResult { Success = false }; var success = new SecretValidationResult { Success = true }; @@ -124,7 +126,7 @@ public class PrivateKeyJwtSecretValidator : ISecretValidator ValidAlgorithms = _options.SupportedClientAssertionSigningAlgorithms }; - var issuer = await _issuerNameService.GetCurrentAsync(); + var issuer = await _issuerNameService.GetCurrentAsync(ct); if (enforceStrictAud) { @@ -153,7 +155,7 @@ public class PrivateKeyJwtSecretValidator : ISecretValidator // token endpoint URL string.Concat(_urls.BaseUrl.EnsureTrailingSlash(), ProtocolRoutePaths.Token), // issuer URL + token (legacy support) - string.Concat((await _issuerNameService.GetCurrentAsync()).EnsureTrailingSlash(), ProtocolRoutePaths.Token), + string.Concat((await _issuerNameService.GetCurrentAsync(ct)).EnsureTrailingSlash(), ProtocolRoutePaths.Token), // issuer URL issuer, // CIBA endpoint: https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#auth_request @@ -193,14 +195,14 @@ public class PrivateKeyJwtSecretValidator : ISecretValidator return fail; } - if (await _replayCache.ExistsAsync(Purpose, jti)) + if (await _replayCache.ExistsAsync(Purpose, jti, ct)) { _logger.LogError("jti is found in replay cache. Possible replay attack."); return fail; } else { - await _replayCache.AddAsync(Purpose, jti, exp.AddMinutes(5)); + await _replayCache.AddAsync(Purpose, jti, exp.AddMinutes(5), ct); } return success; diff --git a/identity-server/src/IdentityServer/Validation/Default/PushedAuthorizationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/PushedAuthorizationRequestValidator.cs index a5618c8e0..0bcc4c230 100644 --- a/identity-server/src/IdentityServer/Validation/Default/PushedAuthorizationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/PushedAuthorizationRequestValidator.cs @@ -44,7 +44,7 @@ internal class PushedAuthorizationRequestValidator( IMtlsEndpointGenerator mtlsEndpointGenerator, ILogger logger) : IPushedAuthorizationRequestValidator { - public async Task ValidateAsync(PushedAuthorizationRequestValidationContext context) + public async Task ValidateAsync(PushedAuthorizationRequestValidationContext context, Ct ct) { // Licensing licenseUsage.FeatureUsed(LicenseFeature.PAR); @@ -96,7 +96,7 @@ internal class PushedAuthorizationRequestValidator( Method = "POST", Url = parUrl }; - var dpopValidationResult = await dpopProofValidator.ValidateAsync(dpopContext); + var dpopValidationResult = await dpopProofValidator.ValidateAsync(dpopContext, ct); if (dpopValidationResult.ServerIssuedNonce != null) { return PushedAuthorizationValidationResult.CreateServerNonceResult(dpopValidationResult.ServerIssuedNonce); @@ -131,7 +131,7 @@ internal class PushedAuthorizationRequestValidator( } // -- Authorization Parameter Validation -- - var authorizeRequestValidation = await authorizeRequestValidator.ValidateAsync(context.RequestParameters, + var authorizeRequestValidation = await authorizeRequestValidator.ValidateAsync(context.RequestParameters, ct, authorizeRequestType: AuthorizeRequestType.PushedAuthorization); if (authorizeRequestValidation.IsError) { diff --git a/identity-server/src/IdentityServer/Validation/Default/RequestObjectValidator.cs b/identity-server/src/IdentityServer/Validation/Default/RequestObjectValidator.cs index ed63b60da..706e7e5f5 100644 --- a/identity-server/src/IdentityServer/Validation/Default/RequestObjectValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/RequestObjectValidator.cs @@ -36,7 +36,7 @@ internal class RequestObjectValidator : IRequestObjectValidator } - public async Task LoadRequestObjectAsync(ValidatedAuthorizeRequest request) + public async Task LoadRequestObjectAsync(ValidatedAuthorizeRequest request, Ct ct) { var requestObject = request.Raw.Get(OidcConstants.AuthorizeRequest.Request); var requestUri = request.Raw.Get(OidcConstants.AuthorizeRequest.RequestUri); @@ -64,7 +64,7 @@ internal class RequestObjectValidator : IRequestObjectValidator { if (IsParRequestUri(requestUri)) { - var validationError = await ValidatePushedAuthorizationRequest(request); + var validationError = await ValidatePushedAuthorizationRequest(request, ct); if (validationError != null) { return validationError; @@ -82,7 +82,7 @@ internal class RequestObjectValidator : IRequestObjectValidator return Invalid(request, error: OidcConstants.AuthorizeErrors.InvalidRequestUri, description: "request_uri is too long"); } - var jwt = await _jwtRequestUriHttpClient.GetJwtAsync(requestUri, request.Client); + var jwt = await _jwtRequestUriHttpClient.GetJwtAsync(requestUri, request.Client, ct); if (jwt.IsMissing()) { LogError("no value returned from request_uri", request); @@ -116,7 +116,7 @@ internal class RequestObjectValidator : IRequestObjectValidator private static string? LoadRequestObjectFromPushedAuthorizationRequest(ValidatedAuthorizeRequest request) => request.Raw.Get(OidcConstants.AuthorizeRequest.Request); - public async Task ValidatePushedAuthorizationRequest(ValidatedAuthorizeRequest request) + public async Task ValidatePushedAuthorizationRequest(ValidatedAuthorizeRequest request, Ct ct) { // Check that the endpoint is still enabled at the time of validation, in case an existing PAR record // is used after PAR is disabled. @@ -127,7 +127,7 @@ internal class RequestObjectValidator : IRequestObjectValidator description: "Pushed authorization is disabled."); } } - var pushedAuthorizationRequest = await GetPushedAuthorizationRequestAsync(request); + var pushedAuthorizationRequest = await GetPushedAuthorizationRequestAsync(request, ct); if (pushedAuthorizationRequest == null) { { @@ -193,12 +193,12 @@ internal class RequestObjectValidator : IRequestObjectValidator return null; } - private async Task GetPushedAuthorizationRequestAsync(ValidatedAuthorizeRequest request) + private async Task GetPushedAuthorizationRequestAsync(ValidatedAuthorizeRequest request, Ct ct) { var referenceValue = GetReferenceValue(request); if (referenceValue != null) { - return await _pushedAuthorizationService.GetPushedAuthorizationRequestAsync(referenceValue); + return await _pushedAuthorizationService.GetPushedAuthorizationRequestAsync(referenceValue, ct); } return null; } @@ -217,7 +217,7 @@ internal class RequestObjectValidator : IRequestObjectValidator return null; } - public async Task ValidateRequestObjectAsync(ValidatedAuthorizeRequest request) + public async Task ValidateRequestObjectAsync(ValidatedAuthorizeRequest request, Ct ct) { ////////////////////////////////////////////////////////// // validate request object @@ -229,7 +229,7 @@ internal class RequestObjectValidator : IRequestObjectValidator { Client = request.Client, JwtTokenString = request.RequestObject - }); + }, ct); if (jwtRequestValidationResult.IsError) { LogError("request JWT validation failure", request); diff --git a/identity-server/src/IdentityServer/Validation/Default/SecretParser.cs b/identity-server/src/IdentityServer/Validation/Default/SecretParser.cs index 40462d353..cdf43eaec 100644 --- a/identity-server/src/IdentityServer/Validation/Default/SecretParser.cs +++ b/identity-server/src/IdentityServer/Validation/Default/SecretParser.cs @@ -31,14 +31,16 @@ public class SecretParser : ISecretsListParser /// Checks the context to find a secret. /// /// The HTTP context. + /// The cancellation token. /// - public async Task ParseAsync(HttpContext context) + /// + public async Task ParseAsync(HttpContext context, Ct ct) { // see if a registered parser finds a secret on the request ParsedSecret bestSecret = null; foreach (var parser in _parsers) { - var parsedSecret = await parser.ParseAsync(context); + var parsedSecret = await parser.ParseAsync(context, ct); if (parsedSecret != null) { _logger.LogDebug("Parser found secret: {type}", parser.GetType().Name); diff --git a/identity-server/src/IdentityServer/Validation/Default/SecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/SecretValidator.cs index 442e3cf9e..9d9a0274f 100644 --- a/identity-server/src/IdentityServer/Validation/Default/SecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/SecretValidator.cs @@ -35,8 +35,10 @@ public class SecretValidator : ISecretsListValidator /// /// The parsed secret. /// The secrets. + /// The cancellation token. /// - public async Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret) + /// + public async Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct) { var secretsArray = secrets as Secret[] ?? secrets.ToArray(); @@ -50,7 +52,7 @@ public class SecretValidator : ISecretsListValidator // see if a registered validator can validate the secret foreach (var validator in _validators) { - var secretValidationResult = await validator.ValidateAsync(currentSecrets, parsedSecret); + var secretValidationResult = await validator.ValidateAsync(currentSecrets, parsedSecret, ct); if (secretValidationResult.Success) { diff --git a/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidator.cs b/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidator.cs index 7e08bb6c6..1c49371ac 100644 --- a/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidator.cs @@ -50,24 +50,11 @@ public class StrictRedirectUriValidator : IRedirectUriValidator /// public virtual Task IsRedirectUriValidAsync(string requestedUri, Client client) => Task.FromResult(StringCollectionContainsString(client.RedirectUris, requestedUri)); - /// - /// Determines whether a post logout URI is valid for a client. - /// - /// The requested URI. - /// The client. - /// - /// true is the URI is valid; false otherwise. - /// - public virtual Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client) => Task.FromResult(StringCollectionContainsString(client.PostLogoutRedirectUris, requestedUri)); + /// + public virtual Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client, Ct _) => Task.FromResult(StringCollectionContainsString(client.PostLogoutRedirectUris, requestedUri)); - /// - /// Determines whether a redirect uri is valid for a context. - /// - /// The context. - /// - /// true is the URI is valid; false otherwise. - /// - public virtual Task IsRedirectUriValidAsync(RedirectUriValidationContext context) + /// + public virtual Task IsRedirectUriValidAsync(RedirectUriValidationContext context, Ct _) { // Check if special case handling for PAR is enabled and that the client // is a confidential client. If so, any pushed redirect uri is allowed diff --git a/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidatorAppAuth.cs b/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidatorAppAuth.cs index fe8b00e9f..ffab440f7 100644 --- a/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidatorAppAuth.cs +++ b/identity-server/src/IdentityServer/Validation/Default/StrictRedirectUriValidatorAppAuth.cs @@ -27,9 +27,9 @@ public class StrictRedirectUriValidatorAppAuth : StrictRedirectUriValidator : base(options) => _logger = logger; /// - public override async Task IsRedirectUriValidAsync(RedirectUriValidationContext context) + public override async Task IsRedirectUriValidAsync(RedirectUriValidationContext context, Ct ct) { - var isAllowed = await base.IsRedirectUriValidAsync(context); + var isAllowed = await base.IsRedirectUriValidAsync(context, ct); if (isAllowed) { return isAllowed; @@ -49,12 +49,13 @@ public class StrictRedirectUriValidatorAppAuth : StrictRedirectUriValidator /// /// The requested URI. /// The client. + /// The cancellation token. /// /// true is the URI is valid; false otherwise. /// - public override async Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client) + public override async Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client, Ct ct) { - var isAllowed = await base.IsPostLogoutRedirectUriValidAsync(requestedUri, client); + var isAllowed = await base.IsPostLogoutRedirectUriValidAsync(requestedUri, client, ct); if (isAllowed) { return isAllowed; diff --git a/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs index b881466b5..2f587f26d 100644 --- a/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs @@ -43,7 +43,6 @@ internal class TokenRequestValidator : ITokenRequestValidator private readonly ResourceLoadedTracker _resourceLoadedTracker; private readonly IMtlsEndpointGenerator _mtlsEndpointGenerator; private readonly ILogger _logger; - private ValidatedTokenRequest _validatedRequest; public TokenRequestValidator( @@ -94,14 +93,15 @@ internal class TokenRequestValidator : ITokenRequestValidator // only here for legacy unit tests // maybe at some point we clean up the unit tests? - internal Task ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult) => ValidateRequestAsync(new TokenRequestValidationContext - { - RequestParameters = parameters, - ClientValidationResult = clientValidationResult - }); + internal Task ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult, Ct ct) => + ValidateRequestAsync(new TokenRequestValidationContext + { + RequestParameters = parameters, + ClientValidationResult = clientValidationResult + }, ct); /// - public async Task ValidateRequestAsync(TokenRequestValidationContext context) + public async Task ValidateRequestAsync(TokenRequestValidationContext context, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenRequestValidator.ValidateRequest"); @@ -114,7 +114,7 @@ internal class TokenRequestValidator : ITokenRequestValidator _validatedRequest = new ValidatedTokenRequest { - IssuerName = await _issuerNameService.GetCurrentAsync(), + IssuerName = await _issuerNameService.GetCurrentAsync(ct), Raw = parameters ?? throw new ArgumentNullException(nameof(context.RequestParameters)), Options = _options }; @@ -192,7 +192,7 @@ internal class TokenRequestValidator : ITokenRequestValidator ////////////////////////////////////////////////////////// // proof token validation ////////////////////////////////////////////////////////// - var proofResult = await ValidateProofToken(context); + var proofResult = await ValidateProofToken(context, ct); if (proofResult.IsError) { return proofResult; @@ -205,20 +205,20 @@ internal class TokenRequestValidator : ITokenRequestValidator return grantType switch { OidcConstants.GrantTypes.AuthorizationCode => await RunValidationAsync( - ValidateAuthorizationCodeRequestAsync, parameters), + ValidateAuthorizationCodeRequestAsync, parameters, ct), OidcConstants.GrantTypes.ClientCredentials => await RunValidationAsync( - ValidateClientCredentialsRequestAsync, parameters), + ValidateClientCredentialsRequestAsync, parameters, ct), OidcConstants.GrantTypes.Password => await RunValidationAsync(ValidateResourceOwnerCredentialRequestAsync, - parameters), + parameters, ct), OidcConstants.GrantTypes.RefreshToken => await RunValidationAsync(ValidateRefreshTokenRequestAsync, - parameters), - OidcConstants.GrantTypes.DeviceCode => await RunValidationAsync(ValidateDeviceCodeRequestAsync, parameters), - OidcConstants.GrantTypes.Ciba => await RunValidationAsync(ValidateCibaRequestRequestAsync, parameters), - _ => await RunValidationAsync(ValidateExtensionGrantRequestAsync, parameters) + parameters, ct), + OidcConstants.GrantTypes.DeviceCode => await RunValidationAsync(ValidateDeviceCodeRequestAsync, parameters, ct), + OidcConstants.GrantTypes.Ciba => await RunValidationAsync(ValidateCibaRequestRequestAsync, parameters, ct), + _ => await RunValidationAsync(ValidateExtensionGrantRequestAsync, parameters, ct) }; } - private async Task ValidateProofToken(TokenRequestValidationContext context) + private async Task ValidateProofToken(TokenRequestValidationContext context, Ct ct) { // mTLS client cert processing @@ -261,7 +261,7 @@ internal class TokenRequestValidator : ITokenRequestValidator Url = tokenUrl, Method = "POST", }; - var dpopResult = await _dPoPProofValidator.ValidateAsync(dpopContext); + var dpopResult = await _dPoPProofValidator.ValidateAsync(dpopContext, ct); if (dpopResult.IsError) { LogError(dpopResult.ErrorDescription ?? dpopResult.Error); @@ -283,10 +283,10 @@ internal class TokenRequestValidator : ITokenRequestValidator return Valid(); } - private async Task RunValidationAsync(Func> validationFunc, NameValueCollection parameters) + private async Task RunValidationAsync(Func> validationFunc, NameValueCollection parameters, Ct ct) { // run standard validation - var result = await validationFunc(parameters); + var result = await validationFunc(parameters, ct); if (result.IsError) { return result; @@ -296,7 +296,7 @@ internal class TokenRequestValidator : ITokenRequestValidator _logger.LogTrace("Calling into custom request validator: {type}", _customRequestValidator.GetType().FullName); var customValidationContext = new CustomTokenRequestValidationContext { Result = result }; - await _customRequestValidator.ValidateAsync(customValidationContext); + await _customRequestValidator.ValidateAsync(customValidationContext, ct); if (customValidationContext.Result.IsError) { @@ -323,7 +323,7 @@ internal class TokenRequestValidator : ITokenRequestValidator return customValidationContext.Result; } - private async Task ValidateAuthorizationCodeRequestAsync(NameValueCollection parameters) + private async Task ValidateAuthorizationCodeRequestAsync(NameValueCollection parameters, Ct ct) { _logger.LogDebug("Start validation of authorization code token request"); @@ -355,7 +355,7 @@ internal class TokenRequestValidator : ITokenRequestValidator _validatedRequest.AuthorizationCodeHandle = code; - var authZcode = await _authorizationCodeStore.GetAuthorizationCodeAsync(code); + var authZcode = await _authorizationCodeStore.GetAuthorizationCodeAsync(code, ct); if (authZcode == null) { LogError("Invalid authorization code", new { code }); @@ -391,7 +391,7 @@ internal class TokenRequestValidator : ITokenRequestValidator // remove code from store // todo: set to consumed in the future? - await _authorizationCodeStore.RemoveAuthorizationCodeAsync(code); + await _authorizationCodeStore.RemoveAuthorizationCodeAsync(code, ct); if (authZcode.CreationTime.HasExceeded(authZcode.Lifetime, _timeProvider.GetUtcNow().UtcDateTime)) { @@ -463,7 +463,7 @@ internal class TokenRequestValidator : ITokenRequestValidator Client = _validatedRequest.Client, Scopes = _validatedRequest.AuthorizationCode.RequestedScopes, ResourceIndicators = _validatedRequest.AuthorizationCode.RequestedResourceIndicators, - }); + }, ct); if (!validatedResources.Succeeded) { @@ -511,7 +511,7 @@ internal class TokenRequestValidator : ITokenRequestValidator // make sure user is enabled ///////////////////////////////////////////// var isActiveCtx = new IsActiveContext(_validatedRequest.AuthorizationCode.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.AuthorizationCodeValidation); - await _profile.IsActiveAsync(isActiveCtx); + await _profile.IsActiveAsync(isActiveCtx, ct); if (isActiveCtx.IsActive == false) { @@ -524,7 +524,7 @@ internal class TokenRequestValidator : ITokenRequestValidator return Valid(); } - private async Task ValidateClientCredentialsRequestAsync(NameValueCollection parameters) + private async Task ValidateClientCredentialsRequestAsync(NameValueCollection parameters, Ct ct) { _logger.LogDebug("Start client credentials token request validation"); @@ -540,7 +540,7 @@ internal class TokenRequestValidator : ITokenRequestValidator ///////////////////////////////////////////// // check if client is allowed to request scopes ///////////////////////////////////////////// - var scopeError = await ValidateRequestedScopesAndResourcesAsync(parameters, ignoreImplicitIdentityScopes: true, ignoreImplicitOfflineAccess: true); + var scopeError = await ValidateRequestedScopesAndResourcesAsync(parameters, ct, ignoreImplicitIdentityScopes: true, ignoreImplicitOfflineAccess: true); if (scopeError != null) { return Invalid(scopeError); @@ -562,7 +562,7 @@ internal class TokenRequestValidator : ITokenRequestValidator return Valid(); } - private async Task ValidateResourceOwnerCredentialRequestAsync(NameValueCollection parameters) + private async Task ValidateResourceOwnerCredentialRequestAsync(NameValueCollection parameters, Ct ct) { _logger.LogDebug("Start resource owner password token request validation"); @@ -578,7 +578,7 @@ internal class TokenRequestValidator : ITokenRequestValidator ///////////////////////////////////////////// // check if client is allowed to request scopes ///////////////////////////////////////////// - var scopeError = await ValidateRequestedScopesAndResourcesAsync(parameters); + var scopeError = await ValidateRequestedScopesAndResourcesAsync(parameters, ct); if (scopeError != null) { return Invalid(scopeError); @@ -620,7 +620,7 @@ internal class TokenRequestValidator : ITokenRequestValidator Password = password, Request = _validatedRequest }; - await _resourceOwnerValidator.ValidateAsync(resourceOwnerContext); + await _resourceOwnerValidator.ValidateAsync(resourceOwnerContext, ct); if (resourceOwnerContext.Result.IsError) { @@ -630,7 +630,7 @@ internal class TokenRequestValidator : ITokenRequestValidator if (resourceOwnerContext.Result.Error == OidcConstants.TokenErrors.UnsupportedGrantType) { LogError("Resource owner password credential grant type not supported"); - await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "password grant type not supported", resourceOwnerContext.Request.Client.ClientId); + await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "password grant type not supported", resourceOwnerContext.Request.Client.ClientId, ct); return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType, customResponse: resourceOwnerContext.Result.CustomResponse); } @@ -643,7 +643,7 @@ internal class TokenRequestValidator : ITokenRequestValidator } LogInformation("User authentication failed: ", errorDescription ?? resourceOwnerContext.Result.Error); - await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, errorDescription, resourceOwnerContext.Request.Client.ClientId); + await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, errorDescription, resourceOwnerContext.Request.Client.ClientId, ct); return Invalid(resourceOwnerContext.Result.Error, errorDescription, resourceOwnerContext.Result.CustomResponse); } @@ -652,7 +652,7 @@ internal class TokenRequestValidator : ITokenRequestValidator { var error = "User authentication failed: no principal returned"; LogError(error); - await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, error, resourceOwnerContext.Request.Client.ClientId); + await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, error, resourceOwnerContext.Request.Client.ClientId, ct); return Invalid(OidcConstants.TokenErrors.InvalidGrant); } @@ -661,12 +661,12 @@ internal class TokenRequestValidator : ITokenRequestValidator // make sure user is enabled ///////////////////////////////////////////// var isActiveCtx = new IsActiveContext(resourceOwnerContext.Result.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.ResourceOwnerValidation); - await _profile.IsActiveAsync(isActiveCtx); + await _profile.IsActiveAsync(isActiveCtx, ct); if (isActiveCtx.IsActive == false) { LogError("User has been disabled", new { subjectId = resourceOwnerContext.Result.Subject.GetSubjectId() }); - await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "user is inactive", resourceOwnerContext.Request.Client.ClientId); + await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "user is inactive", resourceOwnerContext.Request.Client.ClientId, ct); return Invalid(OidcConstants.TokenErrors.InvalidGrant); } @@ -674,12 +674,12 @@ internal class TokenRequestValidator : ITokenRequestValidator _validatedRequest.UserName = userName; _validatedRequest.Subject = resourceOwnerContext.Result.Subject; - await RaiseSuccessfulResourceOwnerAuthenticationEventAsync(userName, resourceOwnerContext.Result.Subject.GetSubjectId(), resourceOwnerContext.Request.Client.ClientId); + await RaiseSuccessfulResourceOwnerAuthenticationEventAsync(userName, resourceOwnerContext.Result.Subject.GetSubjectId(), resourceOwnerContext.Request.Client.ClientId, ct); _logger.LogDebug("Resource owner password token request validation success."); return Valid(resourceOwnerContext.Result.CustomResponse); } - private async Task ValidateRefreshTokenRequestAsync(NameValueCollection parameters) + private async Task ValidateRefreshTokenRequestAsync(NameValueCollection parameters, Ct ct) { _logger.LogDebug("Start validation of refresh token request"); @@ -696,7 +696,7 @@ internal class TokenRequestValidator : ITokenRequestValidator return Invalid(OidcConstants.TokenErrors.InvalidGrant); } - var result = await _refreshTokenService.ValidateRefreshTokenAsync(refreshTokenHandle, _validatedRequest.Client); + var result = await _refreshTokenService.ValidateRefreshTokenAsync(refreshTokenHandle, _validatedRequest.Client, ct); if (result.IsError) { @@ -811,7 +811,7 @@ internal class TokenRequestValidator : ITokenRequestValidator Client = _validatedRequest.Client, Scopes = _validatedRequest.RefreshToken.AuthorizedScopes, ResourceIndicators = resourceIndicators, - }); + }, ct); if (!validatedResources.Succeeded) { @@ -836,7 +836,7 @@ internal class TokenRequestValidator : ITokenRequestValidator return Valid(); } - private async Task ValidateDeviceCodeRequestAsync(NameValueCollection parameters) + private async Task ValidateDeviceCodeRequestAsync(NameValueCollection parameters, Ct ct) { _logger.LogDebug("Start validation of device code request"); @@ -878,7 +878,7 @@ internal class TokenRequestValidator : ITokenRequestValidator // validate device code ///////////////////////////////////////////// var deviceCodeContext = new DeviceCodeValidationContext { DeviceCode = deviceCode, Request = _validatedRequest }; - await _deviceCodeValidator.ValidateAsync(deviceCodeContext); + await _deviceCodeValidator.ValidateAsync(deviceCodeContext, ct); if (deviceCodeContext.Result.IsError) { @@ -893,7 +893,7 @@ internal class TokenRequestValidator : ITokenRequestValidator Client = _validatedRequest.Client, Scopes = _validatedRequest.DeviceCode.AuthorizedScopes, ResourceIndicators = null // not supported for device grant - }); + }, ct); if (!validatedResources.Succeeded) { @@ -917,7 +917,7 @@ internal class TokenRequestValidator : ITokenRequestValidator return Valid(); } - private async Task ValidateCibaRequestRequestAsync(NameValueCollection parameters) + private async Task ValidateCibaRequestRequestAsync(NameValueCollection parameters, Ct ct) { _logger.LogDebug("Start validation of CIBA request"); @@ -957,7 +957,7 @@ internal class TokenRequestValidator : ITokenRequestValidator AuthenticationRequestId = authRequestId, Request = _validatedRequest }; - await _backchannelAuthenticationRequestIdValidator.ValidateAsync(validationContext); + await _backchannelAuthenticationRequestIdValidator.ValidateAsync(validationContext, ct); if (validationContext.Result.IsError) { @@ -982,7 +982,7 @@ internal class TokenRequestValidator : ITokenRequestValidator Client = _validatedRequest.Client, Scopes = _validatedRequest.BackChannelAuthenticationRequest.AuthorizedScopes, ResourceIndicators = _validatedRequest.BackChannelAuthenticationRequest.RequestedResourceIndicators, - }); + }, ct); if (!validatedResources.Succeeded) { @@ -1006,7 +1006,7 @@ internal class TokenRequestValidator : ITokenRequestValidator return Valid(); } - private async Task ValidateExtensionGrantRequestAsync(NameValueCollection parameters) + private async Task ValidateExtensionGrantRequestAsync(NameValueCollection parameters, Ct ct) { _logger.LogDebug("Start validation of custom grant token request"); @@ -1031,7 +1031,7 @@ internal class TokenRequestValidator : ITokenRequestValidator ///////////////////////////////////////////// // check if client is allowed to request scopes ///////////////////////////////////////////// - var scopeError = await ValidateRequestedScopesAndResourcesAsync(parameters); + var scopeError = await ValidateRequestedScopesAndResourcesAsync(parameters, ct); if (scopeError != null) { return Invalid(scopeError); @@ -1040,7 +1040,7 @@ internal class TokenRequestValidator : ITokenRequestValidator ///////////////////////////////////////////// // validate custom grant type ///////////////////////////////////////////// - var result = await _extensionGrantValidator.ValidateAsync(_validatedRequest); + var result = await _extensionGrantValidator.ValidateAsync(_validatedRequest, ct); if (result == null) { @@ -1072,7 +1072,7 @@ internal class TokenRequestValidator : ITokenRequestValidator _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.ExtensionGrantValidation); - await _profile.IsActiveAsync(isActiveCtx); + await _profile.IsActiveAsync(isActiveCtx, ct); if (isActiveCtx.IsActive == false) { @@ -1091,7 +1091,7 @@ internal class TokenRequestValidator : ITokenRequestValidator // todo: do we want to rework the semantics of these ignore params? // also seems like other workflows other than CC clients can omit scopes? - private async Task ValidateRequestedScopesAndResourcesAsync(NameValueCollection parameters, bool ignoreImplicitIdentityScopes = false, bool ignoreImplicitOfflineAccess = false) + private async Task ValidateRequestedScopesAndResourcesAsync(NameValueCollection parameters, Ct ct, bool ignoreImplicitIdentityScopes = false, bool ignoreImplicitOfflineAccess = false) { var scopes = parameters.Get(OidcConstants.TokenRequest.Scope); if (scopes.IsMissing()) @@ -1104,12 +1104,12 @@ internal class TokenRequestValidator : ITokenRequestValidator var clientAllowedScopes = new List(); if (!ignoreImplicitIdentityScopes) { - var resources = await _resourceStore.FindResourcesByScopeAsync(_validatedRequest.Client.AllowedScopes); + var resources = await _resourceStore.FindResourcesByScopeAsync(_validatedRequest.Client.AllowedScopes, ct); clientAllowedScopes.AddRange(resources.ToScopeNames().Where(x => _validatedRequest.Client.AllowedScopes.Contains(x))); } else { - var apiScopes = await _resourceStore.FindApiScopesByNameAsync(_validatedRequest.Client.AllowedScopes); + var apiScopes = await _resourceStore.FindApiScopesByNameAsync(_validatedRequest.Client.AllowedScopes, ct); clientAllowedScopes.AddRange(apiScopes.Select(x => x.Name)); } @@ -1155,7 +1155,7 @@ internal class TokenRequestValidator : ITokenRequestValidator Client = _validatedRequest.Client, Scopes = requestedScopes, ResourceIndicators = resourceIndicators, - }); + }, ct); if (!resourceValidationResult.Succeeded) { @@ -1278,15 +1278,15 @@ internal class TokenRequestValidator : ITokenRequestValidator private void LogSuccess() => LogWithRequestDetails(LogLevel.Information, "Token request validation success"); - private Task RaiseSuccessfulResourceOwnerAuthenticationEventAsync(string userName, string subjectId, string clientId) + private Task RaiseSuccessfulResourceOwnerAuthenticationEventAsync(string userName, string subjectId, string clientId, Ct ct) { Telemetry.Metrics.ResourceOwnerAuthentication(clientId); - return _events.RaiseAsync(new UserLoginSuccessEvent(userName, subjectId, null, interactive: false, clientId)); + return _events.RaiseAsync(new UserLoginSuccessEvent(userName, subjectId, null, interactive: false, clientId), ct); } - private Task RaiseFailedResourceOwnerAuthenticationEventAsync(string userName, string error, string clientId) + private Task RaiseFailedResourceOwnerAuthenticationEventAsync(string userName, string error, string clientId, Ct ct) { Telemetry.Metrics.ResourceOwnerAuthenticationFailure(clientId, error); - return _events.RaiseAsync(new UserLoginFailureEvent(userName, error, interactive: false, clientId: clientId)); + return _events.RaiseAsync(new UserLoginFailureEvent(userName, error, interactive: false, clientId: clientId), ct); } } diff --git a/identity-server/src/IdentityServer/Validation/Default/TokenRevocationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/TokenRevocationRequestValidator.cs index 2b0beb10a..253a1e7b0 100644 --- a/identity-server/src/IdentityServer/Validation/Default/TokenRevocationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/TokenRevocationRequestValidator.cs @@ -35,7 +35,9 @@ internal class TokenRevocationRequestValidator : ITokenRevocationRequestValidato /// or /// client /// - public Task ValidateRequestAsync(NameValueCollection parameters, Client client) + /// The cancellation token. + /// + public Task ValidateRequestAsync(NameValueCollection parameters, Client client, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenRevocationRequestValidator.ValidateRequest"); diff --git a/identity-server/src/IdentityServer/Validation/Default/TokenValidator.cs b/identity-server/src/IdentityServer/Validation/Default/TokenValidator.cs index dadd6689e..325aa831f 100644 --- a/identity-server/src/IdentityServer/Validation/Default/TokenValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/TokenValidator.cs @@ -58,8 +58,7 @@ internal class TokenValidator : ITokenValidator _log = new TokenValidationLog(); } - public async Task ValidateIdentityTokenAsync(string token, string clientId = null, - bool validateLifetime = true) + public async Task ValidateIdentityTokenAsync(string token, string clientId, bool validateLifetime, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenValidator.ValidateIdentityToken"); @@ -85,7 +84,7 @@ internal class TokenValidator : ITokenValidator _log.ClientId = clientId; _log.ValidateLifetime = validateLifetime; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, ct); if (client == null) { _logger.LogError("Unknown or disabled client: {clientId}.", clientId); @@ -95,8 +94,8 @@ internal class TokenValidator : ITokenValidator _log.ClientName = client.ClientName; _logger.LogDebug("Client found: {clientId} / {clientName}", client.ClientId, client.ClientName); - var keys = await _keys.GetValidationKeysAsync(); - var result = await ValidateJwtAsync(token, keys, audience: clientId, validateLifetime: validateLifetime); + var keys = await _keys.GetValidationKeysAsync(ct); + var result = await ValidateJwtAsync(token, keys, ct, validateLifetime: validateLifetime, audience: clientId); result.Client = client; @@ -107,7 +106,7 @@ internal class TokenValidator : ITokenValidator } _logger.LogDebug("Calling into custom token validator: {type}", _customValidator.GetType().FullName); - var customResult = await _customValidator.ValidateIdentityTokenAsync(result); + var customResult = await _customValidator.ValidateIdentityTokenAsync(result, ct); if (customResult.IsError) { @@ -121,7 +120,7 @@ internal class TokenValidator : ITokenValidator return customResult; } - public async Task ValidateAccessTokenAsync(string token, string expectedScope = null) + public async Task ValidateAccessTokenAsync(string token, string expectedScope, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenValidator.ValidateAccessToken"); @@ -149,7 +148,8 @@ internal class TokenValidator : ITokenValidator _log.AccessTokenType = AccessTokenType.Jwt.ToString(); result = await ValidateJwtAsync( token, - await _keys.GetValidationKeysAsync()); + await _keys.GetValidationKeysAsync(ct), + ct); } else { @@ -166,7 +166,7 @@ internal class TokenValidator : ITokenValidator } _log.AccessTokenType = AccessTokenType.Reference.ToString(); - result = await ValidateReferenceAccessTokenAsync(token); + result = await ValidateReferenceAccessTokenAsync(token, ct); } _log.Claims = result.Claims.ToClaimsDictionary(); @@ -180,7 +180,7 @@ internal class TokenValidator : ITokenValidator var clientClaim = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.ClientId); if (clientClaim != null) { - var client = await _clients.FindEnabledClientByIdAsync(clientClaim.Value); + var client = await _clients.FindEnabledClientByIdAsync(clientClaim.Value, ct); if (client == null) { _logger.LogError("Client deleted or disabled: {clientId}", clientClaim.Value); @@ -207,7 +207,7 @@ internal class TokenValidator : ITokenValidator var isActiveCtx = new IsActiveContext(principal, result.Client, IdentityServerConstants.ProfileIsActiveCallers.AccessTokenValidation); - await _profile.IsActiveAsync(isActiveCtx); + await _profile.IsActiveAsync(isActiveCtx, ct); if (isActiveCtx.IsActive == false) { @@ -230,7 +230,7 @@ internal class TokenValidator : ITokenValidator SessionId = sid, Client = result.Client, Type = SessionValidationType.AccessToken - }); + }, ct); if (!sessionResult) { @@ -253,7 +253,7 @@ internal class TokenValidator : ITokenValidator } _logger.LogDebug("Calling into custom token validator: {type}", _customValidator.GetType().FullName); - var customResult = await _customValidator.ValidateAccessTokenAsync(result); + var customResult = await _customValidator.ValidateAccessTokenAsync(result, ct); if (customResult.IsError) { @@ -269,7 +269,7 @@ internal class TokenValidator : ITokenValidator } private async Task ValidateJwtAsync(string jwtString, - IEnumerable validationKeys, bool validateLifetime = true, string audience = null) + IEnumerable validationKeys, Ct ct, bool validateLifetime = true, string audience = null) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenValidator.ValidateJwt"); @@ -277,7 +277,7 @@ internal class TokenValidator : ITokenValidator var parameters = new TokenValidationParameters { - ValidIssuer = await _issuerNameService.GetCurrentAsync(), + ValidIssuer = await _issuerNameService.GetCurrentAsync(ct), IssuerSigningKeys = validationKeys.Select(k => k.Key), ValidateLifetime = validateLifetime, ClockSkew = _options.JwtValidationClockSkew @@ -331,7 +331,7 @@ internal class TokenValidator : ITokenValidator var clientId = id.FindFirst(JwtClaimTypes.ClientId); if (clientId != null) { - client = await _clients.FindEnabledClientByIdAsync(clientId.Value); + client = await _clients.FindEnabledClientByIdAsync(clientId.Value, ct); if (client == null) { LogError($"Client deleted or disabled: {clientId}"); @@ -366,12 +366,12 @@ internal class TokenValidator : ITokenValidator }; } - private async Task ValidateReferenceAccessTokenAsync(string tokenHandle) + private async Task ValidateReferenceAccessTokenAsync(string tokenHandle, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("TokenValidator.ValidateReferenceAccessToken"); _log.TokenHandle = tokenHandle; - var token = await _referenceTokenStore.GetReferenceTokenAsync(tokenHandle); + var token = await _referenceTokenStore.GetReferenceTokenAsync(tokenHandle, ct); if (token == null) { @@ -383,7 +383,7 @@ internal class TokenValidator : ITokenValidator { LogError("Token expired."); - await _referenceTokenStore.RemoveReferenceTokenAsync(tokenHandle); + await _referenceTokenStore.RemoveReferenceTokenAsync(tokenHandle, ct); return Invalid(OidcConstants.ProtectedResourceErrors.ExpiredToken); } @@ -391,7 +391,7 @@ internal class TokenValidator : ITokenValidator Client client = null; if (token.ClientId != null) { - client = await _clients.FindEnabledClientByIdAsync(token.ClientId); + client = await _clients.FindEnabledClientByIdAsync(token.ClientId, ct); } if (client == null) diff --git a/identity-server/src/IdentityServer/Validation/Default/UserInfoRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/UserInfoRequestValidator.cs index b9d514ace..4911d31ce 100644 --- a/identity-server/src/IdentityServer/Validation/Default/UserInfoRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/UserInfoRequestValidator.cs @@ -46,16 +46,18 @@ internal class UserInfoRequestValidator : IUserInfoRequestValidator /// Validates a userinfo request. /// /// The access token. + /// The cancellation token. /// /// - public async Task ValidateRequestAsync(string accessToken) + public async Task ValidateRequestAsync(string accessToken, Ct ct) { using var activity = Tracing.BasicActivitySource.StartActivity("UserInfoRequestValidator.ValidateRequest"); // the access token needs to be valid and have at least the openid scope var tokenResult = await _tokenValidator.ValidateAccessTokenAsync( accessToken, - IdentityServerConstants.StandardScopes.OpenId); + IdentityServerConstants.StandardScopes.OpenId, + ct); if (tokenResult.IsError) { @@ -93,7 +95,7 @@ internal class UserInfoRequestValidator : IUserInfoRequestValidator { SubjectId = subClaim.Value, SessionId = sid, - }); + }, ct); if (sessions.Count == 1) { @@ -113,7 +115,7 @@ internal class UserInfoRequestValidator : IUserInfoRequestValidator // make sure user is still active var isActiveContext = new IsActiveContext(subject, tokenResult.Client!, IdentityServerConstants.ProfileIsActiveCallers.UserInfoRequestValidation); - await _profile.IsActiveAsync(isActiveContext); + await _profile.IsActiveAsync(isActiveContext, ct); if (isActiveContext.IsActive == false) { diff --git a/identity-server/src/IdentityServer/Validation/Default/X509NameSecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/X509NameSecretValidator.cs index 816ab9f55..29ec423c7 100644 --- a/identity-server/src/IdentityServer/Validation/Default/X509NameSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/X509NameSecretValidator.cs @@ -23,7 +23,8 @@ public class X509NameSecretValidator : ISecretValidator public X509NameSecretValidator(ILogger logger) => _logger = logger; /// - public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret) + /// + public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct) { var fail = Task.FromResult(new SecretValidationResult { Success = false }); diff --git a/identity-server/src/IdentityServer/Validation/Default/X509ThumbprintSecretValidator.cs b/identity-server/src/IdentityServer/Validation/Default/X509ThumbprintSecretValidator.cs index 518e21e22..9d772e338 100644 --- a/identity-server/src/IdentityServer/Validation/Default/X509ThumbprintSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/X509ThumbprintSecretValidator.cs @@ -23,7 +23,8 @@ public class X509ThumbprintSecretValidator : ISecretValidator public X509ThumbprintSecretValidator(ILogger logger) => _logger = logger; /// - public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret) + /// + public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct) { var fail = Task.FromResult(new SecretValidationResult { Success = false }); diff --git a/identity-server/src/IdentityServer/Validation/IApiSecretValidator.cs b/identity-server/src/IdentityServer/Validation/IApiSecretValidator.cs index 7d48d5e2e..478995c5d 100644 --- a/identity-server/src/IdentityServer/Validation/IApiSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IApiSecretValidator.cs @@ -17,6 +17,7 @@ public interface IApiSecretValidator /// Tries to authenticate an API client based on the incoming request /// /// The context. + /// The cancellation token. /// - Task ValidateAsync(HttpContext context); + Task ValidateAsync(HttpContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IAuthorizeRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IAuthorizeRequestValidator.cs index 77ae6e3fe..a47f73a9e 100644 --- a/identity-server/src/IdentityServer/Validation/IAuthorizeRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IAuthorizeRequestValidator.cs @@ -1,6 +1,7 @@ // Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. +#nullable enable using System.Collections.Specialized; using System.Security.Claims; @@ -16,8 +17,9 @@ public interface IAuthorizeRequestValidator /// Validates authorize request parameters. /// /// + /// The cancellation token. /// /// /// - Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject = null, AuthorizeRequestType authorizeRequestType = AuthorizeRequestType.Authorize); + Task ValidateAsync(NameValueCollection parameters, Ct ct, ClaimsPrincipal? subject = null, AuthorizeRequestType authorizeRequestType = AuthorizeRequestType.Authorize); } diff --git a/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestIdValidator.cs b/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestIdValidator.cs index 8ffea7182..3d1ee893e 100644 --- a/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestIdValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestIdValidator.cs @@ -13,6 +13,7 @@ public interface IBackchannelAuthenticationRequestIdValidator /// Validates the authentication request id. /// /// The context. + /// The cancellation token. /// - Task ValidateAsync(BackchannelAuthenticationRequestIdValidationContext context); + Task ValidateAsync(BackchannelAuthenticationRequestIdValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestValidator.cs index 7688127fa..e78fb38b0 100644 --- a/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationRequestValidator.cs @@ -16,6 +16,7 @@ public interface IBackchannelAuthenticationRequestValidator /// /// The parameters. /// The client validation result. + /// The cancellation token. /// - Task ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult); + Task ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationUserValidator.cs b/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationUserValidator.cs index de8c4cce6..063fc5aaa 100644 --- a/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationUserValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IBackchannelAuthenticationUserValidator.cs @@ -15,6 +15,7 @@ public interface IBackchannelAuthenticationUserValidator /// Validates the user. /// /// + /// The cancellation token. /// - Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext); + Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IClientConfigurationValidator.cs b/identity-server/src/IdentityServer/Validation/IClientConfigurationValidator.cs index f5be628f5..3d1d659f7 100644 --- a/identity-server/src/IdentityServer/Validation/IClientConfigurationValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IClientConfigurationValidator.cs @@ -15,6 +15,7 @@ public interface IClientConfigurationValidator /// Determines whether the configuration of a client is valid. /// /// The context. + /// The cancellation token. /// - Task ValidateAsync(ClientConfigurationValidationContext context); + Task ValidateAsync(ClientConfigurationValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IClientSecretValidator.cs b/identity-server/src/IdentityServer/Validation/IClientSecretValidator.cs index de57e7239..68bc0312f 100644 --- a/identity-server/src/IdentityServer/Validation/IClientSecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IClientSecretValidator.cs @@ -17,6 +17,7 @@ public interface IClientSecretValidator /// Tries to authenticate a client based on the incoming request /// /// The context. + /// The cancellation token. /// - Task ValidateAsync(HttpContext context); + Task ValidateAsync(HttpContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ICustomAuthorizeRequestValidator.cs b/identity-server/src/IdentityServer/Validation/ICustomAuthorizeRequestValidator.cs index 8d4231b47..0f85d2509 100644 --- a/identity-server/src/IdentityServer/Validation/ICustomAuthorizeRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ICustomAuthorizeRequestValidator.cs @@ -15,5 +15,6 @@ public interface ICustomAuthorizeRequestValidator /// Custom validation logic for the authorize request. /// /// The context. - Task ValidateAsync(CustomAuthorizeRequestValidationContext context); + /// The cancellation token. + Task ValidateAsync(CustomAuthorizeRequestValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ICustomBackchannelAuthenticationValidator.cs b/identity-server/src/IdentityServer/Validation/ICustomBackchannelAuthenticationValidator.cs index a488d4fc2..99ea761de 100644 --- a/identity-server/src/IdentityServer/Validation/ICustomBackchannelAuthenticationValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ICustomBackchannelAuthenticationValidator.cs @@ -13,6 +13,7 @@ public interface ICustomBackchannelAuthenticationValidator /// Validates a CIBA authentication request. /// /// + /// The cancellation token. /// - Task ValidateAsync(CustomBackchannelAuthenticationRequestValidationContext customValidationContext); + Task ValidateAsync(CustomBackchannelAuthenticationRequestValidationContext customValidationContext, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ICustomTokenRequestValidator.cs b/identity-server/src/IdentityServer/Validation/ICustomTokenRequestValidator.cs index bf6c98dd6..3eff10abb 100644 --- a/identity-server/src/IdentityServer/Validation/ICustomTokenRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ICustomTokenRequestValidator.cs @@ -15,8 +15,9 @@ public interface ICustomTokenRequestValidator /// Custom validation logic for a token request. /// /// The context. + /// The cancellation token. /// /// The validation result /// - Task ValidateAsync(CustomTokenRequestValidationContext context); + Task ValidateAsync(CustomTokenRequestValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ICustomTokenValidator.cs b/identity-server/src/IdentityServer/Validation/ICustomTokenValidator.cs index 981217f56..413e1372a 100644 --- a/identity-server/src/IdentityServer/Validation/ICustomTokenValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ICustomTokenValidator.cs @@ -15,13 +15,15 @@ public interface ICustomTokenValidator /// Custom validation logic for access tokens. /// /// The validation result so far. + /// The cancellation token. /// The validation result - Task ValidateAccessTokenAsync(TokenValidationResult result); + Task ValidateAccessTokenAsync(TokenValidationResult result, Ct ct); /// /// Custom validation logic for identity tokens. /// /// The validation result so far. + /// The cancellation token. /// The validation result - Task ValidateIdentityTokenAsync(TokenValidationResult result); + Task ValidateIdentityTokenAsync(TokenValidationResult result, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IDPoPProofValidator.cs b/identity-server/src/IdentityServer/Validation/IDPoPProofValidator.cs index d0ed27327..12749d1fb 100644 --- a/identity-server/src/IdentityServer/Validation/IDPoPProofValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IDPoPProofValidator.cs @@ -14,5 +14,7 @@ public interface IDPoPProofValidator /// /// Validates the DPoP proof. /// - Task ValidateAsync(DPoPProofValidatonContext context); + /// The validation context. + /// The cancellation token. + Task ValidateAsync(DPoPProofValidatonContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IDeviceAuthorizationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IDeviceAuthorizationRequestValidator.cs index af47fbd32..8c7076618 100644 --- a/identity-server/src/IdentityServer/Validation/IDeviceAuthorizationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IDeviceAuthorizationRequestValidator.cs @@ -16,6 +16,7 @@ public interface IDeviceAuthorizationRequestValidator /// /// /// + /// The cancellation token. /// - Task ValidateAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult); + Task ValidateAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IDeviceCodeValidator.cs b/identity-server/src/IdentityServer/Validation/IDeviceCodeValidator.cs index 8e1a5dc1d..1b23102c7 100644 --- a/identity-server/src/IdentityServer/Validation/IDeviceCodeValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IDeviceCodeValidator.cs @@ -13,6 +13,7 @@ public interface IDeviceCodeValidator /// Validates the device code. /// /// The context. + /// The cancellation token. /// - Task ValidateAsync(DeviceCodeValidationContext context); + Task ValidateAsync(DeviceCodeValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IEndSessionRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IEndSessionRequestValidator.cs index 7ed751334..dab994f09 100644 --- a/identity-server/src/IdentityServer/Validation/IEndSessionRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IEndSessionRequestValidator.cs @@ -19,13 +19,15 @@ public interface IEndSessionRequestValidator /// /// /// + /// The cancellation token. /// - Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject); + Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject, Ct ct); /// /// Validates requests from logout page iframe to trigger single signout. /// /// + /// The cancellation token. /// - Task ValidateCallbackAsync(NameValueCollection parameters); + Task ValidateCallbackAsync(NameValueCollection parameters, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IExtensionGrantValidator.cs b/identity-server/src/IdentityServer/Validation/IExtensionGrantValidator.cs index bf5ffaba6..e8ca2c189 100644 --- a/identity-server/src/IdentityServer/Validation/IExtensionGrantValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IExtensionGrantValidator.cs @@ -15,10 +15,11 @@ public interface IExtensionGrantValidator /// Validates the custom grant request. /// /// The context. + /// The cancellation token. /// /// A principal /// - Task ValidateAsync(ExtensionGrantValidationContext context); + Task ValidateAsync(ExtensionGrantValidationContext context, Ct ct); /// /// Returns the grant type this validator can deal with diff --git a/identity-server/src/IdentityServer/Validation/IIdentityProviderConfigurationValidator.cs b/identity-server/src/IdentityServer/Validation/IIdentityProviderConfigurationValidator.cs index f2cd693b0..a0c4e2f4e 100644 --- a/identity-server/src/IdentityServer/Validation/IIdentityProviderConfigurationValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IIdentityProviderConfigurationValidator.cs @@ -15,6 +15,7 @@ public interface IIdentityProviderConfigurationValidator /// Determines whether the configuration of an identity provider is valid. /// /// The context. + /// The cancellation token. /// - Task ValidateAsync(IdentityProviderConfigurationValidationContext context); + Task ValidateAsync(IdentityProviderConfigurationValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IIntrospectionRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IIntrospectionRequestValidator.cs index 3cca78f9c..a05414dab 100644 --- a/identity-server/src/IdentityServer/Validation/IIntrospectionRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IIntrospectionRequestValidator.cs @@ -12,5 +12,5 @@ public interface IIntrospectionRequestValidator /// /// Validates the request. /// - Task ValidateAsync(IntrospectionRequestValidationContext context); + Task ValidateAsync(IntrospectionRequestValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IIssuerPathValidator.cs b/identity-server/src/IdentityServer/Validation/IIssuerPathValidator.cs index a4ba4172a..e62f21032 100644 --- a/identity-server/src/IdentityServer/Validation/IIssuerPathValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IIssuerPathValidator.cs @@ -9,6 +9,7 @@ public interface IIssuerPathValidator /// Validates that the path is valid for issuer URIs used. /// /// A path component of a URI to validate against the issuer for the current request. + /// The cancellation token. /// True if the path component is valid in for the issuer in the context of the current request. - Task ValidateAsync(string path); + Task ValidateAsync(string path, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IJwtRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IJwtRequestValidator.cs index bd4fbcfd3..ebfccdcb7 100644 --- a/identity-server/src/IdentityServer/Validation/IJwtRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IJwtRequestValidator.cs @@ -14,5 +14,7 @@ public interface IJwtRequestValidator /// /// Validates a JWT request object /// - Task ValidateAsync(JwtRequestValidationContext context); + /// The validation context. + /// The cancellation token. + Task ValidateAsync(JwtRequestValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IPushedAuthorizationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IPushedAuthorizationRequestValidator.cs index cef624396..e34d19c8a 100644 --- a/identity-server/src/IdentityServer/Validation/IPushedAuthorizationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IPushedAuthorizationRequestValidator.cs @@ -20,8 +20,9 @@ public interface IPushedAuthorizationRequestValidator /// Validates the pushed authorization request. /// /// The validation context + /// The cancellation token. /// A task containing a pushed authorization result that either /// wraps the validated request values or indicates the error code and /// description. - Task ValidateAsync(PushedAuthorizationRequestValidationContext context); + Task ValidateAsync(PushedAuthorizationRequestValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IRedirectUriValidator.cs b/identity-server/src/IdentityServer/Validation/IRedirectUriValidator.cs index 312445f31..e9bd7124c 100644 --- a/identity-server/src/IdentityServer/Validation/IRedirectUriValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IRedirectUriValidator.cs @@ -27,7 +27,9 @@ public interface IRedirectUriValidator /// /// Determines whether a redirect URI is valid for a client. /// - Task IsRedirectUriValidAsync(RedirectUriValidationContext context) + /// The validation context. + /// The cancellation token. + Task IsRedirectUriValidAsync(RedirectUriValidationContext context, Ct ct) #pragma warning disable CS0618 // Type or member is obsolete => IsRedirectUriValidAsync(context.RequestedUri, context.Client); #pragma warning restore CS0618 // Type or member is obsolete @@ -37,8 +39,9 @@ public interface IRedirectUriValidator /// /// The requested URI. /// The client. + /// The cancellation token. /// true is the URI is valid; false otherwise. - Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client); + Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client, Ct ct); } /// diff --git a/identity-server/src/IdentityServer/Validation/IRequestObjectValidator.cs b/identity-server/src/IdentityServer/Validation/IRequestObjectValidator.cs index 28496aeaa..ff6656b8d 100644 --- a/identity-server/src/IdentityServer/Validation/IRequestObjectValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IRequestObjectValidator.cs @@ -6,7 +6,7 @@ namespace Duende.IdentityServer.Validation; internal interface IRequestObjectValidator { - Task LoadRequestObjectAsync(ValidatedAuthorizeRequest request); - Task ValidatePushedAuthorizationRequest(ValidatedAuthorizeRequest request); - Task ValidateRequestObjectAsync(ValidatedAuthorizeRequest request); + Task LoadRequestObjectAsync(ValidatedAuthorizeRequest request, Ct ct); + Task ValidatePushedAuthorizationRequest(ValidatedAuthorizeRequest request, Ct ct); + Task ValidateRequestObjectAsync(ValidatedAuthorizeRequest request, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IResourceOwnerPasswordValidator.cs b/identity-server/src/IdentityServer/Validation/IResourceOwnerPasswordValidator.cs index bb9a6d239..3816b66e9 100644 --- a/identity-server/src/IdentityServer/Validation/IResourceOwnerPasswordValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IResourceOwnerPasswordValidator.cs @@ -15,5 +15,6 @@ public interface IResourceOwnerPasswordValidator /// Validates the resource owner password credential /// /// The context. - Task ValidateAsync(ResourceOwnerPasswordValidationContext context); + /// The cancellation token. + Task ValidateAsync(ResourceOwnerPasswordValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IResourceValidator.cs b/identity-server/src/IdentityServer/Validation/IResourceValidator.cs index c79ab3a42..4c3ba66f6 100644 --- a/identity-server/src/IdentityServer/Validation/IResourceValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IResourceValidator.cs @@ -16,5 +16,7 @@ public interface IResourceValidator /// /// Validates the requested resources for the client. /// - Task ValidateRequestedResourcesAsync(ResourceValidationRequest request); + /// The resource validation request. + /// The cancellation token. + Task ValidateRequestedResourcesAsync(ResourceValidationRequest request, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ISecretParser.cs b/identity-server/src/IdentityServer/Validation/ISecretParser.cs index 8a5abedd0..f39c3bf12 100644 --- a/identity-server/src/IdentityServer/Validation/ISecretParser.cs +++ b/identity-server/src/IdentityServer/Validation/ISecretParser.cs @@ -18,10 +18,11 @@ public interface ISecretParser /// Tries to find a secret on the context that can be used for authentication /// /// The HTTP context. + /// The cancellation token. /// /// A parsed secret /// - Task ParseAsync(HttpContext context); + Task ParseAsync(HttpContext context, Ct ct); /// /// Returns the authentication method name that this parser implements diff --git a/identity-server/src/IdentityServer/Validation/ISecretValidator.cs b/identity-server/src/IdentityServer/Validation/ISecretValidator.cs index 8822ac07b..ffc32e3ef 100644 --- a/identity-server/src/IdentityServer/Validation/ISecretValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ISecretValidator.cs @@ -18,6 +18,7 @@ public interface ISecretValidator /// /// The stored secrets. /// The received secret. + /// The cancellation token. /// A validation result - Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret); + Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ISecretsListParser.cs b/identity-server/src/IdentityServer/Validation/ISecretsListParser.cs index f6adf3463..14f7da130 100644 --- a/identity-server/src/IdentityServer/Validation/ISecretsListParser.cs +++ b/identity-server/src/IdentityServer/Validation/ISecretsListParser.cs @@ -18,10 +18,11 @@ public interface ISecretsListParser /// Tries to find the best secret on the context that can be used for authentication /// /// The HTTP context. + /// The cancellation token. /// /// A parsed secret /// - Task ParseAsync(HttpContext context); + Task ParseAsync(HttpContext context, Ct ct); /// /// Gets all available authentication methods. diff --git a/identity-server/src/IdentityServer/Validation/ISecretsListValidator.cs b/identity-server/src/IdentityServer/Validation/ISecretsListValidator.cs index 806e698ce..7ca568529 100644 --- a/identity-server/src/IdentityServer/Validation/ISecretsListValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ISecretsListValidator.cs @@ -18,6 +18,7 @@ public interface ISecretsListValidator /// /// The stored secrets. /// The received secret. + /// The cancellation token. /// A validation result - Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret); + Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ITokenRequestValidator.cs b/identity-server/src/IdentityServer/Validation/ITokenRequestValidator.cs index 766dfc72e..d28e86118 100644 --- a/identity-server/src/IdentityServer/Validation/ITokenRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ITokenRequestValidator.cs @@ -12,5 +12,5 @@ public interface ITokenRequestValidator /// /// Validates the request. /// - Task ValidateRequestAsync(TokenRequestValidationContext context); + Task ValidateRequestAsync(TokenRequestValidationContext context, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ITokenRevocationRequestValidator.cs b/identity-server/src/IdentityServer/Validation/ITokenRevocationRequestValidator.cs index 59e11e8e6..3f9b7b8ec 100644 --- a/identity-server/src/IdentityServer/Validation/ITokenRevocationRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ITokenRevocationRequestValidator.cs @@ -17,6 +17,7 @@ public interface ITokenRevocationRequestValidator /// /// The parameters. /// The client. + /// The cancellation token. /// - Task ValidateRequestAsync(NameValueCollection parameters, Client client); + Task ValidateRequestAsync(NameValueCollection parameters, Client client, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/ITokenValidator.cs b/identity-server/src/IdentityServer/Validation/ITokenValidator.cs index e64eabd6c..ad08f0a8e 100644 --- a/identity-server/src/IdentityServer/Validation/ITokenValidator.cs +++ b/identity-server/src/IdentityServer/Validation/ITokenValidator.cs @@ -14,8 +14,9 @@ public interface ITokenValidator /// /// The access token. /// The expected scope. + /// The cancellation token. /// - Task ValidateAccessTokenAsync(string token, string expectedScope = null); + Task ValidateAccessTokenAsync(string token, string expectedScope, Ct ct); /// /// Validates an identity token. @@ -23,6 +24,7 @@ public interface ITokenValidator /// The token. /// The client identifier. /// if set to true the lifetime gets validated. Otherwise not. + /// The cancellation token. /// - Task ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true); + Task ValidateIdentityTokenAsync(string token, string clientId, bool validateLifetime, Ct ct); } diff --git a/identity-server/src/IdentityServer/Validation/IUserInfoRequestValidator.cs b/identity-server/src/IdentityServer/Validation/IUserInfoRequestValidator.cs index 29460b470..4fbc15b9b 100644 --- a/identity-server/src/IdentityServer/Validation/IUserInfoRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/IUserInfoRequestValidator.cs @@ -13,6 +13,7 @@ public interface IUserInfoRequestValidator /// Validates a userinfo request. /// /// The access token. + /// The cancellation token. /// - Task ValidateRequestAsync(string accessToken); + Task ValidateRequestAsync(string accessToken, Ct ct); } diff --git a/identity-server/src/Storage/Services/ICancellationTokenProvider.cs b/identity-server/src/Storage/Services/ICancellationTokenProvider.cs deleted file mode 100644 index adcbd3166..000000000 --- a/identity-server/src/Storage/Services/ICancellationTokenProvider.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Duende Software. All rights reserved. -// See LICENSE in the project root for license information. - - -#nullable enable - -namespace Duende.IdentityServer.Services; - -/// -/// Service to provide CancellationToken for async operations. -/// -public interface ICancellationTokenProvider -{ - /// - /// Returns the current CancellationToken, or null if none present. - /// - CT CancellationToken { get; } -} diff --git a/identity-server/src/Storage/Services/ICorsPolicyService.cs b/identity-server/src/Storage/Services/ICorsPolicyService.cs index 57b263c4b..f9a72b7f0 100644 --- a/identity-server/src/Storage/Services/ICorsPolicyService.cs +++ b/identity-server/src/Storage/Services/ICorsPolicyService.cs @@ -15,6 +15,7 @@ public interface ICorsPolicyService /// Determines whether origin is allowed. /// /// The origin. + /// The cancellation token. /// - Task IsOriginAllowedAsync(string origin); + Task IsOriginAllowedAsync(string origin, Ct ct); } diff --git a/identity-server/src/Storage/Services/NoneCancellationTokenProvider.cs b/identity-server/src/Storage/Services/NoneCancellationTokenProvider.cs deleted file mode 100644 index db480ae91..000000000 --- a/identity-server/src/Storage/Services/NoneCancellationTokenProvider.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Duende Software. All rights reserved. -// See LICENSE in the project root for license information. - - -namespace Duende.IdentityServer.Services; - -/// -/// Implementation of ICancellationTokenProvider that returns CancellationToken.None -/// -public class NoneCancellationTokenProvider : ICancellationTokenProvider -{ - /// - public CT CancellationToken => CT.None; -} diff --git a/identity-server/src/Storage/Stores/IAuthorizationCodeStore.cs b/identity-server/src/Storage/Stores/IAuthorizationCodeStore.cs index 877d9c29f..d87de7787 100644 --- a/identity-server/src/Storage/Stores/IAuthorizationCodeStore.cs +++ b/identity-server/src/Storage/Stores/IAuthorizationCodeStore.cs @@ -17,20 +17,23 @@ public interface IAuthorizationCodeStore /// Stores the authorization code. /// /// The code. + /// The cancellation token. /// - Task StoreAuthorizationCodeAsync(AuthorizationCode code); + Task StoreAuthorizationCodeAsync(AuthorizationCode code, Ct ct); /// /// Gets the authorization code. /// /// The code. + /// The cancellation token. /// - Task GetAuthorizationCodeAsync(string code); + Task GetAuthorizationCodeAsync(string code, Ct ct); /// /// Removes the authorization code. /// /// The code. + /// The cancellation token. /// - Task RemoveAuthorizationCodeAsync(string code); + Task RemoveAuthorizationCodeAsync(string code, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IBackChannelAuthenticationRequestStore.cs b/identity-server/src/Storage/Stores/IBackChannelAuthenticationRequestStore.cs index 0ae64aeda..1805939cc 100644 --- a/identity-server/src/Storage/Stores/IBackChannelAuthenticationRequestStore.cs +++ b/identity-server/src/Storage/Stores/IBackChannelAuthenticationRequestStore.cs @@ -16,30 +16,44 @@ public interface IBackChannelAuthenticationRequestStore /// /// Creates the request. /// - Task CreateRequestAsync(BackChannelAuthenticationRequest request); + /// The request. + /// The cancellation token. + Task CreateRequestAsync(BackChannelAuthenticationRequest request, Ct ct); /// /// Gets the requests. /// - Task> GetLoginsForUserAsync(string subjectId, string? clientId = null); + /// The subject identifier. + /// The cancellation token. + /// The client identifier. + Task> GetLoginsForUserAsync(string subjectId, Ct ct, string? clientId = null); /// /// Gets the request. /// - Task GetByAuthenticationRequestIdAsync(string requestId); + /// The request identifier. + /// The cancellation token. + Task GetByAuthenticationRequestIdAsync(string requestId, Ct ct); /// /// Gets the request. /// - Task GetByInternalIdAsync(string id); + /// The internal identifier. + /// The cancellation token. + Task GetByInternalIdAsync(string id, Ct ct); /// /// Removes the request. /// - Task RemoveByInternalIdAsync(string id); + /// The internal identifier. + /// The cancellation token. + Task RemoveByInternalIdAsync(string id, Ct ct); /// /// Updates the request. /// - Task UpdateByInternalIdAsync(string id, BackChannelAuthenticationRequest request); + /// The internal identifier. + /// The request. + /// The cancellation token. + Task UpdateByInternalIdAsync(string id, BackChannelAuthenticationRequest request, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IClientStore.cs b/identity-server/src/Storage/Stores/IClientStore.cs index 0c81827b3..e01386fb7 100644 --- a/identity-server/src/Storage/Stores/IClientStore.cs +++ b/identity-server/src/Storage/Stores/IClientStore.cs @@ -16,12 +16,14 @@ public interface IClientStore /// Finds a client by id /// /// The client id + /// The cancellation token. /// The client - Task FindClientByIdAsync(string clientId); + Task FindClientByIdAsync(string clientId, Ct ct); /// /// Returns all clients for enumeration purposes (e.g., conformance assessment). /// + /// The cancellation token. /// An async enumerable of all clients. - IAsyncEnumerable GetAllClientsAsync(); + IAsyncEnumerable GetAllClientsAsync(Ct ct); } diff --git a/identity-server/src/Storage/Stores/IDeviceFlowStore.cs b/identity-server/src/Storage/Stores/IDeviceFlowStore.cs index 33c29cf29..2ff1ebac5 100644 --- a/identity-server/src/Storage/Stores/IDeviceFlowStore.cs +++ b/identity-server/src/Storage/Stores/IDeviceFlowStore.cs @@ -19,32 +19,37 @@ public interface IDeviceFlowStore /// The device code. /// The user code. /// The data. + /// The cancellation token. /// - Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data); + Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data, Ct ct); /// /// Finds device authorization by user code. /// /// The user code. + /// The cancellation token. /// - Task FindByUserCodeAsync(string userCode); + Task FindByUserCodeAsync(string userCode, Ct ct); /// /// Finds device authorization by device code. /// /// The device code. - Task FindByDeviceCodeAsync(string deviceCode); + /// The cancellation token. + Task FindByDeviceCodeAsync(string deviceCode, Ct ct); /// /// Updates device authorization, searching by user code. /// /// The user code. /// The data. - Task UpdateByUserCodeAsync(string userCode, DeviceCode data); + /// The cancellation token. + Task UpdateByUserCodeAsync(string userCode, DeviceCode data, Ct ct); /// /// Removes the device authorization, searching by device code. /// /// The device code. - Task RemoveByDeviceCodeAsync(string deviceCode); + /// The cancellation token. + Task RemoveByDeviceCodeAsync(string deviceCode, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IIdentityProviderStore.cs b/identity-server/src/Storage/Stores/IIdentityProviderStore.cs index c83a1cefe..5fedbf8bd 100644 --- a/identity-server/src/Storage/Stores/IIdentityProviderStore.cs +++ b/identity-server/src/Storage/Stores/IIdentityProviderStore.cs @@ -16,12 +16,14 @@ public interface IIdentityProviderStore /// /// Gets all identity providers name. /// - Task> GetAllSchemeNamesAsync(); + /// The cancellation token. + Task> GetAllSchemeNamesAsync(Ct ct); /// /// Gets the identity provider by scheme name. /// - /// + /// The scheme name. + /// The cancellation token. /// - Task GetBySchemeAsync(string scheme); + Task GetBySchemeAsync(string scheme, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IPersistedGrantStore.cs b/identity-server/src/Storage/Stores/IPersistedGrantStore.cs index 85513ac1d..b65f356a3 100644 --- a/identity-server/src/Storage/Stores/IPersistedGrantStore.cs +++ b/identity-server/src/Storage/Stores/IPersistedGrantStore.cs @@ -17,34 +17,39 @@ public interface IPersistedGrantStore /// Stores the grant. /// /// The grant. + /// The cancellation token. /// - Task StoreAsync(PersistedGrant grant); + Task StoreAsync(PersistedGrant grant, Ct ct); /// /// Gets the grant. /// /// The key. + /// The cancellation token. /// - Task GetAsync(string key); + Task GetAsync(string key, Ct ct); /// /// Gets all grants based on the filter. /// /// The filter. + /// The cancellation token. /// - Task> GetAllAsync(PersistedGrantFilter filter); + Task> GetAllAsync(PersistedGrantFilter filter, Ct ct); /// /// Removes the grant by key. /// /// The key. + /// The cancellation token. /// - Task RemoveAsync(string key); + Task RemoveAsync(string key, Ct ct); /// /// Removes all grants based on the filter. /// /// The filter. + /// The cancellation token. /// - Task RemoveAllAsync(PersistedGrantFilter filter); + Task RemoveAllAsync(PersistedGrantFilter filter, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IPushedAuthorizationRequestStore.cs b/identity-server/src/Storage/Stores/IPushedAuthorizationRequestStore.cs index c17f6c678..620546e18 100644 --- a/identity-server/src/Storage/Stores/IPushedAuthorizationRequestStore.cs +++ b/identity-server/src/Storage/Stores/IPushedAuthorizationRequestStore.cs @@ -18,8 +18,9 @@ public interface IPushedAuthorizationRequestStore /// Stores the pushed authorization request. /// /// The request. + /// The cancellation token. /// - Task StoreAsync(PushedAuthorizationRequest pushedAuthorizationRequest); + Task StoreAsync(PushedAuthorizationRequest pushedAuthorizationRequest, Ct ct); /// /// Consumes the pushed authorization request, indicating that it should not @@ -31,8 +32,9 @@ public interface IPushedAuthorizationRequestStore /// The hash of the reference value of the /// pushed authorization request. The reference value is the identifier /// within the request_uri parameter. + /// The cancellation token. /// - Task ConsumeByHashAsync(string referenceValueHash); + Task ConsumeByHashAsync(string referenceValueHash, Ct ct); /// /// Gets the pushed authorization request. @@ -40,8 +42,9 @@ public interface IPushedAuthorizationRequestStore /// The hash of the reference value of the /// pushed authorization request. The reference value is the identifier /// within the request_uri parameter. + /// The cancellation token. /// The pushed authorization request, or null if the request does /// not exist or was previously consumed. /// - Task GetByHashAsync(string referenceValueHash); + Task GetByHashAsync(string referenceValueHash, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IReferenceTokenStore.cs b/identity-server/src/Storage/Stores/IReferenceTokenStore.cs index 32015c398..6fcae3672 100644 --- a/identity-server/src/Storage/Stores/IReferenceTokenStore.cs +++ b/identity-server/src/Storage/Stores/IReferenceTokenStore.cs @@ -17,22 +17,25 @@ public interface IReferenceTokenStore /// Stores the reference token. /// /// The token. + /// The cancellation token. /// - Task StoreReferenceTokenAsync(Token token); + Task StoreReferenceTokenAsync(Token token, Ct ct); /// /// Gets the reference token. /// /// The handle. + /// The cancellation token. /// - Task GetReferenceTokenAsync(string handle); + Task GetReferenceTokenAsync(string handle, Ct ct); /// /// Removes the reference token. /// /// The handle. + /// The cancellation token. /// - Task RemoveReferenceTokenAsync(string handle); + Task RemoveReferenceTokenAsync(string handle, Ct ct); /// /// Removes the reference tokens. @@ -40,6 +43,7 @@ public interface IReferenceTokenStore /// The subject identifier. /// The client identifier. /// The session identifier. + /// The cancellation token. /// - Task RemoveReferenceTokensAsync(string subjectId, string clientId, string? sessionId = null); + Task RemoveReferenceTokensAsync(string subjectId, string clientId, string? sessionId, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IRefreshTokenStore.cs b/identity-server/src/Storage/Stores/IRefreshTokenStore.cs index a1d4a339c..46d967733 100644 --- a/identity-server/src/Storage/Stores/IRefreshTokenStore.cs +++ b/identity-server/src/Storage/Stores/IRefreshTokenStore.cs @@ -17,36 +17,41 @@ public interface IRefreshTokenStore /// Stores the refresh token. /// /// The refresh token. + /// The cancellation token. /// - Task StoreRefreshTokenAsync(RefreshToken refreshToken); + Task StoreRefreshTokenAsync(RefreshToken refreshToken, Ct ct); /// /// Updates the refresh token. /// /// The handle. /// The refresh token. + /// The cancellation token. /// - Task UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken); + Task UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken, Ct ct); /// /// Gets the refresh token. /// /// The refresh token handle. + /// The cancellation token. /// - Task GetRefreshTokenAsync(string refreshTokenHandle); + Task GetRefreshTokenAsync(string refreshTokenHandle, Ct ct); /// /// Removes the refresh token. /// /// The refresh token handle. + /// The cancellation token. /// - Task RemoveRefreshTokenAsync(string refreshTokenHandle); + Task RemoveRefreshTokenAsync(string refreshTokenHandle, Ct ct); /// /// Removes the refresh tokens. /// /// The subject identifier. /// The client identifier. + /// The cancellation token. /// - Task RemoveRefreshTokensAsync(string subjectId, string clientId); + Task RemoveRefreshTokensAsync(string subjectId, string clientId, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IResourceStore.cs b/identity-server/src/Storage/Stores/IResourceStore.cs index 5ad8d2b95..7e0bee35a 100644 --- a/identity-server/src/Storage/Stores/IResourceStore.cs +++ b/identity-server/src/Storage/Stores/IResourceStore.cs @@ -16,25 +16,34 @@ public interface IResourceStore /// /// Gets identity resources by scope name. /// - Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames); + /// The scope names. + /// The cancellation token. + Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct); /// /// Gets API scopes by scope name. /// - Task> FindApiScopesByNameAsync(IEnumerable scopeNames); + /// The scope names. + /// The cancellation token. + Task> FindApiScopesByNameAsync(IEnumerable scopeNames, Ct ct); /// /// Gets API resources by scope name. /// - Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames); + /// The scope names. + /// The cancellation token. + Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames, Ct ct); /// /// Gets API resources by API resource name. /// - Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames); + /// The API resource names. + /// The cancellation token. + Task> FindApiResourcesByNameAsync(IEnumerable apiResourceNames, Ct ct); /// /// Gets all resources. /// - Task GetAllResourcesAsync(); + /// The cancellation token. + Task GetAllResourcesAsync(Ct ct); } diff --git a/identity-server/src/Storage/Stores/IServerSideSessionStore.cs b/identity-server/src/Storage/Stores/IServerSideSessionStore.cs index 771310af9..3327d7b1d 100644 --- a/identity-server/src/Storage/Stores/IServerSideSessionStore.cs +++ b/identity-server/src/Storage/Stores/IServerSideSessionStore.cs @@ -16,43 +16,59 @@ public interface IServerSideSessionStore /// /// Retrieves a session /// - Task GetSessionAsync(string key, CT ct = default); + /// The session key. + /// The cancellation token. + Task GetSessionAsync(string key, Ct ct); /// /// Creates a session /// - Task CreateSessionAsync(ServerSideSession session, CT ct = default); + /// The session to create. + /// The cancellation token. + Task CreateSessionAsync(ServerSideSession session, Ct ct); /// /// Updates a session /// - Task UpdateSessionAsync(ServerSideSession session, CT ct = default); + /// The session to update. + /// The cancellation token. + Task UpdateSessionAsync(ServerSideSession session, Ct ct); /// /// Deletes a session /// - Task DeleteSessionAsync(string key, CT ct = default); + /// The session key. + /// The cancellation token. + Task DeleteSessionAsync(string key, Ct ct); /// /// Gets sessions for a specific subject id and/or session id /// - Task> GetSessionsAsync(SessionFilter filter, CT ct = default); + /// The session filter. + /// The cancellation token. + Task> GetSessionsAsync(SessionFilter filter, Ct ct); /// /// Deletes sessions for a specific subject id and/or session id /// - Task DeleteSessionsAsync(SessionFilter filter, CT ct = default); + /// The session filter. + /// The cancellation token. + Task DeleteSessionsAsync(SessionFilter filter, Ct ct); /// /// Removes and returns expired sessions /// - Task> GetAndRemoveExpiredSessionsAsync(int count, CT ct = default); + /// The maximum number of sessions to return. + /// The cancellation token. + Task> GetAndRemoveExpiredSessionsAsync(int count, Ct ct); /// /// Queries sessions based on filter /// - Task> QuerySessionsAsync(SessionQuery? filter = null, CT ct = default); + /// The cancellation token. + /// The session query filter. + Task> QuerySessionsAsync(Ct ct, SessionQuery? filter = null); } diff --git a/identity-server/src/Storage/Stores/ISigningKeyStore.cs b/identity-server/src/Storage/Stores/ISigningKeyStore.cs index 1a1107194..f20a669f8 100644 --- a/identity-server/src/Storage/Stores/ISigningKeyStore.cs +++ b/identity-server/src/Storage/Stores/ISigningKeyStore.cs @@ -16,20 +16,23 @@ public interface ISigningKeyStore /// /// Returns all the keys in storage. /// + /// The cancellation token. /// - Task> LoadKeysAsync(); + Task> LoadKeysAsync(Ct ct); /// /// Persists new key in storage. /// /// + /// The cancellation token. /// - Task StoreKeyAsync(SerializedKey key); + Task StoreKeyAsync(SerializedKey key, Ct ct); /// /// Deletes key from storage. /// /// + /// The cancellation token. /// - Task DeleteKeyAsync(string id); + Task DeleteKeyAsync(string id, Ct ct); } diff --git a/identity-server/src/Storage/Stores/IUserConsentStore.cs b/identity-server/src/Storage/Stores/IUserConsentStore.cs index 5951b11bc..974a58fc3 100644 --- a/identity-server/src/Storage/Stores/IUserConsentStore.cs +++ b/identity-server/src/Storage/Stores/IUserConsentStore.cs @@ -17,22 +17,25 @@ public interface IUserConsentStore /// Stores the user consent. /// /// The consent. + /// The cancellation token. /// - Task StoreUserConsentAsync(Consent consent); + Task StoreUserConsentAsync(Consent consent, Ct ct); /// /// Gets the user consent. /// /// The subject identifier. /// The client identifier. + /// The cancellation token. /// - Task GetUserConsentAsync(string subjectId, string clientId); + Task GetUserConsentAsync(string subjectId, string clientId, Ct ct); /// /// Removes the user consent. /// /// The subject identifier. /// The client identifier. + /// The cancellation token. /// - Task RemoveUserConsentAsync(string subjectId, string clientId); + Task RemoveUserConsentAsync(string subjectId, string clientId, Ct ct); } diff --git a/identity-server/templates/src/UI/Pages/Grants/Index.cshtml.cs b/identity-server/templates/src/UI/Pages/Grants/Index.cshtml.cs index 75e4f15bb..15ad6dd4e 100644 --- a/identity-server/templates/src/UI/Pages/Grants/Index.cshtml.cs +++ b/identity-server/templates/src/UI/Pages/Grants/Index.cshtml.cs @@ -37,7 +37,7 @@ public class Index : PageModel var list = new List(); foreach (var grant in grants) { - var client = await _clients.FindClientByIdAsync(grant.ClientId); + var client = await _clients.FindClientByIdAsync(grant.ClientId, HttpContext.RequestAborted); if (client != null) { var resources = await _resources.FindResourcesByScopeAsync(grant.Scopes); diff --git a/identity-server/test/IdentityServer.EndToEndTests/TestInfra/IdentityServerPageExtensions.cs b/identity-server/test/IdentityServer.EndToEndTests/TestInfra/IdentityServerPageExtensions.cs index c51165dd6..f66dd36c1 100644 --- a/identity-server/test/IdentityServer.EndToEndTests/TestInfra/IdentityServerPageExtensions.cs +++ b/identity-server/test/IdentityServer.EndToEndTests/TestInfra/IdentityServerPageExtensions.cs @@ -7,7 +7,7 @@ namespace Duende.IdentityServer.EndToEndTests.TestInfra; public static class IdentityServerPageExtensions { - public static async Task Login(this IPage page, string userName = "alice", string password = "alice", CancellationToken ct = default) + public static async Task Login(this IPage page, string userName = "alice", string password = "alice") { await page.GetLink("Secure").ClickAsync(); await page.GetByLabel("Username").FillAsync(userName); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ConfirmationSecretValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ConfirmationSecretValidator.cs index 03f5ffd1a..ba52842d4 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ConfirmationSecretValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ConfirmationSecretValidator.cs @@ -10,7 +10,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class ConfirmationSecretValidator : ISecretValidator { - public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret) + public Task ValidateAsync(IEnumerable secrets, ParsedSecret parsedSecret, Ct _) { if (secrets.Any()) { diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomProfileService.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomProfileService.cs index 14cf0eaea..04f3cb014 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomProfileService.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomProfileService.cs @@ -13,9 +13,9 @@ internal class CustomProfileService : TestUserProfileService public CustomProfileService(TestUserStore users, ILogger logger) : base(users, logger) { } - public override async Task GetProfileDataAsync(ProfileDataRequestContext context) + public override async Task GetProfileDataAsync(ProfileDataRequestContext context, Ct ct) { - await base.GetProfileDataAsync(context); + await base.GetProfileDataAsync(context, ct); if (context.Subject.Identity.AuthenticationType == "custom") { diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseExtensionGrantValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseExtensionGrantValidator.cs index 7f2d873d1..1cd0c9ab7 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseExtensionGrantValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseExtensionGrantValidator.cs @@ -9,7 +9,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class CustomResponseExtensionGrantValidator : IExtensionGrantValidator { - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct _) { var response = new Dictionary { diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseResourceOwnerValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseResourceOwnerValidator.cs index 3aa7e8944..79f6b06f0 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseResourceOwnerValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/CustomResponseResourceOwnerValidator.cs @@ -9,7 +9,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class CustomResponseResourceOwnerValidator : IResourceOwnerPasswordValidator { - public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) + public Task ValidateAsync(ResourceOwnerPasswordValidationContext context, Ct _) { var response = new Dictionary { diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/DynamicParameterExtensionGrantValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/DynamicParameterExtensionGrantValidator.cs index 7f7e5d1c0..54e133a02 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/DynamicParameterExtensionGrantValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/DynamicParameterExtensionGrantValidator.cs @@ -10,7 +10,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class DynamicParameterExtensionGrantValidator : IExtensionGrantValidator { - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct _) { var impersonatedClient = context.Request.Raw.Get("impersonated_client"); var lifetime = context.Request.Raw.Get("lifetime"); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator.cs index b523bca09..8db9a07c7 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator.cs @@ -10,7 +10,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class ExtensionGrantValidator : IExtensionGrantValidator { - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct _) { var credential = context.Request.Raw.Get("custom_credential"); var extraClaim = context.Request.Raw.Get("extra_claim"); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator2.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator2.cs index 518430d8c..e6f955885 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator2.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/ExtensionGrantValidator2.cs @@ -8,7 +8,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class ExtensionGrantValidator2 : IExtensionGrantValidator { - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct _) { var credential = context.Request.Raw.Get("custom_credential"); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/NoSubjectExtensionGrantValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/NoSubjectExtensionGrantValidator.cs index d43d11df0..3f090e5bd 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/NoSubjectExtensionGrantValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/NoSubjectExtensionGrantValidator.cs @@ -9,7 +9,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class NoSubjectExtensionGrantValidator : IExtensionGrantValidator { - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct _) { var credential = context.Request.Raw.Get("custom_credential"); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/TestCustomTokenRequestValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/TestCustomTokenRequestValidator.cs index f731f8b9d..8f3caf32e 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/TestCustomTokenRequestValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/TestCustomTokenRequestValidator.cs @@ -8,7 +8,7 @@ namespace Duende.IdentityServer.IntegrationTests.Clients.Setup; public class TestCustomTokenRequestValidator : ICustomTokenRequestValidator { - public Task ValidateAsync(CustomTokenRequestValidationContext context) + public Task ValidateAsync(CustomTokenRequestValidationContext context, Ct _) { context.Result.CustomResponse = new Dictionary { diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/BrowserHandler.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/BrowserHandler.cs index eb0611fa3..d13385c03 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/BrowserHandler.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/BrowserHandler.cs @@ -22,7 +22,7 @@ public class BrowserHandler : DelegatingHandler { } - protected async override Task SendAsync(HttpRequestMessage request, CT ct) + protected async override Task SendAsync(HttpRequestMessage request, Ct ct) { var response = await SendCookiesAsync(request, ct); @@ -64,7 +64,7 @@ public class BrowserHandler : DelegatingHandler } } - protected async Task SendCookiesAsync(HttpRequestMessage request, CT ct) + protected async Task SendCookiesAsync(HttpRequestMessage request, Ct ct) { if (AllowCookies) { diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs index 7931a6ec9..4b0cdada7 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs @@ -251,7 +251,7 @@ public class IdentityServerPipeline CreateAccountWasCalled = true; var interaction = ctx.RequestServices.GetRequiredService(); CreateAccountReturnUrl = ctx.Request.Query[Options.UserInteraction.CreateAccountReturnUrlParameter].FirstOrDefault(); - CreateAccountRequest = await interaction.GetAuthorizationContextAsync(CreateAccountReturnUrl); + CreateAccountRequest = await interaction.GetAuthorizationContextAsync(CreateAccountReturnUrl, ctx.RequestAborted); await IssueLoginCookie(ctx); } @@ -259,7 +259,7 @@ public class IdentityServerPipeline { var interaction = ctx.RequestServices.GetRequiredService(); LoginReturnUrl = ctx.Request.Query[Options.UserInteraction.LoginReturnUrlParameter].FirstOrDefault(); - LoginRequest = await interaction.GetAuthorizationContextAsync(LoginReturnUrl); + LoginRequest = await interaction.GetAuthorizationContextAsync(LoginReturnUrl, ctx.RequestAborted); } private async Task IssueLoginCookie(HttpContext ctx) @@ -290,7 +290,7 @@ public class IdentityServerPipeline private async Task ReadLogoutRequest(HttpContext ctx) { var interaction = ctx.RequestServices.GetRequiredService(); - LogoutRequest = await interaction.GetLogoutContextAsync(ctx.Request.Query["logoutId"].FirstOrDefault()); + LogoutRequest = await interaction.GetLogoutContextAsync(ctx.Request.Query["logoutId"].FirstOrDefault(), ctx.RequestAborted); } public bool ConsentWasCalled { get; set; } @@ -306,14 +306,14 @@ public class IdentityServerPipeline private async Task ReadConsentMessage(HttpContext ctx) { var interaction = ctx.RequestServices.GetRequiredService(); - ConsentRequest = await interaction.GetAuthorizationContextAsync(ctx.Request.Query["returnUrl"].FirstOrDefault()); + ConsentRequest = await interaction.GetAuthorizationContextAsync(ctx.Request.Query["returnUrl"].FirstOrDefault(), ctx.RequestAborted); } private async Task CreateConsentResponse(HttpContext ctx) { if (ConsentRequest != null && ConsentResponse != null) { var interaction = ctx.RequestServices.GetRequiredService(); - await interaction.GrantConsentAsync(ConsentRequest, ConsentResponse); + await interaction.GrantConsentAsync(ConsentRequest, ConsentResponse, ctx.RequestAborted); ConsentResponse = null; var url = ctx.Request.Query[Options.UserInteraction.ConsentReturnUrlParameter].FirstOrDefault(); @@ -331,7 +331,7 @@ public class IdentityServerPipeline { CustomWasCalled = true; var interaction = ctx.RequestServices.GetRequiredService(); - CustomRequest = await interaction.GetAuthorizationContextAsync(ctx.Request.Query[Options.UserInteraction.ConsentReturnUrlParameter].FirstOrDefault()); + CustomRequest = await interaction.GetAuthorizationContextAsync(ctx.Request.Query[Options.UserInteraction.ConsentReturnUrlParameter].FirstOrDefault(), ctx.RequestAborted); } public bool ErrorWasCalled { get; set; } @@ -347,7 +347,7 @@ public class IdentityServerPipeline private async Task ReadErrorMessage(HttpContext ctx) { var interaction = ctx.RequestServices.GetRequiredService(); - ErrorMessage = await interaction.GetErrorContextAsync(ctx.Request.Query["errorId"].FirstOrDefault()); + ErrorMessage = await interaction.GetErrorContextAsync(ctx.Request.Query["errorId"].FirstOrDefault(), ctx.RequestAborted); } /* helpers */ @@ -602,7 +602,7 @@ public class MockMessageHandler : DelegatingHandler public Func OnInvoke { get; set; } public HttpResponseMessage Response { get; set; } = new HttpResponseMessage(HttpStatusCode.OK); - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct _) { InvokeWasCalled = true; diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MessageHandlerWrapper.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MessageHandlerWrapper.cs index bb2df1fd8..96484e5cf 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MessageHandlerWrapper.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MessageHandlerWrapper.cs @@ -13,7 +13,7 @@ public class MessageHandlerWrapper : DelegatingHandler { } - protected async override Task SendAsync(HttpRequestMessage request, CT ct) + protected async override Task SendAsync(HttpRequestMessage request, Ct ct) { Response = await base.SendAsync(request, ct); return Response; diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCancellationTokenProvider.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MockCancellationTokenProvider.cs deleted file mode 100644 index 71b3e24f6..000000000 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCancellationTokenProvider.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Duende Software. All rights reserved. -// See LICENSE in the project root for license information. - - -using Duende.IdentityServer.Services; - -namespace Duende.IdentityServer.IntegrationTests.Common; - -public class MockCancellationTokenProvider : ICancellationTokenProvider -{ - public CancellationToken CancellationToken => CancellationToken.None; -} diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserNotificationService.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserNotificationService.cs index 2c9851f66..4fd29ac03 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserNotificationService.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserNotificationService.cs @@ -11,7 +11,7 @@ internal class MockCibaUserNotificationService : IBackchannelAuthenticationUserN { public BackchannelUserLoginRequest LoginRequest { get; set; } - public Task SendLoginRequestAsync(BackchannelUserLoginRequest request) + public Task SendLoginRequestAsync(BackchannelUserLoginRequest request, Ct _) { LoginRequest = request; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserValidator.cs index 880a24c32..907323cb4 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MockCibaUserValidator.cs @@ -11,7 +11,7 @@ internal class MockCibaUserValidator : IBackchannelAuthenticationUserValidator public BackchannelAuthenticationUserValidationResult Result { get; set; } = new BackchannelAuthenticationUserValidationResult(); public BackchannelAuthenticationUserValidatorContext UserValidatorContext { get; set; } - public Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext) + public Task ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext, Ct _) { UserValidatorContext = userValidatorContext; return Task.FromResult(Result); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCustomBackchannelAuthenticationValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MockCustomBackchannelAuthenticationValidator.cs index 07e0d609b..357fd44c1 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MockCustomBackchannelAuthenticationValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MockCustomBackchannelAuthenticationValidator.cs @@ -16,7 +16,7 @@ internal class MockCustomBackchannelAuthenticationValidator : ICustomBackchannel /// public Action Thunk { get; set; } = delegate { }; - public Task ValidateAsync(CustomBackchannelAuthenticationRequestValidationContext customValidationContext) + public Task ValidateAsync(CustomBackchannelAuthenticationRequestValidationContext customValidationContext, Ct _) { Thunk(customValidationContext); Context = customValidationContext; diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MockResourceValidator.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MockResourceValidator.cs index 3ea0603c2..125b0b21b 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MockResourceValidator.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MockResourceValidator.cs @@ -12,5 +12,5 @@ internal class MockResourceValidator : IResourceValidator public Task> ParseRequestedScopesAsync(IEnumerable scopeValues) => Task.FromResult(scopeValues.Select(x => new ParsedScopeValue(x))); - public Task ValidateRequestedResourcesAsync(ResourceValidationRequest request) => Task.FromResult(Result); + public Task ValidateRequestedResourcesAsync(ResourceValidationRequest request, Ct _) => Task.FromResult(Result); } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsMessageHandler.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsMessageHandler.cs index 3cf03e47e..77c2abbe3 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsMessageHandler.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsMessageHandler.cs @@ -16,7 +16,7 @@ public class MtlsMessageHandler : DelegatingHandler public MtlsMessageHandler(HttpMessageHandler innerHandler, X509Certificate2 clientCertificate) : base(innerHandler) => _clientCertificate = clientCertificate; - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct ct) { // Add the client certificate as a base64 encoded header for the test middleware to pick up if (_clientCertificate != null) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsTestMiddleware.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsTestMiddleware.cs index c42a94fd2..dcd2a10dd 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsTestMiddleware.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsTestMiddleware.cs @@ -71,6 +71,6 @@ public class TlsConnectionFeature : ITlsConnectionFeature { public X509Certificate2 ClientCertificate { get; set; } - public Task GetClientCertificateAsync(CT ct) + public Task GetClientCertificateAsync(Ct _) => Task.FromResult(ClientCertificate); } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/NetworkHandler.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/NetworkHandler.cs index 54765cb85..e85d63ae7 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/NetworkHandler.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/NetworkHandler.cs @@ -56,7 +56,7 @@ public class NetworkHandler : HttpMessageHandler public NetworkHandler(Func action) => _action = action; - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct _) { Request = request; Body = await SafeReadContentFrom(request); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Configuration/DynamicClientRegistrationTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Configuration/DynamicClientRegistrationTests.cs index 54995bd0f..d4f18d00c 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Configuration/DynamicClientRegistrationTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Configuration/DynamicClientRegistrationTests.cs @@ -11,6 +11,7 @@ namespace Duende.IdentityServer.IntegrationTests.Configuration; public class DynamicClientRegistrationTests : ConfigurationIntegrationTestBase { + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] public async Task valid_request_creates_new_client() { @@ -29,7 +30,7 @@ public class DynamicClientRegistrationTests : ConfigurationIntegrationTestBase var response = await httpResponse.Content.ReadFromJsonAsync(); response.ShouldNotBeNull(); - var newClient = await IdentityServerHost.GetClientAsync(response!.ClientId); // Not null already asserted + var newClient = await IdentityServerHost.GetClientAsync(response!.ClientId, _ct); // Not null already asserted newClient.ShouldNotBeNull(); newClient.ClientId.ShouldBe(response.ClientId); newClient.AllowedGrantTypes.ShouldBe(request.GrantTypes); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs index 42dc08769..592883ef5 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs @@ -1702,7 +1702,7 @@ public class MockAuthzInteractionService : IAuthorizeInteractionResponseGenerato public InteractionResponse Response { get; set; } = new InteractionResponse(); public ValidatedAuthorizeRequest Request { get; internal set; } - public Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null) + public Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent, Ct _) { Request = request; return Task.FromResult(Response); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs index dc0bc847e..c36fc4c11 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs @@ -22,6 +22,7 @@ public class ConsentTests private const string Category = "Authorize and consent tests"; private IdentityServerPipeline _mockPipeline = new IdentityServerPipeline(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public ConsentTests() { @@ -392,7 +393,7 @@ public class ConsentTests ConsumedTime = null, Data = serialized }; - await persistedGrantStore.StoreAsync(legacyConsent); + await persistedGrantStore.StoreAsync(legacyConsent, _ct); // Create a session cookie await _mockPipeline.LoginAsync("bob"); @@ -417,7 +418,7 @@ public class ConsentTests // The legacy consent should be migrated to use a new key... // Old key shouldn't find anything - var grant = await persistedGrantStore.GetAsync(legacyKey); + var grant = await persistedGrantStore.GetAsync(legacyKey, _ct); grant.ShouldBeNull(); // New key should @@ -427,7 +428,7 @@ public class ConsentTests var bytes = Encoding.UTF8.GetBytes(hexEncodedKeyNoHash); var hash = sha.ComputeHash(bytes); var hexEncodedKey = BitConverter.ToString(hash).Replace("-", ""); - grant = await persistedGrantStore.GetAsync(hexEncodedKey); + grant = await persistedGrantStore.GetAsync(hexEncodedKey, _ct); grant.ShouldNotBeNull(); grant.ClientId.ShouldBe(clientId); grant.SubjectId.ShouldBe(subjectId); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs index 557909451..385d991f4 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs @@ -21,6 +21,8 @@ public class CibaTests { private const string Category = "Backchannel Authentication (CIBA) endpoint"; + private readonly Ct _ct = TestContext.Current.CancellationToken; + private IdentityServerPipeline _mockPipeline = new(); private MockCibaUserValidator _mockCibaUserValidator = new(); private MockCibaUserNotificationService _mockCibaUserNotificationService = new(); @@ -1513,7 +1515,7 @@ public class CibaTests var id_token = await tokenService.IssueJwtAsync(600, new Claim[] { new Claim("sub", _user.SubjectId), new Claim("aud", _cibaClient.ClientId), - }); + }, _ct); var bindingMessage = Guid.NewGuid().ToString("n"); var body = new Dictionary diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs index 89a811adc..4d488c798 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs @@ -19,6 +19,7 @@ namespace Duende.IdentityServer.IntegrationTests.Endpoints.Token; public class CibaTokenEndpointTests { private const string Category = "CIBA Token endpoint"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IdentityServerPipeline _mockPipeline = new IdentityServerPipeline(); private MockCibaUserValidator _mockCibaUserValidator = new MockCibaUserValidator(); @@ -146,7 +147,7 @@ public class CibaTokenEndpointTests // user auth/consent var cibaService = _mockPipeline.Resolve(); - var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId); + var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId, _ct); await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(_mockCibaUserNotificationService.LoginRequest.InternalId) { ScopesValuesConsented = request.ValidatedResources.RawScopeValues, @@ -156,7 +157,7 @@ public class CibaTokenEndpointTests IdentityProvider = IdentityServerConstants.LocalIdentityProvider, } .CreatePrincipal() - }); + }, _ct); // token request @@ -253,7 +254,7 @@ public class CibaTokenEndpointTests // user auth/consent var cibaService = _mockPipeline.Resolve(); - var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId); + var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId, _ct); await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(_mockCibaUserNotificationService.LoginRequest.InternalId) { ScopesValuesConsented = request.ValidatedResources.RawScopeValues, @@ -263,7 +264,7 @@ public class CibaTokenEndpointTests IdentityProvider = IdentityServerConstants.LocalIdentityProvider, } .CreatePrincipal() - }); + }, _ct); // token request @@ -316,7 +317,7 @@ public class CibaTokenEndpointTests // user auth/consent var cibaService = _mockPipeline.Resolve(); - var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId); + var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId, _ct); await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(_mockCibaUserNotificationService.LoginRequest.InternalId) { ScopesValuesConsented = request.ValidatedResources.RawScopeValues, @@ -326,7 +327,7 @@ public class CibaTokenEndpointTests IdentityProvider = IdentityServerConstants.LocalIdentityProvider, } .CreatePrincipal() - }); + }, _ct); // token request @@ -379,7 +380,7 @@ public class CibaTokenEndpointTests // user auth/consent var cibaService = _mockPipeline.Resolve(); - var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId); + var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId, _ct); await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(_mockCibaUserNotificationService.LoginRequest.InternalId) { //ScopesValuesConsented = request.ValidatedResources.RawScopeValues, // none to deny @@ -389,7 +390,7 @@ public class CibaTokenEndpointTests IdentityProvider = IdentityServerConstants.LocalIdentityProvider, } .CreatePrincipal() - }); + }, _ct); // token request @@ -442,7 +443,7 @@ public class CibaTokenEndpointTests // user auth/consent var cibaService = _mockPipeline.Resolve(); - var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId); + var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId, _ct); await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(_mockCibaUserNotificationService.LoginRequest.InternalId) { ScopesValuesConsented = request.ValidatedResources.RawScopeValues, @@ -452,7 +453,7 @@ public class CibaTokenEndpointTests IdentityProvider = IdentityServerConstants.LocalIdentityProvider, } .CreatePrincipal() - }); + }, _ct); // token request @@ -511,7 +512,7 @@ public class CibaTokenEndpointTests // user auth/consent var cibaService = _mockPipeline.Resolve(); - var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId); + var request = await cibaService.GetLoginRequestByInternalIdAsync(_mockCibaUserNotificationService.LoginRequest.InternalId, _ct); await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(_mockCibaUserNotificationService.LoginRequest.InternalId) { ScopesValuesConsented = request.ValidatedResources.RawScopeValues, @@ -521,7 +522,7 @@ public class CibaTokenEndpointTests IdentityProvider = IdentityServerConstants.LocalIdentityProvider, } .CreatePrincipal() - }); + }, _ct); // token request diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/EntityFrameworkBasedLogoutTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/EntityFrameworkBasedLogoutTests.cs index 59bc1285c..11017a549 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/EntityFrameworkBasedLogoutTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/EntityFrameworkBasedLogoutTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.IntegrationTests.Common; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; + using Duende.IdentityServer.Services.KeyManagement; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Test; @@ -21,6 +21,7 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework; public class EntityFrameworkBasedLogoutTests { private readonly IdentityServerPipeline _mockPipeline = new(); + private readonly Ct _ct = TestContext.Current.CancellationToken; private static readonly ICollection _clients = [ @@ -79,8 +80,7 @@ public class EntityFrameworkBasedLogoutTests _mockPipeline.OnPostConfigureServices += services => { //Override the default developer signing key store and signing credential store with the EF based implementations to repo bug specific to concurrent access to an EF db context - services.AddSingleton(new SigningKeyStore(context, new NullLogger(), - new NoneCancellationTokenProvider())); + services.AddSingleton(new SigningKeyStore(context, new NullLogger())); services.Replace(ServiceDescriptor.Singleton()); }; _mockPipeline.Initialize(); @@ -103,7 +103,7 @@ public class EntityFrameworkBasedLogoutTests //Clear cache to simulate needing to load from db when creating logout notifications to send var signingKeyStoreCache = _mockPipeline.Resolve(); - await signingKeyStoreCache.StoreKeysAsync([], TimeSpan.Zero); + await signingKeyStoreCache.StoreKeysAsync([], TimeSpan.Zero, _ct); await _mockPipeline.LogoutAsync(); diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/NetworkDelaySimulationInterceptor.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/NetworkDelaySimulationInterceptor.cs index 91418b041..c304479c8 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/NetworkDelaySimulationInterceptor.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/NetworkDelaySimulationInterceptor.cs @@ -12,7 +12,7 @@ public class NetworkDelaySimulationInterceptor(TimeSpan delay) : DbCommandInterc DbCommand command, CommandEventData eventData, InterceptionResult result, - CT ct = default) + Ct ct = default) { await Task.Delay(delay, ct); return result; diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Services/CorsPolicyServiceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Services/CorsPolicyServiceTests.cs index fe34b208a..89de36239 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Services/CorsPolicyServiceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Services/CorsPolicyServiceTests.cs @@ -7,7 +7,6 @@ using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Services; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; @@ -15,6 +14,8 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework.Services; public class CorsPolicyServiceTests : IntegrationTest { + private readonly Ct _ct = TestContext.Current.CancellationToken; + public CorsPolicyServiceTests(DatabaseProviderFixture fixture) : base(fixture) { foreach (var options in TestDatabaseProviders) @@ -49,8 +50,8 @@ public class CorsPolicyServiceTests : IntegrationTest(), new NoneCancellationTokenProvider()); - result = await service.IsOriginAllowedAsync(testCorsOrigin); + var service = new CorsPolicyService(context, new NullLogger()); + result = await service.IsOriginAllowedAsync(testCorsOrigin, _ct); } result.ShouldBeTrue(); @@ -73,8 +74,8 @@ public class CorsPolicyServiceTests : IntegrationTest(), new NoneCancellationTokenProvider()); - result = await service.IsOriginAllowedAsync("InvalidOrigin"); + var service = new CorsPolicyService(context, new NullLogger()); + result = await service.IsOriginAllowedAsync("InvalidOrigin", _ct); } result.ShouldBeFalse(); diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/MockOperationalStoreNotification.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/MockOperationalStoreNotification.cs index b9bd35bd3..546283840 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/MockOperationalStoreNotification.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/MockOperationalStoreNotification.cs @@ -15,14 +15,14 @@ public class MockOperationalStoreNotification : IOperationalStoreNotification public Action> OnPersistedGrantsRemoved = _ => { }; public Action> OnDeviceFlowCodesRemoved = _ => { }; - public Task PersistedGrantsRemovedAsync(IEnumerable persistedGrants, CT ct = default) + public Task PersistedGrantsRemovedAsync(IEnumerable persistedGrants, Ct _) { OnPersistedGrantsRemoved(persistedGrants); PersistedGrantNotifications.Add(persistedGrants); return Task.CompletedTask; } - public Task DeviceCodesRemovedAsync(IEnumerable deviceCodes, CT ct = default) + public Task DeviceCodesRemovedAsync(IEnumerable deviceCodes, Ct _) { OnDeviceFlowCodesRemoved(deviceCodes); DeviceFlowCodeNotifications.Append(deviceCodes); diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ClientStoreTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ClientStoreTests.cs index e3761b506..a4a1484d2 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ClientStoreTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ClientStoreTests.cs @@ -7,7 +7,6 @@ using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; using Xunit.Sdk; @@ -16,6 +15,8 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework.Storage.Stores; public class ClientStoreTests : IntegrationTest { + private readonly Ct _ct = TestContext.Current.CancellationToken; + public ClientStoreTests(DatabaseProviderFixture fixture) : base(fixture) { foreach (var options in TestDatabaseProviders) @@ -29,8 +30,8 @@ public class ClientStoreTests : IntegrationTest options) { await using var context = new ConfigurationDbContext(options); - var store = new ClientStore(context, new NullLogger(), new NoneCancellationTokenProvider()); - var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString()); + var store = new ClientStore(context, new NullLogger()); + var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString(), _ct); client.ShouldBeNull(); } @@ -46,14 +47,14 @@ public class ClientStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - client = await store.FindClientByIdAsync(testClient.ClientId); + var store = new ClientStore(context, new NullLogger()); + client = await store.FindClientByIdAsync(testClient.ClientId, _ct); } client.ShouldNotBeNull(); @@ -80,14 +81,14 @@ public class ClientStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - client = await store.FindClientByIdAsync(testClient.ClientId); + var store = new ClientStore(context, new NullLogger()); + client = await store.FindClientByIdAsync(testClient.ClientId, _ct); } client.ShouldSatisfyAllConditions(c => @@ -142,15 +143,15 @@ public class ClientStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new ClientStore(context, new NullLogger()); const int timeout = 5000; - var task = Task.Run(() => store.FindClientByIdAsync(testClient.ClientId)); + var task = Task.Run(() => store.FindClientByIdAsync(testClient.ClientId, _ct)); if (await Task.WhenAny(task, Task.Delay(timeout)) == task) { @@ -179,12 +180,12 @@ public class ClientStoreTests : IntegrationTest( nameof(GetAllClientsAsync_WhenNoClientsExist_ExpectEmptyCollection), StoreOptions); await using var context = new ConfigurationDbContext(freshOptions); - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(_ct); - var store = new ClientStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new ClientStore(context, new NullLogger()); var clients = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { clients.Add(client); } @@ -209,15 +210,15 @@ public class ClientStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new ClientStore(context, new NullLogger()); var clients = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { clients.Add(client); } @@ -256,10 +257,10 @@ public class ClientStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new ClientStore(context, new NullLogger()); var clients = new List(); - await foreach (var c in store.GetAllClientsAsync()) + await foreach (var c in store.GetAllClientsAsync(_ct)) { clients.Add(c); } diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/DeviceFlowStoreTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/DeviceFlowStoreTests.cs index 0f386215e..f5b20286f 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/DeviceFlowStoreTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/DeviceFlowStoreTests.cs @@ -9,7 +9,6 @@ using Duende.IdentityServer.EntityFramework.Entities; using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores.Serialization; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.InMemory.Infrastructure.Internal; @@ -19,6 +18,7 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework.Storage.Stores; public class DeviceFlowStoreTests : IntegrationTest { + private readonly Ct _ct = TestContext.Current.CancellationToken; private readonly IPersistentGrantSerializer serializer = new PersistentGrantSerializer(); public DeviceFlowStoreTests(DatabaseProviderFixture fixture) : base(fixture) @@ -44,8 +44,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + await store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -72,8 +72,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + await store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -121,13 +121,13 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); // skip odd behaviour of in-memory provider #pragma warning disable EF1001 // Internal EF Core API usage. if (options.Extensions.All(x => x.GetType() != typeof(InMemoryOptionsExtension))) { - var act = () => store.StoreDeviceAuthorizationAsync($"device_{Guid.NewGuid().ToString()}", existingUserCode, deviceCodeData); + var act = () => store.StoreDeviceAuthorizationAsync($"device_{Guid.NewGuid().ToString()}", existingUserCode, deviceCodeData, _ct); await act.ShouldThrowAsync(); } #pragma warning restore EF1001 // Internal EF Core API usage. @@ -166,13 +166,13 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); // skip odd behaviour of in-memory provider #pragma warning disable EF1001 // Internal EF Core API usage. if (options.Extensions.All(x => x.GetType() != typeof(InMemoryOptionsExtension))) { - var act = () => store.StoreDeviceAuthorizationAsync(existingDeviceCode, $"user_{Guid.NewGuid().ToString()}", deviceCodeData); + var act = () => store.StoreDeviceAuthorizationAsync(existingDeviceCode, $"user_{Guid.NewGuid().ToString()}", deviceCodeData, _ct); await act.ShouldThrowAsync(); } #pragma warning restore EF1001 // Internal EF Core API usage. @@ -214,8 +214,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - code = await store.FindByUserCodeAsync(testUserCode); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + code = await store.FindByUserCodeAsync(testUserCode, _ct); } code.ShouldSatisfyAllConditions(c => @@ -235,8 +235,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - var code = await store.FindByUserCodeAsync($"user_{Guid.NewGuid().ToString()}"); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + var code = await store.FindByUserCodeAsync($"user_{Guid.NewGuid().ToString()}", _ct); code.ShouldBeNull(); } } @@ -276,8 +276,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - code = await store.FindByDeviceCodeAsync(testDeviceCode); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + code = await store.FindByDeviceCodeAsync(testDeviceCode, _ct); } code.ShouldSatisfyAllConditions(c => @@ -296,8 +296,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - var code = await store.FindByDeviceCodeAsync($"device_{Guid.NewGuid().ToString()}"); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + var code = await store.FindByDeviceCodeAsync($"device_{Guid.NewGuid().ToString()}", _ct); code.ShouldBeNull(); } } @@ -346,8 +346,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.UpdateByUserCodeAsync(testUserCode, authorizedDeviceCode); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + await store.UpdateByUserCodeAsync(testUserCode, authorizedDeviceCode, _ct); } DeviceFlowCodes updatedCodes; @@ -409,8 +409,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.RemoveByDeviceCodeAsync(testDeviceCode); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + await store.RemoveByDeviceCodeAsync(testDeviceCode, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -423,8 +423,8 @@ public class DeviceFlowStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.RemoveByDeviceCodeAsync($"device_{Guid.NewGuid().ToString()}"); + var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), new NullLogger()); + await store.RemoveByDeviceCodeAsync($"device_{Guid.NewGuid().ToString()}", _ct); } } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/IdentityProviderStoreTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/IdentityProviderStoreTests.cs index 2b8aaaa64..641dec1e5 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/IdentityProviderStoreTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/IdentityProviderStoreTests.cs @@ -7,7 +7,6 @@ using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; @@ -15,6 +14,8 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework.Storage.Stores; public class IdentityProviderStoreTests : IntegrationTest { + private readonly Ct _ct = TestContext.Current.CancellationToken; + public IdentityProviderStoreTests(DatabaseProviderFixture fixture) : base(fixture) { foreach (var options in TestDatabaseProviders) @@ -42,8 +43,8 @@ public class IdentityProviderStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - var item = await store.GetBySchemeAsync("scheme1"); + var store = new IdentityProviderStore(context, new NullLogger()); + var item = await store.GetBySchemeAsync("scheme1", _ct); item.ShouldNotBeNull(); } @@ -66,8 +67,8 @@ public class IdentityProviderStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - var item = await store.GetBySchemeAsync("scheme2"); + var store = new IdentityProviderStore(context, new NullLogger()); + var item = await store.GetBySchemeAsync("scheme2", _ct); item.ShouldBeNull(); } @@ -89,8 +90,8 @@ public class IdentityProviderStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - var item = await store.GetBySchemeAsync("scheme3"); + var store = new IdentityProviderStore(context, new NullLogger()); + var item = await store.GetBySchemeAsync("scheme3", _ct); item.ShouldBeNull(); } diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/PersistedGrantStoreTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/PersistedGrantStoreTests.cs index 1cac84e33..fcc619f45 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/PersistedGrantStoreTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/PersistedGrantStoreTests.cs @@ -7,7 +7,6 @@ using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; @@ -16,6 +15,8 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework.Storage.Stores; public class PersistedGrantStoreTests : IntegrationTest { + private readonly Ct _ct = TestContext.Current.CancellationToken; + public PersistedGrantStoreTests(DatabaseProviderFixture fixture) : base(fixture) { foreach (var options in TestDatabaseProviders) @@ -44,8 +45,8 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.StoreAsync(persistedGrant); + var store = new PersistedGrantStore(context, new NullLogger()); + await store.StoreAsync(persistedGrant, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -69,8 +70,8 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - foundPersistedGrant = await store.GetAsync(persistedGrant.Key); + var store = new PersistedGrantStore(context, new NullLogger()); + foundPersistedGrant = await store.GetAsync(persistedGrant.Key, _ct); } foundPersistedGrant.ShouldNotBeNull(); @@ -90,8 +91,8 @@ public class PersistedGrantStoreTests : IntegrationTest foundPersistedGrants; await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); - foundPersistedGrants = (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = persistedGrant.SubjectId })).ToList(); + var store = new PersistedGrantStore(context, new NullLogger()); + foundPersistedGrants = (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = persistedGrant.SubjectId }, _ct)).ToList(); } foundPersistedGrants.ShouldNotBeNull(); @@ -119,62 +120,62 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1" - })).ToList().Count.ShouldBe(9); + }, _ct)).ToList().Count.ShouldBe(9); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub2" - })).ToList().Count.ShouldBe(0); + }, _ct)).ToList().Count.ShouldBe(0); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c1" - })).ToList().Count.ShouldBe(4); + }, _ct)).ToList().Count.ShouldBe(4); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c2" - })).ToList().Count.ShouldBe(4); + }, _ct)).ToList().Count.ShouldBe(4); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c3" - })).ToList().Count.ShouldBe(1); + }, _ct)).ToList().Count.ShouldBe(1); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c4" - })).ToList().Count.ShouldBe(0); + }, _ct)).ToList().Count.ShouldBe(0); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c1", SessionId = "s1" - })).ToList().Count.ShouldBe(2); + }, _ct)).ToList().Count.ShouldBe(2); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c3", SessionId = "s1" - })).ToList().Count.ShouldBe(0); + }, _ct)).ToList().Count.ShouldBe(0); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c1", SessionId = "s1", Type = "t1" - })).ToList().Count.ShouldBe(1); + }, _ct)).ToList().Count.ShouldBe(1); (await store.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c1", SessionId = "s1", Type = "t3" - })).ToList().Count.ShouldBe(0); + }, _ct)).ToList().Count.ShouldBe(0); } } @@ -191,8 +192,8 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.RemoveAsync(persistedGrant.Key); + var store = new PersistedGrantStore(context, new NullLogger()); + await store.RemoveAsync(persistedGrant.Key, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -215,12 +216,12 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = persistedGrant.SubjectId, ClientId = persistedGrant.ClientId - }); + }, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -243,13 +244,13 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = persistedGrant.SubjectId, ClientId = persistedGrant.ClientId, Type = persistedGrant.Type - }); + }, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -285,111 +286,111 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(1); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub2" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(10); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c1" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(6); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c2" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(6); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c3" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(9); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c4" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(10); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c1", SessionId = "s1" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(8); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "c3", SessionId = "s1" - }); + }, _ct); context.PersistedGrants.Count().ShouldBe(10); } PopulateDb(); await using (var context = new PersistedGrantDbContext(options)) { - var store = new PersistedGrantStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { @@ -397,14 +398,14 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); await store.RemoveAllAsync(new PersistedGrantFilter { @@ -412,7 +413,7 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - await store.StoreAsync(persistedGrant); + var store = new PersistedGrantStore(context, new NullLogger()); + await store.StoreAsync(persistedGrant, _ct); } await using (var context = new PersistedGrantDbContext(options)) @@ -455,9 +456,9 @@ public class PersistedGrantStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); + var store = new PersistedGrantStore(context, new NullLogger()); persistedGrant.Expiration = newDate; - await store.StoreAsync(persistedGrant); + await store.StoreAsync(persistedGrant, _ct); } await using (var context = new PersistedGrantDbContext(options)) diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ResourceStoreTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ResourceStoreTests.cs index f41e180df..1973ef439 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ResourceStoreTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/Stores/ResourceStoreTests.cs @@ -8,7 +8,6 @@ using Duende.IdentityServer.EntityFramework.Mappers; using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; -using Duende.IdentityServer.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; @@ -16,6 +15,8 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework.Storage.Stores; public class ScopeStoreTests : IntegrationTest { + private readonly Ct _ct = TestContext.Current.CancellationToken; + public ScopeStoreTests(DatabaseProviderFixture fixture) : base(fixture) { foreach (var options in TestDatabaseProviders) @@ -75,8 +76,8 @@ public class ScopeStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - foundResource = (await store.FindApiResourcesByNameAsync(new[] { resource.Name })).SingleOrDefault(); + var store = new ResourceStore(context, new NullLogger()); + foundResource = (await store.FindApiResourcesByNameAsync(new[] { resource.Name }, _ct)).SingleOrDefault(); } foundResource.ShouldNotBeNull(); @@ -104,8 +105,8 @@ public class ScopeStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - foundResource = (await store.FindApiResourcesByNameAsync(new[] { resource.Name })).SingleOrDefault(); + var store = new ResourceStore(context, new NullLogger()); + foundResource = (await store.FindApiResourcesByNameAsync(new[] { resource.Name }, _ct)).SingleOrDefault(); } foundResource.ShouldNotBeNull(); @@ -136,11 +137,11 @@ public class ScopeStoreTests : IntegrationTest resources; await using (var context = new ConfigurationDbContext(options)) { - var store = new ResourceStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new ResourceStore(context, new NullLogger()); resources = await store.FindApiResourcesByScopeNameAsync(new List { testApiScope.Name - }); + }, _ct); } resources.ShouldNotBeNull(); @@ -170,8 +171,8 @@ public class ScopeStoreTests : IntegrationTest resources; await using (var context = new ConfigurationDbContext(options)) { - var store = new ResourceStore(context, new NullLogger(), new NoneCancellationTokenProvider()); - resources = await store.FindApiResourcesByScopeNameAsync(new[] { testApiScope.Name }); + var store = new ResourceStore(context, new NullLogger()); + resources = await store.FindApiResourcesByScopeNameAsync(new[] { testApiScope.Name }, _ct); } resources.ShouldNotBeNull(); @@ -193,11 +194,11 @@ public class ScopeStoreTests : IntegrationTest resources; await using (var context = new ConfigurationDbContext(options)) { - var store = new ResourceStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new ResourceStore(context, new NullLogger()); resources = (await store.FindIdentityResourcesByScopeNameAsync(new List { resource.Name - })).ToList(); + }, _ct)).ToList(); } resources.ShouldNotBeNull(); @@ -224,11 +225,11 @@ public class ScopeStoreTests : IntegrationTest resources; await using (var context = new ConfigurationDbContext(options)) { - var store = new ResourceStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new ResourceStore(context, new NullLogger()); resources = (await store.FindIdentityResourcesByScopeNameAsync(new List { resource.Name - })).ToList(); + }, _ct)).ToList(); } resources.ShouldNotBeNull(); @@ -250,11 +251,11 @@ public class ScopeStoreTests : IntegrationTest resources; await using (var context = new ConfigurationDbContext(options)) { - var store = new ResourceStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new ResourceStore(context, new NullLogger()); resources = (await store.FindApiScopesByNameAsync(new List { resource.Name - })).ToList(); + }, _ct)).ToList(); } resources.ShouldNotBeNull(); @@ -281,11 +282,11 @@ public class ScopeStoreTests : IntegrationTest resources; await using (var context = new ConfigurationDbContext(options)) { - var store = new ResourceStore(context, new NullLogger(), new NoneCancellationTokenProvider()); + var store = new ResourceStore(context, new NullLogger()); resources = (await store.FindApiScopesByNameAsync(new List { resource.Name - })).ToList(); + }, _ct)).ToList(); } resources.ShouldNotBeNull(); @@ -328,8 +329,8 @@ public class ScopeStoreTests : IntegrationTest(), new NoneCancellationTokenProvider()); - resources = await store.GetAllResourcesAsync(); + var store = new ResourceStore(context, new NullLogger()); + resources = await store.GetAllResourcesAsync(_ct); } resources.ShouldNotBeNull(); diff --git a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/TokenCleanup/TokenCleanupTests.cs b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/TokenCleanup/TokenCleanupTests.cs index 1f63ac5cd..083353160 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/TokenCleanup/TokenCleanupTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/EntityFramework/Storage/TokenCleanup/TokenCleanupTests.cs @@ -18,6 +18,7 @@ namespace Duende.IdentityServer.IntegrationTests.EntityFramework.Storage.TokenCl public class TokenCleanupTests : IntegrationTest { + private readonly Ct _ct = TestContext.Current.CancellationToken; public TokenCleanupTests(DatabaseProviderFixture fixture) : base(fixture) { foreach (var options in TestDatabaseProviders) @@ -57,7 +58,7 @@ public class TokenCleanupTests : IntegrationTest { svcs.AddSingleton(mockNotifications); - }).CleanupGrantsAsync(); + }).CleanupGrantsAsync(_ct); // The right number of batches executed mockNotifications.PersistedGrantNotifications.Count.ShouldBe(expectedPageCount); @@ -356,7 +357,7 @@ public class TokenCleanupTests : IntegrationTest { svcs.AddSingleton(mockNotifications); - }).CleanupGrantsAsync(); + }).CleanupGrantsAsync(_ct); // Each batch created an extra grant, so we do an extra batch to clean up // the extras @@ -417,7 +418,7 @@ public class TokenCleanupTests : IntegrationTest CreateResponseAsync(ValidatedAuthorizeRequest request) + public override async Task CreateResponseAsync(ValidatedAuthorizeRequest request, Ct ct) { - var baseResponse = await base.CreateResponseAsync(request).ConfigureAwait(false); + var baseResponse = await base.CreateResponseAsync(request, ct).ConfigureAwait(false); if (!baseResponse.IsError) { baseResponse.CustomParameters.Add("custom_parameter", "custom_value"); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs index 84130fc52..3ea10bbbf 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs @@ -77,9 +77,9 @@ public class CustomClaimsService : DefaultClaimsService { } - public override async Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resourceResult, ValidatedRequest request) + public override async Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resourceResult, ValidatedRequest request, Ct ct) { - var result = (await base.GetAccessTokenClaimsAsync(subject, resourceResult, request)).ToList(); + var result = (await base.GetAccessTokenClaimsAsync(subject, resourceResult, request, ct)).ToList(); result.Add(new Claim("foo", "foo1")); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs index a95f5b739..21be2d40c 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs @@ -82,7 +82,7 @@ public class CustomProfileServiceTests public class CustomProfileService : IProfileService { - public Task GetProfileDataAsync(ProfileDataRequestContext context) + public Task GetProfileDataAsync(ProfileDataRequestContext context, Ct _) { var claims = new Claim[] { @@ -92,7 +92,7 @@ public class CustomProfileService : IProfileService return Task.CompletedTask; } - public Task IsActiveAsync(IsActiveContext context) + public Task IsActiveAsync(IsActiveContext context, Ct _) { context.IsActive = true; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs index f06a93062..9cfd423ce 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs @@ -134,7 +134,7 @@ public class StubCorePolicyProvider : ICorsPolicyService public bool Result; public bool WasCalled; - public Task IsOriginAllowedAsync(string origin) + public Task IsOriginAllowedAsync(string origin, Ct _) { WasCalled = true; return Task.FromResult(Result); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs index a91047403..6abab0300 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs @@ -19,6 +19,7 @@ namespace Duende.IdentityServer.IntegrationTests.Hosting; public class DynamicProvidersTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; private GenericHost _host; private GenericHost _idp1; private GenericHost _idp2; @@ -85,7 +86,7 @@ public class DynamicProvidersTests app.MapGet("/account/logout", async ctx => { var isis = ctx.RequestServices.GetRequiredService(); - var logoutCtx = await isis.GetLogoutContextAsync(ctx.Request.Query["logoutId"]); + var logoutCtx = await isis.GetLogoutContextAsync(ctx.Request.Query["logoutId"], ctx.RequestAborted); Idp1FrontChannelLogoutUri = logoutCtx.SignOutIFrameUrl; await ctx.SignOutAsync(); }); @@ -321,7 +322,7 @@ public class DynamicProvidersTests redirectUri.ShouldStartWith("https://server/federation/idp1/signin"); var cache = _host.Resolve>() as DefaultCache; - await cache.RemoveAsync("test"); + await cache.RemoveAsync("test", _ct); response = await _host.BrowserClient.GetAsync(redirectUri); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs index 6dadc19fd..ba3ff92fa 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs @@ -31,6 +31,7 @@ public class ServerSideSessionTests private IPersistedGrantStore _grantStore; private IRefreshTokenStore _refreshTokenStore; private IDataProtector _protector; + private readonly Ct _ct = TestContext.Current.CancellationToken; private MockServerUrls _urls = new MockServerUrls(); @@ -54,7 +55,7 @@ public class ServerSideSessionTests ctx.ShouldRenew = ShouldRenewCookie; if (ShouldRenewCookie) { - await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "bob" }); + await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct); } }; }); @@ -135,9 +136,9 @@ public class ServerSideSessionTests [Trait("Category", Category)] public async Task login_should_create_server_side_session() { - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).ShouldBeEmpty(); await _pipeline.LoginAsync("bob"); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldNotBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).ShouldNotBeEmpty(); (await IsLoggedIn()).ShouldBeTrue(); } @@ -150,7 +151,7 @@ public class ServerSideSessionTests ShouldRenewCookie = true; (await IsLoggedIn()).ShouldBeTrue(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldNotBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).ShouldNotBeEmpty(); } [Fact] @@ -159,8 +160,8 @@ public class ServerSideSessionTests { await _pipeline.LoginAsync("bob"); - await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "bob" }); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); + await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).ShouldBeEmpty(); (await IsLoggedIn()).ShouldBeFalse(); } @@ -172,7 +173,7 @@ public class ServerSideSessionTests await _pipeline.LoginAsync("bob"); await _pipeline.LogoutAsync(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).ShouldBeEmpty(); (await IsLoggedIn()).ShouldBeFalse(); } @@ -183,13 +184,13 @@ public class ServerSideSessionTests { await _pipeline.LoginAsync("bob"); - var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }); - var session = await _sessionStore.GetSessionAsync(sessions.Single().Key); + var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct); + var session = await _sessionStore.GetSessionAsync(sessions.Single().Key, _ct); session.Ticket = "invalid"; - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); (await IsLoggedIn()).ShouldBeFalse(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).ShouldBeEmpty(); } [Fact] @@ -198,12 +199,12 @@ public class ServerSideSessionTests { await _pipeline.LoginAsync("bob"); - var key = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Single().Key; + var key = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).Single().Key; await _pipeline.LoginAsync("bob"); (await IsLoggedIn()).ShouldBeTrue(); - var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }); + var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct); sessions.First().Key.ShouldBe(key); } @@ -213,13 +214,13 @@ public class ServerSideSessionTests { await _pipeline.LoginAsync("bob"); - var bob_session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Single(); + var bob_session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }, _ct)).Single(); await Task.Delay(1000); await _pipeline.LoginAsync("alice"); (await IsLoggedIn()).ShouldBeTrue(); - var alice_session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var alice_session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); alice_session.Key.ShouldBe(bob_session.Key); (alice_session.Created > bob_session.Created).ShouldBeTrue(); @@ -237,8 +238,8 @@ public class ServerSideSessionTests await _pipeline.LoginAsync("alice"); _pipeline.RemoveLoginCookie(); - var tickets = await _ticketService.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }); - var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }); + var tickets = await _ticketService.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct); + var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct); tickets.Select(x => x.SessionId).ShouldBe(sessions.Select(x => x.SessionId)); } @@ -254,9 +255,9 @@ public class ServerSideSessionTests await _pipeline.LoginAsync("bob"); _pipeline.RemoveLoginCookie(); - var tickets = await _ticketService.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); + var tickets = await _ticketService.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }, _ct); tickets.TotalCount.ShouldBe(2); - var sessions = await _sessionStore.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); + var sessions = await _sessionStore.QuerySessionsAsync(_ct, new SessionQuery { SubjectId = "alice" }); sessions.TotalCount.ShouldBe(2); tickets.ResultsToken.ShouldBe(sessions.ResultsToken); @@ -280,8 +281,8 @@ public class ServerSideSessionTests await _pipeline.LoginAsync("alice"); _pipeline.RemoveLoginCookie(); - var sessions = await _sessionMgmt.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); - var tickets = await _ticketService.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); + var sessions = await _sessionMgmt.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }, _ct); + var tickets = await _ticketService.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }, _ct); tickets.ResultsToken.ShouldBe(sessions.ResultsToken); tickets.HasPrevResults.ShouldBe(sessions.HasPrevResults); @@ -308,7 +309,7 @@ public class ServerSideSessionTests RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldNotBeEmpty(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -317,9 +318,9 @@ public class ServerSideSessionTests RevokeConsents = false, RevokeTokens = true, SendBackchannelLogoutNotification = false - }); + }, _ct); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldBeEmpty(); } [Fact] @@ -337,7 +338,7 @@ public class ServerSideSessionTests RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldNotBeEmpty(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -347,9 +348,9 @@ public class ServerSideSessionTests RevokeTokens = true, SendBackchannelLogoutNotification = false, ClientIds = new[] { "foo" } - }); + }, _ct); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldNotBeEmpty(); } [Fact] @@ -376,7 +377,7 @@ public class ServerSideSessionTests RevokeConsents = false, RevokeTokens = false, SendBackchannelLogoutNotification = true - }); + }, _ct); _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } @@ -407,7 +408,7 @@ public class ServerSideSessionTests RevokeTokens = false, SendBackchannelLogoutNotification = true, ClientIds = new List { "foo" } - }); + }, _ct); _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); } @@ -429,7 +430,7 @@ public class ServerSideSessionTests _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).ShouldNotBeEmpty(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -438,9 +439,9 @@ public class ServerSideSessionTests RevokeConsents = false, RevokeTokens = false, SendBackchannelLogoutNotification = false - }); + }, _ct); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).ShouldBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).ShouldBeEmpty(); } [Fact] @@ -471,9 +472,9 @@ public class ServerSideSessionTests }; _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); - var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); session.Expires = System.DateTime.UtcNow.AddMinutes(-1); - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); await Task.Delay(1000); @@ -510,9 +511,9 @@ public class ServerSideSessionTests }; _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); - var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); session.Expires = System.DateTime.UtcNow.AddMinutes(-1); - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); await _pipeline.RequestAuthorizationEndpointAsync("client", "code", "openid api offline_access", "https://client/callback"); @@ -534,15 +535,15 @@ public class ServerSideSessionTests RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldNotBeEmpty(); - var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); session.Expires = System.DateTime.UtcNow.AddMinutes(-1); - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); await Task.Delay(1000); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldBeEmpty(); } [Fact] @@ -560,11 +561,11 @@ public class ServerSideSessionTests RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldNotBeEmpty(); await _pipeline.LogoutAsync(); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" }, _ct)).ShouldBeEmpty(); } [Fact] @@ -582,7 +583,7 @@ public class ServerSideSessionTests RedirectUri = "https://client/callback" }); - var ticket1 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket1 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); var expiration1 = ticket1.GetExpiration(); var issued1 = ticket1.GetIssued(); @@ -596,7 +597,7 @@ public class ServerSideSessionTests RefreshToken = tokenResponse.RefreshToken }); - var ticket2 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket2 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); var expiration2 = ticket2.GetExpiration(); var issued2 = ticket2.GetIssued(); @@ -629,7 +630,7 @@ public class ServerSideSessionTests RefreshToken = tokenResponse.RefreshToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldNotContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -659,7 +660,7 @@ public class ServerSideSessionTests RefreshToken = tokenResponse.RefreshToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldNotContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -688,7 +689,7 @@ public class ServerSideSessionTests RefreshToken = tokenResponse.RefreshToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldNotContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -717,7 +718,7 @@ public class ServerSideSessionTests RefreshToken = tokenResponse.RefreshToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -737,7 +738,7 @@ public class ServerSideSessionTests RedirectUri = "https://client/callback" }); - var expiration1 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single().Expires.Value; + var expiration1 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single().Expires.Value; await _pipeline.BackChannelClient.GetUserInfoAsync(new UserInfoRequest { @@ -747,7 +748,7 @@ public class ServerSideSessionTests Token = tokenResponse.AccessToken }); - var expiration2 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single().Expires.Value; + var expiration2 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single().Expires.Value; expiration2.ShouldBeGreaterThan(expiration1); } @@ -777,7 +778,7 @@ public class ServerSideSessionTests Token = tokenResponse.AccessToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldNotContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -808,7 +809,7 @@ public class ServerSideSessionTests Token = tokenResponse.AccessToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldNotContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -838,7 +839,7 @@ public class ServerSideSessionTests Token = tokenResponse.AccessToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldNotContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -868,7 +869,7 @@ public class ServerSideSessionTests Token = tokenResponse.AccessToken }); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); ticket.Properties.Items.ShouldContainKey(IdentityServerConstants.ForceCookieRenewalFlag); } @@ -903,9 +904,9 @@ public class ServerSideSessionTests { - var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); session.Expires = null; - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); var refreshResponse = await _pipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -918,9 +919,9 @@ public class ServerSideSessionTests { - var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); session.Expires = DateTime.UtcNow.AddMinutes(-1); - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); var refreshResponse = await _pipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -933,7 +934,7 @@ public class ServerSideSessionTests { - await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "alice" }); + await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct); var refreshResponse = await _pipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -976,9 +977,9 @@ public class ServerSideSessionTests { - var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); session.Expires = null; - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); var response = await _pipeline.BackChannelClient.GetUserInfoAsync(new UserInfoRequest { @@ -992,9 +993,9 @@ public class ServerSideSessionTests { - var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); + var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single(); session.Expires = DateTime.UtcNow.AddMinutes(-1); - await _sessionStore.UpdateSessionAsync(session); + await _sessionStore.UpdateSessionAsync(session, _ct); var response = await _pipeline.BackChannelClient.GetUserInfoAsync(new UserInfoRequest { @@ -1008,7 +1009,7 @@ public class ServerSideSessionTests { - await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "alice" }); + await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct); var response = await _pipeline.BackChannelClient.GetUserInfoAsync(new UserInfoRequest { @@ -1034,7 +1035,7 @@ public class ServerSideSessionTests await _pipeline.LoginAsync(user); - var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() + var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }, _ct)).Single() .Deserialize(_protector, null); var claims = ticket.Principal.Claims; claims.ShouldContain(c => c.Issuer == "Custom Issuer" && c.Type == "Test"); diff --git a/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs b/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs index 61bfda2a0..e20a817c8 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs @@ -23,7 +23,7 @@ public class TestBrowserClient : HttpClient { } - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct ct) { CurrentUri = request.RequestUri; var cookieHeader = CookieContainer.GetCookieHeader(request.RequestUri); diff --git a/identity-server/test/IdentityServer.IntegrationTests/TestHosts/ConfigurationHost.cs b/identity-server/test/IdentityServer.IntegrationTests/TestHosts/ConfigurationHost.cs index 145a82130..ff7da4e57 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/TestHosts/ConfigurationHost.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/TestHosts/ConfigurationHost.cs @@ -6,9 +6,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Configuration.EntityFramework; using Duende.IdentityServer.EntityFramework.Options; using Duende.IdentityServer.EntityFramework.Storage; -using Duende.IdentityServer.IntegrationTests.Common; using Duende.IdentityServer.IntegrationTests.TestFramework; -using Duende.IdentityServer.Services; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; @@ -32,8 +30,6 @@ public class ConfigurationHost : GenericHost services.AddRouting(); services.AddAuthorization(); - services.AddSingleton(); - services.AddIdentityServerConfiguration(opt => { diff --git a/identity-server/test/IdentityServer.IntegrationTests/TestHosts/IdentityServerHost.cs b/identity-server/test/IdentityServer.IntegrationTests/TestHosts/IdentityServerHost.cs index ad85b1d4e..254c98d97 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/TestHosts/IdentityServerHost.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/TestHosts/IdentityServerHost.cs @@ -60,9 +60,9 @@ public class IdentityServerHost : GenericHost } - public async Task GetClientAsync(string clientId) + public async Task GetClientAsync(string clientId, Ct ct) { var store = Resolve(); - return await store.FindClientByIdAsync(clientId); + return await store.FindClientByIdAsync(clientId, ct); } } diff --git a/identity-server/test/IdentityServer.UnitTests/AspNetIdentity/DefaultSessionClaimsFilterTests.cs b/identity-server/test/IdentityServer.UnitTests/AspNetIdentity/DefaultSessionClaimsFilterTests.cs index 1303be50b..55b68e73c 100644 --- a/identity-server/test/IdentityServer.UnitTests/AspNetIdentity/DefaultSessionClaimsFilterTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/AspNetIdentity/DefaultSessionClaimsFilterTests.cs @@ -10,6 +10,8 @@ namespace IdentityServer.UnitTests.AspNetIdentity; public class DefaultSessionClaimsFilterTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + [Fact] public async Task FilterToSessionClaimsAsync_with_session_and_non_session_claims_should_filter_to_only_session_claims() { @@ -26,7 +28,7 @@ public class DefaultSessionClaimsFilterTests var filter = new DefaultSessionClaimsFilter(); var context = new SecurityStampRefreshingPrincipalContext() { NewPrincipal = newPrincipal, CurrentPrincipal = currentPrincipal }; - var result = await filter.FilterToSessionClaimsAsync(context); + var result = await filter.FilterToSessionClaimsAsync(context, _ct); var resultTypes = result.Select(c => c.Type).ToList(); resultTypes.Count.ShouldBe(3); @@ -51,7 +53,7 @@ public class DefaultSessionClaimsFilterTests var filter = new DefaultSessionClaimsFilter(); var context = new SecurityStampRefreshingPrincipalContext { NewPrincipal = newPrincipal, CurrentPrincipal = currentPrincipal }; - var result = await filter.FilterToSessionClaimsAsync(context); + var result = await filter.FilterToSessionClaimsAsync(context, _ct); result.Count.ShouldBe(3); string[] expectClaimTypes = [ @@ -75,7 +77,7 @@ public class DefaultSessionClaimsFilterTests var filter = new DefaultSessionClaimsFilter(); var context = new SecurityStampRefreshingPrincipalContext { NewPrincipal = newPrincipal, CurrentPrincipal = currentPrincipal }; - var result = await filter.FilterToSessionClaimsAsync(context); + var result = await filter.FilterToSessionClaimsAsync(context, _ct); result.ShouldBeEmpty(); } @@ -88,7 +90,7 @@ public class DefaultSessionClaimsFilterTests var filter = new DefaultSessionClaimsFilter(); var context = new SecurityStampRefreshingPrincipalContext { NewPrincipal = newPrincipal, CurrentPrincipal = currentPrincipal }; - var result = await filter.FilterToSessionClaimsAsync(context); + var result = await filter.FilterToSessionClaimsAsync(context, _ct); result.ShouldBeEmpty(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Caches/MockCache.cs b/identity-server/test/IdentityServer.UnitTests/Caches/MockCache.cs index 1a8057333..1694bce5a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Caches/MockCache.cs +++ b/identity-server/test/IdentityServer.UnitTests/Caches/MockCache.cs @@ -46,13 +46,13 @@ public class MockCache : ICache CacheItems[key] = ci; } - public Task GetAsync(string key) + public Task GetAsync(string key, Ct _) { TryGetValue(key, out var item); return Task.FromResult(item); } - public async Task GetOrAddAsync(string key, TimeSpan duration, Func> get) + public async Task GetOrAddAsync(string key, TimeSpan duration, Func> get, Ct _) { if (!TryGetValue(key, out var item)) { @@ -63,13 +63,13 @@ public class MockCache : ICache return item; } - public Task RemoveAsync(string key) + public Task RemoveAsync(string key, Ct _) { CacheItems.Remove(key); return Task.CompletedTask; } - public Task SetAsync(string key, T item, TimeSpan expiration) + public Task SetAsync(string key, T item, TimeSpan expiration, Ct _) { Add(key, item, expiration); return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs b/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs index a8e96b4f7..8b6e74927 100644 --- a/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs @@ -13,6 +13,8 @@ namespace IdentityServer.UnitTests.Caches; public class ResourceStoreCacheTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + private List _clients { get; set; } = new List(); private List _identityResources { get; set; } = new List(); private List _resources { get; set; } = new List(); @@ -55,7 +57,7 @@ public class ResourceStoreCacheTests var store = _provider.GetRequiredService(); cache.CacheItems.Count.ShouldBe(0); - var results = await store.FindIdentityResourcesByScopeNameAsync(new[] { "profile" }); + var results = await store.FindIdentityResourcesByScopeNameAsync(new[] { "profile" }, _ct); cache.CacheItems.Count.ShouldBe(1); cache.CacheItems.First().Value.Value.Name.ShouldBe("profile"); @@ -69,7 +71,7 @@ public class ResourceStoreCacheTests var store = _provider.GetRequiredService(); cache.CacheItems.Count.ShouldBe(0); - var results = await store.FindApiResourcesByScopeNameAsync(new[] { "scope1" }); + var results = await store.FindApiResourcesByScopeNameAsync(new[] { "scope1" }, _ct); cache.CacheItems.Count.ShouldBe(1); cache.CacheItems.First().Value.Value.Names.Single().ShouldBe("urn:api1"); @@ -82,7 +84,7 @@ public class ResourceStoreCacheTests var store = _provider.GetRequiredService(); cache.CacheItems.Count.ShouldBe(0); - var results = await store.FindApiScopesByNameAsync(new[] { "scope1" }); + var results = await store.FindApiScopesByNameAsync(new[] { "scope1" }, _ct); cache.CacheItems.Count.ShouldBe(1); cache.CacheItems.First().Value.Value.Name.ShouldBe("scope1"); diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockBackChannelAuthenticationRequestStore.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockBackChannelAuthenticationRequestStore.cs index f21439ee1..d4f42eb07 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockBackChannelAuthenticationRequestStore.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockBackChannelAuthenticationRequestStore.cs @@ -12,7 +12,7 @@ public class MockBackChannelAuthenticationRequestStore : IBackChannelAuthenticat { public Dictionary Items { get; set; } = new Dictionary(); - public Task CreateRequestAsync(BackChannelAuthenticationRequest request) + public Task CreateRequestAsync(BackChannelAuthenticationRequest request, Ct _) { var key = Guid.NewGuid().ToString(); request.InternalId = key.Sha256(); @@ -20,15 +20,15 @@ public class MockBackChannelAuthenticationRequestStore : IBackChannelAuthenticat return Task.FromResult(key); } - public Task GetByAuthenticationRequestIdAsync(string requestId) => Task.FromResult(Items[requestId]); + public Task GetByAuthenticationRequestIdAsync(string requestId, Ct _) => Task.FromResult(Items[requestId]); - public Task GetByInternalIdAsync(string id) + public Task GetByInternalIdAsync(string id, Ct _) { var item = Items.SingleOrDefault(x => x.Value.InternalId == id); return Task.FromResult(item.Value); } - public Task> GetLoginsForUserAsync(string subjectId, string clientId = null) + public Task> GetLoginsForUserAsync(string subjectId, Ct ct, string clientId = null) { var items = Items.Where(x => x.Value.Subject.GetSubjectId() == subjectId && (clientId == null || x.Value.ClientId == clientId) @@ -36,7 +36,7 @@ public class MockBackChannelAuthenticationRequestStore : IBackChannelAuthenticat return Task.FromResult(items.Select(x => x.Value).AsEnumerable()); } - public Task RemoveByInternalIdAsync(string id) + public Task RemoveByInternalIdAsync(string id, Ct _) { var item = Items.SingleOrDefault(x => x.Value.InternalId == id); if (item.Key != null) @@ -46,7 +46,7 @@ public class MockBackChannelAuthenticationRequestStore : IBackChannelAuthenticat return Task.CompletedTask; } - public Task UpdateByInternalIdAsync(string id, BackChannelAuthenticationRequest request) + public Task UpdateByInternalIdAsync(string id, BackChannelAuthenticationRequest request, Ct _) { var item = Items.SingleOrDefault(x => x.Value.InternalId == id); if (item.Key != null) diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockCache.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockCache.cs index 32ab51b4f..6c74dbb5f 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockCache.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockCache.cs @@ -12,30 +12,30 @@ public class MockCache : ICache public Dictionary Items { get; set; } = new Dictionary(); - public Task GetAsync(string key) + public Task GetAsync(string key, Ct _) { Items.TryGetValue(key, out var item); return Task.FromResult(item); } - public async Task GetOrAddAsync(string key, TimeSpan duration, Func> get) + public async Task GetOrAddAsync(string key, TimeSpan duration, Func> get, Ct ct) { - var item = await GetAsync(key); + var item = await GetAsync(key, ct); if (item == null) { item = await get(); - await SetAsync(key, item, duration); + await SetAsync(key, item, duration, ct); } return item; } - public Task RemoveAsync(string key) + public Task RemoveAsync(string key, Ct _) { Items.Remove(key); return Task.CompletedTask; } - public Task SetAsync(string key, T item, TimeSpan expiration) + public Task SetAsync(string key, T item, TimeSpan expiration, Ct _) { Items[key] = item; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockClaimsService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockClaimsService.cs index e76b4827d..18413c38c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockClaimsService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockClaimsService.cs @@ -13,7 +13,7 @@ internal class MockClaimsService : IClaimsService public List IdentityTokenClaims { get; set; } = new List(); public List AccessTokenClaims { get; set; } = new List(); - public Task> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, bool includeAllIdentityClaims, ValidatedRequest request) => Task.FromResult(IdentityTokenClaims.AsEnumerable()); + public Task> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, bool includeAllIdentityClaims, ValidatedRequest request, Ct _) => Task.FromResult(IdentityTokenClaims.AsEnumerable()); - public Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, ValidatedRequest request) => Task.FromResult(AccessTokenClaims.AsEnumerable()); + public Task> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, ValidatedRequest request, Ct _) => Task.FromResult(AccessTokenClaims.AsEnumerable()); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockConsentMessageStore.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockConsentMessageStore.cs index f0bf555e0..31c25eb84 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockConsentMessageStore.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockConsentMessageStore.cs @@ -11,7 +11,7 @@ public class MockConsentMessageStore : IConsentMessageStore { public Dictionary> Messages { get; set; } = new Dictionary>(); - public Task DeleteAsync(string id) + public Task DeleteAsync(string id, Ct _) { if (id != null && Messages.ContainsKey(id)) { @@ -20,7 +20,7 @@ public class MockConsentMessageStore : IConsentMessageStore return Task.CompletedTask; } - public Task> ReadAsync(string id) + public Task> ReadAsync(string id, Ct _) { Message val = null; if (id != null) @@ -30,7 +30,7 @@ public class MockConsentMessageStore : IConsentMessageStore return Task.FromResult(val); } - public Task WriteAsync(string id, Message message) + public Task WriteAsync(string id, Message message, Ct _) { Messages[id] = message; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockConsentService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockConsentService.cs index 050574704..62a410c56 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockConsentService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockConsentService.cs @@ -13,13 +13,13 @@ public class MockConsentService : IConsentService { public bool RequiresConsentResult { get; set; } - public Task RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes) => Task.FromResult(RequiresConsentResult); + public Task RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes, Ct _) => Task.FromResult(RequiresConsentResult); public ClaimsPrincipal ConsentSubject { get; set; } public Client ConsentClient { get; set; } public IEnumerable ConsentScopes { get; set; } - public Task UpdateConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes) + public Task UpdateConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable parsedScopes, Ct _) { ConsentSubject = subject; ConsentClient = client; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockEventSink.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockEventSink.cs index 370f09299..6cb62a1ea 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockEventSink.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockEventSink.cs @@ -11,7 +11,7 @@ internal class MockEventSink : IEventSink { public List Events { get; } = []; - public Task PersistAsync(Event evt) + public Task PersistAsync(Event evt, Ct _) { Events.Add(evt); return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockJwtRequestUriHttpClient.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockJwtRequestUriHttpClient.cs index 8b6938eb4..4e4dfe85d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockJwtRequestUriHttpClient.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockJwtRequestUriHttpClient.cs @@ -11,5 +11,5 @@ public class MockJwtRequestUriHttpClient : IJwtRequestUriHttpClient { public string Jwt { get; set; } - public Task GetJwtAsync(string url, Client client) => Task.FromResult(Jwt); + public Task GetJwtAsync(string url, Client client, Ct _) => Task.FromResult(Jwt); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockKeyMaterialService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockKeyMaterialService.cs index 6304189c2..b3ff7dc24 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockKeyMaterialService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockKeyMaterialService.cs @@ -13,9 +13,9 @@ internal class MockKeyMaterialService : IKeyMaterialService public List SigningCredentials = new List(); public List ValidationKeys = new List(); - public Task> GetAllSigningCredentialsAsync() => Task.FromResult(SigningCredentials.AsEnumerable()); + public Task> GetAllSigningCredentialsAsync(Ct _) => Task.FromResult(SigningCredentials.AsEnumerable()); - public Task GetSigningCredentialsAsync(IEnumerable allowedAlgorithms = null) => Task.FromResult(SigningCredentials.FirstOrDefault()); + public Task GetSigningCredentialsAsync(IEnumerable allowedAlgorithms, Ct _) => Task.FromResult(SigningCredentials.FirstOrDefault()); - public Task> GetValidationKeysAsync() => Task.FromResult(ValidationKeys.AsEnumerable()); + public Task> GetValidationKeysAsync(Ct _) => Task.FromResult(ValidationKeys.AsEnumerable()); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockLogoutNotificationService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockLogoutNotificationService.cs index 78c8f0ebb..fb3161350 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockLogoutNotificationService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockLogoutNotificationService.cs @@ -15,13 +15,13 @@ public class MockLogoutNotificationService : ILogoutNotificationService public bool SendBackChannelLogoutNotificationsCalled { get; set; } public List BackChannelLogoutRequests { get; set; } = new List(); - public Task> GetFrontChannelLogoutNotificationsUrlsAsync(LogoutNotificationContext context) + public Task> GetFrontChannelLogoutNotificationsUrlsAsync(LogoutNotificationContext context, Ct _) { GetFrontChannelLogoutNotificationsUrlsCalled = true; return Task.FromResult(FrontChannelLogoutNotificationsUrls.AsEnumerable()); } - public Task> GetBackChannelLogoutNotificationsAsync(LogoutNotificationContext context) + public Task> GetBackChannelLogoutNotificationsAsync(LogoutNotificationContext context, Ct _) { SendBackChannelLogoutNotificationsCalled = true; return Task.FromResult(BackChannelLogoutRequests.AsEnumerable()); diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockMessageStore.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockMessageStore.cs index 63fcc0367..92948ca1b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockMessageStore.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockMessageStore.cs @@ -11,7 +11,7 @@ public class MockMessageStore : IMessageStore { public Dictionary> Messages { get; set; } = new Dictionary>(); - public Task> ReadAsync(string id) + public Task> ReadAsync(string id, Ct _) { Message val = null; if (id != null) @@ -21,7 +21,7 @@ public class MockMessageStore : IMessageStore return Task.FromResult(val); } - public Task WriteAsync(Message message) + public Task WriteAsync(Message message, Ct _) { var id = Guid.NewGuid().ToString(); Messages[id] = message; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockPersistedGrantService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockPersistedGrantService.cs index cb44a970c..20a3318ba 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockPersistedGrantService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockPersistedGrantService.cs @@ -12,9 +12,9 @@ public class MockPersistedGrantService : IPersistedGrantService public IEnumerable GetAllGrantsResult { get; set; } public bool RemoveAllGrantsWasCalled { get; set; } - public Task> GetAllGrantsAsync(string subjectId) => Task.FromResult(GetAllGrantsResult ?? Enumerable.Empty()); + public Task> GetAllGrantsAsync(string subjectId, Ct _) => Task.FromResult(GetAllGrantsResult ?? Enumerable.Empty()); - public Task RemoveAllGrantsAsync(string subjectId, string clientId, string sessionId = null) + public Task RemoveAllGrantsAsync(string subjectId, Ct _, string clientId = null, string sessionId = null) { RemoveAllGrantsWasCalled = true; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockProfileService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockProfileService.cs index 48772d32e..cf9f1a968 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockProfileService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockProfileService.cs @@ -19,14 +19,14 @@ public class MockProfileService : IProfileService public bool IsActiveWasCalled => ActiveContext != null; public IsActiveContext ActiveContext { get; set; } - public Task GetProfileDataAsync(ProfileDataRequestContext context) + public Task GetProfileDataAsync(ProfileDataRequestContext context, Ct _) { ProfileContext = context; context.IssuedClaims = ProfileClaims.ToList(); return Task.CompletedTask; } - public Task IsActiveAsync(IsActiveContext context) + public Task IsActiveAsync(IsActiveContext context, Ct _) { ActiveContext = context; context.IsActive = IsActive; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockReferenceTokenStore.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockReferenceTokenStore.cs index 3579fa01d..1983b7805 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockReferenceTokenStore.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockReferenceTokenStore.cs @@ -9,11 +9,11 @@ namespace UnitTests.Common; internal class MockReferenceTokenStore : IReferenceTokenStore { - public Task GetReferenceTokenAsync(string handle) => throw new NotImplementedException(); + public Task GetReferenceTokenAsync(string handle, Ct _) => throw new NotImplementedException(); - public Task RemoveReferenceTokenAsync(string handle) => throw new NotImplementedException(); + public Task RemoveReferenceTokenAsync(string handle, Ct _) => throw new NotImplementedException(); - public Task RemoveReferenceTokensAsync(string subjectId, string clientId, string sessionId = null) => throw new NotImplementedException(); + public Task RemoveReferenceTokensAsync(string subjectId, string clientId, string sessionId, Ct _) => throw new NotImplementedException(); - public Task StoreReferenceTokenAsync(Token token) => throw new NotImplementedException(); + public Task StoreReferenceTokenAsync(Token token, Ct _) => throw new NotImplementedException(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockReplayCache.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockReplayCache.cs index 9e836947a..fd0da7b95 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockReplayCache.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockReplayCache.cs @@ -10,7 +10,7 @@ public class MockReplayCache : IReplayCache { public bool Exists { get; set; } - public Task AddAsync(string purpose, string handle, DateTimeOffset expiration) => Task.CompletedTask; + public Task AddAsync(string purpose, string handle, DateTimeOffset expiration, Ct _) => Task.CompletedTask; - public Task ExistsAsync(string purpose, string handle) => Task.FromResult(Exists); + public Task ExistsAsync(string purpose, string handle, Ct _) => Task.FromResult(Exists); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockResourceValidator.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockResourceValidator.cs index c6c01c489..b0edd35d3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockResourceValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockResourceValidator.cs @@ -12,5 +12,5 @@ internal class MockResourceValidator : IResourceValidator public Task> ParseRequestedScopesAsync(IEnumerable scopeValues) => Task.FromResult(scopeValues.Select(x => new ParsedScopeValue(x))); - public Task ValidateRequestedResourcesAsync(ResourceValidationRequest request) => Task.FromResult(Result); + public Task ValidateRequestedResourcesAsync(ResourceValidationRequest request, Ct _) => Task.FromResult(Result); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockReturnUrlParser.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockReturnUrlParser.cs index 37a42166d..3412a1822 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockReturnUrlParser.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockReturnUrlParser.cs @@ -16,7 +16,7 @@ public class MockReturnUrlParser : ReturnUrlParser { } - public override Task ParseAsync(string returnUrl) => Task.FromResult(AuthorizationRequestResult); + public override Task ParseAsync(string returnUrl, Ct _) => Task.FromResult(AuthorizationRequestResult); public override bool IsValidReturnUrl(string returnUrl) => IsValidReturnUrlResult; } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockTokenCreationService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockTokenCreationService.cs index 0dac0ddd0..fb5346077 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockTokenCreationService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockTokenCreationService.cs @@ -12,7 +12,7 @@ internal class MockTokenCreationService : ITokenCreationService public string TokenResult { get; set; } public Token Token { get; set; } - public Task CreateTokenAsync(Token token) + public Task CreateTokenAsync(Token token, Ct _) { Token = token; return Task.FromResult(TokenResult); diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockUiLocaleService.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockUiLocaleService.cs index 7c7e2d978..f82fd97e3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockUiLocaleService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockUiLocaleService.cs @@ -8,5 +8,5 @@ namespace UnitTests.Common; public class MockUiLocaleService : IUiLocalesService { - public Task StoreUiLocalesForRedirectAsync(string? uiLocales) => Task.CompletedTask; + public Task StoreUiLocalesForRedirectAsync(string? uiLocales, Ct _) => Task.CompletedTask; } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/MockUserSession.cs b/identity-server/test/IdentityServer.UnitTests/Common/MockUserSession.cs index 123a48eba..c66c01bcd 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/MockUserSession.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/MockUserSession.cs @@ -21,7 +21,7 @@ public class MockUserSession : IUserSession public AuthenticationProperties Properties { get; set; } - public Task CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties) + public Task CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties, Ct _) { CreateSessionIdWasCalled = true; User = principal; @@ -29,25 +29,25 @@ public class MockUserSession : IUserSession return Task.FromResult(SessionId); } - public Task GetUserAsync() => Task.FromResult(User); + public Task GetUserAsync(Ct _) => Task.FromResult(User); - Task IUserSession.GetSessionIdAsync() => Task.FromResult(SessionId); + Task IUserSession.GetSessionIdAsync(Ct _) => Task.FromResult(SessionId); - public Task EnsureSessionIdCookieAsync() + public Task EnsureSessionIdCookieAsync(Ct _) { EnsureSessionIdCookieWasCalled = true; return Task.CompletedTask; } - public Task RemoveSessionIdCookieAsync() + public Task RemoveSessionIdCookieAsync(Ct _) { RemoveSessionIdCookieWasCalled = true; return Task.CompletedTask; } - public Task> GetClientListAsync() => Task.FromResult>(Clients); + public Task> GetClientListAsync(Ct _) => Task.FromResult>(Clients); - public Task AddClientIdAsync(string clientId) + public Task AddClientIdAsync(string clientId, Ct _) { Clients.Add(clientId); return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/NetworkHandler.cs b/identity-server/test/IdentityServer.UnitTests/Common/NetworkHandler.cs index c2997657e..678b5bac4 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/NetworkHandler.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/NetworkHandler.cs @@ -56,7 +56,7 @@ public class NetworkHandler : HttpMessageHandler public NetworkHandler(Func action) => _action = action; - protected override async Task SendAsync(HttpRequestMessage request, CT ct) + protected override async Task SendAsync(HttpRequestMessage request, Ct _) { Request = request; Body = await SafeReadContentFrom(request); diff --git a/identity-server/test/IdentityServer.UnitTests/Common/StubAuthorizeResponseGenerator.cs b/identity-server/test/IdentityServer.UnitTests/Common/StubAuthorizeResponseGenerator.cs index 2a8496e5b..a5eebf43c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/StubAuthorizeResponseGenerator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/StubAuthorizeResponseGenerator.cs @@ -11,5 +11,5 @@ internal class StubAuthorizeResponseGenerator : IAuthorizeResponseGenerator { public AuthorizeResponse Response { get; set; } = new AuthorizeResponse(); - public Task CreateResponseAsync(ValidatedAuthorizeRequest request) => Task.FromResult(Response); + public Task CreateResponseAsync(ValidatedAuthorizeRequest request, Ct _) => Task.FromResult(Response); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/StubHandleGenerationService.cs b/identity-server/test/IdentityServer.UnitTests/Common/StubHandleGenerationService.cs index 0add75ec9..13c52ec88 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/StubHandleGenerationService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/StubHandleGenerationService.cs @@ -10,13 +10,13 @@ public class StubHandleGenerationService : DefaultHandleGenerationService, IHand { public string Handle { get; set; } - public new Task GenerateAsync(int length) + public new Task GenerateAsync(Ct ct, int length = 32) { if (Handle != null) { return Task.FromResult(Handle); } - return base.GenerateAsync(length); + return base.GenerateAsync(ct, length); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/StubSessionCoordinationService.cs b/identity-server/test/IdentityServer.UnitTests/Common/StubSessionCoordinationService.cs index 794dd55a1..483303186 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/StubSessionCoordinationService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/StubSessionCoordinationService.cs @@ -9,9 +9,9 @@ namespace UnitTests.Common; internal class StubSessionCoordinationService : ISessionCoordinationService { - public Task ProcessExpirationAsync(UserSession session) => Task.CompletedTask; + public Task ProcessExpirationAsync(UserSession session, Ct _) => Task.CompletedTask; - public Task ProcessLogoutAsync(UserSession session) => Task.CompletedTask; + public Task ProcessLogoutAsync(UserSession session, Ct _) => Task.CompletedTask; - public Task ValidateSessionAsync(SessionValidationRequest request) => Task.FromResult(true); + public Task ValidateSessionAsync(SessionValidationRequest request, Ct _) => Task.FromResult(true); } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs b/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs index b90cf64b4..af4f333cf 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs @@ -11,7 +11,7 @@ public class TestEventService : IEventService { private Dictionary _events = new Dictionary(); - public Task RaiseAsync(Event evt) + public Task RaiseAsync(Event evt, Ct _) { _events.Add(evt.GetType(), evt); return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Common/TestReplayCache.cs b/identity-server/test/IdentityServer.UnitTests/Common/TestReplayCache.cs index c3cf2f2bd..da57e2012 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/TestReplayCache.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/TestReplayCache.cs @@ -13,13 +13,13 @@ public class TestReplayCache : IReplayCache public TestReplayCache(TimeProvider clock) => _timeProvider = clock; - public Task AddAsync(string purpose, string handle, DateTimeOffset expiration) + public Task AddAsync(string purpose, string handle, DateTimeOffset expiration, Ct _) { _values[purpose + handle] = expiration; return Task.CompletedTask; } - public Task ExistsAsync(string purpose, string handle) + public Task ExistsAsync(string purpose, string handle, Ct _) { if (_values.TryGetValue(purpose + handle, out var expiration)) { diff --git a/identity-server/test/IdentityServer.UnitTests/Common/TestUserConsentStore.cs b/identity-server/test/IdentityServer.UnitTests/Common/TestUserConsentStore.cs index a8f6265e7..996b8b9c2 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/TestUserConsentStore.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/TestUserConsentStore.cs @@ -20,9 +20,9 @@ public class TestUserConsentStore : IUserConsentStore new DefaultHandleGenerationService(), TestLogger.Create()); - public Task StoreUserConsentAsync(Consent consent) => _userConsentStore.StoreUserConsentAsync(consent); + public Task StoreUserConsentAsync(Consent consent, Ct ct) => _userConsentStore.StoreUserConsentAsync(consent, ct); - public Task GetUserConsentAsync(string subjectId, string clientId) => _userConsentStore.GetUserConsentAsync(subjectId, clientId); + public Task GetUserConsentAsync(string subjectId, string clientId, Ct ct) => _userConsentStore.GetUserConsentAsync(subjectId, clientId, ct); - public Task RemoveUserConsentAsync(string subjectId, string clientId) => _userConsentStore.RemoveUserConsentAsync(subjectId, clientId); + public Task RemoveUserConsentAsync(string subjectId, string clientId, Ct ct) => _userConsentStore.RemoveUserConsentAsync(subjectId, clientId, ct); } diff --git a/identity-server/test/IdentityServer.UnitTests/Cors/MockCorsPolicyService.cs b/identity-server/test/IdentityServer.UnitTests/Cors/MockCorsPolicyService.cs index b87f62287..3021a8a63 100644 --- a/identity-server/test/IdentityServer.UnitTests/Cors/MockCorsPolicyService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Cors/MockCorsPolicyService.cs @@ -11,7 +11,7 @@ public class MockCorsPolicyService : ICorsPolicyService public bool WasCalled { get; set; } public bool Response { get; set; } - public Task IsOriginAllowedAsync(string origin) + public Task IsOriginAllowedAsync(string origin, Ct _) { WasCalled = true; return Task.FromResult(Response); diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs index 899f25d4c..047ecb325 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs @@ -50,6 +50,8 @@ public class AuthorizeEndpointBaseTests private ValidatedAuthorizeRequest _validatedAuthorizeRequest; + private readonly Ct _ct = TestContext.Current.CancellationToken; + public AuthorizeEndpointBaseTests() => Init(); [Fact] @@ -64,7 +66,7 @@ public class AuthorizeEndpointBaseTests _stubAuthorizeRequestValidator.Result.IsError = true; _stubAuthorizeRequestValidator.Result.Error = "login_required"; - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); ((AuthorizeResult)result).Response.IsError.ShouldBeTrue(); @@ -78,7 +80,7 @@ public class AuthorizeEndpointBaseTests _stubAuthorizeRequestValidator.Result.IsError = true; _stubAuthorizeRequestValidator.Result.Error = "some_error"; - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); ((AuthorizeResult)result).Response.IsError.ShouldBeTrue(); @@ -90,7 +92,7 @@ public class AuthorizeEndpointBaseTests { _stubInteractionGenerator.Response.IsConsent = true; - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); } @@ -101,7 +103,7 @@ public class AuthorizeEndpointBaseTests { _stubInteractionGenerator.Response.Error = "error"; - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); ((AuthorizeResult)result).Response.IsError.ShouldBeTrue(); @@ -116,7 +118,7 @@ public class AuthorizeEndpointBaseTests _stubInteractionGenerator.Response.Error = "error"; _stubInteractionGenerator.Response.ErrorDescription = errorDescription; - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); var authorizeResult = ((AuthorizeResult)result); @@ -130,7 +132,7 @@ public class AuthorizeEndpointBaseTests { _stubInteractionGenerator.Response.IsLogin = true; - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); } @@ -142,7 +144,7 @@ public class AuthorizeEndpointBaseTests _mockUserSession.User = _user; _stubInteractionGenerator.Response.RedirectUrl = "http://foo.com"; - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); } @@ -151,7 +153,7 @@ public class AuthorizeEndpointBaseTests [Trait("Category", Category)] public async Task successful_authorization_request_should_generate_authorize_result() { - var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); + var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user, _ct); result.ShouldBeOfType(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeInteractionResponseGenerator.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeInteractionResponseGenerator.cs index 987062915..ea300925b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeInteractionResponseGenerator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeInteractionResponseGenerator.cs @@ -12,5 +12,5 @@ internal class StubAuthorizeInteractionResponseGenerator : IAuthorizeInteraction { internal InteractionResponse Response { get; set; } = new InteractionResponse(); - public Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null) => Task.FromResult(Response); + public Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent, Ct _) => Task.FromResult(Response); } diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeRequestValidator.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeRequestValidator.cs index c4e88c481..3da7a016b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeRequestValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/StubAuthorizeRequestValidator.cs @@ -12,7 +12,7 @@ public class StubAuthorizeRequestValidator : IAuthorizeRequestValidator { public AuthorizeRequestValidationResult Result { get; set; } - public Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject = null, AuthorizeRequestType authorizeRequestType = AuthorizeRequestType.Authorize) + public Task ValidateAsync(NameValueCollection parameters, Ct ct, ClaimsPrincipal subject = null, AuthorizeRequestType authorizeRequestType = AuthorizeRequestType.Authorize) { Result.ValidatedRequest.Raw = parameters; return Task.FromResult(Result); diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubBackChannelLogoutClient.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubBackChannelLogoutClient.cs index 6d1f79068..85f0aa780 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubBackChannelLogoutClient.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubBackChannelLogoutClient.cs @@ -11,7 +11,7 @@ internal class StubBackChannelLogoutClient : IBackChannelLogoutService { public bool SendLogoutsWasCalled { get; set; } - public Task SendLogoutNotificationsAsync(LogoutNotificationContext context) + public Task SendLogoutNotificationsAsync(LogoutNotificationContext context, Ct _) { SendLogoutsWasCalled = true; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubEndSessionRequestValidator.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubEndSessionRequestValidator.cs index eaf3d6197..8358fc32c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubEndSessionRequestValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/StubEndSessionRequestValidator.cs @@ -13,7 +13,7 @@ internal class StubEndSessionRequestValidator : IEndSessionRequestValidator public EndSessionValidationResult EndSessionValidationResult { get; set; } = new EndSessionValidationResult(); public EndSessionCallbackValidationResult EndSessionCallbackValidationResult { get; set; } = new EndSessionCallbackValidationResult(); - public Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject) => Task.FromResult(EndSessionValidationResult); + public Task ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject, Ct _) => Task.FromResult(EndSessionValidationResult); - public Task ValidateCallbackAsync(NameValueCollection parameters) => Task.FromResult(EndSessionCallbackValidationResult); + public Task ValidateCallbackAsync(NameValueCollection parameters, Ct _) => Task.FromResult(EndSessionCallbackValidationResult); } diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs index 3b0520d76..be347e577 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs @@ -23,6 +23,7 @@ namespace UnitTests.Endpoints.Results; public class AuthorizeResultTests { private AuthorizeHttpWriter _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; private AuthorizeResponse _response = new AuthorizeResponse(); private IdentityServerOptions _options = new IdentityServerOptions(); @@ -351,7 +352,7 @@ public class AuthorizeResultTests var queryString = new Uri(location).Query; var queryParams = QueryHelpers.ParseQuery(queryString); var errorId = queryParams.First(kvp => kvp.Key == _options.UserInteraction.ErrorIdParameter).Value; - var errorMessage = await _mockErrorMessageStore.ReadAsync(errorId); + var errorMessage = await _mockErrorMessageStore.ReadAsync(errorId, _ct); errorMessage.Data.RedirectUri.ShouldBeNull(); errorMessage.Data.ResponseMode.ShouldBeNull(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubClientSecretValidator.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubClientSecretValidator.cs index 1a665c28d..692742c5e 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubClientSecretValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubClientSecretValidator.cs @@ -11,5 +11,5 @@ internal class StubClientSecretValidator : IClientSecretValidator { public ClientSecretValidationResult Result { get; set; } - public Task ValidateAsync(HttpContext context) => Task.FromResult(Result); + public Task ValidateAsync(HttpContext context, Ct _) => Task.FromResult(Result); } diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenRequestValidator.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenRequestValidator.cs index 611dc4767..0fc38094f 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenRequestValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenRequestValidator.cs @@ -10,5 +10,5 @@ internal class StubTokenRequestValidator : ITokenRequestValidator { public TokenRequestValidationResult Result { get; set; } - public Task ValidateRequestAsync(TokenRequestValidationContext context) => Task.FromResult(Result); + public Task ValidateRequestAsync(TokenRequestValidationContext context, Ct _) => Task.FromResult(Result); } diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenResponseGenerator.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenResponseGenerator.cs index 0bf38ac07..6dd689130 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenResponseGenerator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Token/StubTokenResponseGenerator.cs @@ -11,5 +11,5 @@ internal class StubTokenResponseGenerator : ITokenResponseGenerator { public TokenResponse Response { get; set; } = new TokenResponse(); - public Task ProcessAsync(TokenRequestValidationResult validationResult) => Task.FromResult(Response); + public Task ProcessAsync(TokenRequestValidationResult validationResult, Ct _) => Task.FromResult(Response); } diff --git a/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs b/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs index 0c183adf4..2e788d49c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs @@ -9,6 +9,8 @@ namespace UnitTests.Extensions; public class IResourceStoreExtensionsTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + [Fact] public async Task GetAllEnabledResourcesAsync_on_duplicate_identity_scopes_should_fail() { @@ -19,7 +21,7 @@ public class IResourceStoreExtensionsTests new IdentityResource { Name = "A" } } }; - Func a = () => store.GetAllEnabledResourcesAsync(); + Func a = () => store.GetAllEnabledResourcesAsync(_ct); var exception = await a.ShouldThrowAsync(); exception.Message.ShouldMatch("Duplicate identity scopes*"); } @@ -34,7 +36,7 @@ public class IResourceStoreExtensionsTests new IdentityResource { Name = "B" } } }; - await store.GetAllEnabledResourcesAsync(); + await store.GetAllEnabledResourcesAsync(_ct); } [Fact] @@ -45,7 +47,7 @@ public class IResourceStoreExtensionsTests ApiResources = { new ApiResource { Name = "a" }, new ApiResource { Name = "a" } } }; - Func a = () => store.GetAllEnabledResourcesAsync(); + Func a = () => store.GetAllEnabledResourcesAsync(_ct); var exception = await a.ShouldThrowAsync(); exception.Message.ShouldMatch("Duplicate api resources*"); } @@ -58,7 +60,7 @@ public class IResourceStoreExtensionsTests ApiResources = { new ApiResource("A"), new ApiResource("B") } }; - await store.GetAllEnabledResourcesAsync(); + await store.GetAllEnabledResourcesAsync(_ct); } [Fact] @@ -71,7 +73,7 @@ public class IResourceStoreExtensionsTests new IdentityResource { Name = "A" } } }; - Func a = () => store.FindResourcesByScopeAsync(new string[] { "A" }); + Func a = () => store.FindResourcesByScopeAsync(new string[] { "A" }, _ct); var exception = await a.ShouldThrowAsync(); exception.Message.ShouldMatch("Duplicate identity scopes*"); } @@ -86,7 +88,7 @@ public class IResourceStoreExtensionsTests new IdentityResource { Name = "B" } } }; - await store.FindResourcesByScopeAsync(new string[] { "A" }); + await store.FindResourcesByScopeAsync(new string[] { "A" }, _ct); } [Fact] @@ -103,7 +105,7 @@ public class IResourceStoreExtensionsTests } }; - var result = await store.FindResourcesByScopeAsync(new string[] { "a" }); + var result = await store.FindResourcesByScopeAsync(new string[] { "a" }, _ct); result.ApiResources.Count.ShouldBe(2); result.ApiScopes.Count.ShouldBe(1); result.ApiResources.Select(x => x.Name).ShouldBe(["api1", "api2"]); @@ -118,7 +120,7 @@ public class IResourceStoreExtensionsTests ApiResources = { new ApiResource("A"), new ApiResource("B") } }; - await store.FindResourcesByScopeAsync(new string[] { "A" }); + await store.FindResourcesByScopeAsync(new string[] { "A" }, _ct); } [Fact] @@ -136,7 +138,7 @@ public class IResourceStoreExtensionsTests } }; - var result = await store.FindResourcesByScopeAsync(new string[] { "a" }); + var result = await store.FindResourcesByScopeAsync(new string[] { "a" }, _ct); result.ApiResources.Count.ShouldBe(1); } @@ -146,7 +148,7 @@ public class IResourceStoreExtensionsTests public List ApiResources { get; set; } = new List(); public List ApiScopes { get; set; } = new List(); - public Task> FindApiResourcesByNameAsync(IEnumerable names) + public Task> FindApiResourcesByNameAsync(IEnumerable names, Ct _) { var apis = from a in ApiResources where names.Contains(a.Name) @@ -154,7 +156,7 @@ public class IResourceStoreExtensionsTests return Task.FromResult(apis); } - public Task> FindApiResourcesByScopeNameAsync(IEnumerable names) + public Task> FindApiResourcesByScopeNameAsync(IEnumerable names, Ct _) { ArgumentNullException.ThrowIfNull(names); @@ -165,7 +167,7 @@ public class IResourceStoreExtensionsTests return Task.FromResult(api); } - public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable names) + public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable names, Ct _) { ArgumentNullException.ThrowIfNull(names); @@ -176,7 +178,7 @@ public class IResourceStoreExtensionsTests return Task.FromResult(identity); } - public Task> FindApiScopesByNameAsync(IEnumerable scopeNames) + public Task> FindApiScopesByNameAsync(IEnumerable scopeNames, Ct _) { var q = from x in ApiScopes where scopeNames.Contains(x.Name) @@ -184,7 +186,7 @@ public class IResourceStoreExtensionsTests return Task.FromResult(q); } - public Task GetAllResourcesAsync() + public Task GetAllResourcesAsync(Ct _) { var result = new Resources(IdentityResources, ApiResources, ApiScopes); return Task.FromResult(result); diff --git a/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs index cffdb1f3b..19f50ab1a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs @@ -13,24 +13,24 @@ public class IdentityServerBuilderExtensionsCacheStoreTests { private class CustomClientStore : IClientStore { - public Task FindClientByIdAsync(string clientId) => throw new System.NotImplementedException(); + public Task FindClientByIdAsync(string clientId, Ct _) => throw new System.NotImplementedException(); #if NET10_0_OR_GREATER - public IAsyncEnumerable GetAllClientsAsync() => throw new System.NotImplementedException(); + public IAsyncEnumerable GetAllClientsAsync(Ct _) => throw new System.NotImplementedException(); #endif } private class CustomResourceStore : IResourceStore { - public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames) => throw new System.NotImplementedException(); + public Task> FindIdentityResourcesByScopeNameAsync(IEnumerable scopeNames, Ct _) => throw new System.NotImplementedException(); - public Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames) => throw new System.NotImplementedException(); + public Task> FindApiResourcesByScopeNameAsync(IEnumerable scopeNames, Ct _) => throw new System.NotImplementedException(); - public Task> FindApiResourcesByNameAsync(IEnumerable names) => throw new System.NotImplementedException(); + public Task> FindApiResourcesByNameAsync(IEnumerable names, Ct _) => throw new System.NotImplementedException(); - public Task GetAllResourcesAsync() => throw new System.NotImplementedException(); + public Task GetAllResourcesAsync(Ct _) => throw new System.NotImplementedException(); - public Task> FindApiScopesByNameAsync(IEnumerable scopeNames) => throw new System.NotImplementedException(); + public Task> FindApiScopesByNameAsync(IEnumerable scopeNames, Ct _) => throw new System.NotImplementedException(); } [Fact] diff --git a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/DiagnosticSummaryTests.cs b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/DiagnosticSummaryTests.cs index eaf48b94b..52b43e610 100644 --- a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/DiagnosticSummaryTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/DiagnosticSummaryTests.cs @@ -13,6 +13,8 @@ namespace IdentityServer.UnitTests.Licensing.V2; public class DiagnosticSummaryTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + [Fact] public async Task PrintSummary_ShouldCallWriteAsyncOnEveryDiagnosticEntry() { @@ -29,7 +31,7 @@ public class DiagnosticSummaryTests var diagnosticService = new DiagnosticDataService(DateTime.UtcNow, entries); var summary = new DiagnosticSummary(diagnosticService, new IdentityServerOptions(), new StubLoggerFactory(logger)); - await summary.PrintSummary(); + await summary.PrintSummary(_ct); firstDiagnosticEntry.WasCalled.ShouldBeTrue(); secondDiagnosticEntry.WasCalled.ShouldBeTrue(); @@ -47,7 +49,7 @@ public class DiagnosticSummaryTests var diagnosticService = new DiagnosticDataService(DateTime.UtcNow, [diagnosticEntry]); var summary = new DiagnosticSummary(diagnosticService, options, new StubLoggerFactory(logger)); - await summary.PrintSummary(); + await summary.PrintSummary(_ct); var logSnapshot = logger.Collector.GetSnapshot().Select(x => x.Message); logSnapshot.ShouldBe([ @@ -68,7 +70,7 @@ public class DiagnosticSummaryTests var summary = new DiagnosticSummary(diagnosticService, options, new StubLoggerFactory(logger)); - await summary.PrintSummary(); + await summary.PrintSummary(_ct); var logSnapshot = logger.Collector.GetSnapshot().Select(x => x.Message); logSnapshot.ShouldBe(["Diagnostic data (1 of 3): {\"test\":", "Diagnostic data (2 of 3): \"\\u20AC\\", "Diagnostic data (3 of 3): u20AC\"}"]); @@ -85,7 +87,7 @@ public class DiagnosticSummaryTests var summary = new DiagnosticSummary(diagnosticService, options, new StubLoggerFactory(logger)); - await summary.PrintSummary(); + await summary.PrintSummary(_ct); foreach (var entry in logger.Collector.GetSnapshot()) { entry.Message.Length.ShouldBeLessThanOrEqualTo(1024 * 8); @@ -101,7 +103,7 @@ public class DiagnosticSummaryTests var diagnosticService = new DiagnosticDataService(DateTime.UtcNow, [diagnosticEntry]); var summary = new DiagnosticSummary(diagnosticService, options, new StubLoggerFactory(logger)); - await summary.PrintSummary(); + await summary.PrintSummary(_ct); var logSnapshot = logger.Collector.GetSnapshot(); logSnapshot.Count.ShouldBeGreaterThan(0); diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs index db379eee4..694e61831 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs @@ -18,6 +18,7 @@ public class AuthorizeInteractionResponseGeneratorTests private Duende.IdentityServer.ResponseHandling.AuthorizeInteractionResponseGenerator _subject; private MockConsentService _mockConsentService = new MockConsentService(); private FakeTimeProvider _timeProvider = new FakeTimeProvider(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public AuthorizeInteractionResponseGeneratorTests() => _subject = new Duende.IdentityServer.ResponseHandling.AuthorizeInteractionResponseGenerator( _options, @@ -48,7 +49,7 @@ public class AuthorizeInteractionResponseGeneratorTests PromptModes = new[] { PromptModes.None }, }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.IsLogin.ShouldBeFalse(); @@ -75,7 +76,7 @@ public class AuthorizeInteractionResponseGeneratorTests MaxAge = 3600 }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.IsLogin.ShouldBeFalse(); @@ -98,7 +99,7 @@ public class AuthorizeInteractionResponseGeneratorTests PromptModes = new[] { PromptModes.None } }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.IsLogin.ShouldBeFalse(); @@ -122,7 +123,7 @@ public class AuthorizeInteractionResponseGeneratorTests PromptModes = new[] { PromptModes.None } }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.IsLogin.ShouldBeFalse(); @@ -145,7 +146,7 @@ public class AuthorizeInteractionResponseGeneratorTests PromptModes = new[] { PromptModes.None } }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.IsLogin.ShouldBeFalse(); diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs index 198ec9106..f6455502b 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs @@ -18,6 +18,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent private IdentityServerOptions _options = new IdentityServerOptions(); private MockConsentService _mockConsent = new MockConsentService(); private MockProfileService _fakeUserService = new MockProfileService(); + private readonly Ct _ct = TestContext.Current.CancellationToken; private void RequiresConsent(bool value) => _mockConsent.RequiresConsentResult = value; @@ -90,7 +91,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent [Fact] public async Task ProcessConsentAsync_NullRequest_Throws() { - Func act = () => _subject.ProcessConsentAsync(null, new ConsentResponse()); + Func act = () => _subject.ProcessConsentAsync(null, new ConsentResponse(), _ct); var exception = await act.ShouldThrowAsync(); exception.ParamName.ShouldBe("request"); @@ -108,7 +109,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RequestedScopes = new List { "openid", "read", "write" }, ValidatedResources = GetValidatedResources("openid", "read", "write"), }; - await _subject.ProcessConsentAsync(request, null); + await _subject.ProcessConsentAsync(request, null, _ct); } [Fact] @@ -125,7 +126,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent ValidatedResources = GetValidatedResources("openid", "read", "write"), }; - Func act = () => _subject.ProcessConsentAsync(request); + Func act = () => _subject.ProcessConsentAsync(request, null, _ct); var exception = await act.ShouldThrowAsync(); exception.Message.ShouldMatch(".*PromptMode.*"); @@ -145,7 +146,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent ValidatedResources = GetValidatedResources("openid", "read", "write"), }; - Func act = () => _subject.ProcessConsentAsync(request); + Func act = () => _subject.ProcessConsentAsync(request, null, _ct); var exception = await act.ShouldThrowAsync(); exception.Message.ShouldMatch(".*PromptMode.*"); @@ -165,7 +166,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RequestedScopes = new List { "openid", "read", "write" }, ValidatedResources = GetValidatedResources("openid", "read", "write"), }; - var result = await _subject.ProcessConsentAsync(request); + var result = await _subject.ProcessConsentAsync(request, null, _ct); request.WasConsentShown.ShouldBeFalse(); result.IsError.ShouldBeTrue(); @@ -185,7 +186,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RequestedScopes = new List { "openid", "read", "write" }, ValidatedResources = GetValidatedResources("openid", "read", "write"), }; - var result = await _subject.ProcessConsentAsync(request); + var result = await _subject.ProcessConsentAsync(request, null, _ct); request.WasConsentShown.ShouldBeFalse(); result.IsConsent.ShouldBeTrue(); AssertUpdateConsentNotCalled(); @@ -204,7 +205,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RequestedScopes = new List { "openid", "read", "write" }, ValidatedResources = GetValidatedResources("openid", "read", "write"), }; - var result = await _subject.ProcessConsentAsync(request); + var result = await _subject.ProcessConsentAsync(request, null, _ct); request.WasConsentShown.ShouldBeFalse(); result.IsConsent.ShouldBeTrue(); AssertUpdateConsentNotCalled(); @@ -228,7 +229,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RememberConsent = false, ScopesValuesConsented = new string[] { } }; - var result = await _subject.ProcessConsentAsync(request, consent); + var result = await _subject.ProcessConsentAsync(request, consent, _ct); request.WasConsentShown.ShouldBeTrue(); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.AccessDenied); @@ -252,7 +253,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RememberConsent = false, ScopesValuesConsented = new string[] { } }; - var result = await _subject.ProcessConsentAsync(request, consent); + var result = await _subject.ProcessConsentAsync(request, consent, _ct); request.WasConsentShown.ShouldBeTrue(); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.AccessDenied); @@ -280,7 +281,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent ScopesValuesConsented = new string[] { "read" } }; - var result = await _subject.ProcessConsentAsync(request, consent); + var result = await _subject.ProcessConsentAsync(request, consent, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.AccessDenied); AssertUpdateConsentNotCalled(); @@ -307,7 +308,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RememberConsent = false, ScopesValuesConsented = new string[] { "openid", "read" } }; - var result = await _subject.ProcessConsentAsync(request, consent); + var result = await _subject.ProcessConsentAsync(request, consent, _ct); request.ValidatedResources.Resources.IdentityResources.Count.ShouldBe(1); request.ValidatedResources.Resources.ApiScopes.Count.ShouldBe(1); "openid".ShouldBe(request.ValidatedResources.Resources.IdentityResources.Select(x => x.Name).First()); @@ -338,7 +339,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RememberConsent = false, ScopesValuesConsented = new string[] { "openid", "read" } }; - var result = await _subject.ProcessConsentAsync(request, consent); + var result = await _subject.ProcessConsentAsync(request, consent, _ct); request.ValidatedResources.Resources.IdentityResources.Count.ShouldBe(1); request.ValidatedResources.Resources.ApiScopes.Count.ShouldBe(1); "read".ShouldBe(request.ValidatedResources.Resources.ApiScopes.First().Name); @@ -368,7 +369,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RememberConsent = true, ScopesValuesConsented = new string[] { "openid", "read" } }; - var result = await _subject.ProcessConsentAsync(request, consent); + var result = await _subject.ProcessConsentAsync(request, consent, _ct); AssertUpdateConsentCalled(client, user, "openid", "read"); } @@ -393,7 +394,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Consent RememberConsent = false, ScopesValuesConsented = new string[] { "openid", "read" } }; - var result = await _subject.ProcessConsentAsync(request, consent); + var result = await _subject.ProcessConsentAsync(request, consent, _ct); AssertUpdateConsentCalled(client, user); } } diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs index b70a66315..48692cb6f 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs @@ -27,24 +27,24 @@ public class CustomAuthorizeInteractionResponseGenerator : Duende.IdentityServer } public InteractionResponse ProcessLoginResponse { get; set; } - protected internal override Task ProcessLoginAsync(ValidatedAuthorizeRequest request) + protected internal override Task ProcessLoginAsync(ValidatedAuthorizeRequest request, Ct ct) { if (ProcessLoginResponse != null) { return Task.FromResult(ProcessLoginResponse); } - return base.ProcessLoginAsync(request); + return base.ProcessLoginAsync(request, ct); } public InteractionResponse ProcessConsentResponse { get; set; } - protected internal override Task ProcessConsentAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null) + protected internal override Task ProcessConsentAsync(ValidatedAuthorizeRequest request, ConsentResponse consent, Ct ct) { if (ProcessConsentResponse != null) { return Task.FromResult(ProcessConsentResponse); } - return base.ProcessConsentAsync(request, consent); + return base.ProcessConsentAsync(request, consent, ct); } } @@ -54,6 +54,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Custom private CustomAuthorizeInteractionResponseGenerator _subject; private MockConsentService _mockConsentService = new MockConsentService(); private FakeTimeProvider _timeProvider = new FakeTimeProvider(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public AuthorizeInteractionResponseGeneratorTests_Custom() => _subject = new CustomAuthorizeInteractionResponseGenerator( _options, @@ -83,7 +84,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Custom RedirectUrl = "/custom" }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsRedirect.ShouldBeTrue(); result.RedirectUrl.ShouldBe("/custom"); @@ -110,7 +111,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Custom IsLogin = true }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("login_required"); @@ -137,7 +138,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Custom RedirectUrl = "/custom" }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("interaction_required"); @@ -165,7 +166,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Custom IsConsent = true }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("consent_required"); diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs index 8d2b015ec..a7ff911aa 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs @@ -19,6 +19,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login private Duende.IdentityServer.ResponseHandling.AuthorizeInteractionResponseGenerator _subject; private MockConsentService _mockConsentService = new MockConsentService(); private FakeTimeProvider _timeProvider = new FakeTimeProvider(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public AuthorizeInteractionResponseGeneratorTests_Login() => _subject = new Duende.IdentityServer.ResponseHandling.AuthorizeInteractionResponseGenerator( _options, @@ -36,7 +37,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login Subject = Principal.Anonymous }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeTrue(); } @@ -55,7 +56,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login }.CreatePrincipal() }; - var result = await _subject.ProcessInteractionAsync(request); + var result = await _subject.ProcessInteractionAsync(request, null, _ct); result.IsLogin.ShouldBeFalse(); } @@ -79,7 +80,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login } }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeFalse(); } @@ -104,7 +105,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login } }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeTrue(); } @@ -125,7 +126,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login }.CreatePrincipal() }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeFalse(); } @@ -146,7 +147,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login }.CreatePrincipal() }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeTrue(); } @@ -168,7 +169,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login }.CreatePrincipal() }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeFalse(); } @@ -190,7 +191,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login }.CreatePrincipal() }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeTrue(); } @@ -211,7 +212,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login }.CreatePrincipal() }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeTrue(); } @@ -227,7 +228,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login Raw = new NameValueCollection() }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeTrue(); } @@ -243,7 +244,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login Raw = new NameValueCollection() }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); result.IsLogin.ShouldBeTrue(); } @@ -262,7 +263,7 @@ public class AuthorizeInteractionResponseGeneratorTests_Login } }; - var result = await _subject.ProcessLoginAsync(request); + var result = await _subject.ProcessLoginAsync(request, _ct); request.Raw.AllKeys.ShouldContain(Constants.ProcessedPrompt); } diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs index d63c7e1d1..a7a0de4cd 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs @@ -17,6 +17,7 @@ namespace UnitTests.ResponseHandling; public class DeviceAuthorizationResponseGeneratorTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; private readonly List identityResources = new List { new IdentityResources.OpenId(), new IdentityResources.Profile() }; private readonly List apiResources = new List { new ApiResource("resource") { Scopes = { "api1" } } }; private readonly List scopes = new List { new ApiScope("api1") }; @@ -50,7 +51,7 @@ public class DeviceAuthorizationResponseGeneratorTests [Fact] public async Task ProcessAsync_when_validationresult_null_expect_exception() { - Func act = () => generator.ProcessAsync(null, TestBaseUrl); + Func act = () => generator.ProcessAsync(null, TestBaseUrl, _ct); await act.ShouldThrowAsync(); } @@ -58,14 +59,14 @@ public class DeviceAuthorizationResponseGeneratorTests public async Task ProcessAsync_when_validationresult_client_null_expect_exception() { var validationResult = new DeviceAuthorizationRequestValidationResult(new ValidatedDeviceAuthorizationRequest()); - Func act = () => generator.ProcessAsync(validationResult, TestBaseUrl); + Func act = () => generator.ProcessAsync(validationResult, TestBaseUrl, _ct); await act.ShouldThrowAsync(); } [Fact] public async Task ProcessAsync_when_baseurl_null_expect_exception() { - Func act = () => generator.ProcessAsync(testResult, null); + Func act = () => generator.ProcessAsync(testResult, null, _ct); await act.ShouldThrowAsync(); } @@ -76,9 +77,9 @@ public class DeviceAuthorizationResponseGeneratorTests timeProvider.SetUtcNow(creationTime); testResult.ValidatedRequest.Client.UserCodeType = FakeUserCodeGenerator.UserCodeTypeValue; - await deviceFlowCodeService.StoreDeviceAuthorizationAsync(FakeUserCodeGenerator.TestCollisionUserCode, new DeviceCode()); + await deviceFlowCodeService.StoreDeviceAuthorizationAsync(FakeUserCodeGenerator.TestCollisionUserCode, new DeviceCode(), _ct); - var response = await generator.ProcessAsync(testResult, TestBaseUrl); + var response = await generator.ProcessAsync(testResult, TestBaseUrl, _ct); response.UserCode.ShouldBe(FakeUserCodeGenerator.TestUniqueUserCode); } @@ -91,9 +92,9 @@ public class DeviceAuthorizationResponseGeneratorTests fakeUserCodeGenerator.RetryLimit = 1; testResult.ValidatedRequest.Client.UserCodeType = FakeUserCodeGenerator.UserCodeTypeValue; - await deviceFlowCodeService.StoreDeviceAuthorizationAsync(FakeUserCodeGenerator.TestCollisionUserCode, new DeviceCode()); + await deviceFlowCodeService.StoreDeviceAuthorizationAsync(FakeUserCodeGenerator.TestCollisionUserCode, new DeviceCode(), _ct); - var act = () => generator.ProcessAsync(testResult, TestBaseUrl); + var act = () => generator.ProcessAsync(testResult, TestBaseUrl, _ct); act.ShouldThrow(); } @@ -110,11 +111,11 @@ public class DeviceAuthorizationResponseGeneratorTests apiResources.Where(x => x.Name == "resource"), scopes.Where(x => x.Name == "api1"))); - var response = await generator.ProcessAsync(testResult, TestBaseUrl); + var response = await generator.ProcessAsync(testResult, TestBaseUrl, _ct); response.UserCode.ShouldNotBeNullOrWhiteSpace(); - var userCode = await deviceFlowCodeService.FindByUserCodeAsync(response.UserCode); + var userCode = await deviceFlowCodeService.FindByUserCodeAsync(response.UserCode, _ct); userCode.ShouldNotBeNull(); userCode.ClientId.ShouldBe(testResult.ValidatedRequest.Client.ClientId); userCode.Lifetime.ShouldBe(testResult.ValidatedRequest.Client.DeviceCodeLifetime); @@ -131,12 +132,12 @@ public class DeviceAuthorizationResponseGeneratorTests var creationTime = DateTime.UtcNow; timeProvider.SetUtcNow(creationTime); - var response = await generator.ProcessAsync(testResult, TestBaseUrl); + var response = await generator.ProcessAsync(testResult, TestBaseUrl, _ct); response.DeviceCode.ShouldNotBeNullOrWhiteSpace(); response.Interval.ShouldBe(options.DeviceFlow.Interval); - var deviceCode = await deviceFlowCodeService.FindByDeviceCodeAsync(response.DeviceCode); + var deviceCode = await deviceFlowCodeService.FindByDeviceCodeAsync(response.DeviceCode, _ct); deviceCode.ShouldNotBeNull(); deviceCode.ClientId.ShouldBe(testResult.ValidatedRequest.Client.ClientId); deviceCode.IsOpenId.ShouldBe(testResult.ValidatedRequest.IsOpenIdRequest); @@ -155,7 +156,7 @@ public class DeviceAuthorizationResponseGeneratorTests options.UserInteraction.DeviceVerificationUrl = "/device"; options.UserInteraction.DeviceVerificationUserCodeParameter = "userCode"; - var response = await generator.ProcessAsync(testResult, baseUrl); + var response = await generator.ProcessAsync(testResult, baseUrl, _ct); response.VerificationUri.ShouldBe("http://localhost:5000/device"); response.VerificationUriComplete.ShouldStartWith("http://localhost:5000/device?userCode="); @@ -168,7 +169,7 @@ public class DeviceAuthorizationResponseGeneratorTests options.UserInteraction.DeviceVerificationUrl = "http://short/device"; options.UserInteraction.DeviceVerificationUserCodeParameter = "userCode"; - var response = await generator.ProcessAsync(testResult, baseUrl); + var response = await generator.ProcessAsync(testResult, baseUrl, _ct); response.VerificationUri.ShouldBe("http://short/device"); response.VerificationUriComplete.ShouldStartWith("http://short/device?userCode="); @@ -192,7 +193,7 @@ internal class FakeUserCodeGenerator : IUserCodeGenerator set => retryLimit = value; } - public Task GenerateAsync() + public Task GenerateAsync(Ct _) { if (tryCount == 0) { diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs index adf64e0f9..ba66d7497 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs @@ -15,6 +15,8 @@ namespace UnitTests.ResponseHandling; public class UserInfoResponseGeneratorTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + private UserInfoResponseGenerator _subject; private MockProfileService _mockProfileService = new MockProfileService(); private ClaimsPrincipal _user; @@ -50,7 +52,7 @@ public class UserInfoResponseGeneratorTests [Fact] public async Task GetRequestedClaimTypesAsync_when_no_scopes_requested_should_return_empty_claim_types() { - var resources = await _subject.GetRequestedResourcesAsync(null); + var resources = await _subject.GetRequestedResourcesAsync(null, _ct); var claims = await _subject.GetRequestedClaimTypesAsync(resources); claims.ShouldBe(new string[] { }); } @@ -61,7 +63,7 @@ public class UserInfoResponseGeneratorTests _identityResources.Add(new IdentityResource("id1", new[] { "c1", "c2" })); _identityResources.Add(new IdentityResource("id2", new[] { "c2", "c3" })); - var resources = await _subject.GetRequestedResourcesAsync(new[] { "id1", "id2", "id3" }); + var resources = await _subject.GetRequestedResourcesAsync(new[] { "id1", "id2", "id3" }, _ct); var claims = await _subject.GetRequestedClaimTypesAsync(resources); claims.ShouldBe(["c1", "c2", "c3"]); } @@ -72,7 +74,7 @@ public class UserInfoResponseGeneratorTests _identityResources.Add(new IdentityResource("id1", new[] { "c1", "c2" }) { Enabled = false }); _identityResources.Add(new IdentityResource("id2", new[] { "c2", "c3" })); - var resources = await _subject.GetRequestedResourcesAsync(new[] { "id1", "id2", "id3" }); + var resources = await _subject.GetRequestedResourcesAsync(new[] { "id1", "id2", "id3" }, _ct); var claims = await _subject.GetRequestedClaimTypesAsync(resources); claims.ShouldBe(["c2", "c3"]); } @@ -98,7 +100,7 @@ public class UserInfoResponseGeneratorTests } }; - var claims = await _subject.ProcessAsync(result); + var claims = await _subject.ProcessAsync(result, _ct); _mockProfileService.GetProfileWasCalled.ShouldBeTrue(); _mockProfileService.ProfileContext.RequestedClaimTypes.ShouldBe(["foo", "bar"]); @@ -141,7 +143,7 @@ public class UserInfoResponseGeneratorTests } }; - var claims = await _subject.ProcessAsync(result); + var claims = await _subject.ProcessAsync(result, _ct); claims.ShouldContainKey("email"); claims["email"].ShouldBe("fred@gmail.com"); @@ -178,7 +180,7 @@ public class UserInfoResponseGeneratorTests } }; - var claims = await _subject.ProcessAsync(result); + var claims = await _subject.ProcessAsync(result, _ct); claims.ShouldContainKey("sub"); claims["sub"].ShouldBe("bob"); @@ -209,7 +211,7 @@ public class UserInfoResponseGeneratorTests } }; - Func act = () => _subject.ProcessAsync(result); + Func act = () => _subject.ProcessAsync(result, _ct); var exception = await act.ShouldThrowAsync(); exception.Message.ShouldMatch(".*subject.*"); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs index d8007221f..b6ace2bc0 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs @@ -17,6 +17,7 @@ namespace UnitTests.Services.Default; public class DefaultBackChannelLogoutServiceTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; private class ServiceTestHarness : DefaultBackChannelLogoutService { public ServiceTestHarness( @@ -32,7 +33,7 @@ public class DefaultBackChannelLogoutServiceTests // CreateTokenAsync is protected, so we use this wrapper to exercise it in our tests - public async Task ExerciseCreateTokenAsync(BackChannelLogoutRequest request) => await CreateTokenAsync(request); + public async Task ExerciseCreateTokenAsync(BackChannelLogoutRequest request, Ct ct) => await CreateTokenAsync(request, ct); } [Fact] @@ -59,7 +60,7 @@ public class DefaultBackChannelLogoutServiceTests { ClientId = "test_client", SubjectId = "test_sub", - }); + }, _ct); var payload = JsonSerializer.Deserialize>(Base64Url.DecodeFromChars(rawToken.Split('.')[1])); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs index d4a0fb783..930169ac1 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs @@ -16,6 +16,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests { private Client _client; private DefaultBackchannelAuthenticationInteractionService _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; private MockBackChannelAuthenticationRequestStore _mockStore = new MockBackChannelAuthenticationRequestStore(); private InMemoryClientStore _clientStore; @@ -50,14 +51,14 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests ClientId = _client.ClientId, Subject = new IdentityServerUser("123").CreatePrincipal(), }; - await _mockStore.CreateRequestAsync(req); + await _mockStore.CreateRequestAsync(req, _ct); await _mockStore.CreateRequestAsync(new BackChannelAuthenticationRequest { ClientId = _client.ClientId, Subject = new IdentityServerUser("other").CreatePrincipal() - }); + }, _ct); - var results = await _subject.GetPendingLoginRequestsForCurrentUserAsync(); + var results = await _subject.GetPendingLoginRequestsForCurrentUserAsync(_ct); results.Count().ShouldBe(1); results.First().InternalId.ShouldBe(req.InternalId); } @@ -71,14 +72,14 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests ClientId = _client.ClientId, Subject = new IdentityServerUser("123").CreatePrincipal(), }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); await _mockStore.CreateRequestAsync(new BackChannelAuthenticationRequest { ClientId = _client.ClientId, Subject = new IdentityServerUser("other").CreatePrincipal() - }); + }, _ct); - var result = await _subject.GetLoginRequestByInternalIdAsync(req.InternalId); + var result = await _subject.GetLoginRequestByInternalIdAsync(req.InternalId, _ct); result.InternalId.ShouldBe(req.InternalId); } @@ -92,7 +93,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req.InternalId) { @@ -107,7 +108,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests AdditionalClaims = { new Claim("foo", "bar") }, AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() - }); + }, _ct); var item = _mockStore.Items[requestId]; item.IsComplete.ShouldBeTrue(); @@ -133,9 +134,9 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); - var f = async () => await _subject.CompleteLoginRequestAsync(null); + var f = async () => await _subject.CompleteLoginRequestAsync(null, _ct); await f.ShouldThrowAsync(); } @@ -149,7 +150,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); var f = async () => await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req.InternalId) { @@ -164,7 +165,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests AdditionalClaims = { new Claim("foo", "bar") }, AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() - }); + }, _ct); var exception = await f.ShouldThrowAsync(); exception.Message.ShouldBe("More scopes consented than originally requested."); } @@ -179,7 +180,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); var f = async () => await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req.InternalId) { @@ -194,7 +195,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests AdditionalClaims = { new Claim("foo", "bar") }, AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() - }); + }, _ct); var exception = await f.ShouldThrowAsync(); exception.Message.ShouldBe("User's subject id: 'invalid' does not match subject id for backchannel authentication request: '123'."); } @@ -208,7 +209,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); var f = async () => await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req.InternalId) { @@ -223,7 +224,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests // AdditionalClaims = { new Claim("foo", "bar") }, // AuthenticationMethods = { "phone", "pin" } //}.CreatePrincipal() - }); + }, _ct); var exception = await f.ShouldThrowAsync(); exception.Message.ShouldBe("Invalid subject."); } @@ -237,7 +238,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); var f = async () => await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest("invalid") { @@ -252,7 +253,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests AdditionalClaims = { new Claim("foo", "bar") }, AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() - }); + }, _ct); var exception = await f.ShouldThrowAsync(); exception.Message.ShouldBe("Invalid backchannel authentication request id."); } @@ -267,7 +268,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); _mockUserSession.User = new IdentityServerUser("123") { @@ -285,7 +286,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests ScopesValuesConsented = new string[] { "scope1", "scope2" }, SessionId = "ignored", //Subject = - }); + }, _ct); var item = _mockStore.Items[requestId]; item.SessionId.ShouldBe("session id"); @@ -308,7 +309,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests Subject = new IdentityServerUser("123").CreatePrincipal(), RequestedScopes = new[] { "scope1", "scope2", "scope3" }, }; - var requestId = await _mockStore.CreateRequestAsync(req); + var requestId = await _mockStore.CreateRequestAsync(req, _ct); await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req.InternalId) { @@ -323,7 +324,7 @@ public class DefaultBackchannelAuthenticationInteractionServiceTests AdditionalClaims = { new Claim("foo", "bar") }, AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() - }); + }, _ct); var item = _mockStore.Items[requestId]; item.Subject.HasClaim("idp", "local").ShouldBeTrue(); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs index bb03226fb..f1783131e 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs @@ -17,6 +17,7 @@ public class DefaultClaimsServiceTests { private DefaultClaimsService _subject; private MockProfileService _mockMockProfileService = new MockProfileService(); + private readonly Ct _ct = TestContext.Current.CancellationToken; private ClaimsPrincipal _user; private Client _client; @@ -58,7 +59,7 @@ public class DefaultClaimsServiceTests [Fact] public async Task GetIdentityTokenClaimsAsync_should_return_standard_user_claims() { - var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest); + var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest, _ct); var types = claims.Select(x => x.Type); types.ShouldContain(JwtClaimTypes.Subject); @@ -73,7 +74,7 @@ public class DefaultClaimsServiceTests { _resources.IdentityResources.Add(new IdentityResource("id_scope", new[] { "foo" })); - var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest); + var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest, _ct); _mockMockProfileService.GetProfileWasCalled.ShouldBeFalse(); } @@ -84,7 +85,7 @@ public class DefaultClaimsServiceTests _resources.IdentityResources.Add(new IdentityResource("id_scope", new[] { "foo" })); _mockMockProfileService.ProfileClaims.Add(new Claim("foo", "foo1")); - var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, true, _validatedRequest); + var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, true, _validatedRequest, _ct); _mockMockProfileService.GetProfileWasCalled.ShouldBeTrue(); _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); @@ -98,7 +99,7 @@ public class DefaultClaimsServiceTests _resources.IdentityResources.Add(new IdentityResource("id_scope", new[] { "foo" })); _mockMockProfileService.ProfileClaims.Add(new Claim("foo", "foo1")); - var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest); + var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest, _ct); _mockMockProfileService.GetProfileWasCalled.ShouldBeTrue(); _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); @@ -110,7 +111,7 @@ public class DefaultClaimsServiceTests _resources.IdentityResources.Add(new IdentityResource("id_scope", new[] { "foo" })); _mockMockProfileService.ProfileClaims.Add(new Claim("aud", "bar")); - var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, true, _validatedRequest); + var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, true, _validatedRequest, _ct); claims.Count(x => x.Type == "aud" && x.Value == "bar").ShouldBe(0); } @@ -118,7 +119,7 @@ public class DefaultClaimsServiceTests [Fact] public async Task GetAccessTokenClaimsAsync_should_contain_client_id() { - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); claims.Count(x => x.Type == JwtClaimTypes.ClientId && x.Value == _client.ClientId).ShouldBe(1); } @@ -126,7 +127,7 @@ public class DefaultClaimsServiceTests [Fact] public async Task GetAccessTokenClaimsAsync_client_claims_should_be_prefixed_with_default_value() { - var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest, _ct); claims.Count(x => x.Type == "client_some_claim" && x.Value == "some_claim_value").ShouldBe(1); } @@ -135,7 +136,7 @@ public class DefaultClaimsServiceTests public async Task GetAccessTokenClaimsAsync_client_claims_should_be_prefixed_with_custom_value() { _validatedRequest.Client.ClientClaimsPrefix = "custom_prefix_"; - var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest, _ct); claims.Count(x => x.Type == "custom_prefix_some_claim" && x.Value == "some_claim_value").ShouldBe(1); } @@ -144,7 +145,7 @@ public class DefaultClaimsServiceTests public async Task GetAccessTokenClaimsAsync_should_contain_client_claims_when_no_subject() { _validatedRequest.Client.ClientClaimsPrefix = null; - var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest, _ct); claims.Count(x => x.Type == "some_claim" && x.Value == "some_claim_value").ShouldBe(1); } @@ -155,7 +156,7 @@ public class DefaultClaimsServiceTests _validatedRequest.Client.ClientClaimsPrefix = null; _validatedRequest.Client.AlwaysSendClientClaims = true; - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); claims.Count(x => x.Type == "some_claim" && x.Value == "some_claim_value").ShouldBe(1); } @@ -168,7 +169,7 @@ public class DefaultClaimsServiceTests _resources.ApiScopes.Add(new ApiScope("api1")); _resources.ApiScopes.Add(new ApiScope("api2")); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); scopes.Count().ShouldBe(4); @@ -185,7 +186,7 @@ public class DefaultClaimsServiceTests ParsedScopes = { new ParsedScopeValue("api:123", "api", "123") } }; - var claims = await _subject.GetAccessTokenClaimsAsync(_user, resourceResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, resourceResult, _validatedRequest, _ct); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); scopes.Count().ShouldBe(1); @@ -197,7 +198,7 @@ public class DefaultClaimsServiceTests { _resources.ApiResources.Add(new ApiResource("api1")); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); scopes.Count().ShouldBe(0); @@ -215,7 +216,7 @@ public class DefaultClaimsServiceTests ParsedScopes = { new ParsedScopeValue("api2") } }; - var claims = await _subject.GetAccessTokenClaimsAsync(_user, resourceResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, resourceResult, _validatedRequest, _ct); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); scopes.Count().ShouldBe(1); @@ -235,7 +236,7 @@ public class DefaultClaimsServiceTests _resources.ApiResources.Add(new ApiResource { Name = "api3", Scopes = { "resource" } }); _resources.ApiScopes.Add(new ApiScope("resource")); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); scopes.Count().ShouldBe(1); @@ -251,7 +252,7 @@ public class DefaultClaimsServiceTests _resources.ApiResources.Add(new ApiResource("api2")); _resources.OfflineAccess = true; - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); scopes.ShouldContain(IdentityServerConstants.StandardScopes.OfflineAccess); @@ -266,7 +267,7 @@ public class DefaultClaimsServiceTests _resources.ApiResources.Add(new ApiResource("api2")); _resources.OfflineAccess = true; - var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest, _ct); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); scopes.ShouldNotContain(IdentityServerConstants.StandardScopes.OfflineAccess); @@ -275,7 +276,7 @@ public class DefaultClaimsServiceTests [Fact] public async Task GetAccessTokenClaimsAsync_should_return_standard_user_claims() { - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); var types = claims.Select(x => x.Type); types.ShouldContain(JwtClaimTypes.Subject); @@ -291,7 +292,7 @@ public class DefaultClaimsServiceTests _resources.IdentityResources.Add(new IdentityResource("id1", new[] { "foo" })); _resources.ApiResources.Add(new ApiResource("api1", new string[] { "bar" })); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); _mockMockProfileService.GetProfileWasCalled.ShouldBeTrue(); _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldNotContain("foo"); @@ -304,7 +305,7 @@ public class DefaultClaimsServiceTests _resources.ApiResources.Add(new ApiResource("api1", new[] { "foo" })); _mockMockProfileService.ProfileClaims.Add(new Claim("aud", "bar")); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); claims.Count(x => x.Type == "aud" && x.Value == "bar").ShouldBe(0); } @@ -314,7 +315,7 @@ public class DefaultClaimsServiceTests { _resources.ApiResources.Add(new ApiResource("api1", new[] { "foo" })); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); } @@ -335,7 +336,7 @@ public class DefaultClaimsServiceTests } ); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); } @@ -357,7 +358,7 @@ public class DefaultClaimsServiceTests } ); - var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); + var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest, _ct); _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("bar"); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs index 3c703a571..c800ce871 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs @@ -23,6 +23,7 @@ public class DefaultConsentServiceTests private Client _client; private TestUserConsentStore _userConsentStore = new TestUserConsentStore(); private FakeTimeProvider _timeProvider = new FakeTimeProvider(); + private readonly Ct _ct = TestContext.Current.CancellationToken; private DateTime now; @@ -70,18 +71,18 @@ public class DefaultConsentServiceTests { _client.AllowRememberConsent = false; - await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); - var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); + var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId, _ct); consent.ShouldBeNull(); } [Fact] public async Task UpdateConsentAsync_should_persist_consent() { - await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); - var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); + var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId, _ct); consent.Scopes.Count().ShouldBe(2); consent.Scopes.ShouldContain("scope1"); consent.Scopes.ShouldContain("scope2"); @@ -90,11 +91,11 @@ public class DefaultConsentServiceTests [Fact] public async Task UpdateConsentAsync_empty_scopes_should_remove_consent() { - await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); - await _subject.UpdateConsentAsync(_user, _client, new ParsedScopeValue[] { }); + await _subject.UpdateConsentAsync(_user, _client, new ParsedScopeValue[] { }, _ct); - var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); + var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId, _ct); consent.ShouldBeNull(); } @@ -103,7 +104,7 @@ public class DefaultConsentServiceTests { _client.RequireConsent = false; - var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); result.ShouldBeFalse(); } @@ -113,7 +114,7 @@ public class DefaultConsentServiceTests { _client.AllowRememberConsent = false; - var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); result.ShouldBeTrue(); } @@ -121,7 +122,7 @@ public class DefaultConsentServiceTests [Fact] public async Task RequiresConsentAsync_no_scopes_should_not_require_consent() { - var result = await _subject.RequiresConsentAsync(_user, _client, new ParsedScopeValue[] { }); + var result = await _subject.RequiresConsentAsync(_user, _client, new ParsedScopeValue[] { }, _ct); result.ShouldBeFalse(); } @@ -129,7 +130,7 @@ public class DefaultConsentServiceTests [Fact] public async Task RequiresConsentAsync_offline_access_should_require_consent() { - var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("offline_access") }); + var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("offline_access") }, _ct); result.ShouldBeTrue(); } @@ -137,7 +138,7 @@ public class DefaultConsentServiceTests [Fact] public async Task RequiresConsentAsync_no_prior_consent_should_require_consent() { - var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); result.ShouldBeTrue(); } @@ -145,9 +146,9 @@ public class DefaultConsentServiceTests [Fact] public async Task RequiresConsentAsync_prior_consent_should_not_require_consent() { - await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); - var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); result.ShouldBeFalse(); } @@ -155,9 +156,9 @@ public class DefaultConsentServiceTests [Fact] public async Task RequiresConsentAsync_prior_consent_with_more_scopes_should_not_require_consent() { - await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2"), new ParsedScopeValue("scope3") }); + await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2"), new ParsedScopeValue("scope3") }, _ct); - var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope2") }); + var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope2") }, _ct); result.ShouldBeFalse(); } @@ -165,9 +166,9 @@ public class DefaultConsentServiceTests [Fact] public async Task RequiresConsentAsync_prior_consent_with_too_few_scopes_should_require_consent() { - await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope2"), new ParsedScopeValue("scope3") }); + await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope2"), new ParsedScopeValue("scope3") }, _ct); - var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); + var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }, _ct); result.ShouldBeTrue(); } @@ -180,12 +181,12 @@ public class DefaultConsentServiceTests var scopes = new[] { new ParsedScopeValue("foo"), new ParsedScopeValue("bar") }; _client.ConsentLifetime = 2; - await _subject.UpdateConsentAsync(_user, _client, scopes); + await _subject.UpdateConsentAsync(_user, _client, scopes, _ct); now = now.AddSeconds(3); _timeProvider.SetUtcNow(now); - var result = await _subject.RequiresConsentAsync(_user, _client, scopes); + var result = await _subject.RequiresConsentAsync(_user, _client, scopes, _ct); result.ShouldBeTrue(); } @@ -198,14 +199,14 @@ public class DefaultConsentServiceTests var scopes = new[] { new ParsedScopeValue("foo"), new ParsedScopeValue("bar") }; _client.ConsentLifetime = 2; - await _subject.UpdateConsentAsync(_user, _client, scopes); + await _subject.UpdateConsentAsync(_user, _client, scopes, _ct); now = now.AddSeconds(3); _timeProvider.SetUtcNow(now); - await _subject.RequiresConsentAsync(_user, _client, scopes); + await _subject.RequiresConsentAsync(_user, _client, scopes, _ct); - var result = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); + var result = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId, _ct); result.ShouldBeNull(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs index 6973a2dcc..e413c5680 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs @@ -12,6 +12,7 @@ public class DefaultCorsPolicyServiceTests private const string Category = "DefaultCorsPolicyService"; private DefaultCorsPolicyService subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; public DefaultCorsPolicyServiceTests() => subject = new DefaultCorsPolicyService(TestLogger.Create()); @@ -19,9 +20,9 @@ public class DefaultCorsPolicyServiceTests [Trait("Category", Category)] public async Task IsOriginAllowed_null_param_ReturnsFalse() { - (await subject.IsOriginAllowedAsync(null)).ShouldBe(false); - (await subject.IsOriginAllowedAsync(string.Empty)).ShouldBe(false); - (await subject.IsOriginAllowedAsync(" ")).ShouldBe(false); + (await subject.IsOriginAllowedAsync(null, _ct)).ShouldBe(false); + (await subject.IsOriginAllowedAsync(string.Empty, _ct)).ShouldBe(false); + (await subject.IsOriginAllowedAsync(" ", _ct)).ShouldBe(false); } [Fact] @@ -29,7 +30,7 @@ public class DefaultCorsPolicyServiceTests public async Task IsOriginAllowed_OriginIsAllowed_ReturnsTrue() { subject.AllowedOrigins.Add("http://foo"); - (await subject.IsOriginAllowedAsync("http://foo")).ShouldBe(true); + (await subject.IsOriginAllowedAsync("http://foo", _ct)).ShouldBe(true); } [Fact] @@ -37,7 +38,7 @@ public class DefaultCorsPolicyServiceTests public async Task IsOriginAllowed_OriginIsNotAllowed_ReturnsFalse() { subject.AllowedOrigins.Add("http://foo"); - (await subject.IsOriginAllowedAsync("http://bar")).ShouldBe(false); + (await subject.IsOriginAllowedAsync("http://bar", _ct)).ShouldBe(false); } [Fact] @@ -47,7 +48,7 @@ public class DefaultCorsPolicyServiceTests subject.AllowedOrigins.Add("http://foo"); subject.AllowedOrigins.Add("http://bar"); subject.AllowedOrigins.Add("http://baz"); - (await subject.IsOriginAllowedAsync("http://bar")).ShouldBe(true); + (await subject.IsOriginAllowedAsync("http://bar", _ct)).ShouldBe(true); } [Fact] @@ -57,7 +58,7 @@ public class DefaultCorsPolicyServiceTests subject.AllowedOrigins.Add("http://foo"); subject.AllowedOrigins.Add("http://bar"); subject.AllowedOrigins.Add("http://baz"); - (await subject.IsOriginAllowedAsync("http://quux")).ShouldBe(false); + (await subject.IsOriginAllowedAsync("http://quux", _ct)).ShouldBe(false); } [Fact] @@ -65,6 +66,6 @@ public class DefaultCorsPolicyServiceTests public async Task IsOriginAllowed_AllowAllTrue_ReturnsTrue() { subject.AllowAll = true; - (await subject.IsOriginAllowedAsync("http://foo")).ShouldBe(true); + (await subject.IsOriginAllowedAsync("http://foo", _ct)).ShouldBe(true); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs index e87ca78ab..dbe544bd2 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs @@ -10,6 +10,7 @@ namespace UnitTests.Services.Default; public class DefaultEventServiceTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] public async Task Raising_an_event_without_http_context_does_not_throw() { @@ -28,7 +29,7 @@ public class DefaultEventServiceTests var evt = new TestEvent(id: 123); - await sut.RaiseAsync(evt); + await sut.RaiseAsync(evt, _ct); sink.Events.ShouldContain(e => e.Id == 123); } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs index 57a2d3add..33c387aa0 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs @@ -16,6 +16,8 @@ namespace UnitTests.Services.Default; public class DefaultIdentityServerInteractionServiceTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + private DefaultIdentityServerInteractionService _subject; private IdentityServerOptions _options = new IdentityServerOptions(); @@ -62,7 +64,7 @@ public class DefaultIdentityServerInteractionServiceTests _mockUserSession.SessionId = null; _mockLogoutMessageStore.Messages.Add("id", new Message(new LogoutMessage() { SessionId = "session" })); - var context = await _subject.GetLogoutContextAsync("id"); + var context = await _subject.GetLogoutContextAsync("id", _ct); context.SignOutIFrameUrl.ShouldBeNull(); } @@ -77,7 +79,7 @@ public class DefaultIdentityServerInteractionServiceTests _mockUserSession.SessionId = "session"; _mockUserSession.User = new IdentityServerUser("123").CreatePrincipal(); - var context = await _subject.GetLogoutContextAsync(null); + var context = await _subject.GetLogoutContextAsync(null, _ct); context.SignOutIFrameUrl.ShouldBeNull(); } @@ -94,7 +96,7 @@ public class DefaultIdentityServerInteractionServiceTests _mockUserSession.SessionId = "session"; _mockUserSession.User = new IdentityServerUser("123").CreatePrincipal(); - var context = await _subject.GetLogoutContextAsync(null); + var context = await _subject.GetLogoutContextAsync(null, _ct); context.SignOutIFrameUrl.ShouldNotBeNull(); } @@ -105,7 +107,7 @@ public class DefaultIdentityServerInteractionServiceTests _mockUserSession.SessionId = null; _mockLogoutMessageStore.Messages.Add("id", new Message(new LogoutMessage())); - var context = await _subject.GetLogoutContextAsync("id"); + var context = await _subject.GetLogoutContextAsync("id", _ct); context.SignOutIFrameUrl.ShouldBeNull(); } @@ -113,7 +115,7 @@ public class DefaultIdentityServerInteractionServiceTests [Fact] public async Task CreateLogoutContextAsync_without_session_should_not_create_session() { - var context = await _subject.CreateLogoutContextAsync(); + var context = await _subject.CreateLogoutContextAsync(_ct); context.ShouldBeNull(); _mockLogoutMessageStore.Messages.ShouldBeEmpty(); @@ -126,7 +128,7 @@ public class DefaultIdentityServerInteractionServiceTests _mockUserSession.User = new IdentityServerUser("123").CreatePrincipal(); _mockUserSession.SessionId = "session"; - var context = await _subject.CreateLogoutContextAsync(); + var context = await _subject.CreateLogoutContextAsync(_ct); context.ShouldNotBeNull(); _mockLogoutMessageStore.Messages.ShouldNotBeEmpty(); @@ -138,6 +140,7 @@ public class DefaultIdentityServerInteractionServiceTests var act = () => _subject.GrantConsentAsync( new AuthorizationRequest(), new ConsentResponse() { ScopesValuesConsented = new[] { "openid" } }, + _ct, null); var exception = await act.ShouldThrowAsync(); @@ -152,7 +155,7 @@ public class DefaultIdentityServerInteractionServiceTests Client = new Client { ClientId = "client" }, ValidatedResources = _resourceValidationResult }; - await _subject.GrantConsentAsync(req, new ConsentResponse { Error = AuthorizationError.AccessDenied }, null); + await _subject.GrantConsentAsync(req, new ConsentResponse { Error = AuthorizationError.AccessDenied }, _ct, null); } [Fact] @@ -165,7 +168,7 @@ public class DefaultIdentityServerInteractionServiceTests Client = new Client { ClientId = "client" }, ValidatedResources = _resourceValidationResult }; - await _subject.GrantConsentAsync(req, new ConsentResponse(), null); + await _subject.GrantConsentAsync(req, new ConsentResponse(), _ct, null); _mockConsentStore.Messages.ShouldNotBeEmpty(); var consentRequest = new ConsentRequest(req, "bob"); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs index dbe20333b..2f069e823 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs @@ -22,6 +22,7 @@ public class DefaultPersistedGrantServiceTests private IUserConsentStore _userConsent; private ClaimsPrincipal _user = new IdentityServerUser("123").CreatePrincipal(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public DefaultPersistedGrantServiceTests() { @@ -56,21 +57,21 @@ public class DefaultPersistedGrantServiceTests ClientId = "client1", SubjectId = "123", Scopes = new string[] { "foo1", "foo2" } - }); + }, _ct); await _userConsent.StoreUserConsentAsync(new Consent() { CreationTime = DateTime.UtcNow, ClientId = "client2", SubjectId = "123", Scopes = new string[] { "foo3" } - }); + }, _ct); await _userConsent.StoreUserConsentAsync(new Consent() { CreationTime = DateTime.UtcNow, ClientId = "client1", SubjectId = "456", Scopes = new string[] { "foo3" } - }); + }, _ct); var handle1 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { @@ -84,7 +85,7 @@ public class DefaultPersistedGrantServiceTests new Claim("scope", "bar1"), new Claim("scope", "bar2") } - }); + }, _ct); var handle2 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { @@ -97,7 +98,7 @@ public class DefaultPersistedGrantServiceTests new Claim("sub", "123"), new Claim("scope", "bar3") } - }); + }, _ct); var handle3 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { @@ -110,7 +111,7 @@ public class DefaultPersistedGrantServiceTests new Claim("sub", "456"), new Claim("scope", "bar3") } - }); + }, _ct); var handle4 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { @@ -119,7 +120,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz1", "baz2" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle5 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client1", @@ -127,7 +128,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz3" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle6 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client2", @@ -135,7 +136,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz3" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle7 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -147,7 +148,7 @@ public class DefaultPersistedGrantServiceTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux1", "quux2" } - }); + }, _ct); var handle8 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -159,7 +160,7 @@ public class DefaultPersistedGrantServiceTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } - }); + }, _ct); var handle9 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -171,9 +172,9 @@ public class DefaultPersistedGrantServiceTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } - }); + }, _ct); - var grants = await _subject.GetAllGrantsAsync("123"); + var grants = await _subject.GetAllGrantsAsync("123", _ct); grants.Count().ShouldBe(2); var grant1 = grants.First(x => x.ClientId == "client1"); @@ -195,19 +196,19 @@ public class DefaultPersistedGrantServiceTests ClientId = "client1", SubjectId = "123", Scopes = new string[] { "foo1", "foo2" } - }); + }, _ct); await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client2", SubjectId = "123", Scopes = new string[] { "foo3" } - }); + }, _ct); await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client1", SubjectId = "456", Scopes = new string[] { "foo3" } - }); + }, _ct); var handle1 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { @@ -222,7 +223,7 @@ public class DefaultPersistedGrantServiceTests new Claim("scope", "bar1"), new Claim("scope", "bar2") } - }); + }, _ct); var handle2 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { @@ -236,7 +237,7 @@ public class DefaultPersistedGrantServiceTests new Claim("sub", "123"), new Claim("scope", "bar3") } - }); + }, _ct); var handle3 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { @@ -250,7 +251,7 @@ public class DefaultPersistedGrantServiceTests new Claim("sub", "456"), new Claim("scope", "bar3") } - }); + }, _ct); var handle4 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { @@ -259,7 +260,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz1", "baz2" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle5 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client1", @@ -267,7 +268,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz3" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle6 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client2", @@ -275,7 +276,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz3" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle7 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -287,7 +288,7 @@ public class DefaultPersistedGrantServiceTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux1", "quux2" } - }); + }, _ct); var handle8 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -299,7 +300,7 @@ public class DefaultPersistedGrantServiceTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } - }); + }, _ct); var handle9 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -311,19 +312,19 @@ public class DefaultPersistedGrantServiceTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } - }); + }, _ct); - await _subject.RemoveAllGrantsAsync("123", "client1"); + await _subject.RemoveAllGrantsAsync("123", _ct, "client1"); - (await _referenceTokens.GetReferenceTokenAsync(handle1)).ShouldBeNull(); - (await _referenceTokens.GetReferenceTokenAsync(handle2)).ShouldNotBeNull(); - (await _referenceTokens.GetReferenceTokenAsync(handle3)).ShouldNotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle4)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle5)).ShouldNotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle6)).ShouldNotBeNull(); - (await _codes.GetAuthorizationCodeAsync(handle7)).ShouldBeNull(); - (await _codes.GetAuthorizationCodeAsync(handle8)).ShouldNotBeNull(); - (await _codes.GetAuthorizationCodeAsync(handle9)).ShouldNotBeNull(); + (await _referenceTokens.GetReferenceTokenAsync(handle1, _ct)).ShouldBeNull(); + (await _referenceTokens.GetReferenceTokenAsync(handle2, _ct)).ShouldNotBeNull(); + (await _referenceTokens.GetReferenceTokenAsync(handle3, _ct)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle4, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle5, _ct)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle6, _ct)).ShouldNotBeNull(); + (await _codes.GetAuthorizationCodeAsync(handle7, _ct)).ShouldBeNull(); + (await _codes.GetAuthorizationCodeAsync(handle8, _ct)).ShouldNotBeNull(); + (await _codes.GetAuthorizationCodeAsync(handle9, _ct)).ShouldNotBeNull(); } [Fact] public async Task RemoveAllGrantsAsync_should_filter_on_session_id() @@ -337,7 +338,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle2 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client2", @@ -346,7 +347,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle3 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client3", @@ -355,16 +356,16 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); - await _subject.RemoveAllGrantsAsync("123"); + await _subject.RemoveAllGrantsAsync("123", _ct); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldBeNull(); - await _refreshTokens.RemoveRefreshTokenAsync(handle1); - await _refreshTokens.RemoveRefreshTokenAsync(handle2); - await _refreshTokens.RemoveRefreshTokenAsync(handle3); + (await _refreshTokens.GetRefreshTokenAsync(handle1, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3, _ct)).ShouldBeNull(); + await _refreshTokens.RemoveRefreshTokenAsync(handle1, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle2, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle3, _ct); } { var handle1 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() @@ -375,7 +376,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle2 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client2", @@ -384,7 +385,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle3 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client3", @@ -393,16 +394,16 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); - await _subject.RemoveAllGrantsAsync("123", "client1"); + await _subject.RemoveAllGrantsAsync("123", _ct, "client1"); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldNotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldNotBeNull(); - await _refreshTokens.RemoveRefreshTokenAsync(handle1); - await _refreshTokens.RemoveRefreshTokenAsync(handle2); - await _refreshTokens.RemoveRefreshTokenAsync(handle3); + (await _refreshTokens.GetRefreshTokenAsync(handle1, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2, _ct)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3, _ct)).ShouldNotBeNull(); + await _refreshTokens.RemoveRefreshTokenAsync(handle1, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle2, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle3, _ct); } { var handle1 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() @@ -413,7 +414,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle2 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client2", @@ -422,7 +423,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle3 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client3", @@ -431,7 +432,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle4 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client1", @@ -440,17 +441,17 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); - await _subject.RemoveAllGrantsAsync("123", "client1", "session1"); + }, _ct); + await _subject.RemoveAllGrantsAsync("123", _ct, "client1", "session1"); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldNotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldNotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle4)).ShouldNotBeNull(); - await _refreshTokens.RemoveRefreshTokenAsync(handle1); - await _refreshTokens.RemoveRefreshTokenAsync(handle2); - await _refreshTokens.RemoveRefreshTokenAsync(handle3); - await _refreshTokens.RemoveRefreshTokenAsync(handle4); + (await _refreshTokens.GetRefreshTokenAsync(handle1, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2, _ct)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3, _ct)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle4, _ct)).ShouldNotBeNull(); + await _refreshTokens.RemoveRefreshTokenAsync(handle1, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle2, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle3, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle4, _ct); } { var handle1 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() @@ -461,7 +462,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle2 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client2", @@ -470,7 +471,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle3 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client3", @@ -479,7 +480,7 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); + }, _ct); var handle4 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { ClientId = "client1", @@ -488,17 +489,17 @@ public class DefaultPersistedGrantServiceTests AuthorizedScopes = new[] { "baz" }, CreationTime = DateTime.UtcNow, Lifetime = 10, - }); - await _subject.RemoveAllGrantsAsync("123", sessionId: "session1"); + }, _ct); + await _subject.RemoveAllGrantsAsync("123", _ct, sessionId: "session1"); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle4)).ShouldNotBeNull(); - await _refreshTokens.RemoveRefreshTokenAsync(handle1); - await _refreshTokens.RemoveRefreshTokenAsync(handle2); - await _refreshTokens.RemoveRefreshTokenAsync(handle3); - await _refreshTokens.RemoveRefreshTokenAsync(handle4); + (await _refreshTokens.GetRefreshTokenAsync(handle1, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3, _ct)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle4, _ct)).ShouldNotBeNull(); + await _refreshTokens.RemoveRefreshTokenAsync(handle1, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle2, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle3, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle4, _ct); } } @@ -510,9 +511,9 @@ public class DefaultPersistedGrantServiceTests ClientId = "client1", SubjectId = "123", Scopes = new string[] { "foo1", "foo2" } - }); + }, _ct); - var grants = await _subject.GetAllGrantsAsync("123"); + var grants = await _subject.GetAllGrantsAsync("123", _ct); grants.Count().ShouldBe(1); grants.First().Scopes.ShouldBe(["foo1", "foo2"]); @@ -527,9 +528,9 @@ public class DefaultPersistedGrantServiceTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } - }); + }, _ct); - grants = await _subject.GetAllGrantsAsync("123"); + grants = await _subject.GetAllGrantsAsync("123", _ct); grants.Count().ShouldBe(1); grants.First().Scopes.ShouldBe(["foo1", "foo2", "quux3"]); @@ -553,15 +554,15 @@ public class DefaultPersistedGrantServiceTests ClientId = "client1", SubjectId = "123", Scopes = new string[] { "foo1", "foo2" } - }); + }, _ct); await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client2", SubjectId = "123", Scopes = new string[] { "foo3" } - }); + }, _ct); - var grants = await _subject.GetAllGrantsAsync("123"); + var grants = await _subject.GetAllGrantsAsync("123", _ct); grants.Count().ShouldBe(1); grants.First().Scopes.ShouldBe(["foo1", "foo2"]); @@ -575,9 +576,9 @@ public class DefaultPersistedGrantServiceTests public CorruptingPersistedGrantStore(IPersistedGrantStore inner) => _inner = inner; - public async Task> GetAllAsync(PersistedGrantFilter filter) + public async Task> GetAllAsync(PersistedGrantFilter filter, Ct ct) { - var items = await _inner.GetAllAsync(filter); + var items = await _inner.GetAllAsync(filter, ct); if (ClientIdToCorrupt != null) { var itemsToCorrupt = items.Where(x => x.ClientId == ClientIdToCorrupt); @@ -589,12 +590,12 @@ public class DefaultPersistedGrantServiceTests return items; } - public Task GetAsync(string key) => _inner.GetAsync(key); + public Task GetAsync(string key, Ct ct) => _inner.GetAsync(key, ct); - public Task RemoveAllAsync(PersistedGrantFilter filter) => _inner.RemoveAllAsync(filter); + public Task RemoveAllAsync(PersistedGrantFilter filter, Ct ct) => _inner.RemoveAllAsync(filter, ct); - public Task RemoveAsync(string key) => _inner.RemoveAsync(key); + public Task RemoveAsync(string key, Ct ct) => _inner.RemoveAsync(key, ct); - public Task StoreAsync(PersistedGrant grant) => _inner.StoreAsync(grant); + public Task StoreAsync(PersistedGrant grant, Ct ct) => _inner.StoreAsync(grant, ct); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs index 22177d25b..4f32bd9fd 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs @@ -21,6 +21,7 @@ public class DefaultRefreshTokenServiceTests private ClaimsPrincipal _user = new IdentityServerUser("123").CreatePrincipal(); private FakeTimeProvider _timeProvider = new FakeTimeProvider(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public DefaultRefreshTokenServiceTests() { @@ -46,9 +47,9 @@ public class DefaultRefreshTokenServiceTests var client = new Client(); var accessToken = new Token(); - var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = accessToken, Client = client }); + var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = accessToken, Client = client }, _ct); - (await _store.GetRefreshTokenAsync(handle)).ShouldNotBeNull(); + (await _store.GetRefreshTokenAsync(handle, _ct)).ShouldNotBeNull(); } [Fact] @@ -62,9 +63,9 @@ public class DefaultRefreshTokenServiceTests AbsoluteRefreshTokenLifetime = 10 }; - var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = new Token(), Client = client }); + var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = new Token(), Client = client }, _ct); - var refreshToken = (await _store.GetRefreshTokenAsync(handle)); + var refreshToken = (await _store.GetRefreshTokenAsync(handle, _ct)); refreshToken.ShouldNotBeNull(); refreshToken.Lifetime.ShouldBe(client.AbsoluteRefreshTokenLifetime); @@ -82,9 +83,9 @@ public class DefaultRefreshTokenServiceTests AbsoluteRefreshTokenLifetime = 10 }; - var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = new Token(), Client = client }); + var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = new Token(), Client = client }, _ct); - var refreshToken = (await _store.GetRefreshTokenAsync(handle)); + var refreshToken = (await _store.GetRefreshTokenAsync(handle, _ct)); refreshToken.ShouldNotBeNull(); refreshToken.Lifetime.ShouldBe(client.AbsoluteRefreshTokenLifetime); @@ -101,9 +102,9 @@ public class DefaultRefreshTokenServiceTests SlidingRefreshTokenLifetime = 10 }; - var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = new Token(), Client = client }); + var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = new Token(), Client = client }, _ct); - var refreshToken = (await _store.GetRefreshTokenAsync(handle)); + var refreshToken = (await _store.GetRefreshTokenAsync(handle, _ct)); refreshToken.ShouldNotBeNull(); refreshToken.Lifetime.ShouldBe(client.SlidingRefreshTokenLifetime); @@ -124,9 +125,9 @@ public class DefaultRefreshTokenServiceTests Lifetime = 10, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); - (await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client })) + (await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }, _ct)) .ShouldNotBeNull() .ShouldNotBe(handle); } @@ -149,14 +150,14 @@ public class DefaultRefreshTokenServiceTests var handle = await _store.StoreRefreshTokenAsync(new RefreshToken { CreationTime = now.AddSeconds(-10), - }); + }, _ct); - var refreshToken = await _store.GetRefreshTokenAsync(handle); - var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); + var refreshToken = await _store.GetRefreshTokenAsync(handle, _ct); + var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }, _ct); newHandle.ShouldBe(handle); - var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); + var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle, _ct); newRefreshToken.ShouldNotBeNull(); newRefreshToken.Lifetime.ShouldBe((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); @@ -180,14 +181,14 @@ public class DefaultRefreshTokenServiceTests var handle = await _store.StoreRefreshTokenAsync(new RefreshToken { CreationTime = now.AddSeconds(-1000), - }); + }, _ct); - var refreshToken = await _store.GetRefreshTokenAsync(handle); - var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); + var refreshToken = await _store.GetRefreshTokenAsync(handle, _ct); + var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }, _ct); newHandle.ShouldBe(handle); - var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); + var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle, _ct); newRefreshToken.ShouldNotBeNull(); newRefreshToken.Lifetime.ShouldBe(client.AbsoluteRefreshTokenLifetime); @@ -211,14 +212,14 @@ public class DefaultRefreshTokenServiceTests var handle = await _store.StoreRefreshTokenAsync(new RefreshToken { CreationTime = now.AddSeconds(-1000), - }); + }, _ct); - var refreshToken = await _store.GetRefreshTokenAsync(handle); - var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); + var refreshToken = await _store.GetRefreshTokenAsync(handle, _ct); + var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }, _ct); newHandle.ShouldBe(handle); - var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); + var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle, _ct); newRefreshToken.ShouldNotBeNull(); newRefreshToken.Lifetime.ShouldBe((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); @@ -244,14 +245,14 @@ public class DefaultRefreshTokenServiceTests ClientId = client.ClientId, Subject = _user, CreationTime = now.AddSeconds(-1000), - }); + }, _ct); - var refreshToken = await _store.GetRefreshTokenAsync(handle); - var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); + var refreshToken = await _store.GetRefreshTokenAsync(handle, _ct); + var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }, _ct); newHandle.ShouldNotBeNull().ShouldNotBe(handle); - var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); + var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle, _ct); newRefreshToken.ShouldNotBeNull(); newRefreshToken.Lifetime.ShouldBe((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); @@ -275,15 +276,15 @@ public class DefaultRefreshTokenServiceTests Lifetime = 10, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); var now = DateTime.UtcNow; _timeProvider.SetUtcNow(now); - var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); + var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }, _ct); - var oldToken = await _store.GetRefreshTokenAsync(handle); - var newToken = await _store.GetRefreshTokenAsync(newHandle); + var oldToken = await _store.GetRefreshTokenAsync(handle, _ct); + var newToken = await _store.GetRefreshTokenAsync(newHandle, _ct); oldToken.ConsumedTime.ShouldBe(now); newToken.ConsumedTime.ShouldBeNull(); @@ -310,15 +311,15 @@ public class DefaultRefreshTokenServiceTests Lifetime = 10, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); var now = DateTime.UtcNow; _timeProvider.SetUtcNow(now); - var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); + var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }, _ct); - var oldToken = await _store.GetRefreshTokenAsync(handle); - var newToken = await _store.GetRefreshTokenAsync(newHandle); + var oldToken = await _store.GetRefreshTokenAsync(handle, _ct); + var newToken = await _store.GetRefreshTokenAsync(newHandle, _ct); oldToken.ShouldBeNull(); newToken.ConsumedTime.ShouldBeNull(); @@ -336,7 +337,7 @@ public class DefaultRefreshTokenServiceTests RefreshTokenUsage = TokenUsage.OneTimeOnly }; - var result = await _subject.ValidateRefreshTokenAsync("invalid", client); + var result = await _subject.ValidateRefreshTokenAsync("invalid", client, _ct); result.IsError.ShouldBeTrue(); } @@ -358,12 +359,12 @@ public class DefaultRefreshTokenServiceTests Lifetime = 10, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); var now = DateTime.UtcNow; _timeProvider.SetUtcNow(now); - var result = await _subject.ValidateRefreshTokenAsync(handle, client); + var result = await _subject.ValidateRefreshTokenAsync(handle, client, _ct); result.IsError.ShouldBeTrue(); } @@ -386,12 +387,12 @@ public class DefaultRefreshTokenServiceTests Lifetime = 10, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); var now = DateTime.UtcNow; _timeProvider.SetUtcNow(now); - var result = await _subject.ValidateRefreshTokenAsync(handle, client); + var result = await _subject.ValidateRefreshTokenAsync(handle, client, _ct); result.IsError.ShouldBeTrue(); } @@ -414,12 +415,12 @@ public class DefaultRefreshTokenServiceTests Lifetime = 10, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); var now = DateTime.UtcNow.AddSeconds(20); _timeProvider.SetUtcNow(now); - var result = await _subject.ValidateRefreshTokenAsync(handle, client); + var result = await _subject.ValidateRefreshTokenAsync(handle, client, _ct); result.IsError.ShouldBeTrue(); } @@ -443,12 +444,12 @@ public class DefaultRefreshTokenServiceTests Subject = _user, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); var now = DateTime.UtcNow; _timeProvider.SetUtcNow(now); - var result = await _subject.ValidateRefreshTokenAsync(handle, client); + var result = await _subject.ValidateRefreshTokenAsync(handle, client, _ct); result.IsError.ShouldBeTrue(); } @@ -471,12 +472,12 @@ public class DefaultRefreshTokenServiceTests Lifetime = 10, }; - var handle = await _store.StoreRefreshTokenAsync(refreshToken); + var handle = await _store.StoreRefreshTokenAsync(refreshToken, _ct); var now = DateTime.UtcNow; _timeProvider.SetUtcNow(now); - var result = await _subject.ValidateRefreshTokenAsync(handle, client); + var result = await _subject.ValidateRefreshTokenAsync(handle, client, _ct); result.IsError.ShouldBeFalse(); } @@ -500,12 +501,12 @@ public class DefaultRefreshTokenServiceTests }; // force create in DB with this key value (pre-v6 format) - await _store.UpdateRefreshTokenAsync("key", refreshToken); + await _store.UpdateRefreshTokenAsync("key", refreshToken, _ct); var now = DateTime.UtcNow; _timeProvider.SetUtcNow(now); - var result = await _subject.ValidateRefreshTokenAsync("key", client); + var result = await _subject.ValidateRefreshTokenAsync("key", client, _ct); result.IsError.ShouldBeFalse(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultSessionCoordinationServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultSessionCoordinationServiceTests.cs index 59f147431..92555f3f9 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultSessionCoordinationServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultSessionCoordinationServiceTests.cs @@ -13,6 +13,7 @@ namespace UnitTests.Services.Default; public class DefaultSessionCoordinationServiceTests { public DefaultSessionCoordinationService Service; + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] public async Task Handles_missing_client_null_reference() @@ -30,7 +31,7 @@ public class DefaultSessionCoordinationServiceTests ClientIds = ["not_found"], SessionId = "1", SubjectId = "1" - }); + }, _ct); stubBackChannelLogoutClient .SendLogoutsWasCalled diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs index 0da24cf04..af95c3669 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs @@ -17,6 +17,7 @@ namespace UnitTests.Services.Default; public class DefaultTokenServiceTests { private DefaultTokenService _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; private MockClaimsService _mockClaimsService = new MockClaimsService(); private MockReferenceTokenStore _mockReferenceTokenStore = new MockReferenceTokenStore(); @@ -71,7 +72,7 @@ public class DefaultTokenServiceTests } }; - var result = await _subject.CreateAccessTokenAsync(request); + var result = await _subject.CreateAccessTokenAsync(request, _ct); result.Audiences.Count.ShouldBe(3); result.Audiences.ShouldBe(["api1", "api2", "api3"]); @@ -106,7 +107,7 @@ public class DefaultTokenServiceTests } }; - var result = await _subject.CreateAccessTokenAsync(request); + var result = await _subject.CreateAccessTokenAsync(request, _ct); result.Audiences.Count.ShouldBe(0); } @@ -124,7 +125,7 @@ public class DefaultTokenServiceTests } }; - var result = await _subject.CreateAccessTokenAsync(request); + var result = await _subject.CreateAccessTokenAsync(request, _ct); result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).ShouldBeNull(); } @@ -142,7 +143,7 @@ public class DefaultTokenServiceTests } }; - var result = await _subject.CreateAccessTokenAsync(request); + var result = await _subject.CreateAccessTokenAsync(request, _ct); result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).Value.ShouldBe("123"); } @@ -158,28 +159,28 @@ public class DefaultTokenServiceTests { token.IncludeJwtId = false; token.Type = OidcConstants.TokenTypes.IdentityToken; - var result = await _subject.CreateSecurityTokenAsync(token); + var result = await _subject.CreateSecurityTokenAsync(token, _ct); _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.IncludeJwtId = false; token.Type = OidcConstants.TokenTypes.AccessToken; - var result = await _subject.CreateSecurityTokenAsync(token); + var result = await _subject.CreateSecurityTokenAsync(token, _ct); _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.IncludeJwtId = true; token.Type = OidcConstants.TokenTypes.IdentityToken; - var result = await _subject.CreateSecurityTokenAsync(token); + var result = await _subject.CreateSecurityTokenAsync(token, _ct); _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.IncludeJwtId = true; token.Type = OidcConstants.TokenTypes.AccessToken; - var result = await _subject.CreateSecurityTokenAsync(token); + var result = await _subject.CreateSecurityTokenAsync(token, _ct); _mockTokenCreationService.Token.Claims.ShouldContain(x => x.Type == "jti"); } } @@ -198,14 +199,14 @@ public class DefaultTokenServiceTests }; { - var result = await _subject.CreateSecurityTokenAsync(token); + var result = await _subject.CreateSecurityTokenAsync(token, _ct); _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.Claims.Add(new Claim("jti", "xoxo")); token.Type = OidcConstants.TokenTypes.AccessToken; - var result = await _subject.CreateSecurityTokenAsync(token); + var result = await _subject.CreateSecurityTokenAsync(token, _ct); _mockTokenCreationService.Token.Claims.ShouldContain(x => x.Type == "jti"); _mockTokenCreationService.Token.Claims.Single(x => x.Type == "jti").Value.ShouldNotBe("xoxo"); } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUiLocalesServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUiLocalesServiceTests.cs index 9dfa43adf..d1ffcc812 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUiLocalesServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUiLocalesServiceTests.cs @@ -15,6 +15,7 @@ namespace UnitTests.Services.Default; public class DefaultUiLocalesServiceTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; private readonly DefaultHttpContext _httpContext; private readonly HttpContextAccessor _httpContextAccessor; private readonly RequestLocalizationOptions _requestLocalizationOptions; @@ -34,7 +35,7 @@ public class DefaultUiLocalesServiceTests { _httpContextAccessor.HttpContext = null; - await _subject.StoreUiLocalesForRedirectAsync("en-US"); + await _subject.StoreUiLocalesForRedirectAsync("en-US", _ct); var setCookieHeader = _httpContext.Response.Headers.Where(x => x.Key == "Set-Cookie"); setCookieHeader.ShouldBeEmpty(); @@ -45,7 +46,7 @@ public class DefaultUiLocalesServiceTests { _requestLocalizationOptions.RequestCultureProviders.Clear(); - await _subject.StoreUiLocalesForRedirectAsync("en-US"); + await _subject.StoreUiLocalesForRedirectAsync("en-US", _ct); var setCookieHeader = _httpContext.Response.Headers.Where(x => x.Key == "Set-Cookie"); setCookieHeader.ShouldBeEmpty(); @@ -56,7 +57,7 @@ public class DefaultUiLocalesServiceTests { _requestLocalizationOptions.SupportedUICultures = new List { new("fr-FR") }; - await _subject.StoreUiLocalesForRedirectAsync("en-US"); + await _subject.StoreUiLocalesForRedirectAsync("en-US", _ct); var setCookieHeader = _httpContext.Response.Headers.Where(x => x.Key == "Set-Cookie"); setCookieHeader.ShouldBeEmpty(); @@ -67,7 +68,7 @@ public class DefaultUiLocalesServiceTests { _requestLocalizationOptions.SupportedUICultures = new List { new("fr-FR") }; - await _subject.StoreUiLocalesForRedirectAsync("en-US nb-NO"); + await _subject.StoreUiLocalesForRedirectAsync("en-US nb-NO", _ct); var setCookieHeader = _httpContext.Response.Headers.Where(x => x.Key == "Set-Cookie"); setCookieHeader.ShouldBeEmpty(); @@ -79,7 +80,7 @@ public class DefaultUiLocalesServiceTests [InlineData(" ")] public async Task StoreUiLocalesForRedirectAsync_NullOrWhitespaceUiLocales_DoesNothing(string? uiLocales) { - await _subject.StoreUiLocalesForRedirectAsync(uiLocales); + await _subject.StoreUiLocalesForRedirectAsync(uiLocales, _ct); var setCookieHeader = _httpContext.Response.Headers.Where(x => x.Key == "Set-Cookie"); setCookieHeader.ShouldBeEmpty(); @@ -90,7 +91,7 @@ public class DefaultUiLocalesServiceTests { _requestLocalizationOptions.SupportedUICultures = new List(); - await _subject.StoreUiLocalesForRedirectAsync("en-US"); + await _subject.StoreUiLocalesForRedirectAsync("en-US", _ct); var setCookieHeader = _httpContext.Response.Headers.Where(x => x.Key == "Set-Cookie"); setCookieHeader.ShouldBeEmpty(); @@ -102,7 +103,7 @@ public class DefaultUiLocalesServiceTests var expectedSetCookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(new CultureInfo("en-US"))); _requestLocalizationOptions.SupportedUICultures = new List { new("en-US") }; - await _subject.StoreUiLocalesForRedirectAsync("en-US"); + await _subject.StoreUiLocalesForRedirectAsync("en-US", _ct); var cookieContainer = new CookieContainer(); var cookies = _httpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); @@ -122,7 +123,7 @@ public class DefaultUiLocalesServiceTests new("de-DE") }; - await _subject.StoreUiLocalesForRedirectAsync("en-US fr-FR"); + await _subject.StoreUiLocalesForRedirectAsync("en-US fr-FR", _ct); var cookieContainer = new CookieContainer(); var cookies = _httpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); @@ -142,7 +143,7 @@ public class DefaultUiLocalesServiceTests new("de-DE") }; - await _subject.StoreUiLocalesForRedirectAsync("fr-FR en-US"); + await _subject.StoreUiLocalesForRedirectAsync("fr-FR en-US", _ct); var cookieContainer = new CookieContainer(); var cookies = _httpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs index de5287039..68f9a050e 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs @@ -17,6 +17,8 @@ namespace UnitTests.Services.Default; public class DefaultUserSessionTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + private DefaultUserSession _subject; private MockHttpContextAccessor _mockHttpContext = new MockHttpContextAccessor(); private MockAuthenticationHandlerProvider _mockAuthenticationHandlerProvider = new MockAuthenticationHandlerProvider(); @@ -43,7 +45,7 @@ public class DefaultUserSessionTests [Fact] public async Task CreateSessionId_when_user_is_anonymous_should_generate_new_sid() { - await _subject.CreateSessionIdAsync(_user, _props); + await _subject.CreateSessionIdAsync(_user, _props, _ct); _props.GetSessionId().ShouldNotBeNull(); } @@ -56,7 +58,7 @@ public class DefaultUserSessionTests var newProps = new AuthenticationProperties(); newProps.SetSessionId("999"); - await _subject.CreateSessionIdAsync(_user, newProps); + await _subject.CreateSessionIdAsync(_user, newProps, _ct); newProps.GetSessionId().ShouldNotBeNull(); newProps.GetSessionId().ShouldBe("999"); @@ -70,7 +72,7 @@ public class DefaultUserSessionTests _props.GetSessionId().ShouldBeNull(); var newProps = new AuthenticationProperties(); - await _subject.CreateSessionIdAsync(_user, newProps); + await _subject.CreateSessionIdAsync(_user, newProps, _ct); newProps.GetSessionId().ShouldNotBeNull(); } @@ -82,7 +84,7 @@ public class DefaultUserSessionTests _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); var newProps = new AuthenticationProperties(); - await _subject.CreateSessionIdAsync(new IdentityServerUser("alice").CreatePrincipal(), newProps); + await _subject.CreateSessionIdAsync(new IdentityServerUser("alice").CreatePrincipal(), newProps, _ct); newProps.GetSessionId().ShouldNotBeNull(); newProps.GetSessionId().ShouldNotBe("999"); @@ -95,7 +97,7 @@ public class DefaultUserSessionTests _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); var newProps = new AuthenticationProperties(); - await _subject.CreateSessionIdAsync(_user, newProps); + await _subject.CreateSessionIdAsync(_user, newProps, _ct); newProps.GetSessionId().ShouldNotBeNull(); newProps.GetSessionId().ShouldBe("999"); @@ -104,7 +106,7 @@ public class DefaultUserSessionTests [Fact] public async Task CreateSessionId_should_issue_session_id_cookie() { - await _subject.CreateSessionIdAsync(_user, _props); + await _subject.CreateSessionIdAsync(_user, _props, _ct); var cookieContainer = new CookieContainer(); var cookies = _mockHttpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); @@ -121,7 +123,7 @@ public class DefaultUserSessionTests _props.SetSessionId("999"); _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - await _subject.EnsureSessionIdCookieAsync(); + await _subject.EnsureSessionIdCookieAsync(_ct); var cookieContainer = new CookieContainer(); var cookies = _mockHttpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); @@ -135,7 +137,7 @@ public class DefaultUserSessionTests [Fact] public async Task EnsureSessionIdCookieAsync_should_not_add_cookie_if_no_sid() { - await _subject.EnsureSessionIdCookieAsync(); + await _subject.EnsureSessionIdCookieAsync(_ct); var cookieContainer = new CookieContainer(); var cookies = _mockHttpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); @@ -152,7 +154,7 @@ public class DefaultUserSessionTests _props.SetSessionId("999"); _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - await _subject.EnsureSessionIdCookieAsync(); + await _subject.EnsureSessionIdCookieAsync(_ct); var cookieContainer = new CookieContainer(); var cookies = _mockHttpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); @@ -162,7 +164,7 @@ public class DefaultUserSessionTests var cookie = cookieContainer.GetCookieHeader(new Uri("http://server")); _mockHttpContext.HttpContext.Request.Headers.Append("Cookie", cookie); - await _subject.RemoveSessionIdCookieAsync(); + await _subject.RemoveSessionIdCookieAsync(_ct); cookies = _mockHttpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); cookieContainer.SetCookies(new Uri("http://server"), string.Join(',', cookies)); @@ -177,14 +179,14 @@ public class DefaultUserSessionTests _props.SetSessionId("999"); _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - var sid = await _subject.GetSessionIdAsync(); + var sid = await _subject.GetSessionIdAsync(_ct); sid.ShouldBe("999"); } [Fact] public async Task GetCurrentSessionIdAsync_when_user_is_anonymous_should_return_null() { - var sid = await _subject.GetSessionIdAsync(); + var sid = await _subject.GetSessionIdAsync(_ct); sid.ShouldBeNull(); } @@ -194,7 +196,7 @@ public class DefaultUserSessionTests _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); _props.Items.Count.ShouldBe(0); - await _subject.AddClientIdAsync("client"); + await _subject.AddClientIdAsync("client", _ct); _props.Items.Count.ShouldBe(1); } @@ -203,7 +205,7 @@ public class DefaultUserSessionTests { _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - var user = await _subject.GetUserAsync(); + var user = await _subject.GetUserAsync(_ct); user.GetSubjectId().ShouldBe("123"); } @@ -213,14 +215,14 @@ public class DefaultUserSessionTests var cp = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim("xoxo", "1") })); _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(cp, _props, "scheme")); - var user = await _subject.GetUserAsync(); + var user = await _subject.GetUserAsync(_ct); user.ShouldBeNull(); } [Fact] public async Task when_anonymous_GetIdentityServerUserAsync_should_return_null() { - var user = await _subject.GetUserAsync(); + var user = await _subject.GetUserAsync(_ct); user.ShouldBeNull(); } @@ -229,11 +231,11 @@ public class DefaultUserSessionTests { _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - await _subject.AddClientIdAsync("client"); + await _subject.AddClientIdAsync("client", _ct); var item = _props.Items.First(); _props.Items[item.Key] = "junk"; - var clients = await _subject.GetClientListAsync(); + var clients = await _subject.GetClientListAsync(_ct); clients.ShouldBeEmpty(); _props.Items.Count.ShouldBe(0); } @@ -243,8 +245,8 @@ public class DefaultUserSessionTests { _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - await _subject.AddClientIdAsync("client"); - var clients = await _subject.GetClientListAsync(); + await _subject.AddClientIdAsync("client", _ct); + var clients = await _subject.GetClientListAsync(_ct); clients.ShouldBe(["client"]); } @@ -253,9 +255,9 @@ public class DefaultUserSessionTests { _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - await _subject.AddClientIdAsync("client1"); - await _subject.AddClientIdAsync("client2"); - var clients = await _subject.GetClientListAsync(); + await _subject.AddClientIdAsync("client1", _ct); + await _subject.AddClientIdAsync("client2", _ct); + var clients = await _subject.GetClientListAsync(_ct); clients.ShouldBe(["client2", "client1"], true); } @@ -265,10 +267,10 @@ public class DefaultUserSessionTests _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); const string clientId = "client"; - await _subject.AddClientIdAsync(clientId); - await _subject.AddClientIdAsync(clientId); + await _subject.AddClientIdAsync(clientId, _ct); + await _subject.AddClientIdAsync(clientId, _ct); - var clients = await _subject.GetClientListAsync(); + var clients = await _subject.GetClientListAsync(_ct); _props.Items.Count.ShouldBe(1); clients.ShouldBe([clientId]); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs index 817a65f3f..679465854 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs @@ -16,6 +16,7 @@ public class DistributedDeviceFlowThrottlingServiceTests { private TestCache cache = new TestCache(); private InMemoryClientStore _store; + private readonly Ct _ct = TestContext.Current.CancellationToken; private readonly IdentityServerOptions options = new IdentityServerOptions { DeviceFlow = new DeviceFlowOptions { Interval = 5 } }; private readonly DeviceCode deviceCode = new DeviceCode @@ -35,7 +36,7 @@ public class DistributedDeviceFlowThrottlingServiceTests var handle = Guid.NewGuid().ToString(); var service = new DistributedDeviceFlowThrottlingService(cache, _store, new FakeTimeProvider(testDate), options); - var result = await service.ShouldSlowDown(handle, deviceCode); + var result = await service.ShouldSlowDown(handle, deviceCode, _ct); result.ShouldBeFalse(); @@ -50,7 +51,7 @@ public class DistributedDeviceFlowThrottlingServiceTests await cache.SetAsync(CacheKey + handle, Encoding.UTF8.GetBytes(testDate.AddSeconds(-1).ToString("O"))); - var result = await service.ShouldSlowDown(handle, deviceCode); + var result = await service.ShouldSlowDown(handle, deviceCode, _ct); result.ShouldBeTrue(); @@ -66,7 +67,7 @@ public class DistributedDeviceFlowThrottlingServiceTests await cache.SetAsync($"devicecode_{handle}", Encoding.UTF8.GetBytes(testDate.AddSeconds(-deviceCode.Lifetime - 1).ToString("O"))); - var result = await service.ShouldSlowDown(handle, deviceCode); + var result = await service.ShouldSlowDown(handle, deviceCode, _ct); result.ShouldBeFalse(); @@ -84,7 +85,7 @@ public class DistributedDeviceFlowThrottlingServiceTests var service = new DistributedDeviceFlowThrottlingService(cache, _store, new FakeTimeProvider(testDate), options); - var result = await service.ShouldSlowDown(handle, deviceCode); + var result = await service.ShouldSlowDown(handle, deviceCode, _ct); result.ShouldBeFalse(); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs index d0dc5a677..efab38136 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs @@ -10,6 +10,7 @@ namespace UnitTests.Services.Default.KeyManagement; public class InMemoryKeyStoreCacheTests { private InMemoryKeyStoreCache _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; private FakeTimeProvider _mockTimeProvider = new FakeTimeProvider(new DateTimeOffset(new DateTime(2018, 3, 1, 9, 0, 0))); public InMemoryKeyStoreCacheTests() => _subject = new InMemoryKeyStoreCache(_mockTimeProvider); @@ -23,18 +24,18 @@ public class InMemoryKeyStoreCacheTests new RsaKeyContainer() { Created = _mockTimeProvider.GetUtcNow().UtcDateTime.Subtract(TimeSpan.FromMinutes(1)) }, new RsaKeyContainer() { Created = _mockTimeProvider.GetUtcNow().UtcDateTime.Subtract(TimeSpan.FromMinutes(2)) }, }; - await _subject.StoreKeysAsync(keys, TimeSpan.FromMinutes(1)); + await _subject.StoreKeysAsync(keys, TimeSpan.FromMinutes(1), _ct); - var result = await _subject.GetKeysAsync(); + var result = await _subject.GetKeysAsync(_ct); result.ShouldBeSameAs(keys); // Verify keys remain cached as time advances within expiration window _mockTimeProvider.SetUtcNow(now.Add(TimeSpan.FromSeconds(59))); - result = await _subject.GetKeysAsync(); + result = await _subject.GetKeysAsync(_ct); result.ShouldBeSameAs(keys); _mockTimeProvider.SetUtcNow(now.Add(TimeSpan.FromMinutes(1))); - result = await _subject.GetKeysAsync(); + result = await _subject.GetKeysAsync(_ct); result.ShouldBeSameAs(keys); } @@ -47,10 +48,10 @@ public class InMemoryKeyStoreCacheTests new RsaKeyContainer() { Created = _mockTimeProvider.GetUtcNow().UtcDateTime.Subtract(TimeSpan.FromMinutes(1)) }, new RsaKeyContainer() { Created = _mockTimeProvider.GetUtcNow().UtcDateTime.Subtract(TimeSpan.FromMinutes(2)) }, }; - await _subject.StoreKeysAsync(keys, TimeSpan.FromMinutes(1)); + await _subject.StoreKeysAsync(keys, TimeSpan.FromMinutes(1), _ct); _mockTimeProvider.SetUtcNow(now.Add(TimeSpan.FromSeconds(61))); - var result = await _subject.GetKeysAsync(); + var result = await _subject.GetKeysAsync(_ct); result.ShouldBeNull(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs index 0c9f32893..4ce844018 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs @@ -18,6 +18,8 @@ public class KeyManagerTests { private KeyManager _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; + private SigningAlgorithmOptions _rsaOptions = new SigningAlgorithmOptions("RS256"); private IdentityServerOptions _options = new IdentityServerOptions(); @@ -119,7 +121,7 @@ public class KeyManagerTests { var id = CreateAndStoreKey(_options.KeyManagement.PropagationTime.Add(TimeSpan.FromHours(1))); - var keys = await _subject.GetCurrentKeysAsync(); + var keys = await _subject.GetCurrentKeysAsync(_ct); var key = keys.Single(); key.Id.ShouldBe(id); } @@ -131,7 +133,7 @@ public class KeyManagerTests { var id = CreateAndStoreKey(_options.KeyManagement.PropagationTime.Add(TimeSpan.FromHours(1))); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); key.Id.ShouldBe(id); @@ -142,7 +144,7 @@ public class KeyManagerTests { var id = CreateAndStoreKey(TimeSpan.FromSeconds(5)); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -156,7 +158,7 @@ public class KeyManagerTests { var id = CreateAndStoreKey(-TimeSpan.FromSeconds(5)); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -168,7 +170,7 @@ public class KeyManagerTests [Fact] public async Task GetAllKeysInternalAsync_when_no_keys_should_create_key() { - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -182,7 +184,7 @@ public class KeyManagerTests { _mockKeyStore.Keys = null; - var (keys, key) = await _subject.GetAllKeysInternalAsync(); + var (keys, key) = await _subject.GetAllKeysInternalAsync(_ct); keys.ShouldNotBeEmpty(); } @@ -192,7 +194,7 @@ public class KeyManagerTests { var id = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Add(TimeSpan.FromSeconds(5))); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -207,7 +209,7 @@ public class KeyManagerTests var id1 = CreateCacheAndStoreKey(_options.KeyManagement.RotationInterval.Add(TimeSpan.FromSeconds(5))); var id2 = CreateAndStoreKey(); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -223,7 +225,7 @@ public class KeyManagerTests var key3 = CreateAndStoreKey(-TimeSpan.FromSeconds(5)); var key4 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Add(TimeSpan.FromSeconds(5))); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -238,7 +240,7 @@ public class KeyManagerTests var key1 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Subtract(TimeSpan.FromSeconds(10))); var key2 = CreateAndStoreKey(-TimeSpan.FromSeconds(5)); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -256,7 +258,7 @@ public class KeyManagerTests var key4 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Add(TimeSpan.FromSeconds(5))); var key5 = CreateAndStoreKey(_options.KeyManagement.KeyRetirementAge.Add(TimeSpan.FromSeconds(5))); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); allKeys.Select(x => x.Id).ShouldBe([key1, key2, key3, key4]); } @@ -272,7 +274,7 @@ public class KeyManagerTests var key4 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Add(TimeSpan.FromSeconds(5))); var key5 = CreateAndStoreKey(_options.KeyManagement.KeyRetirementAge.Add(TimeSpan.FromSeconds(5))); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); allKeys.Select(x => x.Id).ShouldBe([key1, key2, key3, key4]); } @@ -282,7 +284,7 @@ public class KeyManagerTests { var key = CreateAndStoreKey(); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); allKeys.Count().ShouldBe(1); allKeys.Single().Id.ShouldBe(key); @@ -300,7 +302,7 @@ public class KeyManagerTests key }; - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); allKeys.Count().ShouldBe(1); allKeys.Single().Id.ShouldBe(key.Id); @@ -312,7 +314,7 @@ public class KeyManagerTests { var key1 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Subtract(TimeSpan.FromSeconds(1))); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -327,7 +329,7 @@ public class KeyManagerTests var key1 = CreateCacheAndStoreKey(_options.KeyManagement.RotationInterval.Subtract(TimeSpan.FromSeconds(1))); var key2 = CreateAndStoreKey(); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); _mockKeyStore.Keys.Count.ShouldBe(2); } @@ -337,7 +339,7 @@ public class KeyManagerTests { var key1 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Subtract(_options.KeyManagement.PropagationTime.Add(TimeSpan.FromSeconds(1)))); - var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); + var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(_ct); var key = signgingKeys.Single(); @@ -352,7 +354,7 @@ public class KeyManagerTests { var id = CreateCacheAndStoreKey(); - var keys = await _subject.GetAllKeysFromCacheAsync(); + var keys = await _subject.GetAllKeysFromCacheAsync(_ct); keys.Count().ShouldBe(1); keys.Single().Id.ShouldBe(id); @@ -477,7 +479,7 @@ public class KeyManagerTests var key5 = CreateSerializedKey(_options.KeyManagement.PropagationTime); var key6 = CreateSerializedKey(_options.KeyManagement.PropagationTime.Subtract(TimeSpan.FromSeconds(1))); - var result = await _subject.FilterAndDeleteRetiredKeysAsync([key1, key2, key3, key4, key5, key6]); + var result = await _subject.FilterAndDeleteRetiredKeysAsync([key1, key2, key3, key4, key5, key6], _ct); result.Select(x => x.Id).ShouldBe([key3.Id, key4.Id, key5.Id, key6.Id]); } @@ -494,7 +496,7 @@ public class KeyManagerTests var key5 = CreateAndStoreKey(_options.KeyManagement.PropagationTime); var key6 = CreateAndStoreKey(_options.KeyManagement.PropagationTime.Subtract(TimeSpan.FromSeconds(1))); - var keys = await _subject.GetAllKeysAsync(); + var keys = await _subject.GetAllKeysAsync(_ct); _mockKeyStore.DeleteWasCalled.ShouldBeTrue(); _mockKeyStore.Keys.Select(x => x.Id).ShouldBe([key3, key4, key5, key6]); @@ -512,7 +514,7 @@ public class KeyManagerTests var key5 = CreateAndStoreKey(_options.KeyManagement.PropagationTime); var key6 = CreateAndStoreKey(_options.KeyManagement.PropagationTime.Subtract(TimeSpan.FromSeconds(1))); - var keys = await _subject.GetAllKeysAsync(); + var keys = await _subject.GetAllKeysAsync(_ct); _mockKeyStore.DeleteWasCalled.ShouldBeFalse(); _mockKeyStore.Keys.Select(x => x.Id).ShouldBe([key1, key2, key3, key4, key5, key6]); @@ -541,13 +543,13 @@ public class KeyManagerTests public async Task CacheKeysAsync_should_not_store_empty_keys() { { - await _subject.CacheKeysAsync(null); + await _subject.CacheKeysAsync(null, _ct); _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeFalse(); } { - await _subject.CacheKeysAsync(new RsaKeyContainer[0]); + await _subject.CacheKeysAsync(new RsaKeyContainer[0], _ct); _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeFalse(); } @@ -559,7 +561,7 @@ public class KeyManagerTests var key1 = CreateKey(_options.KeyManagement.PropagationTime.Add(TimeSpan.FromMinutes(5))); var key2 = CreateKey(_options.KeyManagement.PropagationTime.Add(TimeSpan.FromMinutes(10))); - await _subject.CacheKeysAsync(new[] { key1, key2 }); + await _subject.CacheKeysAsync(new[] { key1, key2 }, _ct); _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeTrue(); _mockKeyStoreCache.StoreKeysAsyncDuration.ShouldBe(_options.KeyManagement.KeyCacheDuration); @@ -572,7 +574,7 @@ public class KeyManagerTests { var key1 = CreateKey(); - await _subject.CacheKeysAsync(new[] { key1 }); + await _subject.CacheKeysAsync(new[] { key1 }, _ct); _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeTrue(); _mockKeyStoreCache.StoreKeysAsyncDuration.ShouldBe(_options.KeyManagement.InitializationKeyCacheDuration); @@ -585,7 +587,7 @@ public class KeyManagerTests { var key = CreateAndStoreKey(); - var keys = await _subject.GetAllKeysFromStoreAsync(); + var keys = await _subject.GetAllKeysFromStoreAsync(_ct); keys.ShouldNotBeNull(); keys.Single().Id.ShouldBe(key); @@ -601,7 +603,7 @@ public class KeyManagerTests var key4 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Add(TimeSpan.FromSeconds(1))); var key5 = CreateAndStoreKey(_options.KeyManagement.KeyRetirementAge.Add(TimeSpan.FromSeconds(5))); - var keys = await _subject.GetAllKeysFromStoreAsync(); + var keys = await _subject.GetAllKeysFromStoreAsync(_ct); keys.Select(x => x.Id).ShouldBe([key1, key2, key3, key4]); } @@ -615,12 +617,12 @@ public class KeyManagerTests var key4 = CreateAndStoreKey(_options.KeyManagement.RotationInterval.Add(TimeSpan.FromSeconds(1))); var key5 = CreateAndStoreKeyThatCannotBeUnprotected(_options.KeyManagement.KeyRetirementAge.Add(TimeSpan.FromSeconds(5))); - var keys = await _subject.GetAllKeysFromStoreAsync(); + var keys = await _subject.GetAllKeysFromStoreAsync(_ct); keys.Select(x => x.Id).ShouldBe([key1, key2, key3, key4]); _mockKeyStore.DeleteWasCalled.ShouldBeTrue(); - var keysInStore = await _mockKeyStore.LoadKeysAsync(); + var keysInStore = await _mockKeyStore.LoadKeysAsync(_ct); keysInStore.Select(x => x.Id).ShouldBe([key1, key2, key3, key4]); } @@ -630,7 +632,7 @@ public class KeyManagerTests var key1 = CreateAndStoreKey(TimeSpan.FromSeconds(10)); _mockKeyStore.Keys.Add(null); - var keys = await _subject.GetAllKeysFromStoreAsync(); + var keys = await _subject.GetAllKeysFromStoreAsync(_ct); keys.Select(x => x.Id).ShouldBe([key1]); } @@ -640,7 +642,7 @@ public class KeyManagerTests [Fact] public async Task CreateNewKeyAndAddToCacheAsync_when_no_keys_should_store_and_return_new_key() { - var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); + var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(_ct); var key = signingKeys.Single(); _mockKeyStore.Keys.Single().Id.ShouldBe(key.Id); } @@ -650,7 +652,7 @@ public class KeyManagerTests { var key1 = CreateCacheAndStoreKey(_options.KeyManagement.PropagationTime.Add(TimeSpan.FromSeconds(1))); - var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); + var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(_ct); var key = signingKeys.Single(); allKeys.Count().ShouldBe(2); @@ -664,7 +666,7 @@ public class KeyManagerTests { var key1 = CreateCacheAndStoreKey(); - var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); + var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(_ct); allKeys.Select(x => x.Id).ShouldBe(_mockKeyStore.Keys.Select(x => x.Id)); } @@ -678,7 +680,7 @@ public class KeyManagerTests var sw = new Stopwatch(); sw.Start(); - var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); + var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(_ct); sw.Stop(); sw.Elapsed.ShouldBeGreaterThanOrEqualTo(_options.KeyManagement.InitializationSynchronizationDelay); @@ -695,7 +697,7 @@ public class KeyManagerTests var sw = new Stopwatch(); sw.Start(); - var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); + var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(_ct); sw.Stop(); sw.Elapsed.ShouldBeLessThan(_options.KeyManagement.InitializationSynchronizationDelay); @@ -925,7 +927,7 @@ public class KeyManagerTests [Fact] public async Task CreateAndStoreNewKeyAsync_should_create_and_store_and_return_key() { - var result = await _subject.CreateAndStoreNewKeyAsync(_rsaOptions); + var result = await _subject.CreateAndStoreNewKeyAsync(_rsaOptions, _ct); _mockKeyProtector.ProtectWasCalled.ShouldBeTrue(); _mockKeyStore.Keys.Count.ShouldBe(1); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStore.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStore.cs index 9f5d2effb..46260dc80 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStore.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStore.cs @@ -13,7 +13,7 @@ internal class MockSigningKeyStore : ISigningKeyStore public bool LoadKeysAsyncWasCalled { get; set; } public bool DeleteWasCalled { get; set; } - public Task DeleteKeyAsync(string id) + public Task DeleteKeyAsync(string id, Ct _) { DeleteWasCalled = true; if (Keys != null) @@ -23,13 +23,13 @@ internal class MockSigningKeyStore : ISigningKeyStore return Task.CompletedTask; } - public Task> LoadKeysAsync() + public Task> LoadKeysAsync(Ct _) { LoadKeysAsyncWasCalled = true; return Task.FromResult>(Keys); } - public Task StoreKeyAsync(SerializedKey key) + public Task StoreKeyAsync(SerializedKey key, Ct _) { if (Keys == null) { diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStoreCache.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStoreCache.cs index afd4333a6..4185d6900 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStoreCache.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/MockSigningKeyStoreCache.cs @@ -14,13 +14,13 @@ internal class MockSigningKeyStoreCache : ISigningKeyStoreCache public bool StoreKeysAsyncWasCalled { get; set; } public TimeSpan StoreKeysAsyncDuration { get; set; } - public Task> GetKeysAsync() + public Task> GetKeysAsync(Ct _) { GetKeysAsyncWasCalled = true; return Task.FromResult(Cache.AsEnumerable()); } - public Task StoreKeysAsync(IEnumerable keys, TimeSpan duration) + public Task StoreKeysAsync(IEnumerable keys, TimeSpan duration, Ct _) { StoreKeysAsyncWasCalled = true; StoreKeysAsyncDuration = duration; diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs index 3971d327a..f0fc86ad7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs @@ -8,12 +8,14 @@ namespace UnitTests.Services.Default; public class NumericUserCodeGeneratorTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + [Fact] public async Task GenerateAsync_should_return_expected_code() { var sut = new NumericUserCodeGenerator(); - var userCode = await sut.GenerateAsync(); + var userCode = await sut.GenerateAsync(_ct); var userCodeInt = int.Parse(userCode); userCodeInt.ShouldBeGreaterThanOrEqualTo(100000000); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs index 8d055d893..e4d8e0146 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs @@ -31,7 +31,7 @@ public class ParRedirectUriValidatorTests { RequireClientSecret = true, } - }); + }, default); result.ShouldBe(true); } @@ -57,7 +57,7 @@ public class ParRedirectUriValidatorTests { RequireClientSecret = true, } - }); + }, default); result.ShouldBe(true); } @@ -82,7 +82,7 @@ public class ParRedirectUriValidatorTests RequestParameters = pushedParameters, RequestedUri = notThePushedRedirectUri, Client = new Client() - }); + }, default); result.ShouldBe(false); } @@ -110,7 +110,7 @@ public class ParRedirectUriValidatorTests { RedirectUris = { "https://registered.example.com" } } - }); + }, default); registeredRedirectUri.ShouldNotBe(pushedRedirectUri); result.ShouldBe(true); @@ -139,7 +139,7 @@ public class ParRedirectUriValidatorTests { RedirectUris = { "https://registered.example.com" } } - }); + }, default); registeredRedirectUri.ShouldNotBe(requestedRedirectUri); result.ShouldBe(false); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/DiagnosticDataServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/DiagnosticDataServiceTests.cs index ef4178da0..40b6bafb6 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/DiagnosticDataServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/DiagnosticDataServiceTests.cs @@ -10,6 +10,8 @@ namespace IdentityServer.UnitTests.Services; public class DiagnosticDataServiceTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + [Fact] public async Task GetJsonBytesAsync_WithNoEntries_ShouldReturnEmptyJsonObject() { @@ -17,7 +19,7 @@ public class DiagnosticDataServiceTests var entries = new List(); var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonBytesAsync(); + var result = await service.GetJsonBytesAsync(_ct); var json = Encoding.UTF8.GetString(result.Span); json.ShouldBe("{}"); @@ -33,7 +35,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonBytesAsync(); + var result = await service.GetJsonBytesAsync(_ct); var json = Encoding.UTF8.GetString(result.Span); var jsonDoc = JsonDocument.Parse(json); @@ -52,7 +54,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonBytesAsync(); + var result = await service.GetJsonBytesAsync(_ct); var json = Encoding.UTF8.GetString(result.Span); var jsonDoc = JsonDocument.Parse(json); @@ -72,7 +74,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - await service.GetJsonBytesAsync(); + await service.GetJsonBytesAsync(_ct); capturedContext.Context.ShouldNotBeNull(); capturedContext.Context.ServerStartTime.ShouldBe(serverStartTime); @@ -90,7 +92,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonBytesAsync(); + var result = await service.GetJsonBytesAsync(_ct); var json = Encoding.UTF8.GetString(result.Span); json.ShouldNotContain("\n"); @@ -105,7 +107,7 @@ public class DiagnosticDataServiceTests var entries = new List(); var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonStringAsync(); + var result = await service.GetJsonStringAsync(_ct); result.ShouldBe("{}"); } @@ -120,7 +122,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonStringAsync(); + var result = await service.GetJsonStringAsync(_ct); var jsonDoc = JsonDocument.Parse(result); jsonDoc.RootElement.GetProperty("TestProperty").GetString().ShouldBe("TestValue"); @@ -138,7 +140,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonStringAsync(); + var result = await service.GetJsonStringAsync(_ct); var jsonDoc = JsonDocument.Parse(result); jsonDoc.RootElement.GetProperty("Property1").GetString().ShouldBe("Value1"); @@ -156,7 +158,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonStringAsync(); + var result = await service.GetJsonStringAsync(_ct); var jsonDoc = JsonDocument.Parse(result); jsonDoc.RootElement.GetProperty("Property").GetString().ShouldBe("Value with émojis 🎉"); @@ -173,8 +175,8 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var stringResult = await service.GetJsonStringAsync(); - var bytesResult = await service.GetJsonBytesAsync(); + var stringResult = await service.GetJsonStringAsync(_ct); + var bytesResult = await service.GetJsonBytesAsync(_ct); var stringFromBytes = Encoding.UTF8.GetString(bytesResult.Span); stringResult.ShouldBe(stringFromBytes); @@ -190,7 +192,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonBytesAsync(); + var result = await service.GetJsonBytesAsync(_ct); var json = Encoding.UTF8.GetString(result.Span); var jsonDoc = JsonDocument.Parse(json); @@ -210,7 +212,7 @@ public class DiagnosticDataServiceTests }; var service = new DiagnosticDataService(serverStartTime, entries); - var result = await service.GetJsonBytesAsync(); + var result = await service.GetJsonBytesAsync(_ct); var json = Encoding.UTF8.GetString(result.Span); var jsonDoc = JsonDocument.Parse(json); diff --git a/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs b/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs index dfe136213..dae6886b8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs @@ -14,6 +14,7 @@ public class InMemoryCorsPolicyServiceTests private InMemoryCorsPolicyService _subject; private List _clients = new List(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public InMemoryCorsPolicyServiceTests() => _subject = new InMemoryCorsPolicyService(TestLogger.Create(), _clients); @@ -29,7 +30,7 @@ public class InMemoryCorsPolicyServiceTests } }); - var result = await _subject.IsOriginAllowedAsync("http://foo"); + var result = await _subject.IsOriginAllowedAsync("http://foo", _ct); result.ShouldBeTrue(); } @@ -47,7 +48,7 @@ public class InMemoryCorsPolicyServiceTests clientOrigin } }); - var result = await _subject.IsOriginAllowedAsync("http://bar"); + var result = await _subject.IsOriginAllowedAsync("http://bar", _ct); result.ShouldBe(false); } @@ -64,7 +65,7 @@ public class InMemoryCorsPolicyServiceTests "http://baz" } }); - var result = await _subject.IsOriginAllowedAsync("http://bar"); + var result = await _subject.IsOriginAllowedAsync("http://bar", _ct); result.ShouldBe(true); } @@ -81,7 +82,7 @@ public class InMemoryCorsPolicyServiceTests "http://baz" } }); - var result = await _subject.IsOriginAllowedAsync("http://quux"); + var result = await _subject.IsOriginAllowedAsync("http://quux", _ct); result.ShouldBe(false); } @@ -105,7 +106,7 @@ public class InMemoryCorsPolicyServiceTests } } }); - var result = await _subject.IsOriginAllowedAsync("http://foo"); + var result = await _subject.IsOriginAllowedAsync("http://foo", _ct); result.ShouldBeTrue(); } @@ -131,7 +132,7 @@ public class InMemoryCorsPolicyServiceTests } } }); - var result = await _subject.IsOriginAllowedAsync("http://bar"); + var result = await _subject.IsOriginAllowedAsync("http://bar", _ct); result.ShouldBeTrue(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs index c71f44d43..6ec4c6096 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs @@ -11,6 +11,8 @@ namespace UnitTests.Stores.Default; public class CachingResourceStoreTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + private List _identityResources = new List(); private List _apiResources = new List(); private List _apiScopes = new List(); @@ -48,7 +50,7 @@ public class CachingResourceStoreTests _scopeCache.Items.Count.ShouldBe(0); - var items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope1", "scope2", "invalid" }); + var items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope1", "scope2", "invalid" }, _ct); items.Count().ShouldBe(3); _scopeCache.Items.Count.ShouldBe(3); @@ -64,23 +66,23 @@ public class CachingResourceStoreTests _scopeCache.Items.Count.ShouldBe(0); - var items = await _subject.FindApiScopesByNameAsync(new[] { "scope1" }); + var items = await _subject.FindApiScopesByNameAsync(new[] { "scope1" }, _ct); items.Count().ShouldBe(1); _scopeCache.Items.Count.ShouldBe(1); _apiScopes.Remove(_apiScopes.Single(x => x.Name == "scope1")); - items = await _subject.FindApiScopesByNameAsync(new[] { "scope1", "scope2" }); + items = await _subject.FindApiScopesByNameAsync(new[] { "scope1", "scope2" }, _ct); items.Count().ShouldBe(2); _scopeCache.Items.Count.ShouldBe(2); _apiScopes.Remove(_apiScopes.Single(x => x.Name == "scope2")); - items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope2", "scope4" }); + items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope2", "scope4" }, _ct); items.Count().ShouldBe(3); _scopeCache.Items.Count.ShouldBe(4); // this shows we will find it in the cache, even if removed from the DB _apiScopes.Remove(_apiScopes.Single(x => x.Name == "scope3")); - items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope1", "scope2" }); + items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope1", "scope2" }, _ct); items.Count().ShouldBe(3); _scopeCache.Items.Count.ShouldBe(4); } @@ -98,7 +100,7 @@ public class CachingResourceStoreTests { _apiCache.Items.Count.ShouldBe(0); _apiResourceNamesCache.Items.Count.ShouldBe(0); - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "invalid" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "invalid" }, _ct); items.Count().ShouldBe(0); _apiCache.Items.Count.ShouldBe(0); _apiResourceNamesCache.Items.Count.ShouldBe(1); @@ -111,7 +113,7 @@ public class CachingResourceStoreTests _apiCache.Items.Count.ShouldBe(0); _apiResourceNamesCache.Items.Count.ShouldBe(0); - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo1" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo1" }, _ct); items.Count().ShouldBe(1); items.Select(x => x.Name).ShouldBe(new[] { "foo" }); _apiCache.Items.Count.ShouldBe(1); @@ -119,7 +121,7 @@ public class CachingResourceStoreTests } { - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2" }, _ct); items.Count().ShouldBe(1); items.Select(x => x.Name).ShouldBe(["foo"]); _apiCache.Items.Count.ShouldBe(1); @@ -127,7 +129,7 @@ public class CachingResourceStoreTests } { - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo1", "bar1" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo1", "bar1" }, _ct); items.Count().ShouldBe(2); items.Select(x => x.Name).ShouldBe(["foo", "bar"]); _apiCache.Items.Count.ShouldBe(2); @@ -135,7 +137,7 @@ public class CachingResourceStoreTests } { - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }, _ct); items.Count().ShouldBe(2); items.Select(x => x.Name).ShouldBe(["foo", "bar"]); _apiCache.Items.Count.ShouldBe(2); @@ -147,7 +149,7 @@ public class CachingResourceStoreTests _apiResourceNamesCache.Items.Clear(); _resourceCache.Items.Clear(); - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }, _ct); items.Count().ShouldBe(2); items.Select(x => x.Name).ShouldBe(["foo", "bar"]); _apiCache.Items.Count.ShouldBe(2); @@ -160,7 +162,7 @@ public class CachingResourceStoreTests _apiScopes.Clear(); _identityResources.Clear(); - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }, _ct); items.Count().ShouldBe(2); items.Select(x => x.Name).ShouldBe(["foo", "bar"]); _apiCache.Items.Count.ShouldBe(2); @@ -179,12 +181,12 @@ public class CachingResourceStoreTests _apiScopes.Add(new ApiScope("bar1")); { - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo", "foo1", "bar", "bar1" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo", "foo1", "bar", "bar1" }, _ct); items.Count().ShouldBe(2); items.Select(x => x.Name).ShouldBe(["foo", "bar"], true); } { - var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo", "foo1", "bar", "bar1" }); + var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo", "foo1", "bar", "bar1" }, _ct); items.Count().ShouldBe(2); items.Select(x => x.Name).ShouldBe(["foo", "bar"]); } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs index e87802174..69ce868a3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs @@ -22,6 +22,7 @@ public class DefaultPersistedGrantStoreTests private StubHandleGenerationService _stubHandleGenerationService = new StubHandleGenerationService(); private ClaimsPrincipal _user = new IdentityServerUser("123").CreatePrincipal(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public DefaultPersistedGrantStoreTests() { @@ -58,8 +59,8 @@ public class DefaultPersistedGrantStoreTests RequestedScopes = new string[] { "scope1", "scope2" } }; - var handle = await _codes.StoreAuthorizationCodeAsync(code1); - var code2 = await _codes.GetAuthorizationCodeAsync(handle); + var handle = await _codes.StoreAuthorizationCodeAsync(code1, _ct); + var code2 = await _codes.GetAuthorizationCodeAsync(handle, _ct); code1.ClientId.ShouldBe(code2.ClientId); code1.CreationTime.ShouldBe(code2.CreationTime); @@ -86,9 +87,9 @@ public class DefaultPersistedGrantStoreTests RequestedScopes = new string[] { "scope1", "scope2" } }; - var handle = await _codes.StoreAuthorizationCodeAsync(code1); - await _codes.RemoveAuthorizationCodeAsync(handle); - var code2 = await _codes.GetAuthorizationCodeAsync(handle); + var handle = await _codes.StoreAuthorizationCodeAsync(code1, _ct); + await _codes.RemoveAuthorizationCodeAsync(handle, _ct); + var code2 = await _codes.GetAuthorizationCodeAsync(handle, _ct); code2.ShouldBeNull(); } @@ -119,8 +120,8 @@ public class DefaultPersistedGrantStoreTests Version = 4 }; - var handle = await _refreshTokens.StoreRefreshTokenAsync(token1); - var token2 = await _refreshTokens.GetRefreshTokenAsync(handle); + var handle = await _refreshTokens.StoreRefreshTokenAsync(token1, _ct); + var token2 = await _refreshTokens.GetRefreshTokenAsync(handle, _ct); token2.Version.ShouldBe(5); @@ -160,8 +161,8 @@ public class DefaultPersistedGrantStoreTests } }); - var handle = await _refreshTokens.StoreRefreshTokenAsync(token1); - var token2 = await _refreshTokens.GetRefreshTokenAsync(handle); + var handle = await _refreshTokens.StoreRefreshTokenAsync(token1, _ct); + var token2 = await _refreshTokens.GetRefreshTokenAsync(handle, _ct); token1.ClientId.ShouldBe(token2.ClientId); token1.CreationTime.ShouldBe(token2.CreationTime); @@ -186,9 +187,9 @@ public class DefaultPersistedGrantStoreTests }; - var handle = await _refreshTokens.StoreRefreshTokenAsync(token1); - await _refreshTokens.RemoveRefreshTokenAsync(handle); - var token2 = await _refreshTokens.GetRefreshTokenAsync(handle); + var handle = await _refreshTokens.StoreRefreshTokenAsync(token1, _ct); + await _refreshTokens.RemoveRefreshTokenAsync(handle, _ct); + var token2 = await _refreshTokens.GetRefreshTokenAsync(handle, _ct); token2.ShouldBeNull(); } @@ -204,13 +205,13 @@ public class DefaultPersistedGrantStoreTests Lifetime = 10, }; - var handle1 = await _refreshTokens.StoreRefreshTokenAsync(token1); - var handle2 = await _refreshTokens.StoreRefreshTokenAsync(token1); - await _refreshTokens.RemoveRefreshTokensAsync("123", "client"); + var handle1 = await _refreshTokens.StoreRefreshTokenAsync(token1, _ct); + var handle2 = await _refreshTokens.StoreRefreshTokenAsync(token1, _ct); + await _refreshTokens.RemoveRefreshTokensAsync("123", "client", _ct); - var token2 = await _refreshTokens.GetRefreshTokenAsync(handle1); + var token2 = await _refreshTokens.GetRefreshTokenAsync(handle1, _ct); token2.ShouldBeNull(); - token2 = await _refreshTokens.GetRefreshTokenAsync(handle2); + token2 = await _refreshTokens.GetRefreshTokenAsync(handle2, _ct); token2.ShouldBeNull(); } @@ -232,8 +233,8 @@ public class DefaultPersistedGrantStoreTests Version = 1 }; - var handle = await _referenceTokens.StoreReferenceTokenAsync(token1); - var token2 = await _referenceTokens.GetReferenceTokenAsync(handle); + var handle = await _referenceTokens.StoreReferenceTokenAsync(token1, _ct); + var token2 = await _referenceTokens.GetReferenceTokenAsync(handle, _ct); token1.ClientId.ShouldBe(token2.ClientId); token1.Audiences.Count.ShouldBe(1); @@ -261,9 +262,9 @@ public class DefaultPersistedGrantStoreTests Version = 1 }; - var handle = await _referenceTokens.StoreReferenceTokenAsync(token1); - await _referenceTokens.RemoveReferenceTokenAsync(handle); - var token2 = await _referenceTokens.GetReferenceTokenAsync(handle); + var handle = await _referenceTokens.StoreReferenceTokenAsync(token1, _ct); + await _referenceTokens.RemoveReferenceTokenAsync(handle, _ct); + var token2 = await _referenceTokens.GetReferenceTokenAsync(handle, _ct); token2.ShouldBeNull(); } @@ -284,13 +285,13 @@ public class DefaultPersistedGrantStoreTests Version = 1 }; - var handle1 = await _referenceTokens.StoreReferenceTokenAsync(token1); - var handle2 = await _referenceTokens.StoreReferenceTokenAsync(token1); - await _referenceTokens.RemoveReferenceTokensAsync("123", "client"); + var handle1 = await _referenceTokens.StoreReferenceTokenAsync(token1, _ct); + var handle2 = await _referenceTokens.StoreReferenceTokenAsync(token1, _ct); + await _referenceTokens.RemoveReferenceTokensAsync("123", "client", null, _ct); - var token2 = await _referenceTokens.GetReferenceTokenAsync(handle1); + var token2 = await _referenceTokens.GetReferenceTokenAsync(handle1, _ct); token2.ShouldBeNull(); - token2 = await _referenceTokens.GetReferenceTokenAsync(handle2); + token2 = await _referenceTokens.GetReferenceTokenAsync(handle2, _ct); token2.ShouldBeNull(); } @@ -305,8 +306,8 @@ public class DefaultPersistedGrantStoreTests Scopes = new string[] { "foo", "bar" } }; - await _userConsent.StoreUserConsentAsync(consent1); - var consent2 = await _userConsent.GetUserConsentAsync("123", "client"); + await _userConsent.StoreUserConsentAsync(consent1, _ct); + var consent2 = await _userConsent.GetUserConsentAsync("123", "client", _ct); consent2.ClientId.ShouldBe(consent1.ClientId); consent2.SubjectId.ShouldBe(consent1.SubjectId); @@ -324,9 +325,9 @@ public class DefaultPersistedGrantStoreTests Scopes = new string[] { "foo", "bar" } }; - await _userConsent.StoreUserConsentAsync(consent1); - await _userConsent.RemoveUserConsentAsync("123", "client"); - var consent2 = await _userConsent.GetUserConsentAsync("123", "client"); + await _userConsent.StoreUserConsentAsync(consent1, _ct); + await _userConsent.RemoveUserConsentAsync("123", "client", _ct); + var consent2 = await _userConsent.GetUserConsentAsync("123", "client", _ct); consent2.ShouldBeNull(); } @@ -348,7 +349,7 @@ public class DefaultPersistedGrantStoreTests new Claim("scope", "bar1"), new Claim("scope", "bar2") } - }); + }, _ct); await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { @@ -356,7 +357,7 @@ public class DefaultPersistedGrantStoreTests Subject = _user, CreationTime = DateTime.UtcNow, Lifetime = 20, - }); + }, _ct); await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -368,11 +369,11 @@ public class DefaultPersistedGrantStoreTests RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux1", "quux2" } - }); + }, _ct); // the -1 is needed because internally we append a version/suffix the handle for encoding - (await _codes.GetAuthorizationCodeAsync("key-1")).Lifetime.ShouldBe(30); - (await _refreshTokens.GetRefreshTokenAsync("key-1")).Lifetime.ShouldBe(20); - (await _referenceTokens.GetReferenceTokenAsync("key-1")).Lifetime.ShouldBe(10); + (await _codes.GetAuthorizationCodeAsync("key-1", _ct)).Lifetime.ShouldBe(30); + (await _refreshTokens.GetRefreshTokenAsync("key-1", _ct)).Lifetime.ShouldBe(20); + (await _referenceTokens.GetReferenceTokenAsync("key-1", _ct)).Lifetime.ShouldBe(10); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs index 8af0b232e..f45c85303 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs @@ -13,6 +13,7 @@ public class DistributedCacheAuthorizationParametersMessageStoreTests { private MockDistributedCache _mockCache = new MockDistributedCache(); private DistributedCacheAuthorizationParametersMessageStore _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; public DistributedCacheAuthorizationParametersMessageStoreTests() => _subject = new DistributedCacheAuthorizationParametersMessageStore(_mockCache, new DefaultHandleGenerationService()); [Fact] @@ -21,11 +22,11 @@ public class DistributedCacheAuthorizationParametersMessageStoreTests _mockCache.Items.Count.ShouldBe(0); var msg = new Message>(new Dictionary()); - var id = await _subject.WriteAsync(msg); + var id = await _subject.WriteAsync(msg, _ct); _mockCache.Items.Count.ShouldBe(1); - await _subject.DeleteAsync(id); + await _subject.DeleteAsync(id, _ct); _mockCache.Items.Count.ShouldBe(0); } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs index ab2bde7aa..82dada2ae 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs @@ -9,6 +9,7 @@ namespace UnitTests.Stores; public class InMemoryClientStoreTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] public void InMemoryClient_should_throw_if_contain_duplicate_client_ids() { @@ -49,7 +50,7 @@ public class InMemoryClientStoreTests var store = new InMemoryClientStore(clients); var result = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { result.Add(client); } @@ -69,7 +70,7 @@ public class InMemoryClientStoreTests var store = new InMemoryClientStore(clients); var result = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { result.Add(client); } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs index d0602aa61..195d2a93b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs @@ -10,6 +10,7 @@ namespace UnitTests.Stores; public class InMemoryDeviceFlowStoreTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; private InMemoryDeviceFlowStore _store = new InMemoryDeviceFlowStore(); [Fact] @@ -28,8 +29,8 @@ public class InMemoryDeviceFlowStoreTests RequestedScopes = new[] { "scope1", "scope2" } }; - await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data); - var foundData = await _store.FindByUserCodeAsync(userCode); + await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data, _ct); + var foundData = await _store.FindByUserCodeAsync(userCode, _ct); foundData.ClientId.ShouldBe(data.ClientId); foundData.CreationTime.ShouldBe(data.CreationTime); @@ -56,8 +57,8 @@ public class InMemoryDeviceFlowStoreTests RequestedScopes = new[] { "scope1", "scope2" } }; - await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data); - var foundData = await _store.FindByDeviceCodeAsync(deviceCode); + await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data, _ct); + var foundData = await _store.FindByDeviceCodeAsync(deviceCode, _ct); foundData.ClientId.ShouldBe(data.ClientId); foundData.CreationTime.ShouldBe(data.CreationTime); @@ -84,7 +85,7 @@ public class InMemoryDeviceFlowStoreTests RequestedScopes = new[] { "scope1", "scope2" } }; - await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, initialData); + await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, initialData, _ct); var updatedData = new DeviceCode { @@ -97,9 +98,9 @@ public class InMemoryDeviceFlowStoreTests RequestedScopes = new[] { "api1", "api2" } }; - await _store.UpdateByUserCodeAsync(userCode, updatedData); + await _store.UpdateByUserCodeAsync(userCode, updatedData, _ct); - var foundData = await _store.FindByUserCodeAsync(userCode); + var foundData = await _store.FindByUserCodeAsync(userCode, _ct); foundData.ClientId.ShouldBe(updatedData.ClientId); foundData.CreationTime.ShouldBe(updatedData.CreationTime); @@ -126,9 +127,9 @@ public class InMemoryDeviceFlowStoreTests RequestedScopes = new[] { "scope1", "scope2" } }; - await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data); - await _store.RemoveByDeviceCodeAsync(deviceCode); - var foundData = await _store.FindByUserCodeAsync(userCode); + await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data, _ct); + await _store.RemoveByDeviceCodeAsync(deviceCode, _ct); + var foundData = await _store.FindByUserCodeAsync(userCode, _ct); foundData.ShouldBeNull(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs index e3dac51f7..35cbe00a7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs @@ -10,6 +10,7 @@ namespace UnitTests.Stores; public class InMemoryPersistedGrantStoreTests { private InMemoryPersistedGrantStore _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; public InMemoryPersistedGrantStoreTests() => _subject = new InMemoryPersistedGrantStore(); @@ -17,14 +18,14 @@ public class InMemoryPersistedGrantStoreTests public async Task Store_should_persist_value() { { - var item = await _subject.GetAsync("key1"); + var item = await _subject.GetAsync("key1", _ct); item.ShouldBeNull(); } - await _subject.StoreAsync(new PersistedGrant() { Key = "key1" }); + await _subject.StoreAsync(new PersistedGrant() { Key = "key1" }, _ct); { - var item = await _subject.GetAsync("key1"); + var item = await _subject.GetAsync("key1", _ct); item.ShouldNotBeNull(); } } @@ -32,89 +33,89 @@ public class InMemoryPersistedGrantStoreTests [Fact] public async Task GetAll_should_filter() { - await _subject.StoreAsync(new PersistedGrant() { Key = "key1", SubjectId = "sub1", ClientId = "client1", SessionId = "session1" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key2", SubjectId = "sub1", ClientId = "client2", SessionId = "session1" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key3", SubjectId = "sub1", ClientId = "client1", SessionId = "session2" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key4", SubjectId = "sub1", ClientId = "client3", SessionId = "session2" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key5", SubjectId = "sub1", ClientId = "client4", SessionId = "session3" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key6", SubjectId = "sub1", ClientId = "client4", SessionId = "session4" }); + await _subject.StoreAsync(new PersistedGrant() { Key = "key1", SubjectId = "sub1", ClientId = "client1", SessionId = "session1" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key2", SubjectId = "sub1", ClientId = "client2", SessionId = "session1" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key3", SubjectId = "sub1", ClientId = "client1", SessionId = "session2" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key4", SubjectId = "sub1", ClientId = "client3", SessionId = "session2" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key5", SubjectId = "sub1", ClientId = "client4", SessionId = "session3" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key6", SubjectId = "sub1", ClientId = "client4", SessionId = "session4" }, _ct); - await _subject.StoreAsync(new PersistedGrant() { Key = "key7", SubjectId = "sub2", ClientId = "client4", SessionId = "session4" }); + await _subject.StoreAsync(new PersistedGrant() { Key = "key7", SubjectId = "sub2", ClientId = "client4", SessionId = "session4" }, _ct); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key1", "key2", "key3", "key4", "key5", "key6"], true); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub2" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key7"]); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub3" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client1" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key1", "key3"], true); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client2" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key2"]); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client3" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key4"]); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client4" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key5", "key6"]); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client5" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub2", ClientId = "client1" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub2", ClientId = "client4" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key7"]); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub3", ClientId = "client1" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -122,7 +123,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client1", SessionId = "session1" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key1"]); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -130,7 +131,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client1", SessionId = "session2" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key3"]); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -138,7 +139,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client1", SessionId = "session3" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -146,7 +147,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client2", SessionId = "session1" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key2"]); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -154,7 +155,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client2", SessionId = "session2" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -162,7 +163,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client4", SessionId = "session4" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key6"]); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -170,7 +171,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub2", ClientId = "client4", SessionId = "session4" - })) + }, _ct)) .Select(x => x.Key).ShouldBe(["key7"]); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -178,7 +179,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub2", ClientId = "client4", SessionId = "session1" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter @@ -186,7 +187,7 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub2", ClientId = "client4", SessionId = "session5" - })) + }, _ct)) .Select(x => x.Key).ShouldBeEmpty(); } @@ -198,42 +199,42 @@ public class InMemoryPersistedGrantStoreTests await _subject.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1" - }); - (await _subject.GetAsync("key1")).ShouldBeNull(); - (await _subject.GetAsync("key2")).ShouldBeNull(); - (await _subject.GetAsync("key3")).ShouldBeNull(); - (await _subject.GetAsync("key4")).ShouldBeNull(); - (await _subject.GetAsync("key5")).ShouldBeNull(); - (await _subject.GetAsync("key6")).ShouldBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); await _subject.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub2" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldBeNull(); } { await Populate(); await _subject.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub3" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -241,14 +242,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub1", ClientId = "client1" - }); - (await _subject.GetAsync("key1")).ShouldBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -256,14 +257,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub1", ClientId = "client2" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -271,14 +272,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub1", ClientId = "client3" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -286,14 +287,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub1", ClientId = "client4" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldBeNull(); - (await _subject.GetAsync("key6")).ShouldBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -301,14 +302,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub1", ClientId = "client5" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -316,14 +317,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub2", ClientId = "client1" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -331,14 +332,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub1", ClientId = "client4" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldBeNull(); - (await _subject.GetAsync("key6")).ShouldBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -346,14 +347,14 @@ public class InMemoryPersistedGrantStoreTests { SubjectId = "sub3", ClientId = "client1" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -362,14 +363,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client1", SessionId = "session1" - }); - (await _subject.GetAsync("key1")).ShouldBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -378,14 +379,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client1", SessionId = "session2" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -394,14 +395,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client1", SessionId = "session3" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -410,14 +411,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client2", SessionId = "session1" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -426,14 +427,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client2", SessionId = "session2" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -442,14 +443,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub1", ClientId = "client4", SessionId = "session4" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -458,14 +459,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub2", ClientId = "client4", SessionId = "session4" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldBeNull(); } { await Populate(); @@ -474,14 +475,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub2", ClientId = "client4", SessionId = "session1" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -490,14 +491,14 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub2", ClientId = "client4", SessionId = "session5" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } { await Populate(); @@ -506,26 +507,27 @@ public class InMemoryPersistedGrantStoreTests SubjectId = "sub3", ClientId = "client1", SessionId = "session1" - }); - (await _subject.GetAsync("key1")).ShouldNotBeNull(); - (await _subject.GetAsync("key2")).ShouldNotBeNull(); - (await _subject.GetAsync("key3")).ShouldNotBeNull(); - (await _subject.GetAsync("key4")).ShouldNotBeNull(); - (await _subject.GetAsync("key5")).ShouldNotBeNull(); - (await _subject.GetAsync("key6")).ShouldNotBeNull(); - (await _subject.GetAsync("key7")).ShouldNotBeNull(); + }, _ct); + (await _subject.GetAsync("key1", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key2", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key3", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key4", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key5", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key6", _ct)).ShouldNotBeNull(); + (await _subject.GetAsync("key7", _ct)).ShouldNotBeNull(); } } private async Task Populate() { - await _subject.StoreAsync(new PersistedGrant() { Key = "key1", SubjectId = "sub1", ClientId = "client1", SessionId = "session1" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key2", SubjectId = "sub1", ClientId = "client2", SessionId = "session1" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key3", SubjectId = "sub1", ClientId = "client1", SessionId = "session2" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key4", SubjectId = "sub1", ClientId = "client3", SessionId = "session2" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key5", SubjectId = "sub1", ClientId = "client4", SessionId = "session3" }); - await _subject.StoreAsync(new PersistedGrant() { Key = "key6", SubjectId = "sub1", ClientId = "client4", SessionId = "session4" }); + _subject = new InMemoryPersistedGrantStore(); + await _subject.StoreAsync(new PersistedGrant() { Key = "key1", SubjectId = "sub1", ClientId = "client1", SessionId = "session1" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key2", SubjectId = "sub1", ClientId = "client2", SessionId = "session1" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key3", SubjectId = "sub1", ClientId = "client1", SessionId = "session2" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key4", SubjectId = "sub1", ClientId = "client3", SessionId = "session2" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key5", SubjectId = "sub1", ClientId = "client4", SessionId = "session3" }, _ct); + await _subject.StoreAsync(new PersistedGrant() { Key = "key6", SubjectId = "sub1", ClientId = "client4", SessionId = "session4" }, _ct); - await _subject.StoreAsync(new PersistedGrant() { Key = "key7", SubjectId = "sub2", ClientId = "client4", SessionId = "session4" }); + await _subject.StoreAsync(new PersistedGrant() { Key = "key7", SubjectId = "sub2", ClientId = "client4", SessionId = "session4" }, _ct); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/ValidatingClientStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/ValidatingClientStoreTests.cs index eda48fdf1..09ff81419 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/ValidatingClientStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/ValidatingClientStoreTests.cs @@ -3,6 +3,7 @@ #nullable enable +using System.Runtime.CompilerServices; using Duende.IdentityServer.Events; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; @@ -17,6 +18,7 @@ public class ValidatingClientStoreTests { private readonly TestEventService _events = new(); private readonly NullLogger> _logger = new(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] public async Task GetAllClientsAsync_WhenAllClientsAreValid_ShouldReturnAllClients() @@ -32,7 +34,7 @@ public class ValidatingClientStoreTests var store = new ValidatingClientStore(innerStore, validator, _events, _logger); var result = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { result.Add(client); } @@ -61,7 +63,7 @@ public class ValidatingClientStoreTests var store = new ValidatingClientStore(innerStore, validator, _events, _logger); var result = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { result.Add(client); } @@ -84,7 +86,7 @@ public class ValidatingClientStoreTests var store = new ValidatingClientStore(innerStore, validator, _events, _logger); var result = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { result.Add(client); } @@ -101,7 +103,7 @@ public class ValidatingClientStoreTests var store = new ValidatingClientStore(innerStore, validator, _events, _logger); var result = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { result.Add(client); } @@ -124,7 +126,7 @@ public class ValidatingClientStoreTests var store = new ValidatingClientStore(innerStore, validator, eventService, _logger); var result = new List(); - await foreach (var client in store.GetAllClientsAsync()) + await foreach (var client in store.GetAllClientsAsync(_ct)) { result.Add(client); } @@ -151,9 +153,9 @@ public class ValidatingClientStoreTests public static StubClientStore WithClients(IEnumerable clients) => new(clients.FirstOrDefault(), clients); - public Task FindClientByIdAsync(string clientId) => Task.FromResult(_client); + public Task FindClientByIdAsync(string clientId, Ct _) => Task.FromResult(_client); - public async IAsyncEnumerable GetAllClientsAsync() + public async IAsyncEnumerable GetAllClientsAsync([EnumeratorCancellation] Ct _) { foreach (var client in _clients) { @@ -180,7 +182,7 @@ public class ValidatingClientStoreTests _errorMessage = errorMessage; } - public Task ValidateAsync(ClientConfigurationValidationContext context) + public Task ValidateAsync(ClientConfigurationValidationContext context, Ct _) { var isValid = _validationFunc != null ? _validationFunc(context.Client) : _isValid; @@ -199,7 +201,7 @@ public class ValidatingClientStoreTests public bool CanRaiseEventType(EventTypes evtType) => true; - public Task RaiseAsync(Event evt) + public Task RaiseAsync(Event evt, Ct _) { RaisedEventCount++; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs index 7bd55f47d..ad71b819a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs @@ -16,6 +16,7 @@ namespace UnitTests.Validation; public class AccessTokenValidation { private const string Category = "Access token validation"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IClientStore _clients = Factory.CreateClientStore(); private IdentityServerOptions _options = new IdentityServerOptions(); @@ -48,13 +49,9 @@ public class AccessTokenValidation var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"); - var handle = await store.StoreReferenceTokenAsync(token); + var handle = await store.StoreReferenceTokenAsync(token, _ct); - var result = await validator.ValidateAccessTokenAsync(handle); - - result.IsError.ShouldBeFalse(); - result.Claims.Count().ShouldBe(9); - result.Claims.First(c => c.Type == JwtClaimTypes.ClientId).Value.ShouldBe("roclient"); + var result = await validator.ValidateAccessTokenAsync(handle, null, _ct); var claimTypes = result.Claims.Select(c => c.Type).ToList(); claimTypes.ShouldContain("iss"); @@ -76,9 +73,9 @@ public class AccessTokenValidation var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"); - var handle = await store.StoreReferenceTokenAsync(token); + var handle = await store.StoreReferenceTokenAsync(token, _ct); - var result = await validator.ValidateAccessTokenAsync(handle, "read"); + var result = await validator.ValidateAccessTokenAsync(handle, "read", _ct); result.IsError.ShouldBeFalse(); } @@ -92,9 +89,9 @@ public class AccessTokenValidation var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"); - var handle = await store.StoreReferenceTokenAsync(token); + var handle = await store.StoreReferenceTokenAsync(token, _ct); - var result = await validator.ValidateAccessTokenAsync(handle, "missing"); + var result = await validator.ValidateAccessTokenAsync(handle, "missing", _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InsufficientScope); @@ -106,7 +103,7 @@ public class AccessTokenValidation { var validator = Factory.CreateTokenValidator(); - var result = await validator.ValidateAccessTokenAsync("unknown"); + var result = await validator.ValidateAccessTokenAsync("unknown", null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); @@ -120,7 +117,7 @@ public class AccessTokenValidation var options = new IdentityServerOptions(); var longToken = "x".Repeat(options.InputLengthRestrictions.TokenHandle + 1); - var result = await validator.ValidateAccessTokenAsync(longToken); + var result = await validator.ValidateAccessTokenAsync(longToken, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); @@ -138,12 +135,12 @@ public class AccessTokenValidation var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 2, "read", "write"); token.CreationTime = now; - var handle = await store.StoreReferenceTokenAsync(token); + var handle = await store.StoreReferenceTokenAsync(token, _ct); now = now.AddSeconds(3); _timeProvider.SetUtcNow(now); - var result = await validator.ValidateAccessTokenAsync(handle); + var result = await validator.ValidateAccessTokenAsync(handle, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.ExpiredToken); @@ -155,7 +152,7 @@ public class AccessTokenValidation { var validator = Factory.CreateTokenValidator(); - var result = await validator.ValidateAccessTokenAsync("unk.nown"); + var result = await validator.ValidateAccessTokenAsync("unk.nown", null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); @@ -166,10 +163,10 @@ public class AccessTokenValidation public async Task Valid_JWT_Token() { var signer = Factory.CreateDefaultTokenCreator(); - var jwt = await signer.CreateTokenAsync(TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write")); + var jwt = await signer.CreateTokenAsync(TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"), _ct); var validator = Factory.CreateTokenValidator(null); - var result = await validator.ValidateAccessTokenAsync(jwt); + var result = await validator.ValidateAccessTokenAsync(jwt, null, _ct); result.IsError.ShouldBeFalse(); } @@ -184,10 +181,10 @@ public class AccessTokenValidation options.EmitScopesAsSpaceDelimitedStringInJwt = flag; var signer = Factory.CreateDefaultTokenCreator(options); - var jwt = await signer.CreateTokenAsync(TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write")); + var jwt = await signer.CreateTokenAsync(TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"), _ct); var validator = Factory.CreateTokenValidator(null); - var result = await validator.ValidateAccessTokenAsync(jwt); + var result = await validator.ValidateAccessTokenAsync(jwt, null, _ct); result.IsError.ShouldBeFalse(); result.Jwt.ShouldNotBeNullOrEmpty(); @@ -207,10 +204,10 @@ public class AccessTokenValidation var signer = Factory.CreateDefaultTokenCreator(); var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"); token.Issuer = "invalid"; - var jwt = await signer.CreateTokenAsync(token); + var jwt = await signer.CreateTokenAsync(token, _ct); var validator = Factory.CreateTokenValidator(null); - var result = await validator.ValidateAccessTokenAsync(jwt); + var result = await validator.ValidateAccessTokenAsync(jwt, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); @@ -221,10 +218,10 @@ public class AccessTokenValidation public async Task JWT_Token_Too_Long() { var signer = Factory.CreateDefaultTokenCreator(); - var jwt = await signer.CreateTokenAsync(TokenFactory.CreateAccessTokenLong(new Client { ClientId = "roclient" }, "valid", 600, 1000, "read", "write")); + var jwt = await signer.CreateTokenAsync(TokenFactory.CreateAccessTokenLong(new Client { ClientId = "roclient" }, "valid", 600, 1000, "read", "write"), _ct); var validator = Factory.CreateTokenValidator(null); - var result = await validator.ValidateAccessTokenAsync(jwt); + var result = await validator.ValidateAccessTokenAsync(jwt, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); @@ -239,12 +236,12 @@ public class AccessTokenValidation futureClock.SetUtcNow(definitelyNotNow); var signer = Factory.CreateDefaultTokenCreator(timeProvider: futureClock); var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"); - var jwt = await signer.CreateTokenAsync(token); + var jwt = await signer.CreateTokenAsync(token, _ct); var options = TestIdentityServerOptions.Create(); options.JwtValidationClockSkew = TimeSpan.FromSeconds(10); var validator = Factory.CreateTokenValidator(options: options); - var result = await validator.ValidateAccessTokenAsync(jwt); + var result = await validator.ValidateAccessTokenAsync(jwt, null, _ct); result.IsError.ShouldBeFalse(); } @@ -258,12 +255,12 @@ public class AccessTokenValidation futureClock.SetUtcNow(definitelyNotNow); var signer = Factory.CreateDefaultTokenCreator(timeProvider: futureClock); var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"); - var jwt = await signer.CreateTokenAsync(token); + var jwt = await signer.CreateTokenAsync(token, _ct); var options = TestIdentityServerOptions.Create(); options.JwtValidationClockSkew = TimeSpan.FromSeconds(5); var validator = Factory.CreateTokenValidator(options: options); - var result = await validator.ValidateAccessTokenAsync(jwt); + var result = await validator.ValidateAccessTokenAsync(jwt, null, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); @@ -275,13 +272,13 @@ public class AccessTokenValidation { var signer = Factory.CreateDefaultTokenCreator(); var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 600, "read", "write"); - var jwt = await signer.CreateTokenAsync(token); + var jwt = await signer.CreateTokenAsync(token, _ct); var options = TestIdentityServerOptions.Create(); options.SupportedRequestObjectSigningAlgorithms = ["Test"]; options.SupportedClientAssertionSigningAlgorithms = ["Test"]; var validator = Factory.CreateTokenValidator(options: options); - var result = await validator.ValidateAccessTokenAsync(jwt); + var result = await validator.ValidateAccessTokenAsync(jwt, null, _ct); result.IsError.ShouldBeFalse(); } @@ -295,9 +292,9 @@ public class AccessTokenValidation var token = TokenFactory.CreateAccessToken(new Client { ClientId = "unknown" }, "valid", 600, "read", "write"); - var handle = await store.StoreReferenceTokenAsync(token); + var handle = await store.StoreReferenceTokenAsync(token, _ct); - var result = await validator.ValidateAccessTokenAsync(handle); + var result = await validator.ValidateAccessTokenAsync(handle, null, _ct); result.IsError.ShouldBeTrue(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs index a2848a395..f28a064a2 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs @@ -13,6 +13,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ClientValidation_Code { private IdentityServerOptions _options = TestIdentityServerOptions.Create(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", "AuthorizeRequest Client Validation - Code")] @@ -25,7 +26,7 @@ public class Authorize_ClientValidation_Code parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); @@ -42,7 +43,7 @@ public class Authorize_ClientValidation_Code parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -60,7 +61,7 @@ public class Authorize_ClientValidation_Code parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); @@ -78,7 +79,7 @@ public class Authorize_ClientValidation_Code parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); @@ -95,7 +96,7 @@ public class Authorize_ClientValidation_Code parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); @@ -112,7 +113,7 @@ public class Authorize_ClientValidation_Code parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs index 2353a176e..e9332d4d5 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs @@ -13,6 +13,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ClientValidation_IdToken { private IdentityServerOptions _options = TestIdentityServerOptions.Create(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", "AuthorizeRequest Client Validation - IdToken")] @@ -26,7 +27,7 @@ public class Authorize_ClientValidation_IdToken parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs index ef35ac122..4783ad84a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs @@ -13,6 +13,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ClientValidation_Invalid { private const string Category = "AuthorizeRequest Client Validation - Invalid"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IdentityServerOptions _options = TestIdentityServerOptions.Create(); @@ -27,7 +28,7 @@ public class Authorize_ClientValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.IdToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs index c44198a06..db84ead51 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs @@ -13,6 +13,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ClientValidation_Token { private const string Category = "AuthorizeRequest Client Validation - Token"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IdentityServerOptions _options = TestIdentityServerOptions.Create(); @@ -27,7 +28,7 @@ public class Authorize_ClientValidation_Token parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Token); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); @@ -45,7 +46,7 @@ public class Authorize_ClientValidation_Token parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -64,7 +65,7 @@ public class Authorize_ClientValidation_Token parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.CodeIdTokenToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs index cf0ff34db..b0eb1e004 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs @@ -13,6 +13,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ClientValidation_Valid { private const string Category = "AuthorizeRequest Client Validation - Valid"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IdentityServerOptions _options = TestIdentityServerOptions.Create(); @@ -27,7 +28,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -43,7 +44,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -59,7 +60,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -75,7 +76,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -92,7 +93,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.CodeIdToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -109,7 +110,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.CodeIdTokenToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -126,7 +127,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.CodeIdToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -143,7 +144,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.CodeIdTokenToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -160,7 +161,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -177,7 +178,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -194,7 +195,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -210,7 +211,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Token); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -227,7 +228,7 @@ public class Authorize_ClientValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs index 7a360880e..128652b04 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs @@ -28,7 +28,7 @@ public class Authorize_ProtocolValidation_CustomValidator parameters.Add(OidcConstants.AuthorizeRequest.RedirectUri, "https://server/cb"); parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, default); _stubAuthorizeRequestValidator.WasCalled.ShouldBeTrue(); } @@ -47,7 +47,7 @@ public class Authorize_ProtocolValidation_CustomValidator { ctx.Result = new AuthorizeRequestValidationResult(ctx.Result.ValidatedRequest, "foo", "bar"); }; - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("foo"); @@ -60,7 +60,7 @@ public class StubAuthorizeRequestValidator : ICustomAuthorizeRequestValidator public Action Callback; public bool WasCalled { get; set; } - public Task ValidateAsync(CustomAuthorizeRequestValidationContext context) + public Task ValidateAsync(CustomAuthorizeRequestValidationContext context, Ct _) { WasCalled = true; Callback?.Invoke(context); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs index 3002a2fa1..e6fa8d0aa 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs @@ -12,6 +12,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ProtocolValidation_Invalid { private const string Category = "AuthorizeRequest Protocol Validation"; + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] @@ -19,7 +20,7 @@ public class Authorize_ProtocolValidation_Invalid { var validator = Factory.CreateAuthorizeRequestValidator(); - Func act = () => validator.ValidateAsync(null); + Func act = () => validator.ValidateAsync(null, _ct); await act.ShouldThrowAsync(); } @@ -29,7 +30,7 @@ public class Authorize_ProtocolValidation_Invalid public async Task Empty_Parameters() { var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(new NameValueCollection()); + var result = await validator.ValidateAsync(new NameValueCollection(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -47,7 +48,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Token); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); @@ -65,7 +66,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -82,7 +83,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Token); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); @@ -99,7 +100,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.IdToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -115,7 +116,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -131,7 +132,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -147,7 +148,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -166,7 +167,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -183,7 +184,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -199,7 +200,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.RedirectUri, "https://server/cb"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -216,7 +217,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, "unknown"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnsupportedResponseType); @@ -234,7 +235,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Query); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -252,7 +253,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Query); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -270,7 +271,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Query); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -288,7 +289,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Query); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -306,7 +307,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Query); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -324,7 +325,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.MaxAge, "malformed"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -342,7 +343,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.MaxAge, "-1"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -360,7 +361,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Query); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -378,7 +379,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Query); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -397,7 +398,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.Prompt, "none login"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -405,7 +406,7 @@ public class Authorize_ProtocolValidation_Invalid // The next three tests verify that when response_mode is explicitly requested and the // request later fails a grant-type or PKCE check, the error result carries the client's - // requested response_mode rather than the flow default (regression for products#1554). + // requested response_mode rather than the flow _ct (regression for products#1554). [Fact] [Trait("Category", Category)] @@ -421,7 +422,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Fragment); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.ValidatedRequest.ResponseMode.ShouldBe(OidcConstants.ResponseModes.Fragment); @@ -440,7 +441,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Fragment); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.ValidatedRequest.ResponseMode.ShouldBe(OidcConstants.ResponseModes.Fragment); @@ -459,7 +460,7 @@ public class Authorize_ProtocolValidation_Invalid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.FormPost); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.ValidatedRequest.ResponseMode.ShouldBe(OidcConstants.ResponseModes.FormPost); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs index ea57fe7a9..97aa425e6 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs @@ -31,7 +31,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(true); result.ErrorDescription.ShouldBe("Transform algorithm not supported"); @@ -52,7 +52,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(false); } @@ -71,7 +71,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(false); } @@ -90,7 +90,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(true); result.ErrorDescription.ShouldBe("Transform algorithm not supported"); @@ -108,7 +108,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(true); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -126,7 +126,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.CodeIdToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(true); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -150,7 +150,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(true); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -174,7 +174,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(true); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); @@ -197,7 +197,7 @@ public class Authorize_ProtocolValidation_Valid_PKCE parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, default); result.IsError.ShouldBe(true); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs index 09334abef..287ca92aa 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs @@ -20,6 +20,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ProtocolValidation_Resources { private const string Category = "AuthorizeRequest Protocol Validation - Resources"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private readonly AuthorizeRequestValidator _subject; @@ -69,7 +70,7 @@ public class Authorize_ProtocolValidation_Resources parameters.Add(OidcConstants.AuthorizeRequest.RedirectUri, "https://client1"); parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBe(false); result.ValidatedRequest.RequestedResourceIndicators.ShouldBeEmpty(); @@ -86,7 +87,7 @@ public class Authorize_ProtocolValidation_Resources parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); parameters.Add("resource", "not_uri"); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); @@ -103,7 +104,7 @@ public class Authorize_ProtocolValidation_Resources parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); parameters.Add("resource", "http://resource1"); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -119,7 +120,7 @@ public class Authorize_ProtocolValidation_Resources parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Token); parameters.Add("resource", "http://resource1"); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); @@ -136,7 +137,7 @@ public class Authorize_ProtocolValidation_Resources parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); parameters.Add("resource", "http://resource1" + new string('x', 512)); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); @@ -153,7 +154,7 @@ public class Authorize_ProtocolValidation_Resources parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); parameters.Add("resource", "http://resource1#fragment"); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); @@ -172,7 +173,7 @@ public class Authorize_ProtocolValidation_Resources parameters.Add("resource", "http://resource2"); parameters.Add("resource", "urn:test1"); - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.RequestedResourceIndicators @@ -195,7 +196,7 @@ public class Authorize_ProtocolValidation_Resources { InvalidScopes = { "foo" } }; - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_scope"); @@ -206,7 +207,7 @@ public class Authorize_ProtocolValidation_Resources { InvalidResourceIndicators = { "foo" } }; - var result = await _subject.ValidateAsync(parameters); + var result = await _subject.ValidateAsync(parameters, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs index 8e2e5aaa9..377d69c99 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs @@ -12,6 +12,7 @@ namespace UnitTests.Validation.AuthorizeRequest_Validation; public class Authorize_ProtocolValidation_Valid { private const string Category = "AuthorizeRequest Protocol Validation - Valid"; + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] @@ -24,7 +25,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBe(false); } @@ -40,7 +41,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -56,7 +57,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -72,7 +73,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.Token); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -89,7 +90,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -106,7 +107,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -124,7 +125,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -142,7 +143,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -158,7 +159,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.CodeToken); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -175,7 +176,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.ResponseMode, OidcConstants.ResponseModes.Fragment); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.IsError.ShouldBeFalse(); } @@ -193,7 +194,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Prompt, OidcConstants.PromptModes.None); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.ValidatedRequest.SessionId.ShouldNotBeNull(); } @@ -211,7 +212,7 @@ public class Authorize_ProtocolValidation_Valid parameters.Add(OidcConstants.AuthorizeRequest.Prompt, OidcConstants.PromptModes.Consent + ' ' + OidcConstants.PromptModes.Login); var validator = Factory.CreateAuthorizeRequestValidator(); - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.ValidatedRequest.PromptModes.Count().ShouldBe(2); result.ValidatedRequest.PromptModes.ShouldContain(OidcConstants.PromptModes.Login); @@ -233,13 +234,13 @@ public class Authorize_ProtocolValidation_Valid { parameters[OidcConstants.AuthorizeRequest.Prompt] = "consent login"; - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.ValidatedRequest.PromptModes.ShouldBe([OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login]); } { parameters[OidcConstants.AuthorizeRequest.Prompt] = "consent login"; parameters[Constants.ProcessedPrompt] = "login"; - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.ValidatedRequest.PromptModes.ShouldBe([OidcConstants.PromptModes.Consent]); result.ValidatedRequest.OriginalPromptModes.ShouldBe([OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login]); result.ValidatedRequest.ProcessedPromptModes.ShouldBe([OidcConstants.PromptModes.Login]); @@ -247,7 +248,7 @@ public class Authorize_ProtocolValidation_Valid { parameters[OidcConstants.AuthorizeRequest.Prompt] = "consent login"; parameters[Constants.ProcessedPrompt] = "login consent"; - var result = await validator.ValidateAsync(parameters); + var result = await validator.ValidateAsync(parameters, _ct); result.ValidatedRequest.PromptModes.ShouldBeEmpty(); result.ValidatedRequest.OriginalPromptModes.ShouldBe([OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login]); result.ValidatedRequest.ProcessedPromptModes.ShouldBe([OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login], true); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs index db62bbcee..05dd2cd97 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs @@ -501,7 +501,7 @@ public class ClientConfigurationValidation private async Task ValidateAsync(Client client) { var context = new ClientConfigurationValidationContext(client); - await _validator.ValidateAsync(context); + await _validator.ValidateAsync(context, default); return context; } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs index 0a221da00..10e235640 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs @@ -23,6 +23,7 @@ namespace UnitTests.Validation; public class DPoPProofValidatorTests { private const string Category = "DPoP validator tests"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IdentityServerOptions _options = new IdentityServerOptions(); private FakeTimeProvider _timeProvider = new FakeTimeProvider(); @@ -133,7 +134,7 @@ public class DPoPProofValidatorTests { _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); result.JsonWebKeyThumbprint.ShouldBe(_JKT); @@ -150,7 +151,7 @@ public class DPoPProofValidatorTests _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); result.JsonWebKeyThumbprint.ShouldBe(_JKT); @@ -182,7 +183,7 @@ public class DPoPProofValidatorTests _context.AccessTokenClaims = [CnfClaim()]; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); @@ -199,7 +200,7 @@ public class DPoPProofValidatorTests _payload["ath"] = "invalid"; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.ErrorDescription.ShouldBe("Invalid 'ath' value."); @@ -217,7 +218,7 @@ public class DPoPProofValidatorTests _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); @@ -236,7 +237,7 @@ public class DPoPProofValidatorTests _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); @@ -254,7 +255,7 @@ public class DPoPProofValidatorTests _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); @@ -272,7 +273,7 @@ public class DPoPProofValidatorTests _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); @@ -294,7 +295,7 @@ public class DPoPProofValidatorTests _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); @@ -312,7 +313,7 @@ public class DPoPProofValidatorTests _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); @@ -343,7 +344,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); _now = _now.AddMinutes(5); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } @@ -354,7 +355,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); _now = _now.AddMinutes(-5); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } } @@ -376,11 +377,11 @@ public class DPoPProofValidatorTests _now = _now.AddMinutes(5); { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); } } @@ -393,11 +394,11 @@ public class DPoPProofValidatorTests _now = _now.AddMinutes(-5); { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); } } @@ -417,7 +418,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); _now = _now.AddMinutes(5); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } @@ -427,7 +428,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); _now = _now.AddMinutes(-5); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } } @@ -447,11 +448,11 @@ public class DPoPProofValidatorTests _now = _now.AddMinutes(5); { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); } } @@ -463,11 +464,11 @@ public class DPoPProofValidatorTests _now = _now.AddMinutes(-5); { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); } } @@ -483,11 +484,11 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } { - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); } } @@ -498,7 +499,7 @@ public class DPoPProofValidatorTests { _context.ProofToken = ""; - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); } @@ -509,7 +510,7 @@ public class DPoPProofValidatorTests { _context.ProofToken = "malformed"; - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -523,7 +524,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -540,7 +541,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken("HS256", key); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -555,7 +556,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -569,7 +570,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -583,7 +584,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -597,7 +598,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -613,7 +614,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -627,7 +628,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -641,7 +642,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -655,7 +656,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -669,7 +670,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -683,7 +684,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -697,7 +698,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -711,7 +712,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -725,7 +726,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -740,7 +741,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); _context.ClientClockSkew = TimeSpan.FromMinutes(1); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } @@ -755,7 +756,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -771,7 +772,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); } @@ -786,7 +787,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -801,7 +802,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_dpop_proof"); @@ -815,7 +816,7 @@ public class DPoPProofValidatorTests _context.ExpirationValidationMode = DPoPTokenExpirationValidationMode.Nonce; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("use_dpop_nonce"); @@ -829,7 +830,7 @@ public class DPoPProofValidatorTests _context.ExpirationValidationMode = DPoPTokenExpirationValidationMode.Nonce; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); @@ -837,7 +838,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - result = await _subject.ValidateAsync(_context); + result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeFalse(); result.JsonWebKeyThumbprint.ShouldBe(_JKT); @@ -850,7 +851,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); _context.ExpirationValidationMode = DPoPTokenExpirationValidationMode.Nonce; - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); @@ -858,7 +859,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - result = await _subject.ValidateAsync(_context); + result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("use_dpop_nonce"); @@ -872,7 +873,7 @@ public class DPoPProofValidatorTests _context.ExpirationValidationMode = DPoPTokenExpirationValidationMode.Nonce; _context.ProofToken = CreateDPoPProofToken(); - var result = await _subject.ValidateAsync(_context); + var result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); @@ -883,7 +884,7 @@ public class DPoPProofValidatorTests _context.ProofToken = CreateDPoPProofToken(); - result = await _subject.ValidateAsync(_context); + result = await _subject.ValidateAsync(_context, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("use_dpop_nonce"); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/DefaultIssuerPathValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/DefaultIssuerPathValidatorTests.cs index 1422e0485..c7e688e8f 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/DefaultIssuerPathValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/DefaultIssuerPathValidatorTests.cs @@ -17,7 +17,7 @@ public class DefaultIssuerPathValidatorTests var subject = new DefaultIssuerPathValidator(issuerNameService, logger); var path = "/foo"; - var result = await subject.ValidateAsync(path); + var result = await subject.ValidateAsync(path, default); result.ShouldBeTrue(); } @@ -30,7 +30,7 @@ public class DefaultIssuerPathValidatorTests var subject = new DefaultIssuerPathValidator(issuerNameService, logger); var path = string.Empty; - var result = await subject.ValidateAsync(path); + var result = await subject.ValidateAsync(path, default); result.ShouldBeTrue(); } @@ -42,7 +42,7 @@ public class DefaultIssuerPathValidatorTests var logger = new FakeLogger(); var subject = new DefaultIssuerPathValidator(issuerNameService, logger); - var result = await subject.ValidateAsync(null); + var result = await subject.ValidateAsync(null, default); result.ShouldBeTrue(); } @@ -55,7 +55,7 @@ public class DefaultIssuerPathValidatorTests var subject = new DefaultIssuerPathValidator(issuerNameService, logger); var path = "/foo"; - var result = await subject.ValidateAsync(path); + var result = await subject.ValidateAsync(path, default); result.ShouldBeTrue(); } @@ -68,7 +68,7 @@ public class DefaultIssuerPathValidatorTests var subject = new DefaultIssuerPathValidator(issuerNameService, logger); var path = "/foo"; - var result = await subject.ValidateAsync(path); + var result = await subject.ValidateAsync(path, default); result.ShouldBeTrue(); } @@ -81,7 +81,7 @@ public class DefaultIssuerPathValidatorTests var subject = new DefaultIssuerPathValidator(issuerNameService, logger); var path = "/foo/bar"; - var result = await subject.ValidateAsync(path); + var result = await subject.ValidateAsync(path, default); result.ShouldBeTrue(); } @@ -94,7 +94,7 @@ public class DefaultIssuerPathValidatorTests var subject = new DefaultIssuerPathValidator(issuerNameService, logger); var path = "/foo"; - var result = await subject.ValidateAsync(path); + var result = await subject.ValidateAsync(path, default); result.ShouldBeFalse(); } @@ -107,7 +107,7 @@ public class DefaultIssuerPathValidatorTests var subject = new DefaultIssuerPathValidator(issuerNameService, logger); var path = "/foo"; - var result = await subject.ValidateAsync(path); + var result = await subject.ValidateAsync(path, default); result.ShouldBeFalse(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs index 6814090f7..f394fc2c8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs @@ -30,7 +30,7 @@ public class DeviceAuthorizationRequestValidation { var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - Func act = () => validator.ValidateAsync(null, null); + Func act = () => validator.ValidateAsync(null, null, default); await act.ShouldThrowAsync(); } @@ -42,7 +42,7 @@ public class DeviceAuthorizationRequestValidation testClient.ProtocolType = IdentityServerConstants.ProtocolTypes.WsFederation; var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - var result = await validator.ValidateAsync(testParameters, new ClientSecretValidationResult { Client = testClient }); + var result = await validator.ValidateAsync(testParameters, new ClientSecretValidationResult { Client = testClient }, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); @@ -55,7 +55,7 @@ public class DeviceAuthorizationRequestValidation testClient.AllowedGrantTypes = GrantTypes.Implicit; var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - var result = await validator.ValidateAsync(testParameters, new ClientSecretValidationResult { Client = testClient }); + var result = await validator.ValidateAsync(testParameters, new ClientSecretValidationResult { Client = testClient }, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); @@ -68,7 +68,7 @@ public class DeviceAuthorizationRequestValidation var parameters = new NameValueCollection { { "scope", "resource2" } }; var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }); + var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); @@ -81,7 +81,7 @@ public class DeviceAuthorizationRequestValidation var parameters = new NameValueCollection { { "scope", Guid.NewGuid().ToString() } }; var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }); + var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); @@ -94,7 +94,7 @@ public class DeviceAuthorizationRequestValidation var parameters = new NameValueCollection { { "scope", "openid" } }; var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }); + var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }, default); result.IsError.ShouldBeFalse(); result.ValidatedRequest.IsOpenIdRequest.ShouldBeTrue(); @@ -116,7 +116,7 @@ public class DeviceAuthorizationRequestValidation var parameters = new NameValueCollection { { "scope", "resource" } }; var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }); + var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }, default); result.IsError.ShouldBeFalse(); result.ValidatedRequest.IsOpenIdRequest.ShouldBeFalse(); @@ -140,7 +140,7 @@ public class DeviceAuthorizationRequestValidation var parameters = new NameValueCollection { { "scope", "openid resource offline_access" } }; var validator = Factory.CreateDeviceAuthorizationRequestValidator(); - var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }); + var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }, default); result.IsError.ShouldBeFalse(); result.ValidatedRequest.IsOpenIdRequest.ShouldBeTrue(); @@ -168,7 +168,8 @@ public class DeviceAuthorizationRequestValidation var result = await validator.ValidateAsync( new NameValueCollection(), - new ClientSecretValidationResult { Client = testClient }); + new ClientSecretValidationResult { Client = testClient }, + default); result.IsError.ShouldBeFalse(); result.ValidatedRequest.RequestedScopes.ShouldContain(testClient.AllowedScopes); @@ -183,7 +184,8 @@ public class DeviceAuthorizationRequestValidation var result = await validator.ValidateAsync( new NameValueCollection(), - new ClientSecretValidationResult { Client = testClient }); + new ClientSecretValidationResult { Client = testClient }, + default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs index 66efdfe5c..a5020a566 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs @@ -15,6 +15,7 @@ public class DeviceCodeValidation { private const string Category = "Device code validation"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private readonly IClientStore _clients = Factory.CreateClientStore(); private readonly DeviceCode deviceCode = new DeviceCode @@ -32,7 +33,7 @@ public class DeviceCodeValidation [Trait("Category", Category)] public async Task DeviceCode_Missing() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); var validator = Factory.CreateDeviceCodeValidator(service); @@ -42,7 +43,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = null, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -52,10 +53,10 @@ public class DeviceCodeValidation [Trait("Category", Category)] public async Task DeviceCode_From_Different_Client() { - var badActor = await _clients.FindClientByIdAsync("codeclient"); + var badActor = await _clients.FindClientByIdAsync("codeclient", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service); @@ -64,7 +65,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -77,10 +78,10 @@ public class DeviceCodeValidation deviceCode.CreationTime = DateTime.UtcNow.AddDays(-10); deviceCode.Lifetime = 300; - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service); @@ -89,7 +90,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.ExpiredToken); @@ -101,10 +102,10 @@ public class DeviceCodeValidation { deviceCode.AuthorizedScopes = new List(); - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service); @@ -113,7 +114,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.AccessDenied); @@ -125,10 +126,10 @@ public class DeviceCodeValidation { deviceCode.IsAuthorized = false; - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service); @@ -137,7 +138,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.AuthorizationPending); @@ -149,10 +150,10 @@ public class DeviceCodeValidation { deviceCode.Subject = null; - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service); @@ -161,7 +162,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.AuthorizationPending); @@ -172,10 +173,10 @@ public class DeviceCodeValidation [Trait("Category", Category)] public async Task User_Disabled() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service, new TestProfileService(false)); @@ -184,7 +185,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -194,10 +195,10 @@ public class DeviceCodeValidation [Trait("Category", Category)] public async Task DeviceCode_Polling_Too_Fast() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service, throttlingService: new TestDeviceFlowThrottlingService(true)); @@ -206,7 +207,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeTrue(); context.Result.Error.ShouldBe(OidcConstants.TokenErrors.SlowDown); @@ -216,10 +217,10 @@ public class DeviceCodeValidation [Trait("Category", Category)] public async Task Valid_DeviceCode() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var service = Factory.CreateDeviceCodeService(); - var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode); + var handle = await service.StoreDeviceAuthorizationAsync(Guid.NewGuid().ToString(), deviceCode, _ct); var validator = Factory.CreateDeviceCodeValidator(service); @@ -228,7 +229,7 @@ public class DeviceCodeValidation var context = new DeviceCodeValidationContext { DeviceCode = handle, Request = request }; - await validator.ValidateAsync(context); + await validator.ValidateAsync(context, _ct); context.Result.IsError.ShouldBeFalse(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs index 72d4d2f14..1383f27ba 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs @@ -17,6 +17,7 @@ public class EndSessionRequestValidatorTests { private EndSessionRequestValidator _subject; private IdentityServerOptions _options; + private readonly Ct _ct = TestContext.Current.CancellationToken; private StubTokenValidator _stubTokenValidator = new StubTokenValidator(); private StubRedirectUriValidator _stubRedirectUriValidator = new StubRedirectUriValidator(); private MockUserSession _userSession = new MockUserSession(); @@ -46,13 +47,13 @@ public class EndSessionRequestValidatorTests _options.Authentication.RequireAuthenticatedUserForSignOutMessage = true; var parameters = new NameValueCollection(); - var result = await _subject.ValidateAsync(parameters, null); + var result = await _subject.ValidateAsync(parameters, null, _ct); result.IsError.ShouldBeTrue(); - result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal()); + result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal(), _ct); result.IsError.ShouldBeTrue(); - result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal(new ClaimsIdentity())); + result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal(new ClaimsIdentity()), _ct); result.IsError.ShouldBeTrue(); } @@ -73,7 +74,7 @@ public class EndSessionRequestValidatorTests parameters.Add("client_id", "client1"); parameters.Add("state", "foo"); - var result = await _subject.ValidateAsync(parameters, _user); + var result = await _subject.ValidateAsync(parameters, _user, _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.Client.ClientId.ShouldBe("client"); @@ -96,7 +97,7 @@ public class EndSessionRequestValidatorTests var parameters = new NameValueCollection(); parameters.Add("id_token_hint", "id_token"); - var result = await _subject.ValidateAsync(parameters, _user); + var result = await _subject.ValidateAsync(parameters, _user, _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.PostLogOutUri.ShouldBeNull(); } @@ -115,7 +116,7 @@ public class EndSessionRequestValidatorTests var parameters = new NameValueCollection(); parameters.Add("id_token_hint", "id_token"); - var result = await _subject.ValidateAsync(parameters, _user); + var result = await _subject.ValidateAsync(parameters, _user, _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.PostLogOutUri.ShouldBeNull(); } @@ -137,7 +138,7 @@ public class EndSessionRequestValidatorTests parameters.Add("client_id", "client1"); parameters.Add("state", "foo"); - var result = await _subject.ValidateAsync(parameters, _user); + var result = await _subject.ValidateAsync(parameters, _user, _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.Client.ClientId.ShouldBe("client"); @@ -164,7 +165,7 @@ public class EndSessionRequestValidatorTests parameters.Add("client_id", "client1"); parameters.Add("state", "foo"); - var result = await _subject.ValidateAsync(parameters, _user); + var result = await _subject.ValidateAsync(parameters, _user, _ct); result.IsError.ShouldBeTrue(); } @@ -173,7 +174,7 @@ public class EndSessionRequestValidatorTests { var parameters = new NameValueCollection(); - var result = await _subject.ValidateAsync(parameters, _user); + var result = await _subject.ValidateAsync(parameters, _user, _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.Raw.ShouldBeSameAs(parameters); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubRedirectUriValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubRedirectUriValidator.cs index db37fa947..ae471698a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubRedirectUriValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubRedirectUriValidator.cs @@ -12,7 +12,9 @@ public class StubRedirectUriValidator : IRedirectUriValidator public bool IsRedirectUriValid { get; set; } public bool IsPostLogoutRedirectUriValid { get; set; } - public Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client) => Task.FromResult(IsPostLogoutRedirectUriValid); + public Task IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client, Ct _) => Task.FromResult(IsPostLogoutRedirectUriValid); +#pragma warning disable CS0618 public Task IsRedirectUriValidAsync(string requestedUri, Client client) => Task.FromResult(IsRedirectUriValid); +#pragma warning restore CS0618 } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubTokenValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubTokenValidator.cs index a5a06402e..9fdb1daa7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubTokenValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/StubTokenValidator.cs @@ -2,7 +2,6 @@ // See LICENSE in the project root for license information. -using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; namespace UnitTests.Validation.EndSessionRequestValidation; @@ -12,9 +11,7 @@ public class StubTokenValidator : ITokenValidator public TokenValidationResult AccessTokenValidationResult { get; set; } = new TokenValidationResult(); public TokenValidationResult IdentityTokenValidationResult { get; set; } = new TokenValidationResult(); - public Task ValidateAccessTokenAsync(string token, string expectedScope = null) => Task.FromResult(AccessTokenValidationResult); + public Task ValidateAccessTokenAsync(string token, string expectedScope, Ct _) => Task.FromResult(AccessTokenValidationResult); - public Task ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true) => Task.FromResult(IdentityTokenValidationResult); - - public Task ValidateRefreshTokenAsync(string token, Client client) => throw new System.NotImplementedException(); + public Task ValidateIdentityTokenAsync(string token, string clientId, bool validateLifetime, Ct _) => Task.FromResult(IdentityTokenValidationResult); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs index 8efc267dd..314319e8b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs @@ -38,7 +38,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeTrue(); } @@ -53,7 +53,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeFalse(); ctx.ErrorMessage.ShouldContain("registered"); @@ -71,7 +71,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeTrue(); } @@ -91,7 +91,7 @@ public class IdentityProviderConfigurationValidation idp.Scheme = ""; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeFalse(); ctx.ErrorMessage.ToLowerInvariant().ShouldContain("scheme"); @@ -112,7 +112,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeFalse(); ctx.ErrorMessage.ToLowerInvariant().ShouldContain("clientid"); @@ -134,7 +134,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeTrue(); } @@ -154,7 +154,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeFalse(); ctx.ErrorMessage.ToLowerInvariant().ShouldContain("authority"); @@ -175,7 +175,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeFalse(); ctx.ErrorMessage.ToLowerInvariant().ShouldContain("responsetype"); @@ -196,7 +196,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeFalse(); ctx.ErrorMessage.ToLowerInvariant().ShouldContain("scope"); @@ -217,7 +217,7 @@ public class IdentityProviderConfigurationValidation }; var ctx = new IdentityProviderConfigurationValidationContext(idp); - await _validator.ValidateAsync(ctx); + await _validator.ValidateAsync(ctx, default); ctx.IsValid.ShouldBeTrue(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs index ca9f0bc18..a6cd4ee1b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs @@ -14,6 +14,7 @@ namespace UnitTests.Validation; public class IdentityTokenValidation { private const string Category = "Identity token validation"; + private readonly Ct _ct = TestContext.Current.CancellationToken; static IdentityTokenValidation() => JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); @@ -23,10 +24,10 @@ public class IdentityTokenValidation { var creator = Factory.CreateDefaultTokenCreator(); var token = TokenFactory.CreateIdentityToken("roclient", "valid"); - var jwt = await creator.CreateTokenAsync(token); + var jwt = await creator.CreateTokenAsync(token, _ct); var validator = Factory.CreateTokenValidator(); - var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient"); + var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient", true, _ct); result.IsError.ShouldBeFalse(); } @@ -36,10 +37,10 @@ public class IdentityTokenValidation public async Task Valid_IdentityToken_DefaultKeyType_no_ClientId_supplied() { var creator = Factory.CreateDefaultTokenCreator(); - var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityToken("roclient", "valid")); + var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityToken("roclient", "valid"), _ct); var validator = Factory.CreateTokenValidator(); - var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient"); + var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient", true, _ct); result.IsError.ShouldBeFalse(); } @@ -48,10 +49,10 @@ public class IdentityTokenValidation public async Task Valid_IdentityToken_no_ClientId_supplied() { var creator = Factory.CreateDefaultTokenCreator(); - var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityToken("roclient", "valid")); + var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityToken("roclient", "valid"), _ct); var validator = Factory.CreateTokenValidator(); - var result = await validator.ValidateIdentityTokenAsync(jwt); + var result = await validator.ValidateIdentityTokenAsync(jwt, null, true, _ct); result.IsError.ShouldBeFalse(); } @@ -60,10 +61,10 @@ public class IdentityTokenValidation public async Task IdentityToken_InvalidClientId() { var creator = Factory.CreateDefaultTokenCreator(); - var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityToken("roclient", "valid")); + var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityToken("roclient", "valid"), _ct); var validator = Factory.CreateTokenValidator(); - var result = await validator.ValidateIdentityTokenAsync(jwt, "invalid"); + var result = await validator.ValidateIdentityTokenAsync(jwt, "invalid", true, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } @@ -73,10 +74,10 @@ public class IdentityTokenValidation public async Task IdentityToken_Too_Long() { var creator = Factory.CreateDefaultTokenCreator(); - var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityTokenLong("roclient", "valid", 1000)); + var jwt = await creator.CreateTokenAsync(TokenFactory.CreateIdentityTokenLong("roclient", "valid", 1000), _ct); var validator = Factory.CreateTokenValidator(); - var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient"); + var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient", true, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } @@ -90,7 +91,7 @@ public class IdentityTokenValidation id_token.Claims.Add(new System.Security.Claims.Claim("aud", "some_aud")); // this should not throw - var jwt = await creator.CreateTokenAsync(id_token); + var jwt = await creator.CreateTokenAsync(id_token, _ct); // check that the custom aud was ignored var payload = jwt.Split('.')[1]; diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs index 64e4302b6..9e41788bc 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs @@ -15,6 +15,7 @@ namespace UnitTests.Validation; public class IntrospectionRequestValidatorTests { private const string Category = "Introspection request validation"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IntrospectionRequestValidator _subject; private IReferenceTokenStore _referenceTokenStore; @@ -44,7 +45,7 @@ public class IntrospectionRequestValidatorTests new System.Security.Claims.Claim("scope", "b") } }; - var handle = await _referenceTokenStore.StoreReferenceTokenAsync(token); + var handle = await _referenceTokenStore.StoreReferenceTokenAsync(token, _ct); var param = new NameValueCollection() { @@ -56,7 +57,8 @@ public class IntrospectionRequestValidatorTests { Parameters = param, Api = new ApiResource("api") - } + }, + _ct ); result.IsError.ShouldBe(false); @@ -83,7 +85,7 @@ public class IntrospectionRequestValidatorTests { Parameters = param, Api = new ApiResource("api") - }); + }, _ct); result.IsError.ShouldBe(true); result.Error.ShouldBe("missing_token"); @@ -105,7 +107,7 @@ public class IntrospectionRequestValidatorTests { Parameters = param, Api = new ApiResource("api") - }); + }, _ct); result.IsError.ShouldBe(false); result.IsActive.ShouldBe(false); @@ -133,7 +135,7 @@ public class IntrospectionRequestValidatorTests } }; - var handle = await _referenceTokenStore.StoreReferenceTokenAsync(token); + var handle = await _referenceTokenStore.StoreReferenceTokenAsync(token, _ct); var param = new NameValueCollection { { "token", handle } @@ -144,7 +146,8 @@ public class IntrospectionRequestValidatorTests { Parameters = param, Api = new ApiResource("api") - } + }, + _ct ); var claims = result.Claims.Where(c => c.Type == claimType).ToArray(); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs index ebf2f6829..5edb465f3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs @@ -13,6 +13,8 @@ namespace UnitTests.Validation; public class IsLocalUrlTests { + private readonly Ct _ct = TestContext.Current.CancellationToken; + private const string queryParameters = "?client_id=mvc.code" + "&redirect_uri=https%3A%2F%2Flocalhost%3A44302%2Fsignin-oidc" + "&response_type=code" + @@ -65,7 +67,7 @@ public class IsLocalUrlTests { var interactionService = new DefaultIdentityServerInteractionService(null, null, null, null, null, null, null, GetReturnUrlParser(), new LoggerFactory().CreateLogger()); - var actual = await interactionService.GetAuthorizationContextAsync(returnUrl); + var actual = await interactionService.GetAuthorizationContextAsync(returnUrl, _ct); if (expected) { actual.ShouldNotBeNull(); @@ -105,7 +107,7 @@ public class IsLocalUrlTests public async Task OidcReturnUrlParser_ParseAsync(string returnUrl, bool expected) { var oidcParser = GetOidcReturnUrlParser(); - var actual = await oidcParser.ParseAsync(returnUrl); + var actual = await oidcParser.ParseAsync(returnUrl, _ct); if (expected) { actual.ShouldNotBeNull(); @@ -138,7 +140,7 @@ public class IsLocalUrlTests public async Task ReturnUrlParser_ParseAsync(string returnUrl, bool expected) { var parser = GetReturnUrlParser(); - var actual = await parser.ParseAsync(returnUrl); + var actual = await parser.ParseAsync(returnUrl, _ct); if (expected) { actual.ShouldNotBeNull(); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs index 8f4467ce9..ac101f1a4 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs @@ -103,6 +103,7 @@ public class ResourceValidation }; private IResourceStore _subject; + private readonly Ct _ct = TestContext.Current.CancellationToken; public ResourceValidation() => _subject = new InMemoryResourcesStore(_identityResources, _apiResources, _scopes); @@ -117,7 +118,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "offline_access" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldContain("offline_access"); @@ -132,7 +133,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "scope1" } - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.InvalidScopes.ShouldBeEmpty(); @@ -148,7 +149,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "email", "scope1", "unknown" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldContain("unknown"); @@ -160,7 +161,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "scope1", "scope2" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldContain("scope2"); @@ -171,7 +172,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "email", "scope1" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldContain("email"); @@ -187,7 +188,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "scope1", "disabled_scope" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldContain("disabled_scope"); @@ -202,7 +203,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "scope1" } - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.InvalidScopes.ShouldBeEmpty(); @@ -217,7 +218,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "email", "scope1", "scope2" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldContain("email"); @@ -233,7 +234,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid", "scope1" } - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.Resources.IdentityResources.Select(x => x.Name).ShouldBe(["openid"]); @@ -250,7 +251,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "scope1" } - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.Resources.IdentityResources.ShouldBeEmpty(); @@ -267,7 +268,7 @@ public class ResourceValidation { Client = _restrictedClient, Scopes = new[] { "openid" } - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.Resources.IdentityResources.Select(x => x.Name).ShouldContain("openid"); @@ -291,7 +292,7 @@ public class ResourceValidation { Client = new Client { AllowedScopes = { "s" } }, Scopes = new[] { "s" } - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.Resources.ApiResources.Count.ShouldBe(2); @@ -312,7 +313,7 @@ public class ResourceValidation Client = _resourceClient, Scopes = new[] { "scope1", "offline_access" }, ResourceIndicators = new[] { "isolated1" }, - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.Resources.ApiResources.Select(x => x.Name).ShouldBe(["resource1", "isolated1"]); @@ -329,7 +330,7 @@ public class ResourceValidation { Client = _resourceClient, Scopes = new[] { "scope1" }, - }); + }, _ct); result.Succeeded.ShouldBeTrue(); result.Resources.ApiResources.Select(x => x.Name).ShouldBe(["resource1"]); @@ -346,7 +347,7 @@ public class ResourceValidation Client = _resourceClient, Scopes = new[] { "scope1" }, ResourceIndicators = new[] { "invalid" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldBeEmpty(); @@ -363,7 +364,7 @@ public class ResourceValidation Client = _resourceClient, Scopes = new[] { "scope1" }, ResourceIndicators = new[] { "resource3" } - }); + }, _ct); result.Succeeded.ShouldBeFalse(); result.InvalidScopes.ShouldBeEmpty(); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs index 754ce9805..43e1d4cf6 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs @@ -50,7 +50,7 @@ public class RevocationRequestValidation { var parameters = new NameValueCollection(); - var result = await _validator.ValidateRequestAsync(parameters, _client); + var result = await _validator.ValidateRequestAsync(parameters, _client, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); @@ -65,7 +65,7 @@ public class RevocationRequestValidation { "token_type_hint", "access_token" } }; - var result = await _validator.ValidateRequestAsync(parameters, _client); + var result = await _validator.ValidateRequestAsync(parameters, _client, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); @@ -81,7 +81,7 @@ public class RevocationRequestValidation { "token_type_hint", "access_token" } }; - var result = await _validator.ValidateRequestAsync(parameters, _client); + var result = await _validator.ValidateRequestAsync(parameters, _client, default); result.IsError.ShouldBeFalse(); result.Token.ShouldBe("foo"); @@ -98,7 +98,7 @@ public class RevocationRequestValidation { "token_type_hint", "refresh_token" } }; - var result = await _validator.ValidateRequestAsync(parameters, _client); + var result = await _validator.ValidateRequestAsync(parameters, _client, default); result.IsError.ShouldBeFalse(); result.Token.ShouldBe("foo"); @@ -114,7 +114,7 @@ public class RevocationRequestValidation { "token", "foo" } }; - var result = await _validator.ValidateRequestAsync(parameters, _client); + var result = await _validator.ValidateRequestAsync(parameters, _client, default); result.IsError.ShouldBeFalse(); result.Token.ShouldBe("foo"); @@ -131,7 +131,7 @@ public class RevocationRequestValidation { "token_type_hint", "invalid" } }; - var result = await _validator.ValidateRequestAsync(parameters, _client); + var result = await _validator.ValidateRequestAsync(parameters, _client, default); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(Constants.RevocationErrors.UnsupportedTokenType); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs index 9077e5a56..265839cef 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs @@ -16,6 +16,7 @@ namespace UnitTests.Validation.Secrets; public class BasicAuthenticationSecretParsing { private const string Category = "Secrets - Basic Authentication Secret Parsing"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IdentityServerOptions _options; private BasicAuthenticationSecretParser _parser; @@ -32,7 +33,7 @@ public class BasicAuthenticationSecretParsing { var context = new DefaultHttpContext(); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -48,7 +49,7 @@ public class BasicAuthenticationSecretParsing context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); secret.Id.ShouldBe("client"); @@ -79,7 +80,7 @@ public class BasicAuthenticationSecretParsing var headerValue = $"Basic {Convert.ToBase64String(encoding.GetBytes(credential))}"; context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); secret.Id.ShouldBe(userName); @@ -104,7 +105,7 @@ public class BasicAuthenticationSecretParsing var headerValue = $"Basic {credential}"; context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); secret.Id.ShouldBe(userName); @@ -121,7 +122,7 @@ public class BasicAuthenticationSecretParsing Convert.ToBase64String(Encoding.UTF8.GetBytes("client:"))); context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.NoSecret); secret.Id.ShouldBe("client"); @@ -136,7 +137,7 @@ public class BasicAuthenticationSecretParsing context.Request.Headers.Append("Authorization", new StringValues(string.Empty)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -154,7 +155,7 @@ public class BasicAuthenticationSecretParsing Convert.ToBase64String(Encoding.UTF8.GetBytes(credential))); context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -171,7 +172,7 @@ public class BasicAuthenticationSecretParsing Convert.ToBase64String(Encoding.UTF8.GetBytes(credential))); context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -200,7 +201,7 @@ public class BasicAuthenticationSecretParsing Convert.ToBase64String(Encoding.UTF8.GetBytes(credential))); context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await parser.ParseAsync(context); + var secret = await parser.ParseAsync(context, _ct); secret.Id.ShouldBe(clientId); secret.Credential.ShouldBe(clientSecret); } @@ -244,7 +245,7 @@ public class BasicAuthenticationSecretParsing Convert.ToBase64String(Encoding.UTF8.GetBytes(credential))); context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await parser.ParseAsync(context); + var secret = await parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -256,7 +257,7 @@ public class BasicAuthenticationSecretParsing context.Request.Headers.Append("Authorization", new StringValues("Basic ")); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -269,7 +270,7 @@ public class BasicAuthenticationSecretParsing context.Request.Headers.Append("Authorization", new StringValues("Unknown")); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -282,7 +283,7 @@ public class BasicAuthenticationSecretParsing context.Request.Headers.Append("Authorization", new StringValues("Basic somerandomdata")); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -297,7 +298,7 @@ public class BasicAuthenticationSecretParsing Convert.ToBase64String(Encoding.UTF8.GetBytes("client"))); context.Request.Headers.Append("Authorization", new StringValues(headerValue)); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs index 0782cb58e..c8c72c3a9 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs @@ -18,6 +18,7 @@ public class ClientAssertionSecretParsing { private IdentityServerOptions _options; private JwtBearerClientAssertionSecretParser _parser; + private readonly Ct _ct = TestContext.Current.CancellationToken; public ClientAssertionSecretParsing() { @@ -32,7 +33,7 @@ public class ClientAssertionSecretParsing context.Request.Body = new MemoryStream(); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -50,7 +51,7 @@ public class ClientAssertionSecretParsing context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldNotBeNull(); secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.JwtBearer); @@ -68,7 +69,7 @@ public class ClientAssertionSecretParsing context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -83,7 +84,7 @@ public class ClientAssertionSecretParsing context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -97,7 +98,7 @@ public class ClientAssertionSecretParsing context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -113,7 +114,7 @@ public class ClientAssertionSecretParsing context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -129,7 +130,7 @@ public class ClientAssertionSecretParsing context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs index 647058ca8..116f5fb05 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs @@ -24,7 +24,7 @@ public class ClientSecretValidation context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var result = await validator.ValidateAsync(context); + var result = await validator.ValidateAsync(context, default); result.IsError.ShouldBeFalse(); result.Client.ClientId.ShouldBe("roclient"); @@ -42,7 +42,7 @@ public class ClientSecretValidation context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var result = await validator.ValidateAsync(context); + var result = await validator.ValidateAsync(context, default); result.IsError.ShouldBeTrue(); } @@ -59,7 +59,7 @@ public class ClientSecretValidation context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var result = await validator.ValidateAsync(context); + var result = await validator.ValidateAsync(context, default); result.IsError.ShouldBeFalse(); result.Client.ClientId.ShouldBe("roclient.public"); @@ -78,7 +78,7 @@ public class ClientSecretValidation context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var result = await validator.ValidateAsync(context); + var result = await validator.ValidateAsync(context, default); result.IsError.ShouldBeFalse(); result.Client.ClientId.ShouldBe("client.implicit"); @@ -96,7 +96,7 @@ public class ClientSecretValidation context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var result = await validator.ValidateAsync(context); + var result = await validator.ValidateAsync(context, default); result.IsError.ShouldBeTrue(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs index 7983c2030..e9edb09f3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs @@ -15,6 +15,7 @@ namespace UnitTests.Validation.Secrets; public class FormPostCredentialExtraction { private const string Category = "Secrets - Form Post Secret Parsing"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IdentityServerOptions _options; private PostBodySecretParser _parser; @@ -32,7 +33,7 @@ public class FormPostCredentialExtraction var context = new DefaultHttpContext(); context.Request.Body = new MemoryStream(); - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -48,7 +49,7 @@ public class FormPostCredentialExtraction context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); secret.Id.ShouldBe("client"); @@ -67,7 +68,7 @@ public class FormPostCredentialExtraction context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -84,7 +85,7 @@ public class FormPostCredentialExtraction context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -100,7 +101,7 @@ public class FormPostCredentialExtraction context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } @@ -116,7 +117,7 @@ public class FormPostCredentialExtraction context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldNotBeNull(); secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.NoSecret); @@ -133,7 +134,7 @@ public class FormPostCredentialExtraction context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); context.Request.ContentType = "application/x-www-form-urlencoded"; - var secret = await _parser.ParseAsync(context); + var secret = await _parser.ParseAsync(context, _ct); secret.ShouldBeNull(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs index bd1a451da..2fd3a13a5 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs @@ -17,13 +17,14 @@ public class HashedSharedSecretValidation private ISecretValidator _validator = new HashedSharedSecretValidator(new Logger(new LoggerFactory())); private IClientStore _clients = new InMemoryClientStore(ClientValidationTestClients.Get()); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] public async Task Valid_Single_Secret() { var clientId = "single_secret_hashed_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -32,7 +33,7 @@ public class HashedSharedSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -42,7 +43,7 @@ public class HashedSharedSecretValidation public async Task Invalid_Credential_Type() { var clientId = "single_secret_hashed_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -51,7 +52,7 @@ public class HashedSharedSecretValidation Type = "invalid" }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -61,7 +62,7 @@ public class HashedSharedSecretValidation public async Task Valid_Multiple_Secrets() { var clientId = "multiple_secrets_hashed"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -70,19 +71,19 @@ public class HashedSharedSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "foobar"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "quux"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "notexpired"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -91,7 +92,7 @@ public class HashedSharedSecretValidation public async Task Invalid_Single_Secret() { var clientId = "single_secret_hashed_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -100,7 +101,7 @@ public class HashedSharedSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -110,7 +111,7 @@ public class HashedSharedSecretValidation public async Task Invalid_Multiple_Secrets() { var clientId = "multiple_secrets_hashed"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -119,7 +120,7 @@ public class HashedSharedSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -128,7 +129,7 @@ public class HashedSharedSecretValidation public async Task Client_with_no_Secret_Should_Fail() { var clientId = "no_secret_client"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -136,7 +137,7 @@ public class HashedSharedSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -145,7 +146,7 @@ public class HashedSharedSecretValidation public async Task Client_with_null_Secret_Should_Fail() { var clientId = "null_secret_client"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -154,7 +155,7 @@ public class HashedSharedSecretValidation Credential = "secret" }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs index 45a7d5a05..44df513f6 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs @@ -17,6 +17,7 @@ public class MutualTlsSecretValidation private const string Category = "Secrets - MutualTls Secret Validation"; private IClientStore _clients = new InMemoryClientStore(ClientValidationTestClients.Get()); + private readonly Ct _ct = TestContext.Current.CancellationToken; /////////////////// // thumbprints @@ -29,7 +30,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509ThumbprintSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -38,7 +39,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await validator.ValidateAsync(client.ClientSecrets, secret); + var result = await validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -50,7 +51,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509ThumbprintSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -59,7 +60,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.X509Certificate }; - Func act = async () => await validator.ValidateAsync(client.ClientSecrets, secret); + Func act = async () => await validator.ValidateAsync(client.ClientSecrets, secret, _ct); await act.ShouldThrowAsync(); } @@ -70,7 +71,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509ThumbprintSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -79,7 +80,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.X509Certificate }; - var result = await validator.ValidateAsync(client.ClientSecrets, secret); + var result = await validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -91,7 +92,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509ThumbprintSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -100,7 +101,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.X509Certificate }; - var result = await validator.ValidateAsync(client.ClientSecrets, secret); + var result = await validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -116,7 +117,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509NameSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -125,7 +126,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await validator.ValidateAsync(client.ClientSecrets, secret); + var result = await validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -137,7 +138,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509NameSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -146,7 +147,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.X509Certificate }; - Func act = async () => await validator.ValidateAsync(client.ClientSecrets, secret); + Func act = async () => await validator.ValidateAsync(client.ClientSecrets, secret, _ct); await act.ShouldThrowAsync(); } @@ -157,7 +158,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509NameSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -166,7 +167,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.X509Certificate }; - var result = await validator.ValidateAsync(client.ClientSecrets, secret); + var result = await validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -178,7 +179,7 @@ public class MutualTlsSecretValidation ISecretValidator validator = new X509NameSecretValidator(new Logger(new LoggerFactory())); var clientId = "mtls_client_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -187,7 +188,7 @@ public class MutualTlsSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.X509Certificate }; - var result = await validator.ValidateAsync(client.ClientSecrets, secret); + var result = await validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs index 28d9b3d26..557c0af2e 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs @@ -17,13 +17,14 @@ public class PlainTextClientSecretValidation private ISecretValidator _validator = new PlainTextSharedSecretValidator(new Logger(new LoggerFactory())); private IClientStore _clients = new InMemoryClientStore(ClientValidationTestClients.Get()); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] public async Task Valid_Single_Secret() { var clientId = "single_secret_no_protection_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -32,7 +33,7 @@ public class PlainTextClientSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -42,7 +43,7 @@ public class PlainTextClientSecretValidation public async Task Invalid_Credential_Type() { var clientId = "single_secret_no_protection_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -51,7 +52,7 @@ public class PlainTextClientSecretValidation Type = "invalid" }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -61,7 +62,7 @@ public class PlainTextClientSecretValidation public async Task Valid_Multiple_Secrets_No_Protection() { var clientId = "multiple_secrets_no_protection"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -70,19 +71,19 @@ public class PlainTextClientSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "foobar"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "quux"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "notexpired"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -91,7 +92,7 @@ public class PlainTextClientSecretValidation public async Task Invalid_Single_Secret() { var clientId = "single_secret_no_protection_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -100,7 +101,7 @@ public class PlainTextClientSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -110,7 +111,7 @@ public class PlainTextClientSecretValidation public async Task Invalid_Multiple_Secrets() { var clientId = "multiple_secrets_no_protection"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -119,7 +120,7 @@ public class PlainTextClientSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -128,7 +129,7 @@ public class PlainTextClientSecretValidation public async Task Client_with_no_Secret_Should_Fail() { var clientId = "no_secret_client"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -136,7 +137,7 @@ public class PlainTextClientSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -145,7 +146,7 @@ public class PlainTextClientSecretValidation public async Task Client_with_null_Secret_Should_Fail() { var clientId = "null_secret_client"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -154,7 +155,7 @@ public class PlainTextClientSecretValidation Credential = "secret" }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs index a1f0091d6..bb590466d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs @@ -25,6 +25,7 @@ public class PrivateKeyJwtSecretValidation private readonly ISecretValidator _validator; private readonly IClientStore _clients; private readonly IdentityServerOptions _options; + private readonly Ct _ct = TestContext.Current.CancellationToken; public PrivateKeyJwtSecretValidation() { @@ -99,7 +100,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Certificate_X5t_Only_Requires_Full_Certificate() { var clientId = "certificate_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = CreateToken(clientId); var secret = new ParsedSecret @@ -109,7 +110,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -118,7 +119,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Certificate_Thumbprint() { var clientId = "certificate_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -127,7 +128,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -136,7 +137,7 @@ public class PrivateKeyJwtSecretValidation public async Task Valid_Certificate_Base64() { var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -145,7 +146,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -166,7 +167,7 @@ public class PrivateKeyJwtSecretValidation _options.Preview.StrictClientAssertionAudienceValidation = false; var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -175,7 +176,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -192,7 +193,7 @@ public class PrivateKeyJwtSecretValidation _options.Preview.StrictClientAssertionAudienceValidation = true; var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -201,7 +202,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBe(expectSuccess, result.Error); } @@ -218,7 +219,7 @@ public class PrivateKeyJwtSecretValidation _options.Preview.StrictClientAssertionAudienceValidation = false; var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -227,7 +228,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBe(expectSuccess, result.Error); } @@ -244,7 +245,7 @@ public class PrivateKeyJwtSecretValidation _options.Preview.StrictClientAssertionAudienceValidation = setStrictOption; var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = new JwtSecurityTokenHandler().WriteToken(CreateToken( clientId, audiences: ["https://idsrv.com/connect/token"], @@ -257,7 +258,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBe(expectedResult); } @@ -274,7 +275,7 @@ public class PrivateKeyJwtSecretValidation _options.Preview.StrictClientAssertionAudienceValidation = setStrictOption; var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = new JwtSecurityTokenHandler().WriteToken(CreateToken( clientId, audiences: ["https://idsrv.com", "https://idsrv.com/"], @@ -287,7 +288,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBe(expectedResult); } @@ -304,7 +305,7 @@ public class PrivateKeyJwtSecretValidation _options.Preview.StrictClientAssertionAudienceValidation = enforceStrict; var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = new JwtSecurityTokenHandler().WriteToken(CreateToken(clientId, typ: typ)); var secret = new ParsedSecret @@ -314,7 +315,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBe(expectedResult); } @@ -322,7 +323,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Replay() { var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = new JwtSecurityTokenHandler().WriteToken(CreateToken(clientId)); var secret = new ParsedSecret { @@ -331,10 +332,10 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -342,7 +343,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Certificate_Base64() { var clientId = "certificate_base64_invalid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -351,7 +352,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -360,7 +361,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Issuer() { var clientId = "certificate_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = CreateToken(clientId); token.Payload.Remove(JwtClaimTypes.Issuer); @@ -372,7 +373,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -381,7 +382,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Subject() { var clientId = "certificate_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = CreateToken(clientId); token.Payload.Remove(JwtClaimTypes.Subject); @@ -393,7 +394,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -402,7 +403,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Expired_Token() { var clientId = "certificate_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = CreateToken(clientId, nowOverride: DateTime.UtcNow.AddHours(-1)); var secret = new ParsedSecret @@ -412,7 +413,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -421,7 +422,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Unsigned_Token() { var clientId = "certificate_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = CreateToken(clientId); token.Header.Remove("alg"); @@ -433,7 +434,7 @@ public class PrivateKeyJwtSecretValidation Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -442,7 +443,7 @@ public class PrivateKeyJwtSecretValidation public async Task Invalid_Not_Yet_Valid_Token() { var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = CreateToken(clientId, nowOverride: DateTime.UtcNow.AddSeconds(30)); var secret = new ParsedSecret @@ -454,7 +455,7 @@ public class PrivateKeyJwtSecretValidation _options.JwtValidationClockSkew = TimeSpan.FromSeconds(5); - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -463,7 +464,7 @@ public class PrivateKeyJwtSecretValidation public async Task Signing_Algorithm_Not_Allowed_By_Configuration() { var clientId = "certificate_base64_valid"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var token = CreateToken(clientId); var secret = new ParsedSecret @@ -475,7 +476,7 @@ public class PrivateKeyJwtSecretValidation _options.SupportedClientAssertionSigningAlgorithms = ["Test"]; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs index 52a2b2cf3..b6f02f5c7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs @@ -21,6 +21,7 @@ public class SecretValidation private IClientStore _clients = new InMemoryClientStore(ClientValidationTestClients.Get()); private SecretValidator _validator; private IdentityServerOptions _options = new IdentityServerOptions(); + private readonly Ct _ct = TestContext.Current.CancellationToken; public SecretValidation() => _validator = new SecretValidator( new FakeTimeProvider(DateTimeOffset.UtcNow), @@ -32,7 +33,7 @@ public class SecretValidation public async Task Valid_Single_Secret() { var clientId = "single_secret_hashed_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -41,7 +42,7 @@ public class SecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -51,7 +52,7 @@ public class SecretValidation public async Task Invalid_Credential_Type() { var clientId = "single_secret_hashed_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -60,7 +61,7 @@ public class SecretValidation Type = "invalid" }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -70,7 +71,7 @@ public class SecretValidation public async Task Valid_Multiple_Secrets() { var clientId = "multiple_secrets_hashed"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -79,19 +80,19 @@ public class SecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "foobar"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "quux"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); secret.Credential = "notexpired"; - result = await _validator.ValidateAsync(client.ClientSecrets, secret); + result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeTrue(); } @@ -100,7 +101,7 @@ public class SecretValidation public async Task Invalid_Single_Secret() { var clientId = "single_secret_hashed_no_expiration"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -109,7 +110,7 @@ public class SecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -119,7 +120,7 @@ public class SecretValidation public async Task Expired_Secret() { var clientId = "multiple_secrets_hashed"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -128,7 +129,7 @@ public class SecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -137,7 +138,7 @@ public class SecretValidation public async Task Invalid_Multiple_Secrets() { var clientId = "multiple_secrets_hashed"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -146,7 +147,7 @@ public class SecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } @@ -155,7 +156,7 @@ public class SecretValidation public async Task Client_with_no_Secret_Should_Fail() { var clientId = "no_secret_client"; - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var secret = new ParsedSecret { @@ -163,7 +164,7 @@ public class SecretValidation Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret }; - var result = await _validator.ValidateAsync(client.ClientSecrets, secret); + var result = await _validator.ValidateAsync(client.ClientSecrets, secret, _ct); result.Success.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/Factory.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/Factory.cs index 81369918a..69b5f623b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/Factory.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/Factory.cs @@ -285,7 +285,7 @@ internal static class Factory new LoggerFactory().CreateLogger()); jwtRequestUriHttpClient ??= new DefaultJwtRequestUriHttpClient( new HttpClient(new NetworkHandler(new Exception("no jwt request uri response configured"))), options, - new LoggerFactory(), new NoneCancellationTokenProvider()); + new LoggerFactory()); pushedAuthorizationService ??= new TestPushedAuthorizationService(); options ??= TestIdentityServerOptions.Create(); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestBackchannelAuthenticationRequestIdValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestBackchannelAuthenticationRequestIdValidator.cs index f791c1ed4..5e0a5d3e8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestBackchannelAuthenticationRequestIdValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestBackchannelAuthenticationRequestIdValidator.cs @@ -14,7 +14,7 @@ internal class TestBackchannelAuthenticationRequestIdValidator : IBackchannelAut //public DeviceCode DeviceCodeResult { get; set; } = new DeviceCode(); - public Task ValidateAsync(BackchannelAuthenticationRequestIdValidationContext context) + public Task ValidateAsync(BackchannelAuthenticationRequestIdValidationContext context, Ct _) { if (shouldError) { diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceCodeValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceCodeValidator.cs index 6942cc2c8..b6802b496 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceCodeValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceCodeValidator.cs @@ -15,7 +15,7 @@ public class TestDeviceCodeValidator : IDeviceCodeValidator public TestDeviceCodeValidator(bool shouldError = false) => this.shouldError = shouldError; - public Task ValidateAsync(DeviceCodeValidationContext context) + public Task ValidateAsync(DeviceCodeValidationContext context, Ct _) { if (shouldError) { diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceFlowThrottlingService.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceFlowThrottlingService.cs index 1db1069a3..26d4b072f 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceFlowThrottlingService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestDeviceFlowThrottlingService.cs @@ -13,5 +13,5 @@ public class TestDeviceFlowThrottlingService : IDeviceFlowThrottlingService public TestDeviceFlowThrottlingService(bool shouldSlownDown = false) => this.shouldSlownDown = shouldSlownDown; - public Task ShouldSlowDown(string deviceCode, DeviceCode details) => Task.FromResult(shouldSlownDown); + public Task ShouldSlowDown(string deviceCode, DeviceCode details, Ct _) => Task.FromResult(shouldSlownDown); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestGrantValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestGrantValidator.cs index dec703ba3..a5c137773 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestGrantValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestGrantValidator.cs @@ -28,7 +28,7 @@ internal class TestGrantValidator : IExtensionGrantValidator return Task.FromResult(new GrantValidationResult("bob", "CustomGrant")); } - public Task ValidateAsync(ExtensionGrantValidationContext context) + public Task ValidateAsync(ExtensionGrantValidationContext context, Ct _) { if (_isInvalid) { diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestIssuerNameService.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestIssuerNameService.cs index 60289afb1..d5852801e 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestIssuerNameService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestIssuerNameService.cs @@ -12,5 +12,5 @@ internal class TestIssuerNameService : IIssuerNameService public TestIssuerNameService(string value = null) => _value = value ?? "https://identityserver"; - public Task GetCurrentAsync() => Task.FromResult(_value); + public Task GetCurrentAsync(Ct _) => Task.FromResult(_value); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestProfileService.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestProfileService.cs index eca68ba61..65c1bdb76 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestProfileService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestProfileService.cs @@ -13,9 +13,9 @@ internal class TestProfileService : IProfileService public TestProfileService(bool shouldBeActive = true) => _shouldBeActive = shouldBeActive; - public Task GetProfileDataAsync(ProfileDataRequestContext context) => Task.CompletedTask; + public Task GetProfileDataAsync(ProfileDataRequestContext context, Ct _) => Task.CompletedTask; - public Task IsActiveAsync(IsActiveContext context) + public Task IsActiveAsync(IsActiveContext context, Ct _) { context.IsActive = _shouldBeActive; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestPushedAuthorizationService.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestPushedAuthorizationService.cs index d7468ca22..61fdb0e17 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestPushedAuthorizationService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestPushedAuthorizationService.cs @@ -15,19 +15,19 @@ internal class TestPushedAuthorizationService : IPushedAuthorizationService private Dictionary pushedRequests = new(); - public Task ConsumeAsync(string referenceValue) + public Task ConsumeAsync(string referenceValue, Ct _) { pushedRequests.Remove(referenceValue); return Task.CompletedTask; } - public Task GetPushedAuthorizationRequestAsync(string referenceValue) + public Task GetPushedAuthorizationRequestAsync(string referenceValue, Ct _) { pushedRequests.TryGetValue(referenceValue, out var par); return Task.FromResult(par); } - public Task StoreAsync(DeserializedPushedAuthorizationRequest request) + public Task StoreAsync(DeserializedPushedAuthorizationRequest request, Ct _) { pushedRequests[request.ReferenceValue] = request; return Task.CompletedTask; diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestResourceOwnerPasswordValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestResourceOwnerPasswordValidator.cs index 898014a24..60d025713 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestResourceOwnerPasswordValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestResourceOwnerPasswordValidator.cs @@ -23,7 +23,7 @@ public class TestResourceOwnerPasswordValidator : IResourceOwnerPasswordValidato _erroDescription = errorDescription; } - public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) + public Task ValidateAsync(ResourceOwnerPasswordValidationContext context, Ct _) { if (_sendError) { diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestTokenValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestTokenValidator.cs index b2efac60b..ed3313c49 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestTokenValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Setup/TestTokenValidator.cs @@ -2,7 +2,6 @@ // See LICENSE in the project root for license information. -using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; namespace UnitTests.Validation.Setup; @@ -13,9 +12,7 @@ internal class TestTokenValidator : ITokenValidator public TestTokenValidator(TokenValidationResult result) => _result = result; - public Task ValidateAccessTokenAsync(string token, string expectedScope = null) => Task.FromResult(_result); + public Task ValidateAccessTokenAsync(string token, string expectedScope, Ct _) => Task.FromResult(_result); - public Task ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true) => Task.FromResult(_result); - - public Task ValidateRefreshTokenAsync(string token, Client client = null) => Task.FromResult(_result); + public Task ValidateIdentityTokenAsync(string token, string clientId, bool validateLifetime, Ct _) => Task.FromResult(_result); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs index 9e6b9ac9a..fcfac93ac 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs @@ -48,7 +48,7 @@ public class StrictRedirectUriValidatorAppAuthValidation { RequestedUri = requestedUri, Client = clientWithValidLoopbackRedirectUri - }); + }, default); result.ShouldBeTrue(); } @@ -79,7 +79,7 @@ public class StrictRedirectUriValidatorAppAuthValidation { RequestedUri = requestedUri, Client = clientWithValidLoopbackRedirectUri - }); + }, default); result.ShouldBeFalse(); } @@ -93,7 +93,7 @@ public class StrictRedirectUriValidatorAppAuthValidation { RequestedUri = "http://127.0.0.1", Client = clientWithNoRedirectUris, - }); + }, default); result.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs index b2f7c30cf..37d9e54cf 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs @@ -14,19 +14,20 @@ public class TokenRequestValidation_ClientCredentials_Invalid private const string Category = "TokenRequest Validation - ClientCredentials - Invalid"; private IClientStore _clients = Factory.CreateClientStore(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] public async Task Invalid_GrantType_For_Client() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); @@ -36,7 +37,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Request_should_succeed_even_with_allowed_identity_scopes_because_they_are_filtered_out() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection @@ -44,7 +45,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Select(x => x.Name).ShouldBe(["api", "urn:api1", "urn:api2", "urn:api3"]); @@ -55,14 +56,14 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Unknown_Scope() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "unknown"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -72,14 +73,14 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Unknown_Scope_Multiple() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource unknown"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -89,14 +90,14 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Restricted_Scope() { - var client = await _clients.FindEnabledClientByIdAsync("client_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("client_restricted", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource2"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -106,14 +107,14 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Restricted_Scope_Multiple() { - var client = await _clients.FindEnabledClientByIdAsync("client_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("client_restricted", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource resource2"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -123,7 +124,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Identity_scope_is_not_allowed_for_client_credentials_when_specified_explicitly() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection @@ -132,7 +133,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid { OidcConstants.TokenRequest.Scope, "openid" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -142,14 +143,14 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Resource_and_Refresh_Token() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource offline_access"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -160,7 +161,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid [Trait("Category", Category)] public async Task Invalid_resource_indicator() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -169,7 +170,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid { parameters[OidcConstants.TokenRequest.Resource] = "urn:api1" + new string('x', 512); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidTarget); @@ -177,7 +178,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid { parameters[OidcConstants.TokenRequest.Resource] = "api"; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } @@ -185,7 +186,7 @@ public class TokenRequestValidation_ClientCredentials_Invalid parameters[OidcConstants.TokenRequest.Resource] = "urn:api1"; parameters.Add(OidcConstants.TokenRequest.Resource, "urn:api2"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs index 6054bf494..ec53b13cc 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs @@ -19,6 +19,7 @@ public class TokenRequestValidation_Code_Invalid { private IClientStore _clients = Factory.CreateClientStore(); private const string Category = "TokenRequest Validation - AuthorizationCode - Invalid"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private ClaimsPrincipal _subject = new IdentityServerUser("bob").CreatePrincipal(); @@ -26,7 +27,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Missing_AuthorizationCode() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -39,7 +40,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -48,7 +49,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.AuthorizationCode); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -58,7 +59,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Invalid_AuthorizationCode() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -71,7 +72,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -81,7 +82,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, "invalid"); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -91,7 +92,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task AuthorizationCodeTooLong() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var options = new IdentityServerOptions(); @@ -105,7 +106,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -116,7 +117,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, longCode); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -126,7 +127,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task No_Scopes_for_AuthorizationCode() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -139,7 +140,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -149,7 +150,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); OidcConstants.TokenErrors.InvalidRequest.ShouldBe(result.Error); @@ -159,7 +160,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Client_Not_Authorized_For_AuthorizationCode_Flow() { - var client = await _clients.FindEnabledClientByIdAsync("implicitclient"); + var client = await _clients.FindEnabledClientByIdAsync("implicitclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -172,7 +173,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -182,7 +183,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); @@ -192,8 +193,8 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Client_Trying_To_Request_Token_Using_Another_Clients_Code() { - var client1 = await _clients.FindEnabledClientByIdAsync("codeclient"); - var client2 = await _clients.FindEnabledClientByIdAsync("codeclient_restricted"); + var client1 = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); + var client2 = await _clients.FindEnabledClientByIdAsync("codeclient_restricted", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -206,7 +207,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -216,7 +217,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client2.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client2.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -226,7 +227,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Missing_RedirectUri() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -239,7 +240,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -248,7 +249,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.AuthorizationCode); parameters.Add(OidcConstants.TokenRequest.Code, handle); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); @@ -258,7 +259,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Different_RedirectUri_Between_Authorize_And_Token_Request() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -271,7 +272,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -281,7 +282,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server2/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -291,7 +292,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Expired_AuthorizationCode() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -304,7 +305,7 @@ public class TokenRequestValidation_Code_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -314,7 +315,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -324,7 +325,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Reused_AuthorizationCode() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -341,7 +342,7 @@ public class TokenRequestValidation_Code_Invalid } }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -352,7 +353,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); // request first time - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); @@ -360,7 +361,7 @@ public class TokenRequestValidation_Code_Invalid validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); - result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -370,7 +371,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Code_Request_with_disabled_User() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -386,7 +387,7 @@ public class TokenRequestValidation_Code_Invalid } }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store, @@ -397,7 +398,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -407,7 +408,7 @@ public class TokenRequestValidation_Code_Invalid [Trait("Category", Category)] public async Task Invalid_resource_indicator() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var grants = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -424,7 +425,7 @@ public class TokenRequestValidation_Code_Invalid RequestedResourceIndicators = new[] { "urn:api1", "urn:api2" } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -436,7 +437,7 @@ public class TokenRequestValidation_Code_Invalid parameters.Add(OidcConstants.TokenRequest.Resource, "urn:api1" + new string('x', 512)); { - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); @@ -444,14 +445,14 @@ public class TokenRequestValidation_Code_Invalid { parameters[OidcConstants.TokenRequest.Resource] = "api"; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } { parameters[OidcConstants.TokenRequest.Resource] = "urn:api3"; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } @@ -459,7 +460,7 @@ public class TokenRequestValidation_Code_Invalid parameters[OidcConstants.TokenRequest.Resource] = "urn:api1"; parameters.Add(OidcConstants.TokenRequest.Resource, "urn:api2"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } @@ -470,7 +471,7 @@ public class TokenRequestValidation_Code_Invalid public async Task failed_resource_validation_should_fail() { var mockResourceValidator = new MockResourceValidator(); - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var grants = Factory.CreateAuthorizationCodeStore(); { @@ -488,7 +489,7 @@ public class TokenRequestValidation_Code_Invalid RequestedResourceIndicators = new[] { "urn:api1", "urn:api2" } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator(resourceValidator: mockResourceValidator, authorizationCodeStore: grants); var parameters = new NameValueCollection(); @@ -501,7 +502,7 @@ public class TokenRequestValidation_Code_Invalid { InvalidScopes = { "foo" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_scope"); @@ -522,7 +523,7 @@ public class TokenRequestValidation_Code_Invalid RequestedResourceIndicators = new[] { "urn:api1", "urn:api2" } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator(resourceValidator: mockResourceValidator, authorizationCodeStore: grants); var parameters = new NameValueCollection(); @@ -535,7 +536,7 @@ public class TokenRequestValidation_Code_Invalid { InvalidResourceIndicators = { "foo" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs index c66330836..ba491748c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs @@ -17,6 +17,7 @@ public class TokenRequestValidation_DeviceCode_Invalid { private const string Category = "TokenRequest Validation - DeviceCode - Invalid"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private readonly IClientStore _clients = Factory.CreateClientStore(); private readonly DeviceCode deviceCode = new DeviceCode @@ -34,7 +35,7 @@ public class TokenRequestValidation_DeviceCode_Invalid [Trait("Category", Category)] public async Task Missing_DeviceCode() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -43,7 +44,7 @@ public class TokenRequestValidation_DeviceCode_Invalid {OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.DeviceCode} }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); } @@ -52,7 +53,7 @@ public class TokenRequestValidation_DeviceCode_Invalid [Trait("Category", Category)] public async Task DeviceCode_Too_Long() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var longCode = "x".Repeat(new IdentityServerOptions().InputLengthRestrictions.AuthorizationCode + 1); @@ -64,7 +65,7 @@ public class TokenRequestValidation_DeviceCode_Invalid {"device_code", longCode} }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } @@ -73,7 +74,7 @@ public class TokenRequestValidation_DeviceCode_Invalid [Trait("Category", Category)] public async Task Invalid_Grant_For_Client() { - var client = await _clients.FindClientByIdAsync("codeclient"); + var client = await _clients.FindClientByIdAsync("codeclient", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -83,7 +84,7 @@ public class TokenRequestValidation_DeviceCode_Invalid {"device_code", Guid.NewGuid().ToString()} }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); } @@ -92,7 +93,7 @@ public class TokenRequestValidation_DeviceCode_Invalid [Trait("Category", Category)] public async Task DeviceCodeValidator_Failure() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var validator = Factory.CreateTokenRequestValidator(deviceCodeValidator: new TestDeviceCodeValidator(true)); @@ -102,7 +103,7 @@ public class TokenRequestValidation_DeviceCode_Invalid {"device_code", Guid.NewGuid().ToString()} }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldNotBeNull(); } @@ -111,7 +112,7 @@ public class TokenRequestValidation_DeviceCode_Invalid [Trait("Category", Category)] public async Task Invalid_resource_indicator() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var validator = Factory.CreateTokenRequestValidator(deviceCodeValidator: new TestDeviceCodeValidator(true)); @@ -122,7 +123,7 @@ public class TokenRequestValidation_DeviceCode_Invalid { OidcConstants.TokenRequest.Resource, "api" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } @@ -131,7 +132,7 @@ public class TokenRequestValidation_DeviceCode_Invalid [Trait("Category", Category)] public async Task resource_indicator_should_not_be_allowed() { - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var validator = Factory.CreateTokenRequestValidator(deviceCodeValidator: new TestDeviceCodeValidator(true)); @@ -142,7 +143,7 @@ public class TokenRequestValidation_DeviceCode_Invalid { OidcConstants.TokenRequest.Resource, "urn:api1" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs index 482b9b86c..f9796b184 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs @@ -14,12 +14,13 @@ public class TokenRequestValidation_ExtensionGrants_Invalid private const string Category = "TokenRequest Validation - Extension Grants - Invalid"; private IClientStore _clients = Factory.CreateClientStore(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] public async Task Invalid_Extension_Grant_Type_For_Client_Credentials_Client() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection @@ -28,7 +29,7 @@ public class TokenRequestValidation_ExtensionGrants_Invalid { OidcConstants.TokenRequest.Scope, "resource" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); @@ -38,7 +39,7 @@ public class TokenRequestValidation_ExtensionGrants_Invalid [Trait("Category", Category)] public async Task Restricted_Extension_Grant_Type() { - var client = await _clients.FindEnabledClientByIdAsync("customgrantclient"); + var client = await _clients.FindEnabledClientByIdAsync("customgrantclient", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -48,7 +49,7 @@ public class TokenRequestValidation_ExtensionGrants_Invalid { OidcConstants.TokenRequest.Scope, "resource" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); @@ -58,7 +59,7 @@ public class TokenRequestValidation_ExtensionGrants_Invalid [Trait("Category", Category)] public async Task Customer_Error_and_Description_Extension_Grant_Type() { - var client = await _clients.FindEnabledClientByIdAsync("customgrantclient"); + var client = await _clients.FindEnabledClientByIdAsync("customgrantclient", _ct); var validator = Factory.CreateTokenRequestValidator(extensionGrantValidators: new[] { new TestGrantValidator(isInvalid: true, errorDescription: "custom error description") }); @@ -68,7 +69,7 @@ public class TokenRequestValidation_ExtensionGrants_Invalid { OidcConstants.TokenRequest.Scope, "resource" } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -79,7 +80,7 @@ public class TokenRequestValidation_ExtensionGrants_Invalid [Trait("Category", Category)] public async Task inactive_user_should_fail() { - var client = await _clients.FindEnabledClientByIdAsync("customgrantclient"); + var client = await _clients.FindEnabledClientByIdAsync("customgrantclient", _ct); var validator = Factory.CreateTokenRequestValidator( profile: new TestProfileService(shouldBeActive: false)); @@ -92,7 +93,7 @@ public class TokenRequestValidation_ExtensionGrants_Invalid var result = await validator.ValidateRequestAsync( parameters, - client.ToValidationResult()); + client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs index 0027402b0..1a47d8371 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs @@ -18,6 +18,7 @@ public class TokenRequestValidation_General_Invalid private IClientStore _clients = new InMemoryClientStore(TestClients.Get()); private ClaimsPrincipal _subject = new IdentityServerUser("bob").CreatePrincipal(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] @@ -25,7 +26,7 @@ public class TokenRequestValidation_General_Invalid { var validator = Factory.CreateTokenRequestValidator(); - Func act = () => validator.ValidateRequestAsync(null, null); + Func act = () => validator.ValidateRequestAsync(null, null, _ct); await act.ShouldThrowAsync(); } @@ -41,7 +42,7 @@ public class TokenRequestValidation_General_Invalid parameters.Add(OidcConstants.TokenRequest.Code, "valid"); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - Func act = () => validator.ValidateRequestAsync(parameters, null); + Func act = () => validator.ValidateRequestAsync(parameters, null, _ct); await act.ShouldThrowAsync(); } @@ -50,7 +51,7 @@ public class TokenRequestValidation_General_Invalid [Trait("Category", Category)] public async Task Unknown_Grant_Type() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -63,7 +64,7 @@ public class TokenRequestValidation_General_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -73,7 +74,7 @@ public class TokenRequestValidation_General_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); @@ -83,7 +84,7 @@ public class TokenRequestValidation_General_Invalid [Trait("Category", Category)] public async Task Invalid_Protocol_Type() { - var client = await _clients.FindEnabledClientByIdAsync("client.cred.wsfed"); + var client = await _clients.FindEnabledClientByIdAsync("client.cred.wsfed", _ct); var codeStore = Factory.CreateAuthorizationCodeStore(); var validator = Factory.CreateTokenRequestValidator( @@ -92,7 +93,7 @@ public class TokenRequestValidation_General_Invalid var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, "client_credentials"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidClient); @@ -102,7 +103,7 @@ public class TokenRequestValidation_General_Invalid [Trait("Category", Category)] public async Task Missing_Grant_Type() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var store = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -115,7 +116,7 @@ public class TokenRequestValidation_General_Invalid Subject = _subject }; - var handle = await store.StoreAuthorizationCodeAsync(code); + var handle = await store.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: store); @@ -124,7 +125,7 @@ public class TokenRequestValidation_General_Invalid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Invalid.cs index 7b115b7a2..3369b9e5f 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Invalid.cs @@ -16,6 +16,7 @@ public class TokenRequestValidation_Invalid private const string Category = "TokenRequest Validation - General - Invalid"; private readonly IClientStore _clients = Factory.CreateClientStore(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] @@ -39,9 +40,9 @@ public class TokenRequestValidation_Invalid }); var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(refreshTokenStore: grants); @@ -51,7 +52,7 @@ public class TokenRequestValidation_Invalid { OidcConstants.TokenRequest.RefreshToken, handle } }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs index 19ee332ed..abb28b81c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs @@ -21,6 +21,7 @@ public class TokenRequestValidation_PKCE private IClientStore _clients = Factory.CreateClientStore(); private InputLengthRestrictions lengths = new InputLengthRestrictions(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Theory] [InlineData("codeclient.pkce")] @@ -28,7 +29,7 @@ public class TokenRequestValidation_PKCE [Trait("Category", Category)] public async Task valid_pkce_token_request_with_plain_method_should_succeed(string clientId) { - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var grants = Factory.CreateAuthorizationCodeStore(); var verifier = "x".Repeat(lengths.CodeVerifierMinLength); @@ -48,7 +49,7 @@ public class TokenRequestValidation_PKCE } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -59,7 +60,7 @@ public class TokenRequestValidation_PKCE parameters.Add(OidcConstants.TokenRequest.CodeVerifier, verifier); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -68,7 +69,7 @@ public class TokenRequestValidation_PKCE [Trait("Category", Category)] public async Task valid_pkce_token_request_with_plain_method_should_succeed_hybrid() { - var client = await _clients.FindEnabledClientByIdAsync("hybridclient.pkce"); + var client = await _clients.FindEnabledClientByIdAsync("hybridclient.pkce", _ct); var grants = Factory.CreateAuthorizationCodeStore(); var verifier = "x".Repeat(lengths.CodeVerifierMinLength); @@ -88,7 +89,7 @@ public class TokenRequestValidation_PKCE } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -99,7 +100,7 @@ public class TokenRequestValidation_PKCE parameters.Add(OidcConstants.TokenRequest.CodeVerifier, verifier); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -110,7 +111,7 @@ public class TokenRequestValidation_PKCE [Trait("Category", Category)] public async Task valid_pkce_token_request_with_sha256_method_should_succeed(string clientId) { - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var grants = Factory.CreateAuthorizationCodeStore(); var verifier = "x".Repeat(lengths.CodeVerifierMinLength); @@ -132,7 +133,7 @@ public class TokenRequestValidation_PKCE } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -143,7 +144,7 @@ public class TokenRequestValidation_PKCE parameters.Add(OidcConstants.TokenRequest.CodeVerifier, verifier); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -153,7 +154,7 @@ public class TokenRequestValidation_PKCE [Trait("Category", Category)] public async Task token_request_with_missing_code_challenge_and_verifier_should_fail(string clientId) { - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var grants = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -169,7 +170,7 @@ public class TokenRequestValidation_PKCE } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -179,7 +180,7 @@ public class TokenRequestValidation_PKCE parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -191,7 +192,7 @@ public class TokenRequestValidation_PKCE [Trait("Category", Category)] public async Task token_request_with_missing_code_challenge_should_fail(string clientId) { - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var grants = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -208,7 +209,7 @@ public class TokenRequestValidation_PKCE } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -219,7 +220,7 @@ public class TokenRequestValidation_PKCE parameters.Add(OidcConstants.TokenRequest.CodeVerifier, "x".Repeat(lengths.CodeVerifierMinLength)); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -231,7 +232,7 @@ public class TokenRequestValidation_PKCE [Trait("Category", Category)] public async Task token_request_with_invalid_verifier_plain_method_should_fail(string clientId) { - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var grants = Factory.CreateAuthorizationCodeStore(); var verifier = "x".Repeat(lengths.CodeVerifierMinLength); @@ -251,7 +252,7 @@ public class TokenRequestValidation_PKCE } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -262,7 +263,7 @@ public class TokenRequestValidation_PKCE parameters.Add(OidcConstants.TokenRequest.CodeVerifier, verifier + "invalid"); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -274,7 +275,7 @@ public class TokenRequestValidation_PKCE [Trait("Category", Category)] public async Task token_request_with_invalid_verifier_sha256_method_should_fail(string clientId) { - var client = await _clients.FindEnabledClientByIdAsync(clientId); + var client = await _clients.FindEnabledClientByIdAsync(clientId, _ct); var grants = Factory.CreateAuthorizationCodeStore(); var verifier = "x".Repeat(lengths.CodeVerifierMinLength); @@ -296,7 +297,7 @@ public class TokenRequestValidation_PKCE } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -307,7 +308,7 @@ public class TokenRequestValidation_PKCE parameters.Add(OidcConstants.TokenRequest.CodeVerifier, verifier + "invalid"); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs index cb558e741..0e9b87caf 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs @@ -20,12 +20,13 @@ public class TokenRequestValidation_RefreshToken_Invalid private const string Category = "TokenRequest Validation - RefreshToken - Invalid"; private IClientStore _clients = Factory.CreateClientStore(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] public async Task Non_existing_RefreshToken() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -33,7 +34,7 @@ public class TokenRequestValidation_RefreshToken_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, "nonexistent"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -43,7 +44,7 @@ public class TokenRequestValidation_RefreshToken_Invalid [Trait("Category", Category)] public async Task RefreshTokenTooLong() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var options = new IdentityServerOptions(); var validator = Factory.CreateTokenRequestValidator(); @@ -53,7 +54,7 @@ public class TokenRequestValidation_RefreshToken_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, longRefreshToken); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -70,9 +71,9 @@ public class TokenRequestValidation_RefreshToken_Invalid }; var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator( refreshTokenStore: grants); @@ -81,7 +82,7 @@ public class TokenRequestValidation_RefreshToken_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, handle); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -97,9 +98,9 @@ public class TokenRequestValidation_RefreshToken_Invalid }; var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator( refreshTokenStore: grants); @@ -108,7 +109,7 @@ public class TokenRequestValidation_RefreshToken_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, handle); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -126,9 +127,9 @@ public class TokenRequestValidation_RefreshToken_Invalid }; var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted", _ct); var validator = Factory.CreateTokenRequestValidator( refreshTokenStore: grants); @@ -137,7 +138,7 @@ public class TokenRequestValidation_RefreshToken_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, handle); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -158,9 +159,9 @@ public class TokenRequestValidation_RefreshToken_Invalid }; var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator( refreshTokenStore: grants, @@ -170,7 +171,7 @@ public class TokenRequestValidation_RefreshToken_Invalid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, handle); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -190,9 +191,9 @@ public class TokenRequestValidation_RefreshToken_Invalid }; var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(refreshTokenStore: grants); @@ -202,7 +203,7 @@ public class TokenRequestValidation_RefreshToken_Invalid { parameters[OidcConstants.TokenRequest.Resource] = "urn:api1" + new string('x', 512); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidTarget); @@ -210,7 +211,7 @@ public class TokenRequestValidation_RefreshToken_Invalid { parameters[OidcConstants.TokenRequest.Resource] = "api"; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } @@ -218,7 +219,7 @@ public class TokenRequestValidation_RefreshToken_Invalid parameters[OidcConstants.TokenRequest.Resource] = "urn:api1"; parameters.Add(OidcConstants.TokenRequest.Resource, "urn:api2"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); } @@ -230,7 +231,7 @@ public class TokenRequestValidation_RefreshToken_Invalid { var mockResourceValidator = new MockResourceValidator(); var grants = Factory.CreateRefreshTokenStore(); - var client = (await _clients.FindEnabledClientByIdAsync("roclient")).ToValidationResult(); + var client = (await _clients.FindEnabledClientByIdAsync("roclient", _ct)).ToValidationResult(); var validator = Factory.CreateTokenRequestValidator(refreshTokenStore: grants, resourceValidator: mockResourceValidator); @@ -243,7 +244,7 @@ public class TokenRequestValidation_RefreshToken_Invalid CreationTime = DateTime.UtcNow, AuthorizedScopes = new[] { "scope1" } }; - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); @@ -254,7 +255,7 @@ public class TokenRequestValidation_RefreshToken_Invalid { InvalidScopes = { "foo" } }; - var result = await validator.ValidateRequestAsync(parameters, client); + var result = await validator.ValidateRequestAsync(parameters, client, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_scope"); @@ -269,7 +270,7 @@ public class TokenRequestValidation_RefreshToken_Invalid CreationTime = DateTime.UtcNow, AuthorizedScopes = new[] { "scope1" } }; - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); @@ -280,7 +281,7 @@ public class TokenRequestValidation_RefreshToken_Invalid { InvalidResourceIndicators = { "foo" } }; - var result = await validator.ValidateRequestAsync(parameters, client); + var result = await validator.ValidateRequestAsync(parameters, client, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); @@ -292,7 +293,7 @@ public class TokenRequestValidation_RefreshToken_Invalid public async Task resource_indicator_requested_not_in_original_request_should_fail() { var grants = Factory.CreateRefreshTokenStore(); - var client = (await _clients.FindEnabledClientByIdAsync("roclient")).ToValidationResult(); + var client = (await _clients.FindEnabledClientByIdAsync("roclient", _ct)).ToValidationResult(); var validator = Factory.CreateTokenRequestValidator(refreshTokenStore: grants); @@ -305,14 +306,14 @@ public class TokenRequestValidation_RefreshToken_Invalid AuthorizedScopes = new[] { "scope1" }, AuthorizedResourceIndicators = new[] { "urn:api1", "urn:api2" } }; - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, handle); parameters.Add("resource", "urn:api3"); - var result = await validator.ValidateRequestAsync(parameters, client); + var result = await validator.ValidateRequestAsync(parameters, client, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs index d49066184..ef52d8d14 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs @@ -17,19 +17,20 @@ public class TokenRequestValidation_ResourceOwner_Invalid private const string Category = "TokenRequest Validation - ResourceOwner - Invalid"; private IClientStore _clients = Factory.CreateClientStore(); + private readonly Ct _ct = TestContext.Current.CancellationToken; [Fact] [Trait("Category", Category)] public async Task Invalid_GrantType_For_Client() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.Password); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); @@ -39,7 +40,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Unknown_Scope() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -48,7 +49,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "bob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -58,7 +59,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Unknown_Scope_Multiple() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -67,7 +68,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "bob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -77,7 +78,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Restricted_Scope() { - var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -86,7 +87,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "bob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -96,7 +97,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Restricted_Scope_Multiple() { - var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -105,7 +106,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "bob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); @@ -115,14 +116,14 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task No_ResourceOwnerCredentials() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.Password); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -132,7 +133,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Missing_ResourceOwner_UserName() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -140,7 +141,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); parameters.Add(OidcConstants.TokenRequest.Password, "bob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -150,7 +151,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Invalid_ResourceOwner_Credentials() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -159,7 +160,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "notbob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -170,7 +171,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Missing_ResourceOwner_password_for_user_with_password_should_fail() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -178,7 +179,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); parameters.Add(OidcConstants.TokenRequest.UserName, "bob_with_password"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); } @@ -187,7 +188,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Password_GrantType_Not_Supported() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(resourceOwnerValidator: new NotSupportedResourceOwnerPasswordValidator(TestLogger.Create())); var parameters = new NameValueCollection(); @@ -196,7 +197,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "bob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); @@ -207,7 +208,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Inactive_ResourceOwner() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(profile: new TestProfileService(shouldBeActive: false)); var parameters = new NameValueCollection(); @@ -216,7 +217,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "bob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -226,7 +227,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task Password_GrantType_With_Custom_ErrorDescription() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(resourceOwnerValidator: new TestResourceOwnerPasswordValidator(TokenRequestErrors.InvalidGrant, "custom error description")); var parameters = new NameValueCollection(); @@ -235,7 +236,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid parameters.Add(OidcConstants.TokenRequest.UserName, "bob"); parameters.Add(OidcConstants.TokenRequest.Password, "notbob"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); @@ -246,7 +247,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid [Trait("Category", Category)] public async Task failed_resource_validation_should_fail() { - var client = (await _clients.FindEnabledClientByIdAsync("roclient")).ToValidationResult(); + var client = (await _clients.FindEnabledClientByIdAsync("roclient", _ct)).ToValidationResult(); var mockResourceValidator = new MockResourceValidator(); var validator = Factory.CreateTokenRequestValidator(resourceValidator: mockResourceValidator); @@ -262,7 +263,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid { InvalidScopes = { "foo" } }; - var result = await validator.ValidateRequestAsync(parameters, client); + var result = await validator.ValidateRequestAsync(parameters, client, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_scope"); @@ -273,7 +274,7 @@ public class TokenRequestValidation_ResourceOwner_Invalid { InvalidResourceIndicators = { "foo" } }; - var result = await validator.ValidateRequestAsync(parameters, client); + var result = await validator.ValidateRequestAsync(parameters, client, _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe("invalid_target"); diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs index 0a7e6dec3..dcbd481e3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs @@ -16,6 +16,7 @@ public class TokenRequestValidation_Valid { private const string Category = "TokenRequest Validation - General - Valid"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IClientStore _clients = Factory.CreateClientStore(); private TestDeviceCodeValidator _mockDeviceCodeValidator = new TestDeviceCodeValidator(); @@ -23,7 +24,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Missing_ResourceOwner_password_for_user_with_no_password_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); var parameters = new NameValueCollection(); @@ -31,7 +32,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); parameters.Add(OidcConstants.TokenRequest.UserName, "bob_no_password"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); result.ValidatedRequest.UserName.ShouldBe("bob_no_password"); @@ -41,7 +42,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_code_request_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var grants = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -57,7 +58,7 @@ public class TokenRequestValidation_Valid } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -67,7 +68,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -76,7 +77,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_code_request_with_refresh_token_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("codeclient"); + var client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct); var grants = Factory.CreateAuthorizationCodeStore(); var code = new AuthorizationCode @@ -93,7 +94,7 @@ public class TokenRequestValidation_Valid } }; - var handle = await grants.StoreAuthorizationCodeAsync(code); + var handle = await grants.StoreAuthorizationCodeAsync(code, _ct); var validator = Factory.CreateTokenRequestValidator( authorizationCodeStore: grants); @@ -103,7 +104,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.Code, handle); parameters.Add(OidcConstants.TokenRequest.RedirectUri, "https://server/cb"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -112,7 +113,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_client_credentials_request_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("client"); + var client = await _clients.FindEnabledClientByIdAsync("client", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -120,7 +121,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -129,7 +130,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_client_credentials_request_with_default_scopes_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("client_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("client_restricted", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -137,7 +138,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -146,7 +147,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_client_credentials_request_for_implicit_and_client_credentials_client_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("implicit_and_client_creds_client"); + var client = await _clients.FindEnabledClientByIdAsync("implicit_and_client_creds_client", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -154,7 +155,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -163,7 +164,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_client_credentials_request_restricted_client_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("client_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("client_restricted", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -171,7 +172,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.ClientCredentials); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -180,7 +181,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_resource_owner_request_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -190,7 +191,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.Password, "bob"); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -199,7 +200,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_resource_wwner_request_with_refresh_token_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -209,7 +210,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.Password, "bob"); parameters.Add(OidcConstants.TokenRequest.Scope, "resource offline_access"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -218,7 +219,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task Valid_resource_owner_request_restricted_client_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted"); + var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -228,7 +229,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.Password, "bob"); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -237,7 +238,7 @@ public class TokenRequestValidation_Valid [Trait("Category", Category)] public async Task valid_extension_grant_request_should_succeed() { - var client = await _clients.FindEnabledClientByIdAsync("customgrantclient"); + var client = await _clients.FindEnabledClientByIdAsync("customgrantclient", _ct); var validator = Factory.CreateTokenRequestValidator(); @@ -245,7 +246,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.GrantType, "custom_grant"); parameters.Add(OidcConstants.TokenRequest.Scope, "resource"); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -271,9 +272,9 @@ public class TokenRequestValidation_Valid }); var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient"); + var client = await _clients.FindEnabledClientByIdAsync("roclient", _ct); var validator = Factory.CreateTokenRequestValidator( refreshTokenStore: grants); @@ -282,7 +283,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, handle); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -303,9 +304,9 @@ public class TokenRequestValidation_Valid }; var grants = Factory.CreateRefreshTokenStore(); - var handle = await grants.StoreRefreshTokenAsync(refreshToken); + var handle = await grants.StoreRefreshTokenAsync(refreshToken, _ct); - var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted_refresh"); + var client = await _clients.FindEnabledClientByIdAsync("roclient_restricted_refresh", _ct); var validator = Factory.CreateTokenRequestValidator( refreshTokenStore: grants); @@ -314,7 +315,7 @@ public class TokenRequestValidation_Valid parameters.Add(OidcConstants.TokenRequest.GrantType, "refresh_token"); parameters.Add(OidcConstants.TokenRequest.RefreshToken, handle); - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } @@ -334,7 +335,7 @@ public class TokenRequestValidation_Valid AuthorizedScopes = new[] { "openid", "profile", "resource" } }; - var client = await _clients.FindClientByIdAsync("device_flow"); + var client = await _clients.FindClientByIdAsync("device_flow", _ct); var validator = Factory.CreateTokenRequestValidator(deviceCodeValidator: _mockDeviceCodeValidator); _mockDeviceCodeValidator.DeviceCodeResult = deviceCode; @@ -345,7 +346,7 @@ public class TokenRequestValidation_Valid {"device_code", Guid.NewGuid().ToString()} }; - var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); + var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult(), _ct); result.IsError.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs index 4e1798448..a6856eb82 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs @@ -14,6 +14,7 @@ namespace UnitTests.Validation; public class UserInfoRequestValidation { private const string Category = "UserInfo Request Validation Tests"; + private readonly Ct _ct = TestContext.Current.CancellationToken; private IClientStore _clients = new InMemoryClientStore(TestClients.Get()); [Fact] @@ -23,7 +24,7 @@ public class UserInfoRequestValidation var tokenResult = new TokenValidationResult { IsError = false, - Client = await _clients.FindEnabledClientByIdAsync("codeclient"), + Client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct), Claims = new List() }; @@ -32,7 +33,7 @@ public class UserInfoRequestValidation new TestProfileService(shouldBeActive: true), TestLogger.Create()); - var result = await validator.ValidateRequestAsync("token"); + var result = await validator.ValidateRequestAsync("token", _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); @@ -45,7 +46,7 @@ public class UserInfoRequestValidation var tokenResult = new TokenValidationResult { IsError = false, - Client = await _clients.FindEnabledClientByIdAsync("codeclient"), + Client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct), Claims = new List { new Claim("sub", "123") @@ -57,7 +58,7 @@ public class UserInfoRequestValidation new TestProfileService(shouldBeActive: true), TestLogger.Create()); - var result = await validator.ValidateRequestAsync("token"); + var result = await validator.ValidateRequestAsync("token", _ct); result.IsError.ShouldBeFalse(); } @@ -69,7 +70,7 @@ public class UserInfoRequestValidation var tokenResult = new TokenValidationResult { IsError = false, - Client = await _clients.FindEnabledClientByIdAsync("codeclient"), + Client = await _clients.FindEnabledClientByIdAsync("codeclient", _ct), Claims = new List { new Claim("sub", "123") @@ -81,7 +82,7 @@ public class UserInfoRequestValidation new TestProfileService(shouldBeActive: false), TestLogger.Create()); - var result = await validator.ValidateRequestAsync("token"); + var result = await validator.ValidateRequestAsync("token", _ct); result.IsError.ShouldBeTrue(); result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); diff --git a/shared/GlobalAliasses.cs b/shared/Global.cs similarity index 80% rename from shared/GlobalAliasses.cs rename to shared/Global.cs index 488eb2b54..01f78651f 100644 --- a/shared/GlobalAliasses.cs +++ b/shared/Global.cs @@ -2,5 +2,5 @@ // See LICENSE in the project root for license information. #pragma warning disable IDE0005 // Remove unnecessary using directives -global using CT = System.Threading.CancellationToken; +global using Ct = System.Threading.CancellationToken; #pragma warning restore IDE0005 diff --git a/src.props b/src.props index 30d79e324..ed25891fd 100644 --- a/src.props +++ b/src.props @@ -62,7 +62,7 @@ - + diff --git a/test.props b/test.props index f0341758d..6f05c5bec 100644 --- a/test.props +++ b/test.props @@ -28,7 +28,7 @@ - +