forked from PowerShell/PSScriptAnalyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuleSuppression.cs
More file actions
399 lines (342 loc) · 15.2 KB
/
RuleSuppression.cs
File metadata and controls
399 lines (342 loc) · 15.2 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
//
// Copyright (c) Microsoft Corporation.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Linq;
using System.Management.Automation.Language;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Globalization;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
{
/// <summary>
///
/// </summary>
public class RuleSuppression
{
private string _ruleName;
/// <summary>
/// The start offset of the rule suppression attribute (not where it starts to apply)
/// </summary>
public int StartAttributeLine
{
get;
set;
}
/// <summary>
/// The start offset of the rule suppression
/// </summary>
public int StartOffset
{
get;
set;
}
/// <summary>
/// The end offset of the rule suppression
/// </summary>
public int EndOffset
{
get;
set;
}
/// <summary>
/// Name of the rule being suppressed
/// </summary>
public string RuleName
{
get
{
return _ruleName;
}
set
{
_ruleName = value;
if (!String.IsNullOrWhiteSpace(_ruleName)
&& (ScriptAnalyzer.Instance.ScriptRules != null
&& ScriptAnalyzer.Instance.ScriptRules.Count(item => String.Equals(item.GetName(), _ruleName, StringComparison.OrdinalIgnoreCase)) == 0)
&& (ScriptAnalyzer.Instance.TokenRules != null
&& ScriptAnalyzer.Instance.TokenRules.Count(item => String.Equals(item.GetName(), _ruleName, StringComparison.OrdinalIgnoreCase)) == 0)
&& (ScriptAnalyzer.Instance.ExternalRules != null
&& ScriptAnalyzer.Instance.ExternalRules.Count(item => String.Equals(item.GetName(), _ruleName, StringComparison.OrdinalIgnoreCase)) == 0)
&& (ScriptAnalyzer.Instance.DSCResourceRules != null
&& ScriptAnalyzer.Instance.DSCResourceRules.Count(item => String.Equals(item.GetName(), _ruleName, StringComparison.OrdinalIgnoreCase)) == 0))
{
Error = String.Format(Strings.RuleSuppressionRuleNameNotFound, _ruleName);
}
}
}
/// <summary>
/// ID of the violation instance
/// </summary>
public string RuleSuppressionID
{
get;
set;
}
/// <summary>
/// Scope of the rule suppression
/// </summary>
public string Scope
{
get;
set;
}
/// <summary>
/// Target of the rule suppression
/// </summary>
public string Target
{
get;
set;
}
/// <summary>
/// Returns error occurred in trying to parse the attribute
/// </summary>
public string Error
{
get;
set;
}
/// <summary>
/// Returns the justification for the suppression
/// </summary>
public string Justification
{
get;
set;
}
private static HashSet<string> scopeSet;
/// <summary>
/// Initialize the scopeSet
/// </summary>
static RuleSuppression()
{
scopeSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
scopeSet.Add("function");
scopeSet.Add("class");
}
/// <summary>
/// Returns rule suppression from an attribute ast that has the type suppressmessageattribute
/// </summary>
/// <param name="attrAst"></param>
/// <param name="start"></param>
/// <param name="end"></param>
public RuleSuppression(AttributeAst attrAst, int start, int end)
{
Error = String.Empty;
if (attrAst != null)
{
StartAttributeLine = attrAst.Extent.StartLineNumber;
var positionalArguments = attrAst.PositionalArguments;
var namedArguments = attrAst.NamedArguments;
int lastPositionalArgumentsOffset = -1;
if (positionalArguments != null && positionalArguments.Count != 0)
{
int count = positionalArguments.Count;
lastPositionalArgumentsOffset = positionalArguments[positionalArguments.Count - 1].Extent.StartOffset;
if (positionalArguments.Any(item => !(item is StringConstantExpressionAst)))
{
Error = Strings.StringConstantArgumentsSuppressionAttributeError;
}
else
{
switch (count)
{
case 5:
Justification = (positionalArguments[4] as StringConstantExpressionAst).Value;
goto case 4;
case 4:
Target = (positionalArguments[3] as StringConstantExpressionAst).Value;
goto case 3;
case 3:
Scope = (positionalArguments[2] as StringConstantExpressionAst).Value;
goto case 2;
case 2:
RuleSuppressionID = (positionalArguments[1] as StringConstantExpressionAst).Value;
goto case 1;
case 1:
RuleName = (positionalArguments[0] as StringConstantExpressionAst).Value;
goto default;
default:
break;
}
}
}
if (namedArguments != null && namedArguments.Count != 0)
{
foreach (var name in namedArguments)
{
if (name.Extent.StartOffset < lastPositionalArgumentsOffset)
{
Error = Strings.NamedArgumentsBeforePositionalError;
break;
}
else if (!(name.Argument is StringConstantExpressionAst))
{
Error = Strings.StringConstantArgumentsSuppressionAttributeError;
break;
}
switch (name.ArgumentName.ToLower())
{
case "rulename":
if (!String.IsNullOrWhiteSpace(RuleName))
{
Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
}
RuleName = (name.Argument as StringConstantExpressionAst).Value;
goto default;
case "rulesuppressionid":
if (!String.IsNullOrWhiteSpace(RuleSuppressionID))
{
Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
}
RuleSuppressionID = (name.Argument as StringConstantExpressionAst).Value;
goto default;
case "scope":
if (!String.IsNullOrWhiteSpace(Scope))
{
Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
}
Scope = (name.Argument as StringConstantExpressionAst).Value;
if (!scopeSet.Contains(Scope))
{
Error = Strings.WrongScopeArgumentSuppressionAttributeError;
}
goto default;
case "target":
if (!String.IsNullOrWhiteSpace(Target))
{
Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
}
Target = (name.Argument as StringConstantExpressionAst).Value;
goto default;
case "justification":
if (!String.IsNullOrWhiteSpace(Justification))
{
Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
}
Justification = (name.Argument as StringConstantExpressionAst).Value;
goto default;
default:
break;
}
}
}
if (!String.IsNullOrWhiteSpace(Error))
{
// May be cases where the rulename is null because we didn't look at the rulename after
// we found out there is an error
RuleName = String.Empty;
}
else if (String.IsNullOrWhiteSpace(RuleName))
{
RuleName = String.Empty;
Error = Strings.NullRuleNameError;
}
// Must have scope and target together
if (String.IsNullOrWhiteSpace(Scope) && !String.IsNullOrWhiteSpace(Target))
{
Error = Strings.TargetWithoutScopeSuppressionAttributeError;
}
}
StartOffset = start;
EndOffset = end;
if (!String.IsNullOrWhiteSpace(Error))
{
Error = String.Format(CultureInfo.CurrentCulture, Strings.RuleSuppressionErrorFormat, StartAttributeLine,
System.IO.Path.GetFileName(attrAst.Extent.File), Error);
}
}
/// <summary>
/// Constructs rule expression from rule name, id, start, end, startAttributeLine and justification
/// </summary>
/// <param name="ruleName"></param>
/// <param name="ruleSuppressionID"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="startAttributeLine"></param>
/// <param name="justification"></param>
public RuleSuppression(string ruleName, string ruleSuppressionID, int start, int end, int startAttributeLine, string justification)
{
RuleName = ruleName;
RuleSuppressionID = ruleSuppressionID;
StartOffset = start;
EndOffset = end;
StartAttributeLine = startAttributeLine;
Justification = justification;
}
/// <summary>
/// Given a list of attribute asts, return a list of rule suppression
/// with startoffset at start and endoffset at end
/// </summary>
/// <param name="attrAsts"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static List<RuleSuppression> GetSuppressions(IEnumerable<AttributeAst> attrAsts, int start, int end, Ast scopeAst)
{
List<RuleSuppression> result = new List<RuleSuppression>();
if (attrAsts == null || scopeAst == null)
{
return result;
}
IEnumerable<AttributeAst> suppressionAttribute = attrAsts.Where(
item => item.TypeName.GetReflectionType() == typeof(System.Diagnostics.CodeAnalysis.SuppressMessageAttribute));
foreach (var attributeAst in suppressionAttribute)
{
RuleSuppression ruleSupp = new RuleSuppression(attributeAst, start, end);
// If there is no error and scope is not null
if (String.IsNullOrWhiteSpace(ruleSupp.Error) && !String.IsNullOrWhiteSpace(ruleSupp.Scope))
{
if (String.IsNullOrWhiteSpace(ruleSupp.Target))
{
ruleSupp.Target = "*";
}
// regex for wild card *
Regex reg = new Regex(String.Format("^{0}$", Regex.Escape(ruleSupp.Target).Replace(@"\*", ".*")), RegexOptions.IgnoreCase);
IEnumerable<Ast> targetAsts = null;
switch (ruleSupp.Scope.ToLower())
{
case "function":
targetAsts = scopeAst.FindAll(item => item is FunctionDefinitionAst && reg.IsMatch((item as FunctionDefinitionAst).Name), true);
goto default;
case "class":
targetAsts = scopeAst.FindAll(item => item is TypeDefinitionAst && reg.IsMatch((item as TypeDefinitionAst).Name), true);
goto default;
default:
break;
}
if (targetAsts != null)
{
if (targetAsts.Count() == 0)
{
ruleSupp.Error = String.Format(CultureInfo.CurrentCulture, Strings.RuleSuppressionErrorFormat, ruleSupp.StartAttributeLine,
System.IO.Path.GetFileName(scopeAst.Extent.File), String.Format(Strings.TargetCannotBeFoundError, ruleSupp.Target, ruleSupp.Scope));
result.Add(ruleSupp);
continue;
}
foreach (Ast targetAst in targetAsts)
{
result.Add(new RuleSuppression(ruleSupp.RuleName, ruleSupp.RuleSuppressionID, targetAst.Extent.StartOffset,
targetAst.Extent.EndOffset, attributeAst.Extent.StartLineNumber, ruleSupp.Justification));
}
}
}
else
{
// this may add rule suppression that contains error but we will check for this in the engine to throw out error
result.Add(ruleSupp);
}
}
return result;
}
}
}