< Summary

Information
Class: AsiBackbone.Analyzers.LocalDevelopmentSigningProductionAnalyzer
Assembly: AsiBackbone.Analyzers
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Analyzers/LocalDevelopmentSigningProductionAnalyzer.cs
Line coverage
97%
Covered lines: 139
Uncovered lines: 3
Coverable lines: 142
Total lines: 356
Line coverage: 97.8%
Branch coverage
91%
Covered branches: 125
Total branches: 136
Branch coverage: 91.9%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

/home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Analyzers/LocalDevelopmentSigningProductionAnalyzer.cs

#LineLine coverage
 1using System.Collections.Immutable;
 2using Microsoft.CodeAnalysis;
 3using Microsoft.CodeAnalysis.Diagnostics;
 4using Microsoft.CodeAnalysis.Operations;
 5
 6namespace AsiBackbone.Analyzers;
 7
 8/// <summary>
 9/// Reports local-development signing providers that are wired inside a production environment branch, or wired
 10/// without any environment guard.
 11/// </summary>
 12/// <remarks>
 13/// Local-development signing generates an in-process key that is never persisted, so it is suitable only for tests,
 14/// samples, and local proof paths. Production hosts should use a host-owned key provider instead.
 15/// </remarks>
 16[DiagnosticAnalyzer(LanguageNames.CSharp)]
 17public sealed class LocalDevelopmentSigningProductionAnalyzer : DiagnosticAnalyzer
 18{
 19    /// <summary>
 20    /// Reports local-development signing used inside a production environment branch.
 21    /// </summary>
 22    public const string DiagnosticId = "ASIB002";
 23
 24    /// <summary>
 25    /// Reports local-development signing wired with no environment guard at all.
 26    /// </summary>
 27    public const string UnguardedDiagnosticId = "ASIB003";
 28
 29    private const string LocalDevelopmentNamespace = "AsiBackbone.Signing.LocalDevelopment";
 30
 131    private static readonly DiagnosticDescriptor Rule = new(
 132        DiagnosticId,
 133        "Do not wire local-development signing in production branches",
 134        "Local-development signing type '{0}' is used inside a production environment branch; use a host-owned productio
 135        "AsiBackbone.ProductionSafety",
 136        DiagnosticSeverity.Warning,
 137        isEnabledByDefault: true,
 138        description: "LocalDevelopment signing providers generate in-process keys for tests, samples, and local proof pa
 39
 40    /// <remarks>
 41    /// <see cref="Rule" /> only fires on a call the analyzer can see inside a production branch, so an unconditional
 42    /// registration — the shape that actually reaches production — was never reported. The runtime guard in
 43    /// <c>UseLocalDevelopmentSigning</c> throws in Production; this rule surfaces the same problem at build time.
 44    /// </remarks>
 145    private static readonly DiagnosticDescriptor UnguardedRule = new(
 146        UnguardedDiagnosticId,
 147        "Guard local-development signing by environment",
 148        "Local-development signing type '{0}' is wired without an environment guard; it will be registered in whichever 
 149        "AsiBackbone.ProductionSafety",
 150        DiagnosticSeverity.Warning,
 151        isEnabledByDefault: true,
 152        description: "LocalDevelopment signing providers generate an in-process key that is never persisted, so artifact
 53
 54    /// <summary>
 55    /// Gets the diagnostics supported by this analyzer.
 56    /// </summary>
 3257    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule, UnguardedRule];
 58
 59    /// <summary>
 60    /// Initializes the analyzer and registers operation analysis for invocations and object creations that reference
 61    /// local-development signing types.
 62    /// </summary>
 63    /// <param name="context">The analysis context used to register analyzer actions.</param>
 64    public override void Initialize(AnalysisContext context)
 65    {
 3266        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
 3267        context.EnableConcurrentExecution();
 3268        context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation);
 3269        context.RegisterOperationAction(AnalyzeObjectCreation, OperationKind.ObjectCreation);
 3270    }
 71
 72    private static void AnalyzeInvocation(OperationAnalysisContext context)
 73    {
 4774        var invocation = (IInvocationOperation)context.Operation;
 75
 4776        if (IsSuppressedByHostMarker(context.ContainingSymbol)
 4777            || IsNestedInsideInvocationThatAlreadyReferencesLocalDevelopment(invocation))
 78        {
 779            return;
 80        }
 81
 4082        bool insideProductionBranch = IsInsideProductionBranch(invocation);
 83
 4084        if (!insideProductionBranch && IsInsideEnvironmentConditional(invocation))
 85        {
 1186            return;
 87        }
 88
 2989        ITypeSymbol? localDevelopmentType = FindReferencedLocalDevelopmentType(invocation);
 2990        if (localDevelopmentType is null)
 91        {
 1292            return;
 93        }
 94
 1795        context.ReportDiagnostic(
 1796            Diagnostic.Create(
 1797                insideProductionBranch ? Rule : UnguardedRule,
 1798                invocation.Syntax.GetLocation(),
 1799                localDevelopmentType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
 17100    }
 101
 102    private static void AnalyzeObjectCreation(OperationAnalysisContext context)
 103    {
 71104        var objectCreation = (IObjectCreationOperation)context.Operation;
 105
 71106        if (IsSuppressedByHostMarker(context.ContainingSymbol) || !IsInsideProductionBranch(objectCreation))
 107        {
 69108            return;
 109        }
 110
 2111        ITypeSymbol? localDevelopmentType = FindLocalDevelopmentType(objectCreation.Type);
 2112        if (localDevelopmentType is null)
 113        {
 1114            return;
 115        }
 116
 1117        context.ReportDiagnostic(
 1118            Diagnostic.Create(
 1119                Rule,
 1120                objectCreation.Syntax.GetLocation(),
 1121                localDevelopmentType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
 1122    }
 123
 124    private static bool IsNestedInsideInvocationThatAlreadyReferencesLocalDevelopment(IInvocationOperation invocation)
 125    {
 42126        return invocation.Parent is IArgumentOperation { Parent: IInvocationOperation parentInvocation }
 42127            && FindReferencedLocalDevelopmentType(parentInvocation) is not null;
 128    }
 129
 130    private static ITypeSymbol? FindReferencedLocalDevelopmentType(IInvocationOperation invocation)
 131    {
 31132        ITypeSymbol? containingType = FindLocalDevelopmentType(invocation.TargetMethod.ContainingType);
 31133        if (containingType is not null)
 134        {
 0135            return containingType;
 136        }
 137
 84138        foreach (ITypeSymbol typeArgument in invocation.TargetMethod.TypeArguments)
 139        {
 20140            ITypeSymbol? localDevelopmentType = FindLocalDevelopmentType(typeArgument);
 20141            if (localDevelopmentType is not null)
 142            {
 18143                return localDevelopmentType;
 144            }
 145        }
 146
 56147        foreach (IArgumentOperation argument in invocation.Arguments)
 148        {
 15149            ITypeSymbol? localDevelopmentType = FindLocalDevelopmentType(argument.Value.Type);
 15150            if (localDevelopmentType is not null)
 151            {
 0152                return localDevelopmentType;
 153            }
 154        }
 155
 13156        return FindLocalDevelopmentType(invocation.Type);
 157    }
 158
 159    private static ITypeSymbol? FindLocalDevelopmentType(ITypeSymbol? type)
 160    {
 83161        if (type is null)
 162        {
 0163            return null;
 164        }
 165
 83166        if (type is INamedTypeSymbol namedType && namedType.IsGenericType)
 167        {
 7168            foreach (ITypeSymbol typeArgument in namedType.TypeArguments)
 169            {
 2170                ITypeSymbol? localDevelopmentType = FindLocalDevelopmentType(typeArgument);
 2171                if (localDevelopmentType is not null)
 172                {
 1173                    return localDevelopmentType;
 174                }
 175            }
 176        }
 177
 82178        string namespaceName = type.ContainingNamespace?.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat) ?
 82179        return namespaceName.Equals(LocalDevelopmentNamespace, StringComparison.Ordinal)
 82180            ? type
 82181            : null;
 182    }
 183
 184    private static bool IsInsideProductionBranch(IOperation operation)
 185    {
 778186        for (IOperation? current = operation.Parent; current is not null; current = current.Parent)
 187        {
 300188            if (current is IConditionalOperation conditionalOperation
 300189                && IsProductionLikeCondition(conditionalOperation.Condition))
 190            {
 18191                return true;
 192            }
 193        }
 194
 89195        return false;
 196    }
 197
 198    /// <summary>
 199    /// Determines whether the operation sits inside any conditional that tests the host environment.
 200    /// </summary>
 201    /// <remarks>
 202    /// A registration guarded by an environment check — for either the production or the non-production side — is a
 203    /// deliberate choice the host has already made. Only registrations with no environment check at all are reported by
 204    /// <see cref="UnguardedRule" />.
 205    /// </remarks>
 206    private static bool IsInsideEnvironmentConditional(IOperation operation)
 207    {
 178208        for (IOperation? current = operation.Parent; current is not null; current = current.Parent)
 209        {
 76210            if (current is IConditionalOperation conditionalOperation
 76211                && ConditionReferencesEnvironment(conditionalOperation.Condition))
 212            {
 11213                return true;
 214            }
 215        }
 216
 13217        return false;
 218    }
 219
 220    private static bool ConditionReferencesEnvironment(IOperation operation)
 221    {
 24222        operation = Unwrap(operation);
 223
 24224        if (IsEnvironmentNameReference(operation))
 225        {
 2226            return true;
 227        }
 228
 229        switch (operation)
 230        {
 231            case IInvocationOperation invocationOperation:
 12232                IMethodSymbol method = invocationOperation.TargetMethod.ReducedFrom ?? invocationOperation.TargetMethod;
 12233                string namespaceName = method.ContainingNamespace?.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessag
 234
 12235                return namespaceName.Equals("Microsoft.Extensions.Hosting", StringComparison.Ordinal)
 12236                    || InvocationComparesEnvironmentNameToProduction(invocationOperation)
 12237                    || IsEnvironmentNameReference(invocationOperation.Instance);
 238
 239            case IBinaryOperation binaryOperation:
 3240                return ConditionReferencesEnvironment(binaryOperation.LeftOperand)
 3241                    || ConditionReferencesEnvironment(binaryOperation.RightOperand);
 242
 243            case IUnaryOperation unaryOperation:
 2244                return ConditionReferencesEnvironment(unaryOperation.Operand);
 245
 246            case IPropertyReferenceOperation propertyReference:
 3247                return propertyReference.Property.Name.Contains("Environment", StringComparison.Ordinal);
 248
 249            default:
 2250                return false;
 251        }
 252    }
 253
 254    private static bool IsProductionLikeCondition(IOperation operation)
 255    {
 36256        operation = Unwrap(operation);
 257
 36258        return operation switch
 36259        {
 26260            IInvocationOperation invocationOperation => IsProductionInvocation(invocationOperation)
 26261                || InvocationComparesEnvironmentNameToProduction(invocationOperation),
 5262            IBinaryOperation binaryOperation => BinaryComparesEnvironmentNameToProduction(binaryOperation),
 5263            _ => false
 36264        };
 265    }
 266
 267    private static bool IsProductionInvocation(IInvocationOperation invocation)
 268    {
 26269        IMethodSymbol method = invocation.TargetMethod.ReducedFrom ?? invocation.TargetMethod;
 26270        string namespaceName = method.ContainingNamespace?.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)
 271
 26272        return method.Name.Equals("IsProduction", StringComparison.Ordinal)
 26273            && namespaceName.Equals("Microsoft.Extensions.Hosting", StringComparison.Ordinal);
 274    }
 275
 276    private static bool InvocationComparesEnvironmentNameToProduction(IInvocationOperation invocation)
 277    {
 20278        if (!invocation.TargetMethod.Name.Equals("Equals", StringComparison.Ordinal))
 279        {
 8280            return false;
 281        }
 282
 12283        bool hasEnvironmentName = IsEnvironmentNameReference(invocation.Instance);
 12284        bool hasProductionConstant = false;
 285
 56286        foreach (IArgumentOperation argument in invocation.Arguments)
 287        {
 16288            IOperation value = Unwrap(argument.Value);
 16289            hasEnvironmentName = hasEnvironmentName || IsEnvironmentNameReference(value);
 16290            hasProductionConstant = hasProductionConstant || IsProductionConstant(value);
 291        }
 292
 12293        return hasEnvironmentName && hasProductionConstant;
 294    }
 295
 296    private static bool BinaryComparesEnvironmentNameToProduction(IBinaryOperation binaryOperation)
 297    {
 5298        if (binaryOperation.OperatorKind != BinaryOperatorKind.Equals)
 299        {
 2300            return false;
 301        }
 302
 3303        IOperation left = Unwrap(binaryOperation.LeftOperand);
 3304        IOperation right = Unwrap(binaryOperation.RightOperand);
 305
 3306        return (IsEnvironmentNameReference(left) && IsProductionConstant(right))
 3307            || (IsEnvironmentNameReference(right) && IsProductionConstant(left));
 308    }
 309
 310    private static bool IsEnvironmentNameReference(IOperation? operation)
 311    {
 53312        operation = operation is null ? null : Unwrap(operation);
 313
 53314        return operation is IPropertyReferenceOperation propertyReference
 53315            && propertyReference.Property.Name.Equals("EnvironmentName", StringComparison.Ordinal);
 316    }
 317
 318    private static bool IsProductionConstant(IOperation operation)
 319    {
 17320        return operation.ConstantValue.HasValue
 17321            && operation.ConstantValue.Value is string value
 17322            && value.Equals("Production", StringComparison.OrdinalIgnoreCase);
 323    }
 324
 325    private static IOperation Unwrap(IOperation operation)
 326    {
 135327        while (operation is IConversionOperation conversionOperation)
 328        {
 4329            operation = conversionOperation.Operand;
 4330        }
 331
 131332        return operation;
 333    }
 334
 335    private static bool IsSuppressedByHostMarker(ISymbol? symbol)
 336    {
 396337        for (ISymbol? current = symbol; current is not null; current = current.ContainingSymbol)
 338        {
 469339            foreach (AttributeData attribute in current.GetAttributes())
 340            {
 41341                string? attributeName = attribute.AttributeClass?.Name;
 41342                if (attributeName is "AsiBackboneProductionConfigurationReviewed" or "AsiBackboneProductionConfiguration
 343                {
 9344                    return true;
 345                }
 346            }
 347
 189348            if (current is INamedTypeSymbol)
 349            {
 350                break;
 351            }
 352        }
 353
 109354        return false;
 355    }
 356}