-
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
MA0153 Do not log symbols decorated with DataClassificationAttribute …
…directly
- Loading branch information
Showing
9 changed files
with
596 additions
and
215 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# MA0153 - Do not log symbols decorated with DataClassificationAttribute directly | ||
|
||
Detects when a log parameter is decorated with an attribute that inherits from `Microsoft.Extensions.Compliance.Classification.DataClassificationAttribute`. | ||
Most of the time, these values should not be used with `[LogProperties]` to redact values. | ||
|
||
````c# | ||
using Microsoft.Extensions.Logging; | ||
|
||
ILogger logger; | ||
|
||
// non-compliant as Prop is decorated with an attribute that inherits from DataClassificationAttribute | ||
logger.LogInformation("{Prop}", new Dummy().Prop); | ||
|
||
class Dummy | ||
{ | ||
[PiiAttribute] | ||
public string Prop { get; set; } | ||
} | ||
|
||
class PiiAttribute : Microsoft.Extensions.Compliance.Classification.DataClassificationAttribute | ||
{ | ||
public TaxonomyAttribute() : base(default) | ||
{ | ||
} | ||
} | ||
```` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
159 changes: 159 additions & 0 deletions
159
src/Meziantou.Analyzer/Rules/DoNotLogClassifiedDataAnalyzer.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace Meziantou.Analyzer.Rules; | ||
|
||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public sealed class DoNotLogClassifiedDataAnalyzer : DiagnosticAnalyzer | ||
{ | ||
private static readonly DiagnosticDescriptor Rule = new( | ||
RuleIdentifiers.DoNotLogClassifiedData, | ||
title: "Do not log symbols decorated with DataClassificationAttribute directly", | ||
messageFormat: "Do not log symbols decorated with DataClassificationAttribute directly", | ||
RuleCategories.Design, | ||
DiagnosticSeverity.Warning, | ||
isEnabledByDefault: true, | ||
description: "", | ||
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.DoNotLogClassifiedData)); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.EnableConcurrentExecution(); | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); | ||
context.RegisterCompilationStartAction(context => | ||
{ | ||
var ctx = new AnalyzerContext(context.Compilation); | ||
if (!ctx.IsValid) | ||
return; | ||
|
||
context.RegisterOperationAction(ctx.AnalyzeInvocationDeclaration, OperationKind.Invocation); | ||
}); | ||
} | ||
|
||
private sealed class AnalyzerContext | ||
{ | ||
public AnalyzerContext(Compilation compilation) | ||
{ | ||
LoggerSymbol = compilation.GetBestTypeByMetadataName("Microsoft.Extensions.Logging.ILogger"); | ||
if (LoggerSymbol is null) | ||
return; | ||
|
||
LoggerExtensionsSymbol = compilation.GetBestTypeByMetadataName("Microsoft.Extensions.Logging.LoggerExtensions"); | ||
LoggerMessageSymbol = compilation.GetBestTypeByMetadataName("Microsoft.Extensions.Logging.LoggerMessage"); | ||
StructuredLogFieldAttributeSymbol = compilation.GetBestTypeByMetadataName("Meziantou.Analyzer.Annotations.StructuredLogFieldAttribute"); | ||
|
||
DataClassificationAttributeSymbol = compilation.GetBestTypeByMetadataName("Microsoft.Extensions.Compliance.Classification.DataClassificationAttribute"); | ||
} | ||
|
||
public INamedTypeSymbol? StructuredLogFieldAttributeSymbol { get; private set; } | ||
|
||
public INamedTypeSymbol? LoggerSymbol { get; } | ||
public INamedTypeSymbol? LoggerExtensionsSymbol { get; } | ||
public INamedTypeSymbol? LoggerMessageSymbol { get; } | ||
|
||
public INamedTypeSymbol? DataClassificationAttributeSymbol { get; } | ||
|
||
public bool IsValid => DataClassificationAttributeSymbol is not null && LoggerSymbol is not null; | ||
|
||
public void AnalyzeInvocationDeclaration(OperationAnalysisContext context) | ||
{ | ||
var operation = (IInvocationOperation)context.Operation; | ||
if (operation.TargetMethod.ContainingType.IsEqualTo(LoggerExtensionsSymbol) && FindLogParameters(operation.TargetMethod, out var argumentsParameter)) | ||
{ | ||
foreach (var argument in operation.Arguments) | ||
{ | ||
var parameter = argument.Parameter; | ||
if (parameter is null) | ||
continue; | ||
|
||
if (parameter.Equals(argumentsParameter, SymbolEqualityComparer.Default)) | ||
{ | ||
if (argument.ArgumentKind == ArgumentKind.ParamArray && argument.Value is IArrayCreationOperation arrayCreation && arrayCreation.Initializer is not null) | ||
{ | ||
ValidateDataClassification(context, arrayCreation.Initializer.ElementValues); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
private void ValidateDataClassification(DiagnosticReporter diagnosticReporter, IEnumerable<IOperation> operations) | ||
{ | ||
foreach (var operation in operations) | ||
{ | ||
ValidateDataClassification(diagnosticReporter, operation); | ||
} | ||
} | ||
|
||
private void ValidateDataClassification(DiagnosticReporter diagnosticReporter, IOperation operation) | ||
{ | ||
ValidateDataClassification(diagnosticReporter, operation, operation, DataClassificationAttributeSymbol!); | ||
|
||
static void ValidateDataClassification(DiagnosticReporter diagnosticReporter, IOperation operation, IOperation reportOperation, INamedTypeSymbol dataClassificationAttributeSymbol) | ||
{ | ||
operation = operation.UnwrapConversionOperations(); | ||
if (operation is IParameterReferenceOperation parameterReferenceOperation) | ||
{ | ||
if (parameterReferenceOperation.Parameter.HasAttribute(dataClassificationAttributeSymbol, inherits: true)) | ||
{ | ||
diagnosticReporter.ReportDiagnostic(Rule, reportOperation); | ||
} | ||
} | ||
else if (operation is IPropertyReferenceOperation propertyReferenceOperation) | ||
{ | ||
if (propertyReferenceOperation.Property.HasAttribute(dataClassificationAttributeSymbol, inherits: true)) | ||
{ | ||
diagnosticReporter.ReportDiagnostic(Rule, reportOperation); | ||
} | ||
} | ||
else if (operation is IFieldReferenceOperation fieldReferenceOperation) | ||
{ | ||
if (fieldReferenceOperation.Field.HasAttribute(dataClassificationAttributeSymbol, inherits: true)) | ||
{ | ||
diagnosticReporter.ReportDiagnostic(Rule, reportOperation); | ||
} | ||
} | ||
else if (operation is IArrayElementReferenceOperation arrayElementReferenceOperation) | ||
{ | ||
ValidateDataClassification(diagnosticReporter, arrayElementReferenceOperation.ArrayReference, reportOperation, dataClassificationAttributeSymbol); | ||
} | ||
} | ||
} | ||
|
||
private static bool FindLogParameters(IMethodSymbol methodSymbol, out IParameterSymbol? arguments) | ||
{ | ||
IParameterSymbol? message = null; | ||
arguments = null; | ||
foreach (var parameter in methodSymbol.Parameters) | ||
{ | ||
if (parameter.Type.IsString() && | ||
(string.Equals(parameter.Name, "message", StringComparison.Ordinal) || | ||
string.Equals(parameter.Name, "messageFormat", StringComparison.Ordinal) || | ||
string.Equals(parameter.Name, "formatString", StringComparison.Ordinal))) | ||
{ | ||
message = parameter; | ||
} | ||
// When calling logger.BeginScope("{Param}") generic overload would be selected | ||
else if (parameter.Type.SpecialType == SpecialType.System_String && | ||
methodSymbol.Name is "BeginScope" && | ||
parameter.Name is "state") | ||
{ | ||
message = parameter; | ||
} | ||
else if (parameter.IsParams && | ||
parameter.Name is "args") | ||
{ | ||
arguments = parameter; | ||
} | ||
} | ||
|
||
return message is not null; | ||
} | ||
} | ||
} |
Oops, something went wrong.