66 lines
1.8 KiB
C#
66 lines
1.8 KiB
C#
using Microsoft.CodeAnalysis;
|
|
using Microsoft.CodeAnalysis.Diagnostics;
|
|
using Microsoft.CodeAnalysis.Operations;
|
|
using System;
|
|
|
|
namespace StellaOps.AirGap.Policy.Analyzers;
|
|
|
|
public sealed partial class HttpClientUsageAnalyzer
|
|
{
|
|
private static void AnalyzeObjectCreation(OperationAnalysisContext context)
|
|
{
|
|
if (context.Operation is not IObjectCreationOperation creation)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var httpClientSymbol = context.Compilation.GetTypeByMetadataName(HttpClientMetadataName);
|
|
if (httpClientSymbol is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var createdType = creation.Type;
|
|
if (createdType is null || !SymbolEqualityComparer.Default.Equals(createdType, httpClientSymbol))
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (IsWithinAllowedAssembly(context.ContainingSymbol))
|
|
{
|
|
return;
|
|
}
|
|
|
|
context.ReportDiagnostic(CreateDiagnostic(creation.Syntax.GetLocation()));
|
|
}
|
|
|
|
private static bool IsWithinAllowedAssembly(ISymbol? symbol)
|
|
{
|
|
var containingAssembly = symbol?.ContainingAssembly;
|
|
if (containingAssembly is null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var assemblyName = containingAssembly.Name;
|
|
if (string.IsNullOrEmpty(assemblyName))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (string.Equals(assemblyName, "StellaOps.AirGap.Policy", StringComparison.Ordinal))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (assemblyName.EndsWith(".Tests", StringComparison.OrdinalIgnoreCase) ||
|
|
assemblyName.EndsWith(".Test", StringComparison.OrdinalIgnoreCase) ||
|
|
assemblyName.EndsWith(".Testing", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|