Skip to content

Commit

Permalink
[Extensions.AWSXRay] Fix analysis warnings (#951)
Browse files Browse the repository at this point in the history
  • Loading branch information
martincostello authored Mar 10, 2023
1 parent 9dd714a commit 7fda8d4
Show file tree
Hide file tree
Showing 14 changed files with 101 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public static class AWSXRayIdGenerator

internal static void ReplaceTraceId(Sampler? sampler = null)
{
#pragma warning disable CA2000 // Dispose objects before losing scope
var awsXRayActivityListener = new ActivityListener
{
ActivityStarted = (activity) =>
Expand All @@ -63,6 +64,7 @@ internal static void ReplaceTraceId(Sampler? sampler = null)

ShouldListenTo = (_) => true,
};
#pragma warning restore CA2000 // Dispose objects before losing scope

ActivitySource.AddActivityListener(awsXRayActivityListener);
}
Expand Down Expand Up @@ -141,7 +143,9 @@ private static string GenerateHexNumber(int digits)
/// <param name="buffer">An array of bytes to contain random numbers.</param>
private static void NextBytes(byte[] buffer)
{
#pragma warning disable CA5394 // Do not use insecure randomness
Global.NextBytes(buffer);
#pragma warning restore CA5394 // Do not use insecure randomness
}

/// <summary>
Expand All @@ -151,7 +155,9 @@ private static void NextBytes(byte[] buffer)
/// <returns>A 32-bit signed integer that is greater than or equal to 0, and less than maxValue.</returns>
private static int Next(int maxValue)
{
#pragma warning disable CA5394 // Do not use insecure randomness
return Global.Next(maxValue);
#pragma warning restore CA5394 // Do not use insecure randomness
}

private static ActivitySamplingResult ComputeRootActivitySamplingResult(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources;
public class AWSEBSResourceDetector : IResourceDetector
{
private const string AWSEBSMetadataWindowsFilePath = "C:\\Program Files\\Amazon\\XRay\\environment.conf";
#if NETSTANDARD
private const string AWSEBSMetadataLinuxFilePath = "/var/elasticbeanstalk/xray/environment.conf";
#endif

/// <summary>
/// Detector the required and optional resource attributes from AWS ElasticBeanstalk.
Expand All @@ -55,9 +57,9 @@ public class AWSEBSResourceDetector : IResourceDetector
filePath = AWSEBSMetadataWindowsFilePath;
#endif

var metadata = this.GetEBSMetadata(filePath);
var metadata = GetEBSMetadata(filePath);

resourceAttributes = this.ExtractResourceAttributes(metadata);
resourceAttributes = ExtractResourceAttributes(metadata);
}
catch (Exception ex)
{
Expand All @@ -67,7 +69,7 @@ public class AWSEBSResourceDetector : IResourceDetector
return resourceAttributes;
}

internal List<KeyValuePair<string, object?>>? ExtractResourceAttributes(AWSEBSMetadataModel? metadata)
internal static List<KeyValuePair<string, object?>>? ExtractResourceAttributes(AWSEBSMetadataModel? metadata)
{
var resourceAttributes = new List<KeyValuePair<string, object?>>()
{
Expand All @@ -82,7 +84,7 @@ public class AWSEBSResourceDetector : IResourceDetector
return resourceAttributes;
}

internal AWSEBSMetadataModel? GetEBSMetadata(string filePath)
internal static AWSEBSMetadataModel? GetEBSMetadata(string filePath)
{
return ResourceDetectorUtils.DeserializeFromFile<AWSEBSMetadataModel>(filePath);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ public class AWSEC2ResourceDetector : IResourceDetector

try
{
var token = this.GetAWSEC2Token();
var identity = this.GetAWSEC2Identity(token);
var hostName = this.GetAWSEC2HostName(token);
var token = GetAWSEC2Token();
var identity = GetAWSEC2Identity(token);
var hostName = GetAWSEC2HostName(token);

resourceAttributes = this.ExtractResourceAttributes(identity, hostName);
resourceAttributes = ExtractResourceAttributes(identity, hostName);
}
catch (Exception ex)
{
Expand All @@ -55,7 +55,7 @@ public class AWSEC2ResourceDetector : IResourceDetector
return resourceAttributes;
}

internal List<KeyValuePair<string, object?>> ExtractResourceAttributes(AWSEC2IdentityDocumentModel? identity, string hostName)
internal static List<KeyValuePair<string, object?>> ExtractResourceAttributes(AWSEC2IdentityDocumentModel? identity, string hostName)
{
var resourceAttributes = new List<KeyValuePair<string, object?>>()
{
Expand All @@ -72,30 +72,30 @@ public class AWSEC2ResourceDetector : IResourceDetector
return resourceAttributes;
}

internal AWSEC2IdentityDocumentModel? DeserializeResponse(string response)
internal static AWSEC2IdentityDocumentModel? DeserializeResponse(string response)
{
return ResourceDetectorUtils.DeserializeFromString<AWSEC2IdentityDocumentModel>(response);
}

private string GetAWSEC2Token()
private static string GetAWSEC2Token()
{
return ResourceDetectorUtils.SendOutRequest(AWSEC2MetadataTokenUrl, "PUT", new KeyValuePair<string, string>(AWSEC2MetadataTokenTTLHeader, "60")).Result;
}

private AWSEC2IdentityDocumentModel? GetAWSEC2Identity(string token)
private static AWSEC2IdentityDocumentModel? GetAWSEC2Identity(string token)
{
var identity = this.GetIdentityResponse(token);
var identityDocument = this.DeserializeResponse(identity);
var identity = GetIdentityResponse(token);
var identityDocument = DeserializeResponse(identity);

return identityDocument;
}

private string GetIdentityResponse(string token)
private static string GetIdentityResponse(string token)
{
return ResourceDetectorUtils.SendOutRequest(AWSEC2IdentityDocumentUrl, "GET", new KeyValuePair<string, string>(AWSEC2MetadataTokenHeader, token)).Result;
}

private string GetAWSEC2HostName(string token)
private static string GetAWSEC2HostName(string token)
{
return ResourceDetectorUtils.SendOutRequest(AWSEC2HostNameUrl, "GET", new KeyValuePair<string, string>(AWSEC2MetadataTokenHeader, token)).Result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ public class AWSECSResourceDetector : IResourceDetector
{
List<KeyValuePair<string, object?>>? resourceAttributes = null;

if (!this.IsECSProcess())
if (!IsECSProcess())
{
return resourceAttributes;
}

try
{
var containerId = this.GetECSContainerId(AWSECSMetadataPath);
var containerId = GetECSContainerId(AWSECSMetadataPath);

resourceAttributes = this.ExtractResourceAttributes(containerId);
resourceAttributes = ExtractResourceAttributes(containerId);
}
catch (Exception ex)
{
Expand All @@ -55,7 +55,7 @@ public class AWSECSResourceDetector : IResourceDetector
return resourceAttributes;
}

internal List<KeyValuePair<string, object?>> ExtractResourceAttributes(string? containerId)
internal static List<KeyValuePair<string, object?>> ExtractResourceAttributes(string? containerId)
{
var resourceAttributes = new List<KeyValuePair<string, object?>>()
{
Expand All @@ -67,7 +67,7 @@ public class AWSECSResourceDetector : IResourceDetector
return resourceAttributes;
}

internal string? GetECSContainerId(string path)
internal static string? GetECSContainerId(string path)
{
string? containerId = null;

Expand All @@ -87,7 +87,7 @@ public class AWSECSResourceDetector : IResourceDetector
return containerId;
}

internal bool IsECSProcess()
internal static bool IsECSProcess()
{
return Environment.GetEnvironmentVariable(AWSECSMetadataURLKey) != null || Environment.GetEnvironmentVariable(AWSECSMetadataURLV4Key) != null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,20 @@ public class AWSEKSResourceDetector : IResourceDetector
/// <returns>List of key-value pairs of resource attributes.</returns>
public IEnumerable<KeyValuePair<string, object?>>? Detect()
{
var credentials = this.GetEKSCredentials(AWSEKSCredentialPath);
var httpClientHandler = Handler.Create(AWSEKSCertificatePath);
var credentials = GetEKSCredentials(AWSEKSCredentialPath);
using var httpClientHandler = Handler.Create(AWSEKSCertificatePath);

if (credentials == null || !this.IsEKSProcess(credentials, httpClientHandler))
if (credentials == null || !IsEKSProcess(credentials, httpClientHandler))
{
return null;
}

return this.ExtractResourceAttributes(
this.GetEKSClusterName(credentials, httpClientHandler),
this.GetEKSContainerId(AWSEKSMetadataFilePath));
return ExtractResourceAttributes(
GetEKSClusterName(credentials, httpClientHandler),
GetEKSContainerId(AWSEKSMetadataFilePath));
}

internal List<KeyValuePair<string, object?>> ExtractResourceAttributes(string? clusterName, string? containerId)
internal static List<KeyValuePair<string, object?>> ExtractResourceAttributes(string? clusterName, string? containerId)
{
var resourceAttributes = new List<KeyValuePair<string, object?>>()
{
Expand All @@ -74,11 +74,11 @@ public class AWSEKSResourceDetector : IResourceDetector
return resourceAttributes;
}

internal string? GetEKSCredentials(string path)
internal static string? GetEKSCredentials(string path)
{
try
{
StringBuilder stringBuilder = new StringBuilder();
var stringBuilder = new StringBuilder();

using (var streamReader = ResourceDetectorUtils.GetStreamReader(path))
{
Expand All @@ -88,7 +88,9 @@ public class AWSEKSResourceDetector : IResourceDetector
}
}

return "Bearer " + stringBuilder.ToString();
stringBuilder.Insert(0, "Bearer ");

return stringBuilder.ToString();
}
catch (Exception ex)
{
Expand All @@ -98,7 +100,7 @@ public class AWSEKSResourceDetector : IResourceDetector
return null;
}

internal string? GetEKSContainerId(string path)
internal static string? GetEKSContainerId(string path)
{
try
{
Expand All @@ -122,17 +124,17 @@ public class AWSEKSResourceDetector : IResourceDetector
return null;
}

internal AWSEKSClusterInformationModel? DeserializeResponse(string response)
internal static AWSEKSClusterInformationModel? DeserializeResponse(string response)
{
return ResourceDetectorUtils.DeserializeFromString<AWSEKSClusterInformationModel>(response);
}

private string? GetEKSClusterName(string credentials, HttpClientHandler? httpClientHandler)
private static string? GetEKSClusterName(string credentials, HttpClientHandler? httpClientHandler)
{
try
{
var clusterInfo = this.GetEKSClusterInfo(credentials, httpClientHandler);
return this.DeserializeResponse(clusterInfo)?.Data?.ClusterName;
var clusterInfo = GetEKSClusterInfo(credentials, httpClientHandler);
return DeserializeResponse(clusterInfo)?.Data?.ClusterName;
}
catch (Exception ex)
{
Expand All @@ -142,7 +144,7 @@ public class AWSEKSResourceDetector : IResourceDetector
return null;
}

private bool IsEKSProcess(string credentials, HttpClientHandler? httpClientHandler)
private static bool IsEKSProcess(string credentials, HttpClientHandler? httpClientHandler)
{
string? awsAuth = null;
try
Expand All @@ -157,7 +159,7 @@ private bool IsEKSProcess(string credentials, HttpClientHandler? httpClientHandl
return !string.IsNullOrEmpty(awsAuth);
}

private string GetEKSClusterInfo(string credentials, HttpClientHandler? httpClientHandler)
private static string GetEKSClusterInfo(string credentials, HttpClientHandler? httpClientHandler)
{
return ResourceDetectorUtils.SendOutRequest(AWSClusterInfoUrl, "GET", new KeyValuePair<string, string>("Authorization", credentials), httpClientHandler).Result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class AWSLambdaResourceDetector : IResourceDetector

try
{
resourceAttributes = this.ExtractResourceAttributes();
resourceAttributes = ExtractResourceAttributes();
}
catch (Exception ex)
{
Expand All @@ -48,7 +48,7 @@ public class AWSLambdaResourceDetector : IResourceDetector
return resourceAttributes;
}

internal List<KeyValuePair<string, object?>> ExtractResourceAttributes()
internal static List<KeyValuePair<string, object?>> ExtractResourceAttributes()
{
var resourceAttributes = new List<KeyValuePair<string, object?>>()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,27 @@ private static bool LoadCertificateToTrustedCollection(X509Certificate2Collectio
}
}

private static bool HasCommonCertificate(X509Chain chain, X509Certificate2Collection? collection)
{
if (collection == null)
{
return false;
}

foreach (var chainElement in chain.ChainElements)
{
foreach (var certificate in collection)
{
if (Enumerable.SequenceEqual(chainElement.Certificate.GetPublicKey(), certificate.GetPublicKey()))
{
return true;
}
}
}

return false;
}

private bool ValidateCertificate(X509Certificate2 cert, X509Chain chain, SslPolicyErrors errors)
{
var isSslPolicyPassed = errors == SslPolicyErrors.None ||
Expand Down Expand Up @@ -119,7 +140,7 @@ private bool ValidateCertificate(X509Certificate2 cert, X509Chain chain, SslPoli
}

// check if at least one certificate in the chain is in our trust list
var isTrusted = this.HasCommonCertificate(chain, this.trustedCertificates);
var isTrusted = HasCommonCertificate(chain, this.trustedCertificates);
if (!isTrusted)
{
var serverCertificates = string.Empty;
Expand All @@ -144,25 +165,4 @@ private bool ValidateCertificate(X509Certificate2 cert, X509Chain chain, SslPoli

return isSslPolicyPassed && isValidChain && isTrusted;
}

private bool HasCommonCertificate(X509Chain chain, X509Certificate2Collection? collection)
{
if (collection == null)
{
return false;
}

foreach (var chainElement in chain.ChainElements)
{
foreach (var certificate in collection)
{
if (Enumerable.SequenceEqual(chainElement.Certificate.GetPublicKey(), certificate.GetPublicKey()))
{
return true;
}
}
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources;
/// <summary>
/// Class for resource detector utils.
/// </summary>
#pragma warning disable CA1052
public class ResourceDetectorUtils
#pragma warning restore CA1052
{
internal static async Task<string> SendOutRequest(string url, string method, KeyValuePair<string, string> header, HttpClientHandler? handler = null)
{
Expand All @@ -37,11 +39,13 @@ internal static async Task<string> SendOutRequest(string url, string method, Key
httpRequestMessage.Method = new HttpMethod(method);
httpRequestMessage.Headers.Add(header.Key, header.Value);

#pragma warning disable CA2000 // Dispose objects before losing scope
var httpClient = handler == null ? new HttpClient() : new HttpClient(handler);
using (var response = await httpClient.SendAsync(httpRequestMessage))
#pragma warning restore CA2000 // Dispose objects before losing scope
using (var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
Expand Down
Loading

0 comments on commit 7fda8d4

Please sign in to comment.