-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInternalTypeMustHaveInternalsVisibleToAnalyzer.cs
More file actions
189 lines (166 loc) · 7.51 KB
/
Copy pathInternalTypeMustHaveInternalsVisibleToAnalyzer.cs
File metadata and controls
189 lines (166 loc) · 7.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
using Microsoft.CodeAnalysis.Operations;
using Moq.Analyzers.Common;
namespace Moq.Analyzers;
/// <summary>
/// Detects when <c>Mock<T></c> is used where <c>T</c> is an <see langword="internal"/> type
/// and the assembly containing <c>T</c> does not have
/// <c>[InternalsVisibleTo("DynamicProxyGenAssembly2")]</c>.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class InternalTypeMustHaveInternalsVisibleToAnalyzer : MoqDiagnosticAnalyzerBase
{
private static readonly string DynamicProxyAssemblyName = "DynamicProxyGenAssembly2";
private static readonly LocalizableString Title = "Moq: Internal type requires InternalsVisibleTo";
private static readonly LocalizableString Message = "Internal type '{0}' requires [InternalsVisibleTo(\"DynamicProxyGenAssembly2\")] in its assembly to be mocked";
private static readonly LocalizableString Description = "Mocking internal types requires the assembly to grant access to Castle DynamicProxy via InternalsVisibleTo.";
private static readonly DiagnosticDescriptor Rule = new(
DiagnosticIds.InternalTypeMustHaveInternalsVisibleTo,
Title,
Message,
DiagnosticCategory.Usage,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: Description,
helpLinkUri: $"https://github.com/rjmurillo/moq.analyzers/blob/{ThisAssembly.GitCommitId}/docs/rules/{DiagnosticIds.InternalTypeMustHaveInternalsVisibleTo}.md");
/// <inheritdoc />
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
private protected override void RegisterCompilationActions(CompilationStartAnalysisContext context, MoqKnownSymbols knownSymbols)
{
if (knownSymbols.Mock1 is null)
{
return;
}
context.RegisterOperationAction(
operationAnalysisContext => Analyze(operationAnalysisContext, knownSymbols),
OperationKind.ObjectCreation,
OperationKind.Invocation);
}
private static void Analyze(
OperationAnalysisContext context,
MoqKnownSymbols knownSymbols)
{
ITypeSymbol? mockedType = null;
Location? diagnosticLocation = null;
if (context.Operation is IObjectCreationOperation creation &&
MockDetectionHelpers.IsValidMockCreation(creation, knownSymbols, out mockedType))
{
diagnosticLocation = MockDetectionHelpers.GetDiagnosticLocation(context.Operation, creation.Syntax);
}
else if (context.Operation is IInvocationOperation invocation &&
MockDetectionHelpers.IsValidMockInvocation(invocation, knownSymbols, out mockedType))
{
diagnosticLocation = MockDetectionHelpers.GetDiagnosticLocation(context.Operation, invocation.Syntax);
}
else
{
return;
}
if (mockedType != null && diagnosticLocation != null &&
ShouldReportDiagnostic(mockedType, knownSymbols.InternalsVisibleToAttribute))
{
context.ReportDiagnostic(diagnosticLocation.CreateDiagnostic(
Rule,
mockedType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
}
}
/// <summary>
/// Determines whether the mocked type is effectively internal and its assembly
/// lacks InternalsVisibleTo for DynamicProxy.
/// </summary>
private static bool ShouldReportDiagnostic(
ITypeSymbol mockedType,
INamedTypeSymbol? internalsVisibleToAttribute)
{
if (!IsEffectivelyInternal(mockedType))
{
return false;
}
return !HasInternalsVisibleToDynamicProxy(mockedType.ContainingAssembly, internalsVisibleToAttribute);
}
/// <summary>
/// Checks if the type (or any containing type) has accessibility that requires
/// InternalsVisibleTo for DynamicProxy to access it. DynamicProxy resides in a
/// separate assembly and does not derive from containing types, so it relies on
/// assembly-level access. Any of the following accessibility levels on the type
/// or its containers make it inaccessible to DynamicProxy without InternalsVisibleTo:
/// <list type="bullet">
/// <item><see cref="Accessibility.Internal"/> (internal)</item>
/// <item><see cref="Accessibility.ProtectedOrInternal"/> (protected internal) on
/// a containing type, because DynamicProxy does not derive from the container</item>
/// </list>
/// Note: <see cref="Accessibility.Private"/>, <see cref="Accessibility.Protected"/>,
/// and <see cref="Accessibility.ProtectedAndInternal"/> (private protected) are excluded
/// because InternalsVisibleTo cannot help with those - private types are only accessible
/// within their declaring type, and protected/private protected types require inheritance
/// from the containing type, which DynamicProxy does not provide.
/// </summary>
private static bool IsEffectivelyInternal(ITypeSymbol type)
{
ITypeSymbol? current = type;
while (current != null)
{
switch (current.DeclaredAccessibility)
{
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal:
return true;
}
current = current.ContainingType;
}
return false;
}
/// <summary>
/// Checks the assembly's attributes for InternalsVisibleTo targeting DynamicProxy,
/// using symbol-based comparison for the attribute type.
/// </summary>
private static bool HasInternalsVisibleToDynamicProxy(
IAssemblySymbol? assembly,
INamedTypeSymbol? internalsVisibleToAttribute)
{
if (assembly is null)
{
return false;
}
// If we cannot resolve InternalsVisibleToAttribute (highly unlikely), bail out
// conservatively by not reporting a diagnostic (avoiding false positives).
if (internalsVisibleToAttribute is null)
{
return true;
}
foreach (AttributeData attribute in assembly.GetAttributes())
{
if (attribute.AttributeClass is null)
{
continue;
}
// Symbol-based comparison instead of string-based ToDisplayString()
if (!SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, internalsVisibleToAttribute))
{
continue;
}
if (attribute.ConstructorArguments.Length == 1 &&
attribute.ConstructorArguments[0].Value is string assemblyName &&
IsDynamicProxyAssemblyName(assemblyName))
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if the assembly name matches DynamicProxy. The InternalsVisibleTo attribute
/// value can be either the simple name ("DynamicProxyGenAssembly2") or include a
/// public key token ("DynamicProxyGenAssembly2, PublicKey=..."). We match the exact
/// name followed by either end-of-string or a comma separator.
/// </summary>
private static bool IsDynamicProxyAssemblyName(string assemblyName)
{
if (!assemblyName.StartsWith(DynamicProxyAssemblyName, StringComparison.Ordinal))
{
return false;
}
// Must be exact match or followed by comma (for public key suffix)
return assemblyName.Length == DynamicProxyAssemblyName.Length ||
assemblyName[DynamicProxyAssemblyName.Length] == ',';
}
}