-
Notifications
You must be signed in to change notification settings - Fork 91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support queries against properties in the result's and the rule's property bags #2065
Merged
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
e45640f
Introduce a test file for property bag queries.
dd339a1
Support string-valued result properties.
0bf0eb9
Support string-valued rule properties.
0127f51
Merge branch 'master' into users/lgolding/query-enhancements
dae325d
Clarify property bag query syntax and restore ability to recognize in…
f3237ea
Compare property bag properties case-insensitively.
19f9452
Handle integer-valued properties.
ca14f3a
Update version number and release history.
33a380c
Handle float properties.
5db9c2e
Generalize exception messages.
ec49670
Separate property bag tests.
f451593
DRY out test setup into a fixture.
f52c63c
Restore erroneously edited comment.
16dd3a7
Simplify query syntax by inferring whether string or numeric comparis…
f36b8c7
Merge from master; resolve conflicts.
9d31cb2
Fix up test project file.
33bbcde
Remove unnecessary else.
2d97cc0
Case-sensitive property name comparison with minimal code change.
f65d733
Simplify code.
def2fa7
Bump version, correct release history.
2ffff18
Merge branch 'master' into users/lgolding/query-enhancements
2130ff4
Merge branch 'master' into users/lgolding/query-enhancements
0ffaef5
Merge branch 'master' into users/lgolding/query-enhancements
michaelcfanning File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
108 changes: 108 additions & 0 deletions
108
src/Sarif/Query/Evaluators/PropertyBagPropertyEvaluator.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
using System; | ||
using System.Collections; | ||
using System.Collections.Generic; | ||
using System.Collections.ObjectModel; | ||
using System.Globalization; | ||
using System.Linq; | ||
using System.Text.RegularExpressions; | ||
using Newtonsoft.Json; | ||
|
||
namespace Microsoft.CodeAnalysis.Sarif.Query.Evaluators | ||
{ | ||
public class PropertyBagPropertyEvaluator : IExpressionEvaluator<Result> | ||
{ | ||
internal const string ResultPropertyPrefix = "properties."; | ||
internal const string RulePropertyPrefix = "rule.properties."; | ||
|
||
private readonly string _propertyName; | ||
private readonly bool _propertyBelongsToRule; | ||
private readonly IExpressionEvaluator<Result> _evaluator; | ||
|
||
private static readonly Regex s_propertyNameRegex = new Regex( | ||
@$"^ | ||
(?<prefix>properties\.|rule\.properties\.) | ||
(?<name>.+?) | ||
$", | ||
RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace); | ||
|
||
public PropertyBagPropertyEvaluator(TermExpression term) | ||
{ | ||
Match match = s_propertyNameRegex.Match(term.PropertyName); | ||
_propertyName = match.Groups["name"].Value; | ||
|
||
string prefix = match.Groups["prefix"].Value; | ||
if (prefix.Equals(RulePropertyPrefix)) | ||
{ | ||
_propertyBelongsToRule = true; | ||
} | ||
else if (!prefix.Equals(ResultPropertyPrefix)) | ||
{ | ||
throw new ArgumentException( | ||
string.Format( | ||
CultureInfo.CurrentCulture, | ||
SdkResources.ErrorInvalidQueryPropertyPrefix, | ||
"'" + string.Join("', '", ResultPropertyPrefix, RulePropertyPrefix)) + "'", | ||
nameof(term)); | ||
} | ||
|
||
_evaluator = CreateEvaluator(term); | ||
} | ||
|
||
// Create an appropriate evaluator object for the specified term. For operators that apply | ||
// only to strings (":" (contains), "|>" (startswith), or ">|" (endswith), always create | ||
// a string evaluator. All other operators (==, !=, >, <, etc.) can apply to both strings | ||
// and numbers. If the value being compared parses as a number, assume that a numeric | ||
// comparison was intended, and create a numeric evaluator. Otherwise, create a string evaluator. | ||
// This could cause problems if the comparand is string that happens to look like a number. | ||
private IExpressionEvaluator<Result> CreateEvaluator(TermExpression term) => | ||
IsStringComparison(term) | ||
? new StringEvaluator<Result>(GetProperty<string>, term, StringComparison.OrdinalIgnoreCase) as IExpressionEvaluator<Result> | ||
: new DoubleEvaluator<Result>(GetProperty<double>, term); | ||
|
||
private static readonly ReadOnlyCollection<CompareOperator> s_stringSpecificOperators = | ||
new ReadOnlyCollection<CompareOperator>( | ||
new CompareOperator[] | ||
{ | ||
CompareOperator.Contains, | ||
CompareOperator.EndsWith, | ||
CompareOperator.StartsWith | ||
}); | ||
|
||
private bool IsStringComparison(TermExpression term) | ||
=> s_stringSpecificOperators.Contains(term.Operator) || !double.TryParse(term.Value, out _); | ||
|
||
private T GetProperty<T>(Result result) | ||
{ | ||
PropertyBagHolder holder = GetPropertyBagHolder(result); | ||
return GetPropertyFromHolder<T>(holder); | ||
} | ||
|
||
private PropertyBagHolder GetPropertyBagHolder(Result result) => | ||
_propertyBelongsToRule | ||
? result.GetRule() as PropertyBagHolder | ||
: result; | ||
|
||
private T GetPropertyFromHolder<T>(PropertyBagHolder holder) | ||
{ | ||
try | ||
{ | ||
return holder.TryGetProperty(_propertyName, out T value) ? value : default; | ||
} | ||
catch (JsonReaderException) | ||
{ | ||
// Catch exceptions due to trying to perform a numeric comparison on a | ||
// property that turns out to have a string value that can't be parsed | ||
// as a number. The result will be that in such a case, the property | ||
// will be treated as if its value were numeric zero. | ||
} | ||
|
||
return default; | ||
} | ||
|
||
public void Evaluate(ICollection<Result> results, BitArray matches) | ||
=> _evaluator.Evaluate(results, matches); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
src/Test.UnitTests.Sarif.Multitool/QueryCommandPropertyBagTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using System; | ||
using System.IO; | ||
using FluentAssertions; | ||
using Microsoft.CodeAnalysis.Sarif.Query; | ||
using Microsoft.CodeAnalysis.Sarif.Query.Evaluators; | ||
using Newtonsoft.Json; | ||
using Xunit; | ||
|
||
namespace Microsoft.CodeAnalysis.Sarif.Multitool | ||
{ | ||
public class QueryCommandPropertyBagTests : IClassFixture<QueryCommandPropertyBagTests.TestFixture> | ||
{ | ||
private const string FilePath = "property-bag-queries.sarif"; | ||
|
||
public class TestFixture | ||
{ | ||
public TestFixture() | ||
{ | ||
ResourceExtractor extractor = new ResourceExtractor(typeof(QueryCommandPropertyBagTests)); | ||
File.WriteAllText(FilePath, extractor.GetResourceText($"QueryCommand.{FilePath}")); | ||
} | ||
} | ||
|
||
[Fact] | ||
public void QueryCommand_CanAccessResultAndRulePropertyBags() | ||
{ | ||
RunAndVerifyCount(2, "properties.name == 'Terisa'"); | ||
RunAndVerifyCount(2, "rule.properties.Category == 'security'"); | ||
} | ||
|
||
[Fact] | ||
public void QueryCommand_ComparesPropertyBagPropertyNamesCaseSensitively() | ||
{ | ||
RunAndVerifyCount(0, "properties.nAmE == 'Terisa'"); | ||
RunAndVerifyCount(0, "rule.properties.CaTegORy == 'security'"); | ||
} | ||
|
||
[Fact] | ||
public void QueryCommand_ReadsIntegerProperty() | ||
{ | ||
RunAndVerifyCount(1, "properties.count == 42"); | ||
} | ||
|
||
[Fact] | ||
public void QueryCommand_ReadsFloatProperty() | ||
{ | ||
RunAndVerifyCount(2, "properties.confidence >= 0.95"); | ||
} | ||
|
||
[Fact] | ||
public void QueryCommand_PerformsStringSpecificComparisons() | ||
{ | ||
RunAndVerifyCount(1, "properties.confidence : 95"); // contains | ||
RunAndVerifyCount(3, "properties.confidence |> 0."); // startswith | ||
RunAndVerifyCount(1, "properties.confidence >| 9"); // endswith | ||
} | ||
|
||
[Fact] | ||
public void QueryCommand_TreatsUnparseableValueAsHavingTheDefaultValue() | ||
{ | ||
// In this test, all the results will match, so we need to know how many there are. | ||
SarifLog sarifLog = JsonConvert.DeserializeObject<SarifLog>(File.ReadAllText(FilePath)); | ||
int numResults = sarifLog.Runs[0].Results.Count; | ||
|
||
// 'name' is a string-valued property that doesn't parse to an integer. The | ||
// PropertyBagPropertyEvaluator sees a number on the right-hand side of the comparison | ||
// and decides that a numeric comparison is intended. When it encounters a property | ||
// value that can't be parsed as a number, it treats it as numeric 0 rather than | ||
// throwing. | ||
RunAndVerifyCount(numResults, "properties.name == 0"); | ||
} | ||
|
||
// The above tests cover all but one code block in the underlying PropertyBagPropertyEvaluator. | ||
// It doesn't cover the case of an invalid "prefix" (that is, a property name that doesn't | ||
// start with "properties." or "rule.properties"), because QueryCommand never creates a | ||
// PropertyBagPropertyEvaluator for a term with such a property name. So we cover that | ||
// case here: | ||
[Fact] | ||
public void PropertyBagPropertyEvaluator_RejectsPropertyNameWithInvalidPrefix() | ||
{ | ||
var expression = new TermExpression(propertyName: "invalid.prefix", op: CompareOperator.Equals, value: string.Empty); | ||
|
||
Action action = () => new PropertyBagPropertyEvaluator(expression); | ||
|
||
action.Should().Throw<ArgumentException>(); | ||
} | ||
|
||
private void RunAndVerifyCount(int expectedCount, string expression) | ||
{ | ||
var options = new QueryOptions | ||
{ | ||
Expression = expression, | ||
InputFilePath = FilePath, | ||
ReturnCount = true | ||
}; | ||
|
||
int exitCode = new QueryCommand().RunWithoutCatch(options); | ||
exitCode.Should().Be(expectedCount); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this looks weird. Why is this named TryGetProperty if it can raise an exception? seems wrong to me. instead, TryProperty should handle the exception and return 'false'.
i won't block on this but i don't this it's right.