Skip to content

Commit

Permalink
Merge pull request #1630 from SimonCropp:leverage-argument-throw-helpers
Browse files Browse the repository at this point in the history
leverage argument throw helpers
  • Loading branch information
damianh authored Dec 3, 2024
2 parents be7848e + 4451ddd commit 1c24032
Show file tree
Hide file tree
Showing 36 changed files with 65 additions and 97 deletions.
2 changes: 1 addition & 1 deletion src/EntityFramework.Storage/Stores/ResourceStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public virtual async Task<IEnumerable<ApiResource>> FindApiResourcesByNameAsync(
using var activity = Tracing.StoreActivitySource.StartActivity("ResourceStore.FindApiResourcesByName");
activity?.SetTag(Tracing.Properties.ApiResourceNames, apiResourceNames.ToSpaceSeparatedString());

if (apiResourceNames == null) throw new ArgumentNullException(nameof(apiResourceNames));
ArgumentNullException.ThrowIfNull(apiResourceNames);

var query =
from apiResource in Context.ApiResources
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBu
/// <exception cref="InvalidOperationException">X509 certificate does not have a private key.</exception>
public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBuilder builder, X509Certificate2 certificate, string signingAlgorithm = SecurityAlgorithms.RsaSha256)
{
if (certificate == null) throw new ArgumentNullException(nameof(certificate));
ArgumentNullException.ThrowIfNull(certificate);

if (!certificate.HasPrivateKey)
{
Expand Down Expand Up @@ -261,7 +261,7 @@ public static IIdentityServerBuilder AddValidationKey(
X509Certificate2 certificate,
string signingAlgorithm = SecurityAlgorithms.RsaSha256)
{
if (certificate == null) throw new ArgumentNullException(nameof(certificate));
ArgumentNullException.ThrowIfNull(certificate);

// add signing algorithm name to key ID to allow using the same key for two different algorithms (e.g. RS256 and PS56);
var key = new X509SecurityKey(certificate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public static IApplicationBuilder UseIdentityServer(this IApplicationBuilder app
internal static void Validate(this IApplicationBuilder app)
{
var loggerFactory = app.ApplicationServices.GetService<ILoggerFactory>();
if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));

ArgumentNullException.ThrowIfNull(loggerFactory);
var logger = loggerFactory.CreateLogger("Duende.IdentityServer.Startup");
logger.LogInformation("Starting Duende IdentityServer version {version} ({netversion})",
typeof(IdentityServerMiddleware).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public static void SetClientList(this AuthenticationProperties properties, IEnum
/// <param name="clientId"></param>
public static void AddClientId(this AuthenticationProperties properties, string clientId)
{
if (clientId == null) throw new ArgumentNullException(nameof(clientId));
ArgumentNullException.ThrowIfNull(clientId);

var clients = properties.GetClientList();
if (!clients.Contains(clientId))
Expand Down
2 changes: 1 addition & 1 deletion src/IdentityServer/Extensions/HttpContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static class HttpContextExtensions
{
internal static void SetSignOutCalled(this HttpContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
ArgumentNullException.ThrowIfNull(context);
context.Items[Constants.EnvironmentKeys.SignOutCalled] = "true";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public static class ProfileDataRequestContextExtensions
/// <returns></returns>
public static List<Claim> FilterClaims(this ProfileDataRequestContext context, IEnumerable<Claim> claims)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (claims == null) throw new ArgumentNullException(nameof(claims));
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(claims);

return claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public static void RemoveAcrValue(this ValidatedAuthorizeRequest request, string

public static void AddAcrValue(this ValidatedAuthorizeRequest request, string value)
{
if (String.IsNullOrWhiteSpace(value)) throw new ArgumentNullException(nameof(value));
ArgumentNullException.ThrowIfNullOrWhiteSpace(value);

request.AuthenticationContextReferenceClasses.Add(value);
var acr_values = request.AuthenticationContextReferenceClasses.ToSpaceSeparatedString();
Expand Down
2 changes: 1 addition & 1 deletion src/IdentityServer/Hosting/EndpointRouter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public EndpointRouter(IEnumerable<Endpoint> endpoints, IdentityServerOptions opt

public IEndpointHandler Find(HttpContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
ArgumentNullException.ThrowIfNull(context);

foreach(var endpoint in _endpoints)
{
Expand Down
6 changes: 3 additions & 3 deletions src/IdentityServer/IdentityServerTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,9 @@ public virtual Task<string> IssueJwtAsync(int lifetime, string issuer, IEnumerab
/// <inheritdoc/>
public virtual async Task<string> IssueJwtAsync(int lifetime, string issuer, string tokenType, IEnumerable<Claim> claims)
{
if (String.IsNullOrWhiteSpace(issuer)) throw new ArgumentNullException(nameof(issuer));
if (String.IsNullOrWhiteSpace(tokenType)) throw new ArgumentNullException(nameof(tokenType));
if (claims == null) throw new ArgumentNullException(nameof(claims));
ArgumentNullException.ThrowIfNullOrWhiteSpace(issuer);
ArgumentNullException.ThrowIfNullOrWhiteSpace(tokenType);
ArgumentNullException.ThrowIfNull(claims);

var token = new Token(tokenType)
{
Expand Down
3 changes: 1 addition & 2 deletions src/IdentityServer/Infrastructure/MessageCookie.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ private IEnumerable<string> GetCookieNames()
public void Write(string id, Message<TModel> message)
{
ClearOverflow();

if (message == null) throw new ArgumentNullException(nameof(message));
ArgumentNullException.ThrowIfNull(message);

var name = GetCookieFullName(id);
var data = Protect(message);
Expand Down
4 changes: 2 additions & 2 deletions src/IdentityServer/Models/Contexts/IsActiveContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public class IsActiveContext
/// </summary>
public IsActiveContext(ClaimsPrincipal subject, Client client, string caller)
{
if (subject == null) throw new ArgumentNullException(nameof(subject));
if (client == null) throw new ArgumentNullException(nameof(client));
ArgumentNullException.ThrowIfNull(subject);
ArgumentNullException.ThrowIfNull(client);
if (caller.IsMissing()) throw new ArgumentNullException(nameof(caller));

Subject = subject;
Expand Down
5 changes: 1 addition & 4 deletions src/IdentityServer/Models/Messages/AuthorizationRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,7 @@ public AuthorizationRequest()
/// <exception cref="ArgumentNullException"><paramref name="request"/> is null.</exception>
public AuthorizationRequest(ValidatedAuthorizeRequest request)
{
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
ArgumentNullException.ThrowIfNull(request);

Client = request.Client;
RedirectUri = request.RedirectUri;
Expand Down
4 changes: 2 additions & 2 deletions src/IdentityServer/Models/TokenCreationRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public class TokenCreationRequest
/// </summary>
public void Validate()
{
if (ValidatedResources == null) throw new ArgumentNullException(nameof(ValidatedResources));
if (ValidatedRequest == null) throw new ArgumentNullException(nameof(ValidatedRequest));
ArgumentNullException.ThrowIfNull(ValidatedResources);
ArgumentNullException.ThrowIfNull(ValidatedRequest);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,8 @@ protected internal virtual async Task<InteractionResponse> ProcessLoginAsync(Val
protected internal virtual async Task<InteractionResponse> ProcessConsentAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null)
{
using var activity = Tracing.BasicActivitySource.StartActivity("AuthorizeInteractionResponseGenerator.ProcessConsent");
if (request == null) throw new ArgumentNullException(nameof(request));

ArgumentNullException.ThrowIfNull(request);

if (request.PromptModes.Any() &&
!request.PromptModes.Contains(OidcConstants.PromptModes.None) &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public virtual async Task<BackchannelAuthenticationResponse> ProcessAsync(Backch
{
using var activity = Tracing.BasicActivitySource.StartActivity("BackchannelAuthenticationResponseGenerator.Process");

if (validationResult == null) throw new ArgumentNullException(nameof(validationResult));
ArgumentNullException.ThrowIfNull(validationResult);
if (validationResult.ValidatedRequest == null) throw new ArgumentNullException(nameof(validationResult.ValidatedRequest));
if (validationResult.ValidatedRequest.Client == null) throw new ArgumentNullException(nameof(validationResult.ValidatedRequest.Client));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ public DeviceAuthorizationResponseGenerator(IdentityServerOptions options, IUser
public virtual async Task<DeviceAuthorizationResponse> ProcessAsync(DeviceAuthorizationRequestValidationResult validationResult, string baseUrl)
{
using var activity = Tracing.BasicActivitySource.StartActivity("DeviceAuthorizationResponseGenerator.Process");
if (validationResult == null) throw new ArgumentNullException(nameof(validationResult));

ArgumentNullException.ThrowIfNull(validationResult);
if (validationResult.ValidatedRequest.Client == null) throw new ArgumentNullException(nameof(validationResult.ValidatedRequest.Client));
if (string.IsNullOrWhiteSpace(baseUrl)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(baseUrl));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ public async Task<IEnumerable<BackchannelUserLoginRequest>> GetPendingLoginReque
public async Task CompleteLoginRequestAsync(CompleteBackchannelLoginRequest completionRequest)
{
using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultBackchannelAuthenticationInteractionService.CompleteLoginRequest");
if (completionRequest == null) throw new ArgumentNullException(nameof(completionRequest));

ArgumentNullException.ThrowIfNull(completionRequest);

var request = await _requestStore.GetByInternalIdAsync(completionRequest.InternalId);
if (request == null)
Expand Down
4 changes: 2 additions & 2 deletions src/IdentityServer/Services/Default/DefaultCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ public Task RemoveAsync(string key)
public async Task<T> GetOrAddAsync(string key, TimeSpan duration, Func<Task<T>> get)
{
using var activity = Tracing.CacheActivitySource.StartActivity("DefaultCache.GetOrAdd");
if (get == null) throw new ArgumentNullException(nameof(get));

ArgumentNullException.ThrowIfNull(get);
if (key == null) return null;

var item = await GetAsync(key);
Expand Down
12 changes: 6 additions & 6 deletions src/IdentityServer/Services/Default/DefaultConsentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ public DefaultConsentService(IClock clock, IUserConsentStore userConsentStore, I
public virtual async Task<bool> RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable<ParsedScopeValue> parsedScopes)
{
using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultConsentService.RequiresConsent");
if (client == null) throw new ArgumentNullException(nameof(client));
if (subject == null) throw new ArgumentNullException(nameof(subject));

ArgumentNullException.ThrowIfNull(client);
ArgumentNullException.ThrowIfNull(subject);

if (!client.RequireConsent)
{
Expand Down Expand Up @@ -156,9 +156,9 @@ public virtual async Task<bool> RequiresConsentAsync(ClaimsPrincipal subject, Cl
public virtual async Task UpdateConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable<ParsedScopeValue> parsedScopes)
{
using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultConsentService.UpdateConsent");
if (client == null) throw new ArgumentNullException(nameof(client));
if (subject == null) throw new ArgumentNullException(nameof(subject));

ArgumentNullException.ThrowIfNull(client);
ArgumentNullException.ThrowIfNull(subject);

if (client.AllowRememberConsent)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ public async Task<DeviceFlowAuthorizationRequest> GetAuthorizationContextAsync(s

public async Task<DeviceFlowInteractionResult> HandleRequestAsync(string userCode, ConsentResponse consent)
{
if (userCode == null) throw new ArgumentNullException(nameof(userCode));
if (consent == null) throw new ArgumentNullException(nameof(consent));
ArgumentNullException.ThrowIfNull(userCode);
ArgumentNullException.ThrowIfNull(consent);

var deviceAuth = await _devices.FindByUserCodeAsync(userCode);
if (deviceAuth == null) return LogAndReturnError("Invalid user code", "Device authorization failure - user code is invalid");
Expand Down
2 changes: 1 addition & 1 deletion src/IdentityServer/Services/Default/DefaultEventService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public DefaultEventService(IdentityServerOptions options, IHttpContextAccessor c
/// <exception cref="System.ArgumentNullException">evt</exception>
public async Task RaiseAsync(Event evt)
{
if (evt == null) throw new ArgumentNullException(nameof(evt));
ArgumentNullException.ThrowIfNull(evt);

if (CanRaiseEvent(evt))
{
Expand Down
2 changes: 1 addition & 1 deletion src/IdentityServer/Services/Default/DefaultEventSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public DefaultEventSink(ILogger<DefaultEventService> logger)
/// <exception cref="System.ArgumentNullException">evt</exception>
public virtual Task PersistAsync(Event evt)
{
if (evt == null) throw new ArgumentNullException(nameof(evt));
ArgumentNullException.ThrowIfNull(evt);

_logger.LogInformation("{@event}", evt);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public async Task<IEnumerable<Grant>> GetAllGrantsAsync(string subjectId)
{
using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultPersistedGrantService.GetAllGrants");

if (String.IsNullOrWhiteSpace(subjectId)) throw new ArgumentNullException(nameof(subjectId));
ArgumentNullException.ThrowIfNullOrWhiteSpace(subjectId);

var grants = (await _store.GetAllAsync(new PersistedGrantFilter { SubjectId = subjectId }))
.Where(x => x.ConsumedTime == null) // filter consumed grants
Expand Down Expand Up @@ -179,7 +179,7 @@ public Task RemoveAllGrantsAsync(string subjectId, string clientId = null, strin
{
using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultPersistedGrantService.RemoveAllGrants");

if (String.IsNullOrWhiteSpace(subjectId)) throw new ArgumentNullException(nameof(subjectId));
ArgumentNullException.ThrowIfNullOrWhiteSpace(subjectId);

return _store.RemoveAllAsync(new PersistedGrantFilter
{
Expand Down
6 changes: 3 additions & 3 deletions src/IdentityServer/Services/Default/DefaultUserSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,8 @@ protected virtual async Task AuthenticateAsync()
/// </exception>
public virtual async Task<string> CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties)
{
if (principal == null) throw new ArgumentNullException(nameof(principal));
if (properties == null) throw new ArgumentNullException(nameof(properties));
ArgumentNullException.ThrowIfNull(principal);
ArgumentNullException.ThrowIfNull(properties);

var currentSubjectId = (await GetUserAsync())?.GetSubjectId();
var newSubjectId = principal.GetSubjectId();
Expand Down Expand Up @@ -305,7 +305,7 @@ public virtual void IssueSessionIdCookie(string sid)
/// <exception cref="ArgumentNullException">clientId</exception>
public virtual async Task AddClientIdAsync(string clientId)
{
if (clientId == null) throw new ArgumentNullException(nameof(clientId));
ArgumentNullException.ThrowIfNull(clientId);

await AuthenticateAsync();
if (Properties != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ public async Task<bool> ShouldSlowDown(string requestId, BackChannelAuthenticati
{
using var activity = Tracing.ServiceActivitySource.StartActivity("DistributedBackchannelAuthenticationThrottlingService.ShouldSlowDown");

if (requestId == null)
{
throw new ArgumentNullException(nameof(requestId));
}
ArgumentNullException.ThrowIfNull(requestId);

var key = KeyPrefix + requestId;
var options = new DistributedCacheEntryOptions { AbsoluteExpiration = _clock.UtcNow.AddSeconds(details.Lifetime) };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ public DistributedDeviceFlowThrottlingService(
public async Task<bool> ShouldSlowDown(string deviceCode, DeviceCode details)
{
using var activity = Tracing.ServiceActivitySource.StartActivity("DistributedDeviceFlowThrottlingService.ShouldSlowDown");
if (deviceCode == null) throw new ArgumentNullException(nameof(deviceCode));

ArgumentNullException.ThrowIfNull(deviceCode);

var key = KeyPrefix + deviceCode;
var options = new DistributedCacheEntryOptions {AbsoluteExpiration = _clock.UtcNow.AddSeconds(details.Lifetime)};

Expand Down
12 changes: 4 additions & 8 deletions src/IdentityServer/Stores/InMemory/InMemoryResourcesStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,9 @@ public Task<Resources> GetAllResourcesAsync()
/// <inheritdoc/>
public Task<IEnumerable<ApiResource>> FindApiResourcesByNameAsync(IEnumerable<string> apiResourceNames)
{
ArgumentNullException.ThrowIfNull(apiResourceNames);
using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindApiResourcesByName");
activity?.SetTag(Tracing.Properties.ApiResourceNames, apiResourceNames.ToSpaceSeparatedString());

if (apiResourceNames == null) throw new ArgumentNullException(nameof(apiResourceNames));

var query = from a in _apiResources
where apiResourceNames.Contains(a.Name)
Expand All @@ -74,10 +73,9 @@ where apiResourceNames.Contains(a.Name)
/// <inheritdoc/>
public Task<IEnumerable<IdentityResource>> FindIdentityResourcesByScopeNameAsync(IEnumerable<string> scopeNames)
{
ArgumentNullException.ThrowIfNull(scopeNames);
using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindIdentityResourcesByScopeName");
activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString());

if (scopeNames == null) throw new ArgumentNullException(nameof(scopeNames));

var identity = from i in _identityResources
where scopeNames.Contains(i.Name)
Expand All @@ -89,10 +87,9 @@ where scopeNames.Contains(i.Name)
/// <inheritdoc/>
public Task<IEnumerable<ApiResource>> FindApiResourcesByScopeNameAsync(IEnumerable<string> scopeNames)
{
ArgumentNullException.ThrowIfNull(scopeNames);
using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindApiResourcesByScopeName");
activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString());

if (scopeNames == null) throw new ArgumentNullException(nameof(scopeNames));

var query = from a in _apiResources
where a.Scopes.Any(x => scopeNames.Contains(x))
Expand All @@ -104,10 +101,9 @@ where a.Scopes.Any(x => scopeNames.Contains(x))
/// <inheritdoc/>
public Task<IEnumerable<ApiScope>> FindApiScopesByNameAsync(IEnumerable<string> scopeNames)
{
ArgumentNullException.ThrowIfNull(scopeNames);
using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryResourceStore.FindApiScopesByName");
activity?.SetTag(Tracing.Properties.ScopeNames, scopeNames.ToSpaceSeparatedString());

if (scopeNames == null) throw new ArgumentNullException(nameof(scopeNames));

var query =
from x in _apiScopes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,10 @@ public DefaultResourceValidator(IResourceStore store, IScopeParser scopeParser,
/// <inheritdoc/>
public virtual async Task<ResourceValidationResult> ValidateRequestedResourcesAsync(ResourceValidationRequest request)
{
ArgumentNullException.ThrowIfNull(request);
using var activity = Tracing.ValidationActivitySource.StartActivity("DefaultResourceValidator.ValidateRequestedResources");
activity?.SetTag(Tracing.Properties.Scope, request.Scopes.ToSpaceSeparatedString());
activity?.SetTag(Tracing.Properties.Resource, request.ResourceIndicators.ToSpaceSeparatedString());

if (request == null) throw new ArgumentNullException(nameof(request));

var result = new ResourceValidationResult();

Expand Down
Loading

0 comments on commit 1c24032

Please sign in to comment.