Skip to content

Commit a329d98

Browse files
author
Kapil Borle
committed
Fix ignoring localhost in AvoidUsingComputerNameHardcoded rule
The rule did not ignore localhost, 127.0.0.1 and ::1 as computer name arguments. This commit fixes the issue and also adds relevant test cases.
1 parent a266c62 commit a329d98

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

Rules/AvoidUsingComputerNameHardcoded.cs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,18 +55,26 @@ public override bool ParameterCondition(CommandAst CmdAst, CommandElementAst CeA
5555
if (String.Equals(cmdParamAst.ParameterName, "computername", StringComparison.OrdinalIgnoreCase))
5656
{
5757
List<string> localhostRepresentations = new List<string> { "localhost", ".", "::1", "127.0.0.1" };
58-
Ast computerNameArgument = GetComputerNameArg(CmdAst, cmdParamAst.Extent.StartOffset);
58+
Ast computerNameArgument = GetComputerNameArg(CmdAst, cmdParamAst.Extent.StartOffset);
5959

6060
if (null != computerNameArgument)
6161
{
62-
if (!localhostRepresentations.Contains(computerNameArgument.Extent.Text.ToLower()))
62+
var constExprAst = computerNameArgument as ConstantExpressionAst;
63+
if (null != constExprAst)
6364
{
64-
return computerNameArgument is ConstantExpressionAst;
65+
var constExprVal = constExprAst.Value as string;
66+
if (null != constExprVal)
67+
{
68+
return !localhostRepresentations.Contains<string>(
69+
constExprVal,
70+
StringComparer.OrdinalIgnoreCase);
71+
}
72+
6573
}
6674

6775
return false;
6876
}
69-
77+
7078
if (null != cmdParamAst.Argument && !localhostRepresentations.Contains(cmdParamAst.Argument.ToString().Replace("\"", "").Replace("'", "").ToLower()))
7179
{
7280
return cmdParamAst.Argument is ConstantExpressionAst;

Tests/Rules/AvoidUsingComputerNameHardcoded.tests.ps1

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,23 @@ Describe "AvoidUsingComputerNameHardcoded" {
2222
$noViolations.Count | Should Be 0
2323
}
2424
}
25+
26+
Context "When the argument refers to localhost" {
27+
$testCases = @(
28+
@{ localhostName = 'localhost' },
29+
@{ localhostName = '127.0.0.1' },
30+
@{ localhostName = '::1' }
31+
)
32+
33+
It "returns no violation for <localhostName>" -TestCases $testCases {
34+
param($localhostName)
35+
$params = @{
36+
ScriptDefinition = "Invoke-Command -ComputerName $localhostName"
37+
IncludeRule = $violationName
38+
}
39+
40+
$violations = Invoke-ScriptAnalyzer @params
41+
$violations.Count | Should Be 0
42+
}
43+
}
2544
}

0 commit comments

Comments
 (0)