Skip to content

Commit

Permalink
Enable EnforceCodeStyleInBuild and fix findings (#2763)
Browse files Browse the repository at this point in the history
* Enable EnforceCodeStyleInBuild and fix findings

Have to enable GenerateDocumentationFile for test csproj to work around
dotnet/roslyn#41640

Fix up code generated by roslyn fixer

Don't consider GlobalSuppressions.cs or TrimmingAttributes.cs

---------

Co-authored-by: Keegan Caruso <[email protected]>
  • Loading branch information
keegan-caruso and Keegan Caruso authored Aug 6, 2024
1 parent 0b066f1 commit 15e26cf
Show file tree
Hide file tree
Showing 204 changed files with 732 additions and 783 deletions.
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,21 @@ dotnet_diagnostic.CA1303.severity = none
dotnet_diagnostic.IDE0073.severity = warning
file_header_template = Copyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the MIT License.

# IDE0005: Remove unnecessary usings
dotnet_diagnostic.IDE0005.severity = warning

# IDE0055: All formatting rules
dotnet_diagnostic.IDE0055.severity = warning

# CA1845: Use span-based 'string.Concat'
dotnet_diagnostic.CA1845.severity = warning

# CA1846: Prefer AsSpan over Substring
dotnet_diagnostic.CA1846.severity = warning

[{GlobalSuppressions.cs,TrimmingAttributes.cs}]
dotnet_diagnostic.IDE0073.severity = none

# C++ Files
[*.{cpp,h,in}]
curly_bracket_next_line = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,20 @@ public class AsymmetricAdapterSignatures
[GlobalSetup]
public void Setup()
{
SecurityTokenDescriptor securityTokenDescriptor = new ()
SecurityTokenDescriptor securityTokenDescriptor = new()
{
SigningCredentials = BenchmarkUtils.SigningCredentialsRsaSha256,
Claims = BenchmarkUtils.Claims,
TokenType = JwtHeaderParameterNames.Jwk
};

_bytesToSign = Encoding.UTF8.GetBytes((new JsonWebTokenHandler()).CreateToken(securityTokenDescriptor));
_rsaAsymmetricAdapter = new AsymmetricAdapter(
BenchmarkUtils.SigningCredentialsRsaSha256.Key,
SecurityAlgorithms.RsaSha256,
SHA256.Create(),
SupportedAlgorithms.GetHashAlgorithmName(SecurityAlgorithms.RsaSha256),
true );
_rsaAsymmetricAdapter = new AsymmetricAdapter(
BenchmarkUtils.SigningCredentialsRsaSha256.Key,
SecurityAlgorithms.RsaSha256,
SHA256.Create(),
SupportedAlgorithms.GetHashAlgorithmName(SecurityAlgorithms.RsaSha256),
true);

_signatureBuffer = new byte[256];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public BenchmarkConfig()
.WithOrderer(new DefaultOrderer(SummaryOrderPolicy.Method))
.HideColumns(Column.WarmupCount, Column.Type, Column.Job)
.AddDiagnoser(MemoryDiagnoser.Default); // https://benchmarkdotnet.org/articles/configs/diagnosers.html
//.AddDiagnoser(new EtwProfiler()) // Uncomment to generate traces / flame graphs. Doc: https://adamsitnik.com/ETW-Profiler/
//.AddDiagnoser(new EtwProfiler()) // Uncomment to generate traces / flame graphs. Doc: https://adamsitnik.com/ETW-Profiler/
}
}
}
1 change: 1 addition & 0 deletions build/common.props
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<TargetFrameworks Condition=" '$(OS)' != 'Windows_NT' ">$(SrcStandardTargets)</TargetFrameworks>
<NetStandardImplicitPackageVersion>$(NetStandardVersion)</NetStandardImplicitPackageVersion>
<LangVersion>12</LangVersion>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

<!-- Wilson version -->
Expand Down
2 changes: 2 additions & 0 deletions build/commonTest.props
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<RuntimeFrameworkVersion Condition=" '$(TargetFramework)' == 'netcoreapp2.1'">$(DotNetCoreAppRuntimeVersion)</RuntimeFrameworkVersion>
<IsPackable>false</IsPackable>
<LangVersion>12</LangVersion>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp2.1' OR '$(TargetFramework)' == 'net6.0' Or '$(TargetFramework)' == 'net8.0' Or '$(TargetFramework)' == 'net9.0'">
Expand All @@ -27,6 +28,7 @@
<PropertyGroup>
<NoWarn>$(NoWarn);SYSLIB0050</NoWarn>
<NoWarn>$(NoWarn);SYSLIB0051</NoWarn>
<NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ internal static void CreateClaimFromObject(List<Claim> claims, string claimType,
else if (value is double d)
claims.Add(new Claim(claimType, d.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer));
else if (value is DateTime dt)
claims.Add(new Claim(claimType, dt.ToString("o",CultureInfo.InvariantCulture), ClaimValueTypes.DateTime, issuer, issuer));
claims.Add(new Claim(claimType, dt.ToString("o", CultureInfo.InvariantCulture), ClaimValueTypes.DateTime, issuer, issuer));
else if (value is float f)
claims.Add(new Claim(claimType, f.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer));
else if (value is decimal m)
Expand Down Expand Up @@ -320,7 +320,7 @@ internal T GetValue<T>(string key, bool throwEx, out bool found)
else if (typeof(T) == typeof(Collection<object>))
return (T)(object)new Collection<object> { obj };

else if(typeof(T).IsEnum)
else if (typeof(T).IsEnum)
{
return (T)Enum.Parse(typeof(T), obj.ToString(), ignoreCase: true);
}
Expand All @@ -342,15 +342,15 @@ internal T GetValue<T>(string key, bool throwEx, out bool found)
if (objType == typeof(long))
return (T)(object)new long[] { (long)obj };

if(objType == typeof(int))
if (objType == typeof(int))
return (T)(object)new long[] { (int)obj };

if (long.TryParse(obj.ToString(), out long value))
return (T)(object)new long[] { value };
}
else if (typeof(T) == typeof(double))
{
if(double.TryParse(obj.ToString(), out double value))
if (double.TryParse(obj.ToString(), out double value))
return (T)(object)value;
}
else if (typeof(T) == typeof(uint))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal JsonClaimSet CreateHeaderClaimSet(byte[] bytes, int length)
}

internal JsonClaimSet CreateHeaderClaimSet(ReadOnlySpan<byte> byteSpan)
{
{
Utf8JsonReader reader = new(byteSpan);
if (!JsonSerializerPrimitives.IsReaderAtTokenType(ref reader, JsonTokenType.StartObject, true))
throw LogHelper.LogExceptionMessage(
Expand Down
8 changes: 4 additions & 4 deletions src/Microsoft.IdentityModel.JsonWebTokens/JsonWebToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public string EncodedHeader
if (!_encodedTokenMemory.IsEmpty)
_encodedHeader = _encodedTokenMemory.Span.Slice(0, Dot1).ToString();
else
_encodedHeader = (_encodedToken is not null) ? _encodedToken.Substring(0, Dot1) : string.Empty;
_encodedHeader = (_encodedToken is not null) ? _encodedToken.Substring(0, Dot1) : string.Empty;
}

return _encodedHeader;
Expand Down Expand Up @@ -324,10 +324,10 @@ public string EncodedToken
{
get
{
if (_encodedToken is null && !_encodedTokenMemory.IsEmpty)
if (_encodedToken is null && !_encodedTokenMemory.IsEmpty)
_encodedToken = _encodedTokenMemory.ToString();

return _encodedToken;
return _encodedToken;
}
}

Expand Down Expand Up @@ -395,7 +395,7 @@ public string InitializationVector
/// </remarks>
public override SecurityKey SigningKey { get; set; }

internal byte[] MessageBytes{ get; set; }
internal byte[] MessageBytes { get; set; }

internal int NumberOfDots { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ internal static string CreateToken
IDictionary<string, object> additionalInnerHeaderClaims,
string tokenType)
{
using (MemoryStream utf8ByteMemoryStream = new ())
using (MemoryStream utf8ByteMemoryStream = new())
{
Utf8JsonWriter writer = null;
char[] encodedChars = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ internal TokenDecryptionResult DecryptToken(
else
keys = configurationKeys;
}

}

if (jwtToken.Alg.Equals(JwtConstants.DirectKeyUseAlg, StringComparison.Ordinal)
Expand Down Expand Up @@ -205,7 +205,7 @@ internal TokenDecryptionResult DecryptToken(
typeof(SecurityTokenKeyWrapException),
new System.Diagnostics.StackFrame());
return (null, exceptionDetail);
}
}
}

/// <summary>
Expand Down Expand Up @@ -234,7 +234,7 @@ internal TokenDecryptionResult DecryptToken(

if (!string.IsNullOrEmpty(jwtToken.X5t) && validationParameters.TokenDecryptionKeys != null)
{
for(int i = 0; i < validationParameters.TokenDecryptionKeys.Count; i++)
for (int i = 0; i < validationParameters.TokenDecryptionKeys.Count; i++)
{
var key = validationParameters.TokenDecryptionKeys[i];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.IdentityModel.Abstractions;
using Microsoft.IdentityModel.JsonWebTokens.Results;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
Expand Down Expand Up @@ -135,7 +134,7 @@ private static SignatureValidationResult ValidateSignatureUsingAllKeys(
new StackFrame()));

StringBuilder exceptionStrings = new();
StringBuilder keysAttempted = new ();
StringBuilder keysAttempted = new();

PopulateFailedResults(configFailedResult, exceptionStrings, keysAttempted);
PopulateFailedResults(vpFailedResult, exceptionStrings, keysAttempted);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ internal async ValueTask<TokenValidationResult> ValidateTokenAsync(
}
}

TokenValidationResult tokenValidationResult = jsonWebToken.IsEncrypted ?
TokenValidationResult tokenValidationResult = jsonWebToken.IsEncrypted ?
await ValidateJWEAsync(jsonWebToken, validationParameters, currentConfiguration).ConfigureAwait(false) :
await ValidateJWSAsync(jsonWebToken, validationParameters, currentConfiguration).ConfigureAwait(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Licensed under the MIT License.

using System;
using System.Text;

namespace Microsoft.IdentityModel.JsonWebTokens
{
Expand Down Expand Up @@ -97,20 +96,20 @@ internal readonly struct JwtHeaderUtf8Bytes
{
// Please keep this alphabetical order

public static ReadOnlySpan<byte> Alg =>"alg"u8;
public static ReadOnlySpan<byte> Apu =>"apu"u8;
public static ReadOnlySpan<byte> Apv =>"apv"u8;
public static ReadOnlySpan<byte> Cty =>"cty"u8;
public static ReadOnlySpan<byte> Enc =>"enc"u8;
public static ReadOnlySpan<byte> Epk =>"epk"u8;
public static ReadOnlySpan<byte> IV =>"iv"u8;
public static ReadOnlySpan<byte> Jku =>"jku"u8;
public static ReadOnlySpan<byte> Jwk =>"jwk"u8;
public static ReadOnlySpan<byte> Kid =>"kid"u8;
public static ReadOnlySpan<byte> Typ =>"typ"u8;
public static ReadOnlySpan<byte> X5c =>"x5c"u8;
public static ReadOnlySpan<byte> X5t =>"x5t"u8;
public static ReadOnlySpan<byte> X5u =>"x5u"u8;
public static ReadOnlySpan<byte> Zip =>"zip"u8;
public static ReadOnlySpan<byte> Alg => "alg"u8;
public static ReadOnlySpan<byte> Apu => "apu"u8;
public static ReadOnlySpan<byte> Apv => "apv"u8;
public static ReadOnlySpan<byte> Cty => "cty"u8;
public static ReadOnlySpan<byte> Enc => "enc"u8;
public static ReadOnlySpan<byte> Epk => "epk"u8;
public static ReadOnlySpan<byte> IV => "iv"u8;
public static ReadOnlySpan<byte> Jku => "jku"u8;
public static ReadOnlySpan<byte> Jwk => "jwk"u8;
public static ReadOnlySpan<byte> Kid => "kid"u8;
public static ReadOnlySpan<byte> Typ => "typ"u8;
public static ReadOnlySpan<byte> X5c => "x5c"u8;
public static ReadOnlySpan<byte> X5t => "x5t"u8;
public static ReadOnlySpan<byte> X5u => "x5u"u8;
public static ReadOnlySpan<byte> Zip => "zip"u8;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ public void Write(EventLevel level, Exception innerException, string message, pa
// Obtain the current library version dynamically.
WriteAlways(string.Format(CultureInfo.InvariantCulture, _versionLogMessage, typeof(IdentityModelEventSource).GetTypeInfo().Assembly.GetName().Version.ToString()));
WriteAlways(string.Format(CultureInfo.InvariantCulture, _dateLogMessage, DateTime.UtcNow));
if (ShowPII)
if (ShowPII)
WriteAlways(_piiOnLogMessage);
else
WriteAlways(_piiOffLogMessage);
Expand Down Expand Up @@ -340,7 +340,7 @@ public EventLevel LogLevel
{
get; set;
}

private static string PrepareMessage(EventLevel level, string message, params object[] args)
{
if (message == null)
Expand Down
12 changes: 8 additions & 4 deletions src/Microsoft.IdentityModel.Logging/LogHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ public static void LogInformation(string message, params object[] args)
public static void LogVerbose(string message, params object[] args)
{
if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Verbose, EventKeywords.All))
IdentityModelEventSource.Logger.WriteVerbose(message, args);
IdentityModelEventSource.Logger.WriteVerbose(message, args);

if (Logger.IsEnabled(EventLogLevel.Verbose))
Logger.Log(WriteEntry(EventLogLevel.Verbose, null, message, args));
Expand All @@ -310,7 +310,7 @@ public static void LogVerbose(string message, params object[] args)
public static void LogWarning(string message, params object[] args)
{
if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Warning, EventKeywords.All))
IdentityModelEventSource.Logger.WriteWarning(message, args);
IdentityModelEventSource.Logger.WriteWarning(message, args);

if (Logger.IsEnabled(EventLogLevel.Warning))
Logger.Log(WriteEntry(EventLogLevel.Warning, null, message, args));
Expand All @@ -324,7 +324,7 @@ public static void LogWarning(string message, params object[] args)
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
private static T LogExceptionImpl<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, Exception innerException, string format, params object[] args) where T : Exception
private static T LogExceptionImpl<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, Exception innerException, string format, params object[] args) where T : Exception
{
string message;
if (args != null)
Expand All @@ -339,16 +339,20 @@ public static void LogWarning(string message, params object[] args)
if (Logger.IsEnabled(eventLogLevel))
Logger.Log(WriteEntry(eventLogLevel, innerException, message, null));

if (innerException != null)
if (innerException != null)
{
if (string.IsNullOrEmpty(argumentName))
return (T)Activator.CreateInstance(typeof(T), message, innerException);
else
return (T)Activator.CreateInstance(typeof(T), argumentName, message, innerException);
}
else
{
if (string.IsNullOrEmpty(argumentName))
return (T)Activator.CreateInstance(typeof(T), message);
else
return (T)Activator.CreateInstance(typeof(T), argumentName, message);
}
}

private static EventLogLevel EventLevelToEventLogLevel(EventLevel eventLevel) =>
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.IdentityModel.Logging/LoggerContext.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@

using System;
using System.Linq;
using System.Web;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;

namespace Microsoft.IdentityModel.Protocols.OpenIdConnect.Configuration
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ public OpenIdConnectProtocolException(String message, Exception innerException)
{
}

/// <summary>
/// Initializes a new instance of the <see cref="OpenIdConnectProtocolException"/> class.
/// </summary>
/// <param name="info">the <see cref="SerializationInfo"/> that holds the serialized object data.</param>
/// <param name="context">The contextual information about the source or destination.</param>
protected OpenIdConnectProtocolException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenIdConnectProtocolException"/> class.
/// </summary>
/// <param name="info">the <see cref="SerializationInfo"/> that holds the serialized object data.</param>
/// <param name="context">The contextual information about the source or destination.</param>
protected OpenIdConnectProtocolException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
#if NET8_0_OR_GREATER
Expand Down
Loading

0 comments on commit 15e26cf

Please sign in to comment.