Skip to content

Commit 4857578

Browse files
authored
Use allowlist and blocklist terminology, supply alternate configuration key for PSAvoidUsingCmdletAliases (#1604)
1 parent cf2adbd commit 4857578

15 files changed

+78
-50
lines changed

CHANGELOG.MD

+2-2
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,7 @@ Many thanks to @rkeithhill for contributing the _Stroustrup_ style code formatti
503503
## [1.11.1](https://github.com/PowerShell/PSScriptAnalyzer/tree/1.11.1) - 2017-04-04
504504
### Fixed
505505
- CodeFormatting settings file (#727, #728).
506-
- Whitelisted aliases comparison in AvoidUsingCmdletAliases rule (#739).
506+
- Allowlist aliases comparison in AvoidUsingCmdletAliases rule (#739).
507507
- PlaceCloseBrace rule behavior for NewLineAfter option (#741).
508508
- UseConsistentIndentation rule to ignore open brace in magic methods (#744).
509509

@@ -600,7 +600,7 @@ Here are some improvements since the last release.
600600
- Fix `SaveDscDependency` switch implementation, which use fail if more than one parameter is given to `Import-DSCResource` dynamic keyword.
601601
- Add support for external AST based rule suppression
602602
- Fix rule suppression caused by inavlid offsets
603-
- Whitelist `Data` in `PSUseSingularNoun` rule
603+
- Allowlist `Data` in `PSUseSingularNoun` rule
604604
- Fix rule documentation of `PSDSCExamplesPresent`
605605
- Fix false positives caused by PSD1 files which are not module manifests
606606
- affects `PSUseToExportFieldsInManifest`, `PSMissingModuleManifestField` and `PSAvoidUsingDeprecatedManifestFields` rules

RuleDocumentation/AvoidOverwritingBuiltInCmdlets.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
## Description
66

7-
This rule flags cmdlets that are available in a given edition/version of PowerShell on a given operating system which are overwritten by a function declaration. It works by comparing function declarations against a set of whitelists which ship with PSScriptAnalyzer. These whitelist files are used by other PSScriptAnalyzer rules. More information can be found in the documentation for the [UseCompatibleCmdlets](./UseCompatibleCmdlets.md) rule.
7+
This rule flags cmdlets that are available in a given edition/version of PowerShell on a given operating system which are overwritten by a function declaration. It works by comparing function declarations against a set of allowlists which ship with PSScriptAnalyzer. These allowlist files are used by other PSScriptAnalyzer rules. More information can be found in the documentation for the [UseCompatibleCmdlets](./UseCompatibleCmdlets.md) rule.
88

99
## Configuration
1010

@@ -25,7 +25,7 @@ To enable the rule to check if your script is compatible on PowerShell Core on W
2525

2626
#### PowerShellVersion
2727

28-
The parameter `PowerShellVersion` is a list of whitelists that ship with PSScriptAnalyzer.
28+
The parameter `PowerShellVersion` is a list of allowlists that ship with PSScriptAnalyzer.
2929

3030
**Note**: The default value for `PowerShellVersion` is `"core-6.1.0-windows"` if PowerShell 6 or later is installed, and `"desktop-5.1.14393.206-windows"` if it is not.
3131

RuleDocumentation/AvoidUsingCmdletAliases.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ The use of full command names also allows for syntax highlighting in sites and a
1818

1919
Use the full cmdlet name and not an alias.
2020

21-
## Alias Whitelist
21+
## Alias Allowlist
2222

23-
To prevent `PSScriptAnalyzer` from flagging your preferred aliases, create a whitelist of the aliases in your settings file and point `PSScriptAnalyzer` to use the settings file. For example, to disable `PSScriptAnalyzer` from flagging `cd`, which is an alias of `Set-Location`, set the settings file content to the following.
23+
To prevent `PSScriptAnalyzer` from flagging your preferred aliases, create an allowlist of the aliases in your settings file and point `PSScriptAnalyzer` to use the settings file. For example, to disable `PSScriptAnalyzer` from flagging `cd`, which is an alias of `Set-Location`, set the settings file content to the following.
2424

2525
```PowerShell
2626
# PSScriptAnalyzerSettings.psd1

RuleDocumentation/UseCompatibleCmdlets.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
## Description
66

7-
This rule flags cmdlets that are not available in a given Edition/Version of PowerShell on a given Operating System. It works by comparing a cmdlet against a set of whitelists which ship with PSScriptAnalyzer. They can be found at `/path/to/PSScriptAnalyzerModule/Settings`. These files are of the form, `PSEDITION-PSVERSION-OS.json` where `PSEDITION` can be either `Core` or `Desktop`, `OS` can be either `Windows`, `Linux` or `MacOS`, and `Version` is the PowerShell version. To enable the rule to check if your script is compatible on PowerShell Core on windows, put the following your settings file:
7+
This rule flags cmdlets that are not available in a given Edition/Version of PowerShell on a given Operating System. It works by comparing a cmdlet against a set of allowlists which ship with PSScriptAnalyzer. They can be found at `/path/to/PSScriptAnalyzerModule/Settings`. These files are of the form, `PSEDITION-PSVERSION-OS.json` where `PSEDITION` can be either `Core` or `Desktop`, `OS` can be either `Windows`, `Linux` or `MacOS`, and `Version` is the PowerShell version. To enable the rule to check if your script is compatible on PowerShell Core on windows, put the following your settings file:
88

99
```PowerShell
1010
@{

Rules/AvoidAlias.cs

+16-13
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,11 @@ namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
2222
#endif
2323
public class AvoidAlias : IScriptRule
2424
{
25-
private readonly string whiteListArgName = "whitelist";
25+
private readonly string allowListArgName = "allowlist";
26+
// keep legacy argument name for next version to allow customers to transition but remove later
27+
private readonly string allowListLegacyArgName = "whitelist";
2628
private bool isPropertiesSet;
27-
private List<string> whiteList;
28-
public List<string> WhiteList
29-
{
30-
get { return whiteList; }
31-
}
29+
public List<string> AllowList { get; private set; }
3230

3331
public AvoidAlias()
3432
{
@@ -38,22 +36,27 @@ public AvoidAlias()
3836
/// <summary>
3937
/// Configure the rule.
4038
///
41-
/// Sets the whitelist of this rule
39+
/// Sets the allowlist of this rule
4240
/// </summary>
4341
private void SetProperties()
4442
{
45-
whiteList = new List<string>();
43+
AllowList = new List<string>();
4644
isPropertiesSet = true;
4745
Dictionary<string, object> ruleArgs = Helper.Instance.GetRuleArguments(GetName());
4846
if (ruleArgs == null)
4947
{
5048
return;
5149
}
52-
object obj;
53-
if (!ruleArgs.TryGetValue(whiteListArgName, out obj))
50+
object objLegacy = null;
51+
if (!ruleArgs.TryGetValue(allowListArgName, out object obj) &&
52+
!ruleArgs.TryGetValue(allowListLegacyArgName, out objLegacy))
5453
{
5554
return;
5655
}
56+
// Fallback for object from legacy allowlist argument name
57+
if (obj == null) {
58+
obj = objLegacy;
59+
}
5760
IEnumerable<string> aliases = obj as IEnumerable<string>;
5861
if (aliases == null)
5962
{
@@ -72,13 +75,13 @@ private void SetProperties()
7275
}
7376
else
7477
{
75-
whiteList.Add(y);
78+
AllowList.Add(y);
7679
}
7780
}
7881
}
7982
else
8083
{
81-
whiteList.AddRange(aliases);
84+
AllowList.AddRange(aliases);
8285
}
8386
}
8487

@@ -110,7 +113,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
110113
// You can also review the remark section in following document,
111114
// MSDN: CommandAst.GetCommandName Method
112115
if (commandName == null
113-
|| whiteList.Contains<string>(commandName, StringComparer.OrdinalIgnoreCase))
116+
|| AllowList.Contains<string>(commandName, StringComparer.OrdinalIgnoreCase))
114117
{
115118
continue;
116119
}

Rules/AvoidUserNameAndPasswordParams.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
3636

3737
List<String> passwords = new List<String>() {"Password", "Passphrase"};
3838
List<String> usernames = new List<String>() { "Username", "User"};
39-
Type[] typeWhiteList = {typeof(CredentialAttribute),
39+
Type[] typeAllowList = {typeof(CredentialAttribute),
4040
typeof(PSCredential),
4141
typeof(System.Security.SecureString),
4242
typeof(SwitchParameter),
@@ -54,7 +54,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
5454
// Iterates all ParamAsts and check if their names are on the list.
5555
foreach (ParameterAst paramAst in paramAsts)
5656
{
57-
var attributes = typeWhiteList.Select(x => GetAttributeOfType(paramAst.Attributes, x));
57+
var attributes = typeAllowList.Select(x => GetAttributeOfType(paramAst.Attributes, x));
5858
String paramName = paramAst.Name.VariablePath.ToString();
5959
foreach (String password in passwords)
6060
{

Rules/ProvideCommentHelp.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -264,13 +264,13 @@ private void GetCorrectionPosition(
264264

265265
private class ViolationFinder : AstVisitor
266266
{
267-
private HashSet<string> functionWhitelist;
267+
private HashSet<string> functionAllowList;
268268
private List<FunctionDefinitionAst> functionDefinitionAsts;
269-
private bool useFunctionWhitelist;
269+
private bool useFunctionAllowList;
270270

271271
public ViolationFinder()
272272
{
273-
functionWhitelist = new HashSet<string>();
273+
functionAllowList = new HashSet<string>();
274274
functionDefinitionAsts = new List<FunctionDefinitionAst>();
275275
}
276276

@@ -281,12 +281,12 @@ public ViolationFinder(HashSet<string> exportedFunctions) : this()
281281
throw new ArgumentNullException(nameof(exportedFunctions));
282282
}
283283

284-
this.functionWhitelist = exportedFunctions;
284+
this.functionAllowList = exportedFunctions;
285285
}
286286

287287
public ViolationFinder(HashSet<string> exportedFunctions, bool exportedOnly) : this(exportedFunctions)
288288
{
289-
this.useFunctionWhitelist = exportedOnly;
289+
this.useFunctionAllowList = exportedOnly;
290290
}
291291

292292
public IEnumerable<FunctionDefinitionAst> FunctionDefinitionAsts
@@ -299,7 +299,7 @@ public IEnumerable<FunctionDefinitionAst> FunctionDefinitionAsts
299299

300300
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst funcAst)
301301
{
302-
if ((!useFunctionWhitelist || functionWhitelist.Contains(funcAst.Name))
302+
if ((!useFunctionAllowList || functionAllowList.Contains(funcAst.Name))
303303
&& funcAst.GetHelpContent() == null)
304304
{
305305
functionDefinitionAsts.Add(funcAst);

Rules/UseCompatibleCmdlets.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,7 @@ private bool RuleParamsValid(Dictionary<string, object> ruleArgs)
498498
}
499499

500500
/// <summary>
501-
/// Check if current command is present in the whitelists
501+
/// Check if current command is present in the allowlists
502502
/// If not, flag the corresponding value in curCmdletCompatibilityMap
503503
/// </summary>
504504
private void CheckCompatibility()

Rules/UseConsistentWhitespace.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ private enum ErrorKind { BeforeOpeningBrace, Paren, Operator, SeparatorComma, Se
2626
AfterOpeningBrace, BeforeClosingBrace, BeforePipe, AfterPipe, BetweenParameter };
2727
private const int whiteSpaceSize = 1;
2828
private const string whiteSpace = " ";
29-
private readonly SortedSet<TokenKind> openParenKeywordWhitelist = new SortedSet<TokenKind>()
29+
private readonly SortedSet<TokenKind> openParenKeywordAllowList = new SortedSet<TokenKind>()
3030
{
3131
TokenKind.If,
3232
TokenKind.ElseIf,
@@ -474,7 +474,7 @@ private DiagnosticRecord getDiagnosticRecord(
474474

475475
private bool IsKeyword(Token token)
476476
{
477-
return openParenKeywordWhitelist.Contains(token.Kind);
477+
return openParenKeywordAllowList.Contains(token.Kind);
478478
}
479479

480480
private static bool IsPreviousTokenApartByWhitespace(LinkedListNode<Token> tokenNode)

Rules/UseSingularNouns.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
2828
[Export(typeof(IScriptRule))]
2929
public class CmdletSingularNoun : IScriptRule {
3030

31-
private readonly string[] nounWhiteList =
31+
private readonly string[] nounAllowList =
3232
{
3333
"Data"
3434
};
@@ -68,7 +68,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName) {
6868
if (!ps.IsSingular(noun) && ps.IsPlural(noun))
6969
{
7070
IScriptExtent extent = Helper.Instance.GetScriptExtentForFunctionName(funcAst);
71-
if (nounWhiteList.Contains(noun, StringComparer.OrdinalIgnoreCase))
71+
if (nounAllowList.Contains(noun, StringComparer.OrdinalIgnoreCase))
7272
{
7373
continue;
7474
}

Tests/Engine/ModuleHelp.Tests.ps1

+5-5
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ $RequiredVersion = (Get-Command Invoke-ScriptAnalyzer).Module.Version
5858

5959
$ms = $null
6060
$commands = $null
61-
$paramBlackList = @(
61+
$paramBlockList = @(
6262
'AttachAndDebug' # Reason: When building with DEGUG configuration, an additional parameter 'AttachAndDebug' will be added to Invoke-ScriptAnalyzer and Invoke-Formatter, but there is no Help for those, as they are not intended for production usage.
6363
)
6464
[string] $ModuleName = 'PSScriptAnalyzer'
@@ -89,11 +89,11 @@ $testCases = $commands.ForEach{
8989

9090

9191
BeforeAll {
92-
$paramBlackList = @(
92+
$paramBlockList = @(
9393
'AttachAndDebug' # Reason: When building with DEGUG configuration, an additional parameter 'AttachAndDebug' will be added to Invoke-ScriptAnalyzer and Invoke-Formatter, but there is no Help for those, as they are not intended for production usage.
9494
)
9595
if ($PSVersionTable.PSVersion -lt '5.0') {
96-
$paramBlackList += 'SaveDscDependency'
96+
$paramBlockList += 'SaveDscDependency'
9797
}
9898
}
9999

@@ -217,7 +217,7 @@ Describe 'Cmdlet parameter help' {
217217
$HelpParameterNames = $Help.Parameters.Parameter.Name | Sort-Object -Unique
218218

219219
foreach ($parameter in $parameters) {
220-
if ($parameter.Name -in $paramBlackList) {
220+
if ($parameter.Name -in $paramBlockList) {
221221
continue
222222
}
223223
$parameterName = $parameter.Name
@@ -242,7 +242,7 @@ Describe 'Cmdlet parameter help' {
242242
}
243243

244244
foreach ($helpParam in $HelpParameterNames) {
245-
if ($helpParam -in $paramBlackList) {
245+
if ($helpParam -in $paramBlockList) {
246246
continue
247247
}
248248
$helpParam -in $parameterNames | Should -BeTrue -Because "There should be no extra parameters in help. '$helpParam' was not in '$parameterNames'"

Tests/Engine/Settings.tests.ps1

+26-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,32 @@ Describe "Settings Class" {
7979
}
8080
}
8181

82-
Context "When rule arguments are provided in a hashtable" {
82+
Context 'When rule arguments are provided in a hashtable' {
83+
BeforeAll {
84+
$settingsHashtable = @{
85+
Rules = @{
86+
PSAvoidUsingCmdletAliases = @{
87+
AllowList = @('cd', 'cp')
88+
}
89+
}
90+
}
91+
$settings = New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable
92+
}
93+
94+
It 'Should return the rule arguments' {
95+
$settings.RuleArguments['PSAvoidUsingCmdletAliases']['AllowList'].Count | Should -Be 2
96+
$settings.RuleArguments['PSAvoidUsingCmdletAliases']['AllowList'][0] | Should -Be 'cd'
97+
$settings.RuleArguments['PSAvoidUsingCmdletAliases']['AllowList'][1] | Should -Be 'cp'
98+
}
99+
100+
It 'Should Be case insensitive' {
101+
$settings.RuleArguments['psAvoidUsingCmdletAliases']['AllowList'].Count | Should -Be 2
102+
$settings.RuleArguments['psAvoidUsingCmdletAliases']['AllowList'][0] | Should -Be 'cd'
103+
$settings.RuleArguments['psAvoidUsingCmdletAliases']['AllowList'][1] | Should -Be 'cp'
104+
}
105+
}
106+
107+
Context 'When rule arguments are provided in a hashtable (legacy argument name)' {
83108
BeforeAll {
84109
$settingsHashtable = @{
85110
Rules = @{

Tests/Engine/SettingsTest/Issue828/PSScriptAnalyzerSettings.psd1

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
@{
22
Severity = @(
3-
'Error',
4-
'Warning',
3+
'Error',
4+
'Warning',
55
'Information'
66
)
77
ExcludeRules = @(
@@ -14,7 +14,7 @@
1414
CheckHashtable = $true
1515
}
1616
PSAvoidUsingCmdletAliases = @{
17-
# only whitelist verbs from *-Object cmdlets
17+
# only allowlist verbs from *-Object cmdlets
1818
Whitelist = @(
1919
'%',
2020
'?',

Tests/Rules/AvoidUsingAlias.tests.ps1

+7-7
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,9 @@ Configuration MyDscConfiguration {
6767
}
6868
}
6969

70-
Context "Settings file provides whitelist" {
70+
Context "Settings file provides allowlist" {
7171
BeforeAll {
72-
$whiteListTestScriptDef = 'gci; cd;'
72+
$allowListTestScriptDef = 'gci; cd;'
7373
$settings = @{
7474
'Rules' = @{
7575
'PSAvoidUsingCmdletAliases' = @{
@@ -79,26 +79,26 @@ Configuration MyDscConfiguration {
7979
}
8080
}
8181

82-
It "honors the whitelist provided as hashtable" {
82+
It "honors the allowlist provided as hashtable" {
8383
$settings = @{
8484
'Rules' = @{
8585
'PSAvoidUsingCmdletAliases' = @{
8686
'Whitelist' = @('cd')
8787
}
8888
}
8989
}
90-
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $whiteListTestScriptDef -Settings $settings -IncludeRule $violationName
90+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $allowListTestScriptDef -Settings $settings -IncludeRule $violationName
9191
$violations.Count | Should -Be 1
9292
}
9393

94-
It "honors the whitelist provided through settings file" {
94+
It "honors the allowlist provided through settings file" {
9595
# even though join-path returns string, if we do not use tostring, then invoke-scriptanalyzer cannot cast it to string type
9696
$settingsFilePath = (Join-Path $PSScriptRoot (Join-Path 'TestSettings' 'AvoidAliasSettings.psd1')).ToString()
97-
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $whiteListTestScriptDef -Settings $settingsFilePath -IncludeRule $violationName
97+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $allowListTestScriptDef -Settings $settingsFilePath -IncludeRule $violationName
9898
$violations.Count | Should -Be 1
9999
}
100100

101-
It "honors the whitelist in a case-insensitive manner" {
101+
It "honors the allowlist in a case-insensitive manner" {
102102
$violations = Invoke-ScriptAnalyzer -ScriptDefinition "CD" -Settings $settings -IncludeRule $violationName
103103
$violations.Count | Should -Be 0
104104
}

Tests/Rules/UseSingularNounsReservedVerbs.tests.ps1

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Describe "UseSingularNouns" -Skip:$IsCoreCLR {
3030
}
3131
}
3232

33-
Context "When function names have nouns from whitelist" {
33+
Context "When function names have nouns from allowlist" {
3434

3535
It "ignores function name ending with Data" {
3636
$nounViolationScript = @'

0 commit comments

Comments
 (0)