Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Modules/DSCParser/DSCParser.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
RootModule = 'DSCParser.psm1'

# Version number of this module.
ModuleVersion = '3.1.0.4'
ModuleVersion = '3.1.0.5'

# ID used to uniquely identify this module
GUID = 'e168239a-233d-468d-9025-d6dfc0e4e2b6'
Expand Down Expand Up @@ -110,7 +110,7 @@
IconUri = 'https://github.com/Microsoft365DSC/DSCParser/blob/master/Images/DSCParser.png?raw=true'

# ReleaseNotes of this module
ReleaseNotes = '* Improve caching and performance during discovery and parsing of DSC resources.'
ReleaseNotes = '* Quote unquoted property values that PowerShell cannot parse as an expression, such as a GUID substituted for a variable reference.'
} # End of PSData hashtable

} # End of PrivateData hashtable
Expand Down
135 changes: 127 additions & 8 deletions src/DSCParser.CSharp/DscParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,31 @@ public static List<DscResourceInstance> ConvertToDscObject(string? path = null,
ScriptBlockAst ast;
Token[] tokens;
ParseError[] parseErrors;
ConfigurationDefinitionAst? configAst;
try
{
RegisterKeywords(modulesToLoad, errorPrefix);
DscKeywordRegistry.MaterializeKeywordTable();
ast = Parser.ParseInput(
RemoveImportDscResourceStatements(dscContent), out tokens, out parseErrors);
string parseContent = RemoveImportDscResourceStatements(dscContent);
ast = Parser.ParseInput(parseContent, out tokens, out parseErrors);
configAst = FindConfigurationAst(ast);

if (HasFatalParseError(parseErrors, configAst) &&
TryReparseWithQuotedValues(parseContent, errorPrefix, hasFatalError: (errors, candidateAst) =>
HasFatalParseError(errors, FindConfigurationAst(candidateAst)),
out ScriptBlockAst repairedAst, out Token[] repairedTokens, out ParseError[] repairedErrors))
{
ast = repairedAst;
tokens = repairedTokens;
parseErrors = repairedErrors;
configAst = FindConfigurationAst(ast);
}
}
finally
{
DscKeywordRegistry.ClearKeywordTable();
}

// Find the Configuration definition
ConfigurationDefinitionAst? configAst = ast.Find(a => a is ConfigurationDefinitionAst, false) as ConfigurationDefinitionAst;

ReportParseErrors(parseErrors, configAst, errorPrefix);

if (configAst is null)
Expand Down Expand Up @@ -392,6 +402,31 @@ private static void RegisterKeywords(List<ModuleReference> modulesToLoad, string
}
}

private static ConfigurationDefinitionAst? FindConfigurationAst(ScriptBlockAst ast)
{
return ast.Find(a => a is ConfigurationDefinitionAst, false) as ConfigurationDefinitionAst;
}

private static bool IsOutsideConfiguration(ParseError error, ConfigurationDefinitionAst? configAst)
{
return configAst is not null &&
(error.Extent.StartOffset < configAst.Extent.StartOffset ||
error.Extent.EndOffset > configAst.Extent.EndOffset);
}

private static bool HasFatalParseError(ParseError[] parseErrors, ConfigurationDefinitionAst? configAst)
{
foreach (ParseError error in parseErrors)
{
if (!IsOutsideConfiguration(error, configAst) && !IsRecoverableParseError(error))
{
return true;
}
}

return false;
}

/// <summary>
/// Errors outside the configuration block never affected the conversion, and registering the
/// keywords up front makes PowerShell report some constructs that follow the block, such as the
Expand All @@ -401,9 +436,7 @@ private static void ReportParseErrors(ParseError[] parseErrors, ConfigurationDef
{
foreach (ParseError error in parseErrors)
{
if (configAst is not null &&
(error.Extent.StartOffset < configAst.Extent.StartOffset ||
error.Extent.EndOffset > configAst.Extent.EndOffset))
if (IsOutsideConfiguration(error, configAst))
{
continue;
}
Expand All @@ -419,6 +452,82 @@ private static void ReportParseErrors(ParseError[] parseErrors, ConfigurationDef
}
}

/// <summary>
/// Quotes the unparsable bare values in the content and reparses it, keeping the result only
/// when it removes every fatal error.
/// </summary>
/// <returns>True when the reparsed content replaced the original.</returns>
private static bool TryReparseWithQuotedValues(
string content,
string errorPrefix,
Func<ParseError[], ScriptBlockAst, bool> hasFatalError,
out ScriptBlockAst ast,
out Token[] tokens,
out ParseError[] parseErrors)
{
ast = null!;
tokens = [];
parseErrors = [];

string repaired = QuoteUnparsableBareValues(content, out int repairedCount);
if (repairedCount == 0)
{
return false;
}

ScriptBlockAst repairedAst = Parser.ParseInput(repaired, out Token[] repairedTokens, out ParseError[] repairedErrors);
if (hasFatalError(repairedErrors, repairedAst))
{
return false;
}

ast = repairedAst;
tokens = repairedTokens;
parseErrors = repairedErrors;

ReportWarning(
$"{errorPrefix}Quoted {repairedCount} unquoted value(s) that PowerShell cannot parse as an expression, " +
"such as a GUID substituted for a variable reference. They were converted as strings.");

return true;
}

// Matches a line holding nothing but a single bare token, either as the right-hand side of a
// property assignment or as a standalone array element. Requiring a single token keeps
// statements such as "Configuration Name" out of the repair.
private static readonly Regex BareValueLineRegex = new(
@"^(?<lead>[ \t]*(?:[A-Za-z_]\w*[ \t]*=[ \t]*)?)(?<value>[^\s""'$@(){}\[\]#`,;|]+)(?<trail>[ \t]*[;,]?[ \t]*\r?)$",
RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Multiline);

private const string BareValueProbePrefix = "$DscParserBareValueProbe = ";

/// <summary>
/// Wraps every bare value that is not a valid PowerShell expression in single quotes. Textual
/// variable substitution can leave a value such as "12345678-1234-1234-ad9c-123456789abc"
/// unquoted, which PowerShell tokenizes as arithmetic and rejects.
/// </summary>
private static string QuoteUnparsableBareValues(string content, out int repairedCount)
{
int count = 0;
string result = BareValueLineRegex.Replace(content, match =>
{
string value = match.Groups["value"].Value;

_ = Parser.ParseInput(BareValueProbePrefix + value, out Token[] _, out ParseError[] probeErrors);
if (probeErrors.Length == 0)
{
return match.Value;
}

count++;
return $"{match.Groups["lead"].Value}'{value}'{match.Groups["trail"].Value}";
});

repairedCount = count;

return result;
}

private readonly struct ModuleReference(string name, Version? version)
{
public string Name { get; } = name;
Expand Down Expand Up @@ -457,6 +566,16 @@ private static List<DscResourceInstance> ConvertUsingRegisteredKeywords(
{
DscKeywordRegistry.MaterializeSchemaCacheKeywords();
nodeAst = Parser.ParseInput(nodeBody, out tokens, out parseErrors);

if (HasFatalParseError(parseErrors, configAst: null) &&
TryReparseWithQuotedValues(nodeBody, errorPrefix, hasFatalError: (errors, _) =>
HasFatalParseError(errors, configAst: null),
out ScriptBlockAst repairedAst, out Token[] repairedTokens, out ParseError[] repairedErrors))
{
nodeAst = repairedAst;
tokens = repairedTokens;
parseErrors = repairedErrors;
}
}
finally
{
Expand Down
109 changes: 108 additions & 1 deletion src/DSCParser.Tests/DscParserEndToEndTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,4 +251,111 @@ public void ConvertToDscObject_WithNullPathAndContent_ShouldThrow()
DscParser.ClearCaches();
}
}
}

[Fact]
public void ConvertToDscObject_WithUnquotedGuidValue_ShouldQuoteItAndParse()
{
SeedResources("File");
try
{
const string config = """
Configuration TestConfig
{
Node localhost
{
File Sample
{
DestinationPath = 'C:\x';
OrganizationId = 12345678-1234-1234-ad9c-123456789abc;
Ensure = 'Present';
}
}
}
""";

var warnings = new List<string>();
DscParser.WarningSink = warnings.Add;
try
{
var result = DscParser.ConvertToDscObject(content: config);

Assert.Single(result);
Assert.Equal("12345678-1234-1234-ad9c-123456789abc", result[0].Properties["OrganizationId"]);
Assert.Equal("Present", result[0].Properties["Ensure"]);
}
finally
{
DscParser.WarningSink = null;
}

Assert.Contains(warnings, w => w.Contains("Quoted 1 unquoted value"));
}
finally
{
DscParser.ClearCaches();
}
}

[Fact]
public void ConvertToDscObject_WithUnquotedGuidInsideCimInstance_ShouldQuoteIt()
{
SeedResources("File");
try
{
const string config = """
Configuration TestConfig
{
Node localhost
{
File Sample
{
DestinationPath = 'C:\x';
PsDscRunAsCredential = MSFT_Credential{
UserName = 12345678-1234-1234-ad9c-123456789abc
Password = 'p'
};
}
}
}
""";

var result = DscParser.ConvertToDscObject(content: config);

Assert.Single(result);
var credential = (IDictionary)result[0].Properties["PsDscRunAsCredential"]!;
Assert.Equal("12345678-1234-1234-ad9c-123456789abc", credential["UserName"]);
Assert.Equal("p", credential["Password"]);
}
finally
{
DscParser.ClearCaches();
}
}

[Fact]
public void ConvertToDscObject_WithUnrepairableError_ShouldStillThrow()
{
SeedResources("File");
try
{
const string config = """
Configuration TestConfig
{
Node localhost
{
File Sample
{
DestinationPath = 'C:\x'; Ensure = @{
}
}
}
""";

Assert.Throws<InvalidOperationException>(() => DscParser.ConvertToDscObject(content: config));
}
finally
{
DscParser.ClearCaches();
}
}
}
53 changes: 53 additions & 0 deletions src/DSCParser.Tests/DscParserPrivateMethodTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -561,4 +561,57 @@ public void ReportWarning_WithNullSink_ShouldDoNothing()
}

#endregion

#region QuoteUnparsableBareValues

private static readonly MethodInfo _quoteUnparsableBareValues =
typeof(DscParser).GetMethod("QuoteUnparsableBareValues", BindingFlags.NonPublic | BindingFlags.Static)
?? throw new InvalidOperationException("QuoteUnparsableBareValues method not found");

private static string QuoteUnparsableBareValues(string content, out int repairedCount)
{
object?[] arguments = [content, 0];
string result = (string)_quoteUnparsableBareValues.Invoke(null, arguments)!;
repairedCount = (int)arguments[1]!;

return result;
}

[Fact]
public void QuoteUnparsableBareValues_ShouldQuoteAnAssignmentAndAnArrayElement()
{
const string content = """
Ids = @(
11111111-1234-1234-ad9c-123456789abc
22222222-1234-1234-ad9c-123456789abc
)
OrganizationId = 12345678-1234-1234-ad9c-123456789abc;
""";

string result = QuoteUnparsableBareValues(content, out int repairedCount);

Assert.Equal(3, repairedCount);
Assert.Contains("'11111111-1234-1234-ad9c-123456789abc'", result, StringComparison.Ordinal);
Assert.Contains("'22222222-1234-1234-ad9c-123456789abc'", result, StringComparison.Ordinal);
Assert.Contains("OrganizationId = '12345678-1234-1234-ad9c-123456789abc';", result, StringComparison.Ordinal);
}

[Theory]
[InlineData("Configuration TestConfig")]
[InlineData("Node localhost")]
[InlineData("Import-DscResource -ModuleName Microsoft365DSC")]
[InlineData(" Ensure = 'Present'")]
[InlineData(" Ensure = Present")]
[InlineData(" TenantId = $OrganizationName")]
[InlineData(" Id = abcdef78-1234-1234-ad9c-123456789abc")]
[InlineData(" # OrganizationId = 12345678-1234-1234-ad9c-123456789abc")]
public void QuoteUnparsableBareValues_WithParsableContent_ShouldLeaveItUnchanged(string content)
{
string result = QuoteUnparsableBareValues(content, out int repairedCount);

Assert.Equal(0, repairedCount);
Assert.Equal(content, result);
}

#endregion
}
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryUrl>https://github.com/Microsoft365DSC/DSCParser</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Version>3.1.0.4</Version>
<Version>3.1.0.5</Version>
</PropertyGroup>

</Project>