Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
More work on S134 & S3776
Browse files Browse the repository at this point in the history
thompson-tomo committed Feb 3, 2024

Verified

This commit was signed with the committer’s verified signature.
Erutis K Agajanian
1 parent 8119e20 commit 800ff5a
Showing 9 changed files with 106 additions and 86 deletions.
Original file line number Diff line number Diff line change
@@ -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)
16 changes: 10 additions & 6 deletions src/Common/src/Common/Reflection/ReflectionHelpers.cs
Original file line number Diff line number Diff line change
@@ -463,12 +463,7 @@ private static void TryLoadAssembliesWithAttribute<T>()
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<T>(assemblyRef, filename);
}
catch
{
@@ -478,6 +473,15 @@ private static void TryLoadAssembliesWithAttribute<T>()
}
}

private static void FindAssemblyByFullName<T>(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);
}
}

/// <summary>
/// Build a list of file paths that are relevant to this task.
/// </summary>
Original file line number Diff line number Diff line change
@@ -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<string, string?>(StringComparer.OrdinalIgnoreCase);

if (!string.IsNullOrEmpty(env.State))
@@ -383,16 +382,7 @@ internal void UpdateSettingsFromDiscovery(IEnumerable<IServiceInstance> 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<IServiceInstance> instance
}
}

private string ExtractPath(IDictionary<string, string> 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)
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
Original file line number Diff line number Diff line change
@@ -760,10 +760,12 @@ private static IEnumerable<string> 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);

32 changes: 19 additions & 13 deletions src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs
Original file line number Diff line number Diff line change
@@ -57,25 +57,31 @@ protected override async Task<LoggersResponse> InvokeEndpointHandlerAsync(HttpCo
string loggerName = remaining.Value!.TrimStart('/');

Dictionary<string, string> 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<string, string> 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<Dictionary<string, string>> DeserializeRequestAsync(Stream stream)
Original file line number Diff line number Diff line change
@@ -69,7 +69,7 @@ internal IList<KeyValuePair<string, string>> ParseTags(IQueryCollection query)
{
var results = new List<KeyValuePair<string, string>>();

foreach (KeyValuePair<string, StringValues> parameter in query.Where(X => X.Key.Equals("tag", StringComparison.OrdinalIgnoreCase)))
foreach (KeyValuePair<string, StringValues> parameter in query.Where(x => x.Key.Equals("tag", StringComparison.OrdinalIgnoreCase)))
{
foreach (string? value in parameter.Value)
{
Original file line number Diff line number Diff line change
@@ -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<string, object?>? payload in eventData.Payload)
{
if (payload != null)
Original file line number Diff line number Diff line change
@@ -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 =>

0 comments on commit 800ff5a

Please sign in to comment.