-
Notifications
You must be signed in to change notification settings - Fork 393
/
Copy pathUseIdenticalMandatoryParametersDSC.cs
339 lines (302 loc) · 12.9 KB
/
UseIdenticalMandatoryParametersDSC.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// this rule can only compile on v4+
#if (PSV4 || !PSV3)
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
#if !CORECLR
using System.ComponentModel.Composition;
#endif
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation.Language;
using System.Reflection;
using Microsoft.Management.Infrastructure;
using Microsoft.PowerShell.DesiredStateConfiguration.Internal;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// UseIdenticalMandatoryParametersDSC: Check that the Get/Test/Set TargetResource
/// have identical mandatory parameters.
/// </summary>
#if !CORECLR
[Export(typeof(IDSCResourceRule))]
#endif
public class UseIdenticalMandatoryParametersDSC : IDSCResourceRule
{
private bool isDSCClassCacheInitialized = false;
private string fileName;
private IDictionary<string, string> propAttrDict;
private IEnumerable<FunctionDefinitionAst> resourceFunctions;
private Func<string, Tuple<string, Version>, Collection<Exception>, List<CimClass>> dscClassImporter;
/// <summary>
/// Constructs an object of type UseIdenticalMandatoryParametersDSC
/// </summary>
public UseIdenticalMandatoryParametersDSC()
{
var importClassesMethod = typeof(DscClassCache).GetMethod(
"ImportClasses",
BindingFlags.Public | BindingFlags.Static);
if (importClassesMethod != null)
{
// In some version of S.M.A DscClassCache.ImportClasses method takes 4 parameters
// while in others it takes 3.
if (importClassesMethod.GetParameters().Count() == 4)
{
dscClassImporter = (path, moduleInfo, errors) =>
{
return importClassesMethod.Invoke(
null,
new object[] { path, moduleInfo, errors, false }) as List<CimClass>;
};
}
else
{
dscClassImporter = (path, moduleInfo, errors) =>
{
return importClassesMethod.Invoke(
null,
new object[] { path, moduleInfo, errors}) as List<CimClass>;
};
}
}
else
{
dscClassImporter = (path, moduleInfo, errors) => null;
}
}
/// <summary>
/// AnalyzeDSCResource: Analyzes given DSC Resource
/// </summary>
/// <param name="ast">The script's ast</param>
/// <param name="fileName">The name of the script file being analyzed</param>
/// <returns>The results of the analysis</returns>
public IEnumerable<DiagnosticRecord> AnalyzeDSCResource(Ast ast, string fileName)
{
if (ast == null)
{
throw new ArgumentNullException(Strings.NullAstErrorMessage);
}
if (fileName == null)
{
throw new ArgumentNullException(nameof(fileName));
}
// Get the keys in the corresponding mof file
this.fileName = fileName;
this.propAttrDict = GetKeys(fileName);
this.resourceFunctions = Helper.Instance.DscResourceFunctions(ast)
.Cast<FunctionDefinitionAst>()
.ToArray();
var funcManParamMap = resourceFunctions
.ToDictionary(
f => f.Name,
f => Tuple.Create(
f,
GetMandatoryParameters(f)
.Select(p => p.Name.VariablePath.UserPath)
.ToArray()));
// Loop through Set/Test/Get TargetResource DSC cmdlets
foreach (var kvp in funcManParamMap)
{
var functionDefinitionAst = kvp.Value.Item1;
var manParams = kvp.Value.Item2;
foreach (var key in propAttrDict.Keys.Except(manParams))
{
yield return new DiagnosticRecord(
string.Format(
CultureInfo.InvariantCulture,
Strings.UseIdenticalMandatoryParametersDSCError,
propAttrDict[key],
key,
functionDefinitionAst.Name),
Helper.Instance.GetScriptExtentForFunctionName(functionDefinitionAst),
GetName(),
DiagnosticSeverity.Error,
fileName);
}
}
}
/// <summary>
/// AnalyzeDSCClass: This function returns nothing in the case of dsc class.
/// </summary>
/// <param name="ast"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public IEnumerable<DiagnosticRecord> AnalyzeDSCClass(Ast ast, string fileName)
{
// For DSC Class based resource, this rule is N/A, since the Class Properties
// are declared only once and available to Get(), Set(), Test() functions
return Enumerable.Empty<DiagnosticRecord>();
}
/// <summary>
/// GetName: Retrieves the name of this rule.
/// </summary>
/// <returns>The name of this rule</returns>
public string GetName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.NameSpaceFormat, GetSourceName(), Strings.UseIdenticalMandatoryParametersDSCName);
}
/// <summary>
/// GetCommonName: Retrieves the Common name of this rule.
/// </summary>
/// <returns>The common name of this rule</returns>
public string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseIdenticalMandatoryParametersDSCCommonName);
}
/// <summary>
/// GetDescription: Retrieves the description of this rule.
/// </summary>
/// <returns>The description of this rule</returns>
public string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseIdenticalMandatoryParametersDSCDescription);
}
/// <summary>
/// GetSourceType: Retrieves the type of the rule: builtin, managed or module.
/// </summary>
public SourceType GetSourceType()
{
return SourceType.Builtin;
}
/// <summary>
/// GetSeverity: Retrieves the severity of the rule: error, warning of information.
/// </summary>
/// <returns></returns>
public RuleSeverity GetSeverity()
{
return RuleSeverity.Error;
}
/// <summary>
/// GetSourceName: Retrieves the module/assembly name the rule is from.
/// </summary>
public string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.DSCSourceName);
}
private IEnumerable<ParameterAst> GetMandatoryParameters(FunctionDefinitionAst functionDefinitionAst)
{
return functionDefinitionAst.GetParameterAsts()?.Where(IsParameterMandatory) ??
Enumerable.Empty<ParameterAst>();
}
private bool IsParameterMandatory(ParameterAst paramAst)
{
var attrAsts = from attr in paramAst.Attributes
where IsParameterAttribute(attr) && attr is AttributeAst
select (AttributeAst)attr;
return attrAsts.Any(a => a.NamedArguments.Any(IsNamedAttributeArgumentMandatory));
}
private bool IsParameterAttribute(AttributeBaseAst attributeBaseAst)
{
return attributeBaseAst.TypeName.GetReflectionType().Name.Equals("ParameterAttribute");
}
private bool IsNamedAttributeArgumentMandatory(NamedAttributeArgumentAst namedAttrArgAst)
{
return namedAttrArgAst.ArgumentName.Equals("mandatory", StringComparison.OrdinalIgnoreCase) &&
namedAttrArgAst.GetValue();
}
private IDictionary<string, string> GetKeys(string fileName)
{
var moduleInfo = GetModuleInfo(fileName);
var emptyDictionary = new Dictionary<string, string>();
if (moduleInfo == null)
{
return emptyDictionary;
}
var mofFilepath = GetMofFilepath(fileName);
if (mofFilepath == null)
{
return emptyDictionary;
}
var errors = new System.Collections.ObjectModel.Collection<Exception>();
var keys = new List<string>();
List<CimClass> cimClasses = null;
try
{
if (!isDSCClassCacheInitialized)
{
DscClassCache.Initialize();
isDSCClassCacheInitialized = true;
}
cimClasses = dscClassImporter(mofFilepath, moduleInfo, errors);
}
catch
{
// todo log the error
}
var cimClass = cimClasses?.FirstOrDefault(_cimClass => _cimClass.CimSuperClass != null);
var cimSuperClassProperties = new HashSet<string>(
cimClass?.CimSuperClass?.CimClassProperties.Select(cimPropertyDeclaration => cimPropertyDeclaration.Name) ??
Enumerable.Empty<string>());
return cimClass?
.CimClassProperties?
.Where(p => (p.Flags.HasFlag(CimFlags.Key) ||
p.Flags.HasFlag(CimFlags.Required)) &&
!cimSuperClassProperties.Contains(p.Name))
.ToDictionary(
p => p.Name,
p => p.Flags.HasFlag(CimFlags.Key) ?
CimFlags.Key.ToString() :
CimFlags.Required.ToString()) ??
emptyDictionary;
}
private string GetMofFilepath(string filePath)
{
var mofFilePath = Path.Combine(
Path.GetDirectoryName(filePath),
Path.GetFileNameWithoutExtension(filePath)) + ".schema.mof";
return File.Exists(mofFilePath) ? mofFilePath : null;
}
private Tuple<string, Version> GetModuleInfo(string fileName)
{
var moduleManifest = GetModuleManifest(fileName);
if (moduleManifest == null)
{
return null;
}
var moduleName = Path.GetFileNameWithoutExtension(moduleManifest.Name);
Token[] tokens;
ParseError[] parseErrors;
var ast = Parser.ParseFile(moduleManifest.FullName, out tokens, out parseErrors);
if ((parseErrors != null && parseErrors.Length > 0) || ast == null)
{
return null;
}
var foundAst = ast.Find(x => x is HashtableAst, false);
if (foundAst == null)
{
return null;
}
var moduleVersionKvp = ((HashtableAst)foundAst).KeyValuePairs.FirstOrDefault(t =>
{
var keyAst = t.Item1 as StringConstantExpressionAst;
return keyAst != null &&
keyAst.Value.Equals("ModuleVersion", StringComparison.OrdinalIgnoreCase);
});
if (moduleVersionKvp == null)
{
return null;
}
var valueAst = moduleVersionKvp.Item2.Find(a => a is StringConstantExpressionAst, false);
var versionText = valueAst == null ? null : ((StringConstantExpressionAst)valueAst).Value;
Version version;
Version.TryParse(versionText, out version); // this handles null so no need to check versionText
return version == null ? null : Tuple.Create(moduleName, version);
}
private FileInfo GetModuleManifest(string fileName)
{
return Directory
.GetParent(fileName)?
.Parent?
.Parent?
.GetFiles("*.psd1")
.Where(f => Helper.IsModuleManifest(f.FullName))
.FirstOrDefault();
}
}
}
#endif