diff --git a/src/Antiforgery/ref/Directory.Build.props b/src/Antiforgery/ref/Directory.Build.props new file mode 100644 index 0000000000..5001ef12be --- /dev/null +++ b/src/Antiforgery/ref/Directory.Build.props @@ -0,0 +1,7 @@ + + + + + annotations + + \ No newline at end of file diff --git a/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.csproj b/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.csproj index 451b80df95..ab33043f0c 100644 --- a/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.csproj @@ -2,6 +2,7 @@ $(DefaultNetCoreTargetFramework) + annotations diff --git a/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.netcoreapp.cs b/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.netcoreapp.cs index 4ca6748cce..ca33981a59 100644 --- a/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.netcoreapp.cs +++ b/src/Antiforgery/ref/Microsoft.AspNetCore.Antiforgery.netcoreapp.cs @@ -9,21 +9,21 @@ namespace Microsoft.AspNetCore.Antiforgery public AntiforgeryOptions() { } public Microsoft.AspNetCore.Http.CookieBuilder Cookie { get { throw null; } set { } } public string FormFieldName { get { throw null; } set { } } - public string HeaderName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute] set { } } + public string? HeaderName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute] set { } } public bool SuppressXFrameOptionsHeader { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute] set { } } } public partial class AntiforgeryTokenSet { - public AntiforgeryTokenSet(string requestToken, string cookieToken, string formFieldName, string headerName) { } - public string CookieToken { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } } + public AntiforgeryTokenSet(string? requestToken, string? cookieToken, string formFieldName, string? headerName) { } + public string? CookieToken { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } } public string FormFieldName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } } - public string HeaderName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } } - public string RequestToken { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } } + public string? HeaderName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } } + public string? RequestToken { [System.Runtime.CompilerServices.CompilerGeneratedAttribute] get { throw null; } } } public partial class AntiforgeryValidationException : System.Exception { public AntiforgeryValidationException(string message) { } - public AntiforgeryValidationException(string message, System.Exception innerException) { } + public AntiforgeryValidationException(string message, System.Exception? innerException) { } } public partial interface IAntiforgery { diff --git a/src/Antiforgery/src/AntiforgeryOptions.cs b/src/Antiforgery/src/AntiforgeryOptions.cs index 36906cf475..b7d50b22d6 100644 --- a/src/Antiforgery/src/AntiforgeryOptions.cs +++ b/src/Antiforgery/src/AntiforgeryOptions.cs @@ -73,7 +73,7 @@ namespace Microsoft.AspNetCore.Antiforgery /// Specifies the name of the header value that is used by the antiforgery system. If null then /// antiforgery validation will only consider form data. /// - public string HeaderName { get; set; } = AntiforgeryTokenHeaderName; + public string? HeaderName { get; set; } = AntiforgeryTokenHeaderName; /// /// Specifies whether to suppress the generation of X-Frame-Options header diff --git a/src/Antiforgery/src/AntiforgeryTokenSet.cs b/src/Antiforgery/src/AntiforgeryTokenSet.cs index 033e5e0731..5aa4669276 100644 --- a/src/Antiforgery/src/AntiforgeryTokenSet.cs +++ b/src/Antiforgery/src/AntiforgeryTokenSet.cs @@ -18,10 +18,10 @@ namespace Microsoft.AspNetCore.Antiforgery /// The name of the form field used for the request token. /// The name of the header used for the request token. public AntiforgeryTokenSet( - string requestToken, - string cookieToken, + string? requestToken, + string? cookieToken, string formFieldName, - string headerName) + string? headerName) { if (formFieldName == null) { @@ -37,7 +37,7 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// Gets the request token. /// - public string RequestToken { get; } + public string? RequestToken { get; } /// /// Gets the name of the form field used for the request token. @@ -47,11 +47,11 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// Gets the name of the header used for the request token. /// - public string HeaderName { get; } + public string? HeaderName { get; } /// /// Gets the cookie token. /// - public string CookieToken { get; } + public string? CookieToken { get; } } -} \ No newline at end of file +} diff --git a/src/Antiforgery/src/AntiforgeryValidationException.cs b/src/Antiforgery/src/AntiforgeryValidationException.cs index f1ade05d34..700c13f34b 100644 --- a/src/Antiforgery/src/AntiforgeryValidationException.cs +++ b/src/Antiforgery/src/AntiforgeryValidationException.cs @@ -26,7 +26,7 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// The message that describes the error. /// The inner . - public AntiforgeryValidationException(string message, Exception innerException) + public AntiforgeryValidationException(string message, Exception? innerException) : base(message, innerException) { } diff --git a/src/Antiforgery/src/Internal/AntiforgeryFeature.cs b/src/Antiforgery/src/Internal/AntiforgeryFeature.cs index 632c835df8..5d65e8ac70 100644 --- a/src/Antiforgery/src/Internal/AntiforgeryFeature.cs +++ b/src/Antiforgery/src/Internal/AntiforgeryFeature.cs @@ -10,23 +10,23 @@ namespace Microsoft.AspNetCore.Antiforgery { public bool HaveDeserializedCookieToken { get; set; } - public AntiforgeryToken CookieToken { get; set; } + public AntiforgeryToken? CookieToken { get; set; } public bool HaveDeserializedRequestToken { get; set; } - public AntiforgeryToken RequestToken { get; set; } + public AntiforgeryToken? RequestToken { get; set; } public bool HaveGeneratedNewCookieToken { get; set; } // After HaveGeneratedNewCookieToken is true, remains null if CookieToken is valid. - public AntiforgeryToken NewCookieToken { get; set; } + public AntiforgeryToken? NewCookieToken { get; set; } // After HaveGeneratedNewCookieToken is true, remains null if CookieToken is valid. - public string NewCookieTokenString { get; set; } + public string? NewCookieTokenString { get; set; } - public AntiforgeryToken NewRequestToken { get; set; } + public AntiforgeryToken? NewRequestToken { get; set; } - public string NewRequestTokenString { get; set; } + public string? NewRequestTokenString { get; set; } // Always false if NewCookieToken is null. Never store null cookie token or re-store cookie token from request. public bool HaveStoredNewCookieToken { get; set; } diff --git a/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs b/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs index 6bc7e60cd5..7c5b1d49e7 100644 --- a/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs +++ b/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs @@ -8,15 +8,15 @@ namespace Microsoft.AspNetCore.Antiforgery { internal static class AntiforgeryLoggerExtensions { - private static readonly Action _failedToDeserialzeTokens; - private static readonly Action _validationFailed; - private static readonly Action _validated; - private static readonly Action _missingCookieToken; - private static readonly Action _missingRequestToken; - private static readonly Action _newCookieToken; - private static readonly Action _reusedCookieToken; - private static readonly Action _tokenDeserializeException; - private static readonly Action _responseCacheHeadersOverridenToNoCache; + private static readonly Action _failedToDeserialzeTokens; + private static readonly Action _validationFailed; + private static readonly Action _validated; + private static readonly Action _missingCookieToken; + private static readonly Action _missingRequestToken; + private static readonly Action _newCookieToken; + private static readonly Action _reusedCookieToken; + private static readonly Action _tokenDeserializeException; + private static readonly Action _responseCacheHeadersOverridenToNoCache; static AntiforgeryLoggerExtensions() { @@ -28,11 +28,11 @@ namespace Microsoft.AspNetCore.Antiforgery LogLevel.Debug, new EventId(2, "Validated"), "Antiforgery successfully validated a request."); - _missingCookieToken = LoggerMessage.Define( + _missingCookieToken = LoggerMessage.Define( LogLevel.Warning, new EventId(3, "MissingCookieToken"), "The required antiforgery cookie '{CookieName}' is not present."); - _missingRequestToken = LoggerMessage.Define( + _missingRequestToken = LoggerMessage.Define( LogLevel.Warning, new EventId(4, "MissingRequestToken"), "The required antiforgery request token was not provided in either form field '{FormFieldName}' " @@ -71,12 +71,12 @@ namespace Microsoft.AspNetCore.Antiforgery _validated(logger, null); } - public static void MissingCookieToken(this ILogger logger, string cookieName) + public static void MissingCookieToken(this ILogger logger, string? cookieName) { _missingCookieToken(logger, cookieName, null); } - public static void MissingRequestToken(this ILogger logger, string formFieldName, string headerName) + public static void MissingRequestToken(this ILogger logger, string formFieldName, string? headerName) { _missingRequestToken(logger, formFieldName, headerName, null); } diff --git a/src/Antiforgery/src/Internal/AntiforgerySerializationContext.cs b/src/Antiforgery/src/Internal/AntiforgerySerializationContext.cs index 87fe89d49c..342d1d8fb4 100644 --- a/src/Antiforgery/src/Internal/AntiforgerySerializationContext.cs +++ b/src/Antiforgery/src/Internal/AntiforgerySerializationContext.cs @@ -23,11 +23,11 @@ namespace Microsoft.AspNetCore.Antiforgery // Don't let _chars grow beyond 512k characters. private const int MaximumCharsLength = 0x80000; - private char[] _chars; - private MemoryStream _stream; - private BinaryReader _reader; - private BinaryWriter _writer; - private SHA256 _sha256; + private char[]? _chars; + private MemoryStream? _stream; + private BinaryReader? _reader; + private BinaryWriter? _writer; + private SHA256? _sha256; public MemoryStream Stream { @@ -126,9 +126,9 @@ namespace Microsoft.AspNetCore.Antiforgery { if (Stream.Capacity > MaximumStreamSize) { - Stream = null; - Reader = null; - Writer = null; + _stream = null; + _reader = null; + _writer = null; } else { diff --git a/src/Antiforgery/src/Internal/AntiforgeryToken.cs b/src/Antiforgery/src/Internal/AntiforgeryToken.cs index 59e9b83e5a..590f92f554 100644 --- a/src/Antiforgery/src/Internal/AntiforgeryToken.cs +++ b/src/Antiforgery/src/Internal/AntiforgeryToken.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Antiforgery private string _additionalData = string.Empty; private string _username = string.Empty; - private BinaryBlob _securityToken; + private BinaryBlob? _securityToken; public string AdditionalData { @@ -21,11 +21,11 @@ namespace Microsoft.AspNetCore.Antiforgery } } - public BinaryBlob ClaimUid { get; set; } + public BinaryBlob? ClaimUid { get; set; } public bool IsCookieToken { get; set; } - public BinaryBlob SecurityToken + public BinaryBlob? SecurityToken { get { @@ -41,7 +41,7 @@ namespace Microsoft.AspNetCore.Antiforgery } } - public string Username + public string? Username { get { return _username; } set diff --git a/src/Antiforgery/src/Internal/BinaryBlob.cs b/src/Antiforgery/src/Internal/BinaryBlob.cs index 9313175b36..a33f727bd4 100644 --- a/src/Antiforgery/src/Internal/BinaryBlob.cs +++ b/src/Antiforgery/src/Internal/BinaryBlob.cs @@ -59,12 +59,12 @@ namespace Microsoft.AspNetCore.Antiforgery } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as BinaryBlob); } - public bool Equals(BinaryBlob other) + public bool Equals(BinaryBlob? other) { if (other == null) { diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgery.cs b/src/Antiforgery/src/Internal/DefaultAntiforgery.cs index f88d18bf8a..b310d2286b 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgery.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgery.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -125,9 +126,7 @@ namespace Microsoft.AspNetCore.Antiforgery } // Extract cookie & request tokens - AntiforgeryToken deserializedCookieToken; - AntiforgeryToken deserializedRequestToken; - if (!TryDeserializeTokens(httpContext, tokens, out deserializedCookieToken, out deserializedRequestToken)) + if (!TryDeserializeTokens(httpContext, tokens, out var deserializedCookieToken, out var deserializedRequestToken)) { return false; } @@ -137,7 +136,7 @@ namespace Microsoft.AspNetCore.Antiforgery httpContext, deserializedCookieToken, deserializedRequestToken, - out string message); + out var message); if (result) { @@ -145,7 +144,7 @@ namespace Microsoft.AspNetCore.Antiforgery } else { - _logger.ValidationFailed(message); + _logger.ValidationFailed(message!); } return result; @@ -210,12 +209,11 @@ namespace Microsoft.AspNetCore.Antiforgery out deserializedRequestToken); // Validate - string message; if (!_tokenGenerator.TryValidateTokenSet( httpContext, deserializedCookieToken, deserializedRequestToken, - out message)) + out var message)) { throw new AntiforgeryValidationException(message); } @@ -306,7 +304,7 @@ namespace Microsoft.AspNetCore.Antiforgery return antiforgeryFeature; } - AntiforgeryToken cookieToken; + AntiforgeryToken? cookieToken; if (antiforgeryFeature.HaveDeserializedCookieToken) { cookieToken = antiforgeryFeature.CookieToken; @@ -319,7 +317,7 @@ namespace Microsoft.AspNetCore.Antiforgery antiforgeryFeature.HaveDeserializedCookieToken = true; } - AntiforgeryToken newCookieToken; + AntiforgeryToken? newCookieToken; if (_tokenGenerator.IsCookieTokenValid(cookieToken)) { // No need for the cookie token from the request after it has been verified. @@ -338,7 +336,7 @@ namespace Microsoft.AspNetCore.Antiforgery return antiforgeryFeature; } - private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext) + private AntiforgeryToken? GetCookieTokenDoesNotThrow(HttpContext httpContext) { try { @@ -367,7 +365,7 @@ namespace Microsoft.AspNetCore.Antiforgery var cookieToken = antiforgeryFeature.NewCookieToken ?? antiforgeryFeature.CookieToken; antiforgeryFeature.NewRequestToken = _tokenGenerator.GenerateRequestToken( httpContext, - cookieToken); + cookieToken!); } return antiforgeryFeature; @@ -391,8 +389,7 @@ namespace Microsoft.AspNetCore.Antiforgery private void LogCacheHeaderOverrideWarning(HttpResponse response) { var logWarning = false; - CacheControlHeaderValue cacheControlHeaderValue; - if (CacheControlHeaderValue.TryParse(response.Headers[HeaderNames.CacheControl].ToString(), out cacheControlHeaderValue)) + if (CacheControlHeaderValue.TryParse(response.Headers[HeaderNames.CacheControl].ToString(), out var cacheControlHeaderValue)) { if (!cacheControlHeaderValue.NoCache) { @@ -434,7 +431,7 @@ namespace Microsoft.AspNetCore.Antiforgery return new AntiforgeryTokenSet( antiforgeryFeature.NewRequestTokenString, - antiforgeryFeature.NewCookieTokenString, + antiforgeryFeature.NewCookieTokenString!, _options.FormFieldName, _options.HeaderName); } @@ -442,8 +439,8 @@ namespace Microsoft.AspNetCore.Antiforgery private bool TryDeserializeTokens( HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet, - out AntiforgeryToken cookieToken, - out AntiforgeryToken requestToken) + [NotNullWhen(true)] out AntiforgeryToken? cookieToken, + [NotNullWhen(true)] out AntiforgeryToken? requestToken) { try { @@ -470,11 +467,11 @@ namespace Microsoft.AspNetCore.Antiforgery if (antiforgeryFeature.HaveDeserializedCookieToken) { - cookieToken = antiforgeryFeature.CookieToken; + cookieToken = antiforgeryFeature.CookieToken!; } else { - cookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken); + cookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken!); antiforgeryFeature.CookieToken = cookieToken; antiforgeryFeature.HaveDeserializedCookieToken = true; @@ -482,11 +479,11 @@ namespace Microsoft.AspNetCore.Antiforgery if (antiforgeryFeature.HaveDeserializedRequestToken) { - requestToken = antiforgeryFeature.RequestToken; + requestToken = antiforgeryFeature.RequestToken!; } else { - requestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken); + requestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken!); antiforgeryFeature.RequestToken = requestToken; antiforgeryFeature.HaveDeserializedRequestToken = true; diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs index 03994ec1e9..62230190bc 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Security.Claims; using System.Security.Principal; using Microsoft.AspNetCore.Http; @@ -89,7 +90,7 @@ namespace Microsoft.AspNetCore.Antiforgery // Application says user is authenticated, but we have no identifier for the user. throw new InvalidOperationException( Resources.FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername( - authenticatedIdentity.GetType(), + authenticatedIdentity?.GetType() ?? typeof(ClaimsIdentity), nameof(IIdentity.IsAuthenticated), "true", nameof(IIdentity.Name), @@ -101,7 +102,7 @@ namespace Microsoft.AspNetCore.Antiforgery } /// - public bool IsCookieTokenValid(AntiforgeryToken cookieToken) + public bool IsCookieTokenValid(AntiforgeryToken? cookieToken) { return cookieToken != null && cookieToken.IsCookieToken; } @@ -111,7 +112,7 @@ namespace Microsoft.AspNetCore.Antiforgery HttpContext httpContext, AntiforgeryToken cookieToken, AntiforgeryToken requestToken, - out string message) + [NotNullWhen(false)] out string? message) { if (httpContext == null) { @@ -148,7 +149,7 @@ namespace Microsoft.AspNetCore.Antiforgery // Is the incoming token meant for the current user? var currentUsername = string.Empty; - BinaryBlob currentClaimUid = null; + BinaryBlob? currentClaimUid = null; var authenticatedIdentity = GetAuthenticatedIdentity(httpContext.User); if (authenticatedIdentity != null) @@ -193,7 +194,7 @@ namespace Microsoft.AspNetCore.Antiforgery return true; } - private static BinaryBlob GetClaimUidBlob(string base64ClaimUid) + private static BinaryBlob? GetClaimUidBlob(string? base64ClaimUid) { if (base64ClaimUid == null) { @@ -203,7 +204,7 @@ namespace Microsoft.AspNetCore.Antiforgery return new BinaryBlob(256, Convert.FromBase64String(base64ClaimUid)); } - private static ClaimsIdentity GetAuthenticatedIdentity(ClaimsPrincipal claimsPrincipal) + private static ClaimsIdentity? GetAuthenticatedIdentity(ClaimsPrincipal? claimsPrincipal) { if (claimsPrincipal == null) { diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs index 73a0e0ad63..fff8aa9175 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs @@ -39,7 +39,7 @@ namespace Microsoft.AspNetCore.Antiforgery { var serializationContext = _pool.Get(); - Exception innerException = null; + Exception? innerException = null; try { var count = serializedToken.Length; @@ -90,7 +90,7 @@ namespace Microsoft.AspNetCore.Antiforgery * | `- Username: UTF-8 string with 7-bit integer length prefix * `- AdditionalData: UTF-8 string with 7-bit integer length prefix */ - private static AntiforgeryToken Deserialize(BinaryReader reader) + private static AntiforgeryToken? Deserialize(BinaryReader reader) { // we can only consume tokens of the same serialized version that we generate var embeddedVersion = reader.ReadByte(); @@ -144,7 +144,7 @@ namespace Microsoft.AspNetCore.Antiforgery { var writer = serializationContext.Writer; writer.Write(TokenVersion); - writer.Write(token.SecurityToken.GetData()); + writer.Write(token.SecurityToken!.GetData()); writer.Write(token.IsCookieToken); if (!token.IsCookieToken) @@ -157,7 +157,7 @@ namespace Microsoft.AspNetCore.Antiforgery else { writer.Write(false /* isClaimsBased */); - writer.Write(token.Username); + writer.Write(token.Username!); } writer.Write(token.AdditionalData); diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs index e30fe0df4d..b35358fea2 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs @@ -24,11 +24,11 @@ namespace Microsoft.AspNetCore.Antiforgery _options = optionsAccessor.Value; } - public string GetCookieToken(HttpContext httpContext) + public string? GetCookieToken(HttpContext httpContext) { Debug.Assert(httpContext != null); - var requestCookie = httpContext.Request.Cookies[_options.Cookie.Name]; + var requestCookie = httpContext.Request.Cookies[_options.Cookie.Name!]; if (string.IsNullOrEmpty(requestCookie)) { // unable to find the cookie. @@ -42,7 +42,7 @@ namespace Microsoft.AspNetCore.Antiforgery { Debug.Assert(httpContext != null); - var cookieToken = httpContext.Request.Cookies[_options.Cookie.Name]; + var cookieToken = httpContext.Request.Cookies[_options.Cookie.Name!]; // We want to delay reading the form as much as possible, for example in case of large file uploads, // request token could be part of the header. @@ -84,7 +84,7 @@ namespace Microsoft.AspNetCore.Antiforgery } } - httpContext.Response.Cookies.Append(_options.Cookie.Name, token, options); + httpContext.Response.Cookies.Append(_options.Cookie.Name!, token, options); } } } diff --git a/src/Antiforgery/src/Internal/DefaultClaimUidExtractor.cs b/src/Antiforgery/src/Internal/DefaultClaimUidExtractor.cs index fb4d386516..3df55b523f 100644 --- a/src/Antiforgery/src/Internal/DefaultClaimUidExtractor.cs +++ b/src/Antiforgery/src/Internal/DefaultClaimUidExtractor.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Antiforgery } /// - public string ExtractClaimUid(ClaimsPrincipal claimsPrincipal) + public string? ExtractClaimUid(ClaimsPrincipal claimsPrincipal) { Debug.Assert(claimsPrincipal != null); @@ -37,7 +37,7 @@ namespace Microsoft.AspNetCore.Antiforgery return Convert.ToBase64String(claimUidBytes); } - public static IList GetUniqueIdentifierParameters(IEnumerable claimsIdentities) + public static IList? GetUniqueIdentifierParameters(IEnumerable claimsIdentities) { var identitiesList = claimsIdentities as List; if (identitiesList == null) diff --git a/src/Antiforgery/src/Internal/IAntiforgeryFeature.cs b/src/Antiforgery/src/Internal/IAntiforgeryFeature.cs index c96db16708..c73c33f1aa 100644 --- a/src/Antiforgery/src/Internal/IAntiforgeryFeature.cs +++ b/src/Antiforgery/src/Internal/IAntiforgeryFeature.cs @@ -1,8 +1,10 @@ +using System.Diagnostics.CodeAnalysis; + namespace Microsoft.AspNetCore.Antiforgery { internal interface IAntiforgeryFeature { - AntiforgeryToken CookieToken { get; set; } + AntiforgeryToken? CookieToken { get; set; } bool HaveDeserializedCookieToken { get; set; } @@ -12,14 +14,14 @@ namespace Microsoft.AspNetCore.Antiforgery bool HaveStoredNewCookieToken { get; set; } - AntiforgeryToken NewCookieToken { get; set; } + AntiforgeryToken? NewCookieToken { get; set; } - string NewCookieTokenString { get; set; } + string? NewCookieTokenString { get; set; } - AntiforgeryToken NewRequestToken { get; set; } + AntiforgeryToken? NewRequestToken { get; set; } - string NewRequestTokenString { get; set; } + string? NewRequestTokenString { get; set; } - AntiforgeryToken RequestToken { get; set; } + AntiforgeryToken? RequestToken { get; set; } } } diff --git a/src/Antiforgery/src/Internal/IAntiforgeryTokenGenerator.cs b/src/Antiforgery/src/Internal/IAntiforgeryTokenGenerator.cs index 59cb3118cd..b3629ff468 100644 --- a/src/Antiforgery/src/Internal/IAntiforgeryTokenGenerator.cs +++ b/src/Antiforgery/src/Internal/IAntiforgeryTokenGenerator.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Antiforgery @@ -29,7 +30,7 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// A valid cookie token. /// true if the cookie token is valid, otherwise false. - bool IsCookieTokenValid(AntiforgeryToken cookieToken); + bool IsCookieTokenValid(AntiforgeryToken? cookieToken); /// /// Attempts to validate a cookie and request token set for the given . @@ -45,6 +46,6 @@ namespace Microsoft.AspNetCore.Antiforgery HttpContext httpContext, AntiforgeryToken cookieToken, AntiforgeryToken requestToken, - out string message); + [NotNullWhen(false)] out string? message); } } diff --git a/src/Antiforgery/src/Internal/IAntiforgeryTokenStore.cs b/src/Antiforgery/src/Internal/IAntiforgeryTokenStore.cs index dd3f29e835..f202e90f5e 100644 --- a/src/Antiforgery/src/Internal/IAntiforgeryTokenStore.cs +++ b/src/Antiforgery/src/Internal/IAntiforgeryTokenStore.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Antiforgery { internal interface IAntiforgeryTokenStore { - string GetCookieToken(HttpContext httpContext); + string? GetCookieToken(HttpContext httpContext); /// /// Gets the cookie and request tokens from the request. diff --git a/src/Antiforgery/src/Internal/IClaimUidExtractor.cs b/src/Antiforgery/src/Internal/IClaimUidExtractor.cs index 29d264789d..0153e10bc7 100644 --- a/src/Antiforgery/src/Internal/IClaimUidExtractor.cs +++ b/src/Antiforgery/src/Internal/IClaimUidExtractor.cs @@ -15,6 +15,6 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// The . /// The claims identifier. - string ExtractClaimUid(ClaimsPrincipal claimsPrincipal); + string? ExtractClaimUid(ClaimsPrincipal claimsPrincipal); } } diff --git a/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj index 566e221871..4723a65cec 100644 --- a/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj @@ -7,6 +7,7 @@ true aspnetcore;antiforgery false + enable diff --git a/src/Antiforgery/test/AntiforgeryTokenTest.cs b/src/Antiforgery/test/AntiforgeryTokenTest.cs index 9cafd306b0..c44f5be575 100644 --- a/src/Antiforgery/test/AntiforgeryTokenTest.cs +++ b/src/Antiforgery/test/AntiforgeryTokenTest.cs @@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal("additional data", token.AdditionalData); // Act & assert - 3 - token.AdditionalData = null; + token.AdditionalData = null!; Assert.Equal("", token.AdditionalData); } @@ -91,7 +91,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert Assert.NotNull(securityToken); - Assert.Equal(AntiforgeryToken.SecurityTokenBitLength, securityToken.BitLength); + Assert.Equal(AntiforgeryToken.SecurityTokenBitLength, securityToken!.BitLength); // check that we're not making a new one each property call Assert.Equal(securityToken, token.SecurityToken); @@ -123,10 +123,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert Assert.NotNull(securityToken); - Assert.Equal(AntiforgeryToken.SecurityTokenBitLength, securityToken.BitLength); + Assert.Equal(AntiforgeryToken.SecurityTokenBitLength, securityToken!.BitLength); // check that we're not making a new one each property call Assert.Equal(securityToken, token.SecurityToken); } } -} \ No newline at end of file +} diff --git a/src/Antiforgery/test/BinaryBlobTest.cs b/src/Antiforgery/test/BinaryBlobTest.cs index 2ab5b12fc1..01c77ff684 100644 --- a/src/Antiforgery/test/BinaryBlobTest.cs +++ b/src/Antiforgery/test/BinaryBlobTest.cs @@ -57,7 +57,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [InlineData((object[])null)] + [InlineData((object[]?)null)] [InlineData(new byte[] { 0x01, 0x02, 0x03 })] public void Ctor_Data_Bad(byte[] data) { @@ -93,7 +93,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange object blobA = new BinaryBlob(32); - object blobB = null; + object? blobB = null; // Act & assert Assert.NotEqual(blobA, blobB); @@ -126,4 +126,4 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(expectedHashCode, actualHashCode); } } -} \ No newline at end of file +} diff --git a/src/Antiforgery/test/DefaultAntiforgeryTest.cs b/src/Antiforgery/test/DefaultAntiforgeryTest.cs index 63ee690f35..048efea215 100644 --- a/src/Antiforgery/test/DefaultAntiforgeryTest.cs +++ b/src/Antiforgery/test/DefaultAntiforgeryTest.cs @@ -509,7 +509,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var antiforgeryFeature = new AntiforgeryFeature(); var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); - string message; + string? message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, @@ -543,7 +543,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); context.HttpContext.Request.Method = "POST"; - string message; + string? message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, @@ -583,7 +583,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); context.HttpContext.Request.Method = "POST"; - string message; + string? message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, @@ -622,7 +622,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var context = CreateMockContext(new AntiforgeryOptions()); context.HttpContext.Request.Method = httpMethod; - string message; + string? message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, @@ -659,7 +659,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var context = CreateMockContext(new AntiforgeryOptions()); context.HttpContext.Request.Method = httpMethod; - string message; + string? message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, @@ -718,7 +718,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var antiforgeryFeature = new AntiforgeryFeature(); var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); - string message; + string? message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, @@ -859,7 +859,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }; var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); - string message; + string? message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, @@ -1122,7 +1122,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal antiforgeryFeature: antiforgeryFeature); var testTokenSet = new TestTokenSet { - OldCookieTokenString = null + OldCookieTokenString = null! }; var nullTokenStore = GetTokenStore(context.HttpContext, testTokenSet, false); @@ -1135,7 +1135,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal antiforgery.SetCookieTokenAndHeader(context.HttpContext); // Assert - context.TokenSerializer.Verify(s => s.Deserialize(null), Times.Never); + context.TokenSerializer.Verify(s => s.Deserialize(null!), Times.Never); } [Fact] @@ -1159,7 +1159,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal antiforgeryFeature: antiforgeryFeature); var testTokenSet = new TestTokenSet { - OldCookieTokenString = null + OldCookieTokenString = null! }; var nullTokenStore = GetTokenStore(context.HttpContext, testTokenSet, false); @@ -1285,10 +1285,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private DefaultAntiforgery GetAntiforgery( HttpContext httpContext, - AntiforgeryOptions options = null, - IAntiforgeryTokenGenerator tokenGenerator = null, - IAntiforgeryTokenSerializer tokenSerializer = null, - IAntiforgeryTokenStore tokenStore = null) + AntiforgeryOptions? options = null, + IAntiforgeryTokenGenerator? tokenGenerator = null, + IAntiforgeryTokenSerializer? tokenSerializer = null, + IAntiforgeryTokenStore? tokenStore = null) { var optionsManager = new TestOptionsManager(); if (options != null) @@ -1299,9 +1299,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var loggerFactory = httpContext.RequestServices.GetRequiredService(); return new DefaultAntiforgery( antiforgeryOptionsAccessor: optionsManager, - tokenGenerator: tokenGenerator, - tokenSerializer: tokenSerializer, - tokenStore: tokenStore, + tokenGenerator: tokenGenerator!, + tokenSerializer: tokenSerializer!, + tokenStore: tokenStore!, loggerFactory: loggerFactory); } @@ -1313,7 +1313,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return builder.BuildServiceProvider(); } - private HttpContext GetHttpContext(IAntiforgeryFeature antiforgeryFeature = null) + private HttpContext GetHttpContext(IAntiforgeryFeature? antiforgeryFeature = null) { var httpContext = new DefaultHttpContext(); antiforgeryFeature = antiforgeryFeature ?? new AntiforgeryFeature(); @@ -1388,7 +1388,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal AntiforgeryOptions options, bool useOldCookie = false, bool isOldCookieValid = true, - IAntiforgeryFeature antiforgeryFeature = null) + IAntiforgeryFeature? antiforgeryFeature = null) { // Arrange var httpContext = GetHttpContext(antiforgeryFeature); @@ -1445,32 +1445,32 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private class TestTokenSet { - public AntiforgeryToken RequestToken { get; set; } + public AntiforgeryToken RequestToken { get; set; } = default!; - public string FormTokenString { get; set; } + public string FormTokenString { get; set; } = default!; - public AntiforgeryToken OldCookieToken { get; set; } + public AntiforgeryToken OldCookieToken { get; set; } = default!; - public string OldCookieTokenString { get; set; } + public string OldCookieTokenString { get; set; } = default!; - public AntiforgeryToken NewCookieToken { get; set; } + public AntiforgeryToken NewCookieToken { get; set; } = default!; - public string NewCookieTokenString { get; set; } + public string NewCookieTokenString { get; set; } = default!; } private class AntiforgeryMockContext { - public AntiforgeryOptions Options { get; set; } + public AntiforgeryOptions Options { get; set; } = default!; - public TestTokenSet TestTokenSet { get; set; } + public TestTokenSet TestTokenSet { get; set; } = default!; - public HttpContext HttpContext { get; set; } + public HttpContext HttpContext { get; set; } = default!; - public Mock TokenGenerator { get; set; } + public Mock TokenGenerator { get; set; } = default!; - public Mock TokenStore { get; set; } + public Mock TokenStore { get; set; } = default!; - public Mock TokenSerializer { get; set; } + public Mock TokenSerializer { get; set; } = default!; } private class TestOptionsManager : IOptions diff --git a/src/Antiforgery/test/DefaultAntiforgeryTokenGeneratorTest.cs b/src/Antiforgery/test/DefaultAntiforgeryTokenGeneratorTest.cs index 3df264d48d..39f8d4ac10 100644 --- a/src/Antiforgery/test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/src/Antiforgery/test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +#nullable disable using System; using System.Security.Claims; using System.Security.Cryptography; @@ -621,3 +622,4 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } } +#nullable restore diff --git a/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs b/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs index 494b91c540..d205f8efc2 100644 --- a/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs +++ b/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs @@ -282,7 +282,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); - Assert.True(cookies.Options.HttpOnly); + Assert.True(cookies.Options!.HttpOnly); Assert.Equal(defaultCookieSecureValue, cookies.Options.Secure); } @@ -321,7 +321,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); - Assert.True(cookies.Options.HttpOnly); + Assert.True(cookies.Options!.HttpOnly); Assert.Equal(expectedCookiePath, cookies.Options.Path); } @@ -361,7 +361,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); - Assert.True(cookies.Options.HttpOnly); + Assert.True(cookies.Options!.HttpOnly); Assert.Equal(expectedCookiePath, cookies.Options.Path); } @@ -400,7 +400,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); - Assert.True(cookies.Options.HttpOnly); + Assert.True(cookies.Options!.HttpOnly); Assert.Equal("/vdir1", cookies.Options.Path); Assert.Equal(expectedCookieDomain, cookies.Options.Domain); } @@ -421,9 +421,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private class MockResponseCookieCollection : IResponseCookies { - public string Key { get; set; } - public string Value { get; set; } - public CookieOptions Options { get; set; } + public string? Key { get; set; } + public string? Value { get; set; } + public CookieOptions? Options { get; set; } public int Count { get; set; } public void Append(string key, string value, CookieOptions options) diff --git a/src/Antiforgery/test/DefaultClaimUidExtractorTest.cs b/src/Antiforgery/test/DefaultClaimUidExtractorTest.cs index 67d690a83a..2a9b994d77 100644 --- a/src/Antiforgery/test/DefaultClaimUidExtractorTest.cs +++ b/src/Antiforgery/test/DefaultClaimUidExtractorTest.cs @@ -65,7 +65,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var claimsIdentity = (ClaimsIdentity)identity; // Act - var identiferParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { claimsIdentity }) + var identiferParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { claimsIdentity })! .ToArray(); var claims = claimsIdentity.Claims.ToList(); claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal)); @@ -258,4 +258,4 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }, uniqueIdentifierParameters); } } -} \ No newline at end of file +} diff --git a/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test.csproj index d7654d288d..1dceca09be 100644 --- a/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -2,6 +2,7 @@ $(DefaultNetCoreTargetFramework) + enable