|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.Linq; |
| 8 | +using Microsoft.AspNetCore.App.Analyzers.Infrastructure; |
| 9 | +using Microsoft.CodeAnalysis; |
| 10 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 11 | + |
| 12 | +namespace Microsoft.AspNetCore.Analyzers.Mvc; |
| 13 | + |
| 14 | +using WellKnownType = WellKnownTypeData.WellKnownType; |
| 15 | + |
| 16 | +public partial class MvcAnalyzer |
| 17 | +{ |
| 18 | + /// <summary> |
| 19 | + /// This tries to detect [Authorize] attributes that are unwittingly overridden by [AllowAnonymous] attributes that are "farther" away from a controller. |
| 20 | + /// </summary> |
| 21 | + /// <remarks> |
| 22 | + /// This might report the same [Authorize] attribute multiple times if it's on a shared base type, but we'd have to disable parallelization of the |
| 23 | + /// entire MvcAnalyzer to avoid that. We assume that this scenario is rare enough and that overreporting is benign enough to not warrant the performance hit. |
| 24 | + /// See AuthorizeOnControllerBaseWithMultipleChildren_AllowAnonymousOnControllerBaseBaseType_HasMultipleDiagnostics. |
| 25 | + /// </remarks> |
| 26 | + private static void DetectOverriddenAuthorizeAttributeOnController(SymbolAnalysisContext context, WellKnownTypes wellKnownTypes, |
| 27 | + INamedTypeSymbol controllerSymbol, List<AttributeInfo> authorizeAttributes, out string? allowAnonClass) |
| 28 | + { |
| 29 | + Debug.Assert(authorizeAttributes.Count is 0); |
| 30 | + |
| 31 | + var isCheckingBaseType = false; |
| 32 | + allowAnonClass = null; |
| 33 | + |
| 34 | + foreach (var currentClass in controllerSymbol.GetTypeHierarchy()) |
| 35 | + { |
| 36 | + FindAuthorizeAndAllowAnonymous(wellKnownTypes, currentClass, isCheckingBaseType, authorizeAttributes, out var foundAllowAnonymous); |
| 37 | + if (foundAllowAnonymous) |
| 38 | + { |
| 39 | + // Anything we find after this would be farther away, so we can short circuit. |
| 40 | + ReportOverriddenAuthorizeAttributeDiagnosticsIfAny(context, authorizeAttributes, currentClass.Name); |
| 41 | + // Keep track of the nearest class with [AllowAnonymous] for later reporting of action-level [Authorize] attributes. |
| 42 | + allowAnonClass = currentClass.Name; |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + isCheckingBaseType = true; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /// <summary> |
| 51 | + /// This tries to detect [Authorize] attributes that are unwittingly overridden by [AllowAnonymous] attributes that are "farther" away from a controller action. |
| 52 | + /// To do so, it first searches the action method and then the controller class. It repeats this process for each virtual method the action may override and for |
| 53 | + /// each base class the controller may inherit from. Since it searches for the attributes closest to the action first, it short circuits as soon as [AllowAnonymous] is found. |
| 54 | + /// If it has already detected a closer [Authorize] attribute, it reports a diagnostic at the [Authorize] attribute's location indicating that it will be overridden. |
| 55 | + /// </summary> |
| 56 | + private static void DetectOverriddenAuthorizeAttributeOnAction(SymbolAnalysisContext context, WellKnownTypes wellKnownTypes, |
| 57 | + IMethodSymbol actionSymbol, List<AttributeInfo> authorizeAttributes, string? allowAnonClass) |
| 58 | + { |
| 59 | + Debug.Assert(authorizeAttributes.Count is 0); |
| 60 | + |
| 61 | + var isCheckingBaseType = false; |
| 62 | + var currentMethod = actionSymbol; |
| 63 | + |
| 64 | + foreach (var currentClass in actionSymbol.ContainingType.GetTypeHierarchy()) |
| 65 | + { |
| 66 | + bool foundAllowAnonymous; |
| 67 | + |
| 68 | + if (currentMethod is not null && IsSameSymbol(currentMethod.ContainingType, currentClass)) |
| 69 | + { |
| 70 | + FindAuthorizeAndAllowAnonymous(wellKnownTypes, currentMethod, isCheckingBaseType, authorizeAttributes, out foundAllowAnonymous); |
| 71 | + if (foundAllowAnonymous) |
| 72 | + { |
| 73 | + // [AllowAnonymous] was found on the action method. Anything we find after this would be farther away, so we short circuit. |
| 74 | + ReportOverriddenAuthorizeAttributeDiagnosticsIfAny(context, authorizeAttributes, currentMethod.ContainingType.Name, currentMethod.Name); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + currentMethod = currentMethod.OverriddenMethod; |
| 79 | + |
| 80 | + // We've already checked the controller and any base classes for overridden attributes in DetectOverriddenAuthorizeAttributeOnController. |
| 81 | + // If there are no more base methods, and we are not tracking any unreported [Authorize] attributes that might be overridden by a class, we're done. |
| 82 | + if (currentMethod is null && (authorizeAttributes.Count is 0 || !isCheckingBaseType)) |
| 83 | + { |
| 84 | + if (allowAnonClass is not null) |
| 85 | + { |
| 86 | + // We don't use allowAnonClass once we start checking overrides to avoid false positives. But if we found [Authorize] directly on a non-virtual |
| 87 | + // action, we can report it without rechecking the controller or its base types for [AllowAnonymous] when given a non-null allowAnonClass. |
| 88 | + ReportOverriddenAuthorizeAttributeDiagnosticsIfAny(context, authorizeAttributes, allowAnonClass); |
| 89 | + } |
| 90 | + |
| 91 | + return; |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + // Now, we're mostly trying to detect [Authorize] on virtual actions which are not covered by allowAnonClass. Overridden [Authorize] attributes on classes |
| 96 | + // have mostly been reported already, but we still need to track those too just in case there is [AllowAnonymous] on a base method farther away. |
| 97 | + FindAuthorizeAndAllowAnonymous(wellKnownTypes, currentClass, isCheckingBaseType, authorizeAttributes, out foundAllowAnonymous); |
| 98 | + if (foundAllowAnonymous) |
| 99 | + { |
| 100 | + // We are only concerned with method-level [Authorize] attributes that are overridden by the [AllowAnonymous] found on this class. |
| 101 | + // Any child classes should have already been reported in DetectOverriddenAuthorizeAttributeOnController. |
| 102 | + ReportOverriddenAuthorizeAttributeDiagnosticsIfAny(context, authorizeAttributes.Where(a => a.IsTargetingMethod), currentClass.Name); |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + isCheckingBaseType = true; |
| 107 | + } |
| 108 | + |
| 109 | + Debug.Assert(currentMethod is null); |
| 110 | + } |
| 111 | + |
| 112 | + private static bool IsSameSymbol(ISymbol? x, ISymbol? y) => SymbolEqualityComparer.Default.Equals(x, y); |
| 113 | + |
| 114 | + private static bool IsInheritableAttribute(WellKnownTypes wellKnownTypes, INamedTypeSymbol attribute) |
| 115 | + { |
| 116 | + // [AttributeUsage] is sealed but inheritable. |
| 117 | + var attributeUsageAttributeType = wellKnownTypes.Get(WellKnownType.System_AttributeUsageAttribute); |
| 118 | + var attributeUsage = attribute.GetAttributes(attributeUsageAttributeType, inherit: true).FirstOrDefault(); |
| 119 | + |
| 120 | + if (attributeUsage is not null) |
| 121 | + { |
| 122 | + foreach (var arg in attributeUsage.NamedArguments) |
| 123 | + { |
| 124 | + if (arg.Key == nameof(AttributeUsageAttribute.Inherited)) |
| 125 | + { |
| 126 | + return (bool)arg.Value.Value!; |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + // If [AttributeUsage] is not found or the Inherited property is not set, the default is true. |
| 132 | + return true; |
| 133 | + } |
| 134 | + |
| 135 | + private static bool IsMatchingAttribute(WellKnownTypes wellKnownTypes, INamedTypeSymbol attribute, |
| 136 | + INamedTypeSymbol commonAttribute, ITypeSymbol attributeInterface, bool mustBeInheritable) |
| 137 | + { |
| 138 | + // The "common" attribute is either [Authorize] or [AllowAnonymous] so we can skip the interface and inheritable checks. |
| 139 | + if (IsSameSymbol(attribute, commonAttribute)) |
| 140 | + { |
| 141 | + return true; |
| 142 | + } |
| 143 | + |
| 144 | + if (!attributeInterface.IsAssignableFrom(attribute)) |
| 145 | + { |
| 146 | + return false; |
| 147 | + } |
| 148 | + |
| 149 | + return !mustBeInheritable || IsInheritableAttribute(wellKnownTypes, attribute); |
| 150 | + } |
| 151 | + |
| 152 | + private static void FindAuthorizeAndAllowAnonymous(WellKnownTypes wellKnownTypes, ISymbol symbol, bool isCheckingBaseType, |
| 153 | + List<AttributeInfo> authorizeAttributes, out bool foundAllowAnonymous) |
| 154 | + { |
| 155 | + AttributeData? localAuthorizeAttribute = null; |
| 156 | + List<AttributeData>? localAuthorizeAttributeOverflow = null; |
| 157 | + foundAllowAnonymous = false; |
| 158 | + |
| 159 | + foreach (var attribute in symbol.GetAttributes()) |
| 160 | + { |
| 161 | + if (attribute.AttributeClass is null) |
| 162 | + { |
| 163 | + continue; |
| 164 | + } |
| 165 | + |
| 166 | + var authInterfaceType = wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Authorization_IAuthorizeData); |
| 167 | + var authAttributeType = wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Authorization_AuthorizeAttribute); |
| 168 | + if (IsMatchingAttribute(wellKnownTypes, attribute.AttributeClass, authAttributeType, authInterfaceType, isCheckingBaseType)) |
| 169 | + { |
| 170 | + if (localAuthorizeAttribute is null) |
| 171 | + { |
| 172 | + localAuthorizeAttribute = attribute; |
| 173 | + } |
| 174 | + else |
| 175 | + { |
| 176 | + // This is ony allocated if there are multiple [Authorize] attributes on the same symbol which we assume is rare. |
| 177 | + localAuthorizeAttributeOverflow ??= []; |
| 178 | + localAuthorizeAttributeOverflow.Add(attribute); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + var anonInterfaceType = wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Authorization_IAllowAnonymous); |
| 183 | + var anonAttributeType = wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Authorization_AllowAnonymousAttribute); |
| 184 | + if (IsMatchingAttribute(wellKnownTypes, attribute.AttributeClass, anonAttributeType, anonInterfaceType, isCheckingBaseType)) |
| 185 | + { |
| 186 | + // If localAuthorizeAttribute is not null, [AllowAnonymous] came after [Authorize] on the same method or class. We assume |
| 187 | + // this closer [AllowAnonymous] was intended to override the [Authorize] attribute which it always does regardless of order. |
| 188 | + // [Authorize(...)] could still be useful for configuring the authentication scheme even if the endpoint allows anonymous requests. |
| 189 | + localAuthorizeAttribute = null; |
| 190 | + localAuthorizeAttributeOverflow?.Clear(); |
| 191 | + foundAllowAnonymous = true; |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + if (localAuthorizeAttribute is not null) |
| 196 | + { |
| 197 | + var isTargetingMethod = symbol is IMethodSymbol; |
| 198 | + authorizeAttributes.Add(new(localAuthorizeAttribute, isTargetingMethod)); |
| 199 | + foreach (var extraAttribute in localAuthorizeAttributeOverflow ?? Enumerable.Empty<AttributeData>()) |
| 200 | + { |
| 201 | + authorizeAttributes.Add(new(extraAttribute, isTargetingMethod)); |
| 202 | + } |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + private static void ReportOverriddenAuthorizeAttributeDiagnosticsIfAny(SymbolAnalysisContext context, |
| 207 | + IEnumerable<AttributeInfo> authorizeAttributes, string allowAnonClass, string? allowAnonMethod = null) |
| 208 | + { |
| 209 | + string? allowAnonLocation = null; |
| 210 | + |
| 211 | + foreach (var authorizeAttribute in authorizeAttributes) |
| 212 | + { |
| 213 | + if (authorizeAttribute.AttributeData.ApplicationSyntaxReference is { } syntaxReference) |
| 214 | + { |
| 215 | + allowAnonLocation ??= allowAnonMethod is null ? allowAnonClass : $"{allowAnonClass}.{allowAnonMethod}"; |
| 216 | + context.ReportDiagnostic(Diagnostic.Create( |
| 217 | + DiagnosticDescriptors.OverriddenAuthorizeAttribute, |
| 218 | + syntaxReference.GetSyntax(context.CancellationToken).GetLocation(), |
| 219 | + allowAnonLocation)); |
| 220 | + } |
| 221 | + } |
| 222 | + } |
| 223 | +} |
0 commit comments