diff --git a/src/Common/src/Abstractions/DynamicTypeAccess/PackageResolver.cs b/src/Common/src/Abstractions/DynamicTypeAccess/PackageResolver.cs index 571f16d5bd..769b412f95 100644 --- a/src/Common/src/Abstractions/DynamicTypeAccess/PackageResolver.cs +++ b/src/Common/src/Abstractions/DynamicTypeAccess/PackageResolver.cs @@ -88,6 +88,7 @@ protected TypeAccessor ResolveType(params string[] typeNames) foreach (string typeName in typeNames) { +#pragma warning disable S134 // Control flow statements "if", "switch", "for", "foreach", "while", "do" and "try" should not be nested too deeply try { Type type = assembly.GetType(typeName, true)!; @@ -97,6 +98,7 @@ protected TypeAccessor ResolveType(params string[] typeNames) { exceptions.Add(exception); } +#pragma warning restore S134 // Control flow statements "if", "switch", "for", "foreach", "while", "do" and "try" should not be nested too deeply } } catch (Exception exception) when (exception is ArgumentException or IOException or BadImageFormatException) diff --git a/src/Common/src/Common/Reflection/ReflectionHelpers.cs b/src/Common/src/Common/Reflection/ReflectionHelpers.cs index 8c09f619ba..34c6abeb44 100644 --- a/src/Common/src/Common/Reflection/ReflectionHelpers.cs +++ b/src/Common/src/Common/Reflection/ReflectionHelpers.cs @@ -463,12 +463,7 @@ private static void TryLoadAssembliesWithAttribute() try { Assembly assemblyRef = loadContext.LoadFromAssemblyPath(assembly); - - // haven't been able to get actual type comparison to work (assembly of the attribute not found?), falling back on matching the type name - if (CustomAttributeData.GetCustomAttributes(assemblyRef).Any(attr => attr.AttributeType.FullName == typeof(T).FullName)) - { - FindAssembly(filename); - } + FindAssemblyByFullName(assemblyRef, filename); } catch { @@ -478,6 +473,15 @@ private static void TryLoadAssembliesWithAttribute() } } + private static void FindAssemblyByFullName(Assembly assemblyRef, string filename) + { + // haven't been able to get actual type comparison to work (assembly of the attribute not found?), falling back on matching the type name + if (CustomAttributeData.GetCustomAttributes(assemblyRef).Any(attr => attr.AttributeType.FullName == typeof(T).FullName)) + { + FindAssembly(filename); + } + } + /// /// Build a list of file paths that are relevant to this task. /// diff --git a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs index c7d890576d..fe9ecdf0d7 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +using System; using System.Globalization; using System.Net; using System.Net.Http.Json; @@ -226,21 +227,19 @@ public override void Load() { return await DoLoadAsync(updateDictionary, cancellationToken); } - catch (ConfigServerException e) + catch (ConfigServerException e) when (attempts < Settings.RetryAttempts) { Logger.LogInformation(e, "Failed fetching configuration from server at: {uri}.", Settings.Uri); attempts++; - if (attempts < Settings.RetryAttempts) - { - Thread.CurrentThread.Join(backOff); - int nextBackOff = (int)(backOff * Settings.RetryMultiplier); - backOff = Math.Min(nextBackOff, Settings.RetryMaxInterval); - } - else - { - throw; - } + Thread.CurrentThread.Join(backOff); + int nextBackOff = (int)(backOff * Settings.RetryMultiplier); + backOff = Math.Min(nextBackOff, Settings.RetryMaxInterval); + } + catch (ConfigServerException e) when (attempts >= Settings.RetryAttempts) + { + Logger.LogInformation(e, "Failed fetching configuration for the final time from server at: {uri} .", Settings.Uri); + throw; } } while (true); @@ -275,10 +274,7 @@ public override void Load() Logger.LogInformation("Located environment name: {name}, profiles: {profiles}, labels: {label}, version: {version}, state: {state}", env.Name, env.Profiles, env.Label, env.Version, env.State); - if (updateDictionary) - { - UpdateDictionary(env); - } + UpdateDictionaryData(updateDictionary, env); return env; } @@ -299,9 +295,12 @@ public override void Load() return null; } - private void UpdateDictionary(ConfigEnvironment env) + private void UpdateDictionaryData(bool updateDictionary, ConfigEnvironment env) { - + if (updateDictionary) + { + return; + } var data = new Dictionary(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(env.State)) @@ -383,16 +382,7 @@ internal void UpdateSettingsFromDiscovery(IEnumerable instance settings.Username = username; settings.Password = password; } - - if (metaData.TryGetValue("configPath", out string? path)) - { - if (uri.EndsWith('/') && path.StartsWith('/')) - { - uri = uri.Substring(0, uri.Length - 1); - } - - uri += path; - } + uri += ExtractPath(metaData, uri); } endpoints.Append(uri); @@ -406,6 +396,15 @@ internal void UpdateSettingsFromDiscovery(IEnumerable instance } } + private string ExtractPath(IDictionary metaData, string uri) + { + if (metaData.TryGetValue("configPath", out string? path)) + { + return uri.EndsWith('/') && path.StartsWith('/')? path.Substring(1, path.Length - 1) : path; + } + return string.Empty; + } + internal async Task ProvideRuntimeReplacementsAsync(IDiscoveryClient? discoveryClientFromDi, CancellationToken cancellationToken) { if (_configServerDiscoveryService is not null) diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs index 0db3867b44..034ee88344 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs @@ -117,7 +117,9 @@ private string ToConnectionString() return builder.Uri.AbsoluteUri; } +#pragma warning disable S3776 // Cognitive Complexity of methods should not be too high private void FromConnectionString(string? connectionString, bool preserveUnknownSettings) +#pragma warning restore S3776 // Cognitive Complexity of methods should not be too high { if (preserveUnknownSettings) { @@ -131,53 +133,54 @@ private void FromConnectionString(string? connectionString, bool preserveUnknown _settings.Clear(); } - if (!string.IsNullOrEmpty(connectionString)) + if (string.IsNullOrEmpty(connectionString)) { - if (connectionString.Contains(',')) - { - // MongoDB allows multiple servers in the connection string, but we haven't found any service bindings that actually use that. - throw new NotImplementedException("Support for multiple servers is not implemented. Please open a GitHub issue if you need this."); - } + return; + } + if (connectionString.Contains(',')) + { + // MongoDB allows multiple servers in the connection string, but we haven't found any service bindings that actually use that. + throw new NotImplementedException("Support for multiple servers is not implemented. Please open a GitHub issue if you need this."); + } - // MongoDB allows semicolon as separator for query string parameters, to provide backwards compatibility. - connectionString = connectionString.Replace(';', '&'); + // MongoDB allows semicolon as separator for query string parameters, to provide backwards compatibility. + connectionString = connectionString.Replace(';', '&'); - var uri = new Uri(connectionString); + var uri = new Uri(connectionString); - if (!string.IsNullOrEmpty(uri.UserInfo)) - { - string[] parts = uri.UserInfo.Split(':', 2); + if (!string.IsNullOrEmpty(uri.UserInfo)) + { + string[] parts = uri.UserInfo.Split(':', 2); - _settings[KnownKeywords.Username] = Uri.UnescapeDataString(parts[0]); + _settings[KnownKeywords.Username] = Uri.UnescapeDataString(parts[0]); - if (parts.Length == 2) - { - _settings[KnownKeywords.Password] = Uri.UnescapeDataString(parts[1]); - } + if (parts.Length == 2) + { + _settings[KnownKeywords.Password] = Uri.UnescapeDataString(parts[1]); } + } - _settings[KnownKeywords.Server] = uri.Host; + _settings[KnownKeywords.Server] = uri.Host; - if (uri.Port != -1) - { - _settings[KnownKeywords.Port] = uri.Port.ToString(CultureInfo.InvariantCulture); - } + if (uri.Port != -1) + { + _settings[KnownKeywords.Port] = uri.Port.ToString(CultureInfo.InvariantCulture); + } - if (uri.AbsolutePath.StartsWith('/') && uri.AbsolutePath.Length > 1) - { - _settings[KnownKeywords.AuthenticationDatabase] = Uri.UnescapeDataString(uri.AbsolutePath[1..]); - } + if (uri.AbsolutePath.StartsWith('/') && uri.AbsolutePath.Length > 1) + { + _settings[KnownKeywords.AuthenticationDatabase] = Uri.UnescapeDataString(uri.AbsolutePath[1..]); + } - NameValueCollection queryCollection = HttpUtility.ParseQueryString(uri.Query); + NameValueCollection queryCollection = HttpUtility.ParseQueryString(uri.Query); - foreach (string? key in queryCollection.AllKeys.Where(x => x != null)) - { - string? value = queryCollection.Get(key); + foreach (string? key in queryCollection.AllKeys.Where(x => x != null)) + { + string? value = queryCollection.Get(key); - if (key != null && value != null) - { - _settings[key] = value; - } + if (key != null && value != null) + { + _settings[key] = value; } } } diff --git a/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs b/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs index 3516f465ad..4ef5b5ae43 100644 --- a/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs @@ -760,10 +760,12 @@ private static IEnumerable ExtractConnectionStringParameters(string? con string name = nameValuePair[0]; string value = nameValuePair[1]; +#pragma warning disable S134 // Control flow statements "if", "switch", "for", "foreach", "while", "do" and "try" should not be nested too deeply if (TempFileKeys.Contains(name)) { value = File.ReadAllText(value); } +#pragma warning restore S134 // Control flow statements "if", "switch", "for", "foreach", "while", "do" and "try" should not be nested too deeply value = value.Replace("\n", Environment.NewLine, StringComparison.Ordinal); diff --git a/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs b/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs index 61f7d41c5e..81c60fd252 100644 --- a/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs @@ -57,25 +57,31 @@ protected override async Task InvokeEndpointHandlerAsync(HttpCo string loggerName = remaining.Value!.TrimStart('/'); Dictionary change = await DeserializeRequestAsync(request.Body); + return CheckLogger(loggerName, change); + } + } - change.TryGetValue("configuredLevel", out string? level); + return new LoggersRequest(); + } - _logger.LogDebug("Change Request: {name}, {level}", loggerName, level ?? "RESET"); + private LoggersRequest? CheckLogger(string loggerName, Dictionary change) + { - if (!string.IsNullOrEmpty(loggerName)) - { - if (!string.IsNullOrEmpty(level) && LoggerLevels.StringToLogLevel(level) == null) - { - _logger.LogDebug("Invalid LogLevel specified: {level}", level); - return null; - } + change.TryGetValue("configuredLevel", out string? level); - return new LoggersRequest(loggerName, level); - } - } + _logger.LogDebug("Change Request: {name}, {level}", loggerName, level ?? "RESET"); + + if (string.IsNullOrEmpty(loggerName)) + { + return new LoggersRequest(); + } + if (!string.IsNullOrEmpty(level) && LoggerLevels.StringToLogLevel(level) == null) + { + _logger.LogDebug("Invalid LogLevel specified: {level}", level); + return null; } - return new LoggersRequest(); + return new LoggersRequest(loggerName, level); } private async Task> DeserializeRequestAsync(Stream stream) diff --git a/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs b/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs index 3e17dea2c3..1d09252d48 100644 --- a/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs @@ -69,7 +69,7 @@ internal IList> ParseTags(IQueryCollection query) { var results = new List>(); - foreach (KeyValuePair parameter in query.Where(X => X.Key.Equals("tag", StringComparison.OrdinalIgnoreCase))) + foreach (KeyValuePair parameter in query.Where(x => x.Key.Equals("tag", StringComparison.OrdinalIgnoreCase))) { foreach (string? value in parameter.Value) { diff --git a/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs b/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs index af9fed8248..d9c55ae173 100644 --- a/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs +++ b/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs @@ -64,13 +64,13 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) { ArgumentGuard.NotNull(eventData); - if (!_isInitialized || (string.Equals(eventData.EventName, EventName, StringComparison.OrdinalIgnoreCase) && eventData.Payload != null)) - { - return; - } - try { + + if (!_isInitialized || string.Equals(eventData.EventName, EventName, StringComparison.OrdinalIgnoreCase) || eventData.Payload == null) + { + return; + } foreach (IDictionary? payload in eventData.Payload) { if (payload != null) diff --git a/src/Security/test/Authentication.Mtls.Test/ClientCertificateAuthenticationTests.cs b/src/Security/test/Authentication.Mtls.Test/ClientCertificateAuthenticationTests.cs index 7abe07486c..8adcc2b6b7 100644 --- a/src/Security/test/Authentication.Mtls.Test/ClientCertificateAuthenticationTests.cs +++ b/src/Security/test/Authentication.Mtls.Test/ClientCertificateAuthenticationTests.cs @@ -359,7 +359,9 @@ public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() } [Fact] +#pragma warning disable S3776 // Cognitive Complexity of methods should not be too high public async Task VerifyNoEventWireUpWithAValidCertificateCreatesADefaultUser() +#pragma warning restore S3776 // Cognitive Complexity of methods should not be too high { TestServer server = CreateServer(new MutualTlsAuthenticationOptions { @@ -512,7 +514,9 @@ public async Task VerifyValidationEventPrincipalIsPropagated() Assert.Single(responseAsXml.Elements("claim")); } +#pragma warning disable S3776 // Cognitive Complexity of methods should not be too high private static TestServer CreateServer(MutualTlsAuthenticationOptions configureOptions, X509Certificate2 clientCertificate = null, Uri baseAddress = null, +#pragma warning restore S3776 // Cognitive Complexity of methods should not be too high bool wireUpHeaderMiddleware = false, string headerName = "") { IWebHostBuilder builder = new WebHostBuilder().Configure(app =>