Fix potential issue fetching keys (#335)

* Don't create unneeded dictionaries.

* Update .gitignore

* Code cleanup

* Update MetaData.cs

* Address Nullability Issues

* Simplify excerpt
This commit is contained in:
Gabe Stocco 2021-03-30 13:34:44 -07:00 коммит произвёл GitHub
Родитель 8fb53d0fd1
Коммит 46710cfc12
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
10 изменённых файлов: 45 добавлений и 31 удалений

1
.gitignore поставляемый
Просмотреть файл

@ -267,3 +267,4 @@ __pycache__/
/AppInspector/ApplicationInspector.Commands.xml
AppInspector/Resources/defaultRulesPkd.json
/AppInspector.CLI/Properties/launchSettings.json
RulesPacker/appinspector.log.txt

Просмотреть файл

@ -68,7 +68,7 @@ namespace Microsoft.ApplicationInspector.CLI
}
else
{
if (File.Exists(Utils.LogFilePath))
if (Utils.LogFilePath is not null && File.Exists(Utils.LogFilePath))
{
var fileInfo = new FileInfo(Utils.LogFilePath);
if (fileInfo.Length > 0)

Просмотреть файл

@ -253,7 +253,7 @@ namespace Microsoft.ApplicationInspector.CLI
foreach (TagSearchPattern pattern in tagGroup.Patterns ?? new List<TagSearchPattern>())
{
pattern.Detected = _appMetaData != null && _appMetaData.UniqueTags.Any(v => v.Contains(pattern.SearchPattern));
pattern.Detected = _appMetaData?.UniqueTags is not null && _appMetaData.UniqueTags.Any(v => v.Contains(pattern.SearchPattern));
if (unSupportedGroupsOrPatterns.Any(x => pattern.SearchPattern.ToLower().Contains(x)))
{
WriteOnce.Log?.Warn($"Unsupported tag group or pattern detected '{pattern.SearchPattern}'. See online documentation at https://github.com/microsoft/ApplicationInspector/wiki/3.5-Tags");

Просмотреть файл

@ -119,7 +119,7 @@ namespace Microsoft.ApplicationInspector.CLI
WriteOnce.General(string.Format("Source path: {0}", metaData.SourcePath));
WriteOnce.General(string.Format("Authors: {0}", metaData.Authors));
WriteOnce.General(string.Format("Last Updated: {0}", metaData.LastUpdated));
WriteOnce.General(string.Format("Languages: {0}", StringList(metaData.Languages.ToImmutableSortedDictionary())));
WriteOnce.General(string.Format("Languages: {0}", StringList(metaData.Languages?.ToImmutableSortedDictionary() ?? new Dictionary<string,int>().ToImmutableSortedDictionary())));
WriteOnce.General(string.Format(MakeHeading("Scan Settings")));
WriteOnce.General(string.Format("Date scanned: {0}", metaData.DateScanned));
WriteOnce.General(string.Format(MakeHeading("Source Info")));

Просмотреть файл

@ -144,7 +144,7 @@ namespace Microsoft.ApplicationInspector.Commands
{
throw new OpException(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_RESULTS_FAIL));
}
packRulesResult.Rules = new List<Rule>(verifier.CompiledRuleset.AsEnumerable());
packRulesResult.Rules = new List<Rule>(verifier.CompiledRuleset?.AsEnumerable() ?? new RuleSet(null).AsEnumerable());
packRulesResult.ResultCode = PackRulesResult.ExitCode.Success;
}
catch (OpException e)

Просмотреть файл

@ -106,7 +106,7 @@ namespace Microsoft.ApplicationInspector.Commands
}
bool CounterOnlyTagSet = false;
var selected = TagCounters.Where(x => matchRecord.Tags.Any(y => y.Contains(x.Value.Tag ?? "")));
var selected = matchRecord.Tags is not null ? TagCounters.Where(x => matchRecord.Tags.Any(y => y.Contains(x.Value.Tag ?? ""))) : new Dictionary<string, MetricTagCounter>();
foreach (var select in selected)
{
CounterOnlyTagSet = true;
@ -139,16 +139,28 @@ namespace Microsoft.ApplicationInspector.Commands
/// </summary>
public void PrepareReport()
{
Metadata.CPUTargets = CPUTargets.ToImmutableSortedDictionary().Keys.ToList();
Metadata.AppTypes = AppTypes.ToImmutableSortedDictionary().Keys.ToList();
Metadata.OSTargets = OSTargets.ToImmutableSortedDictionary().Keys.ToList();
Metadata.UniqueDependencies = UniqueDependencies.ToImmutableSortedDictionary().Keys.ToList();
Metadata.UniqueTags = UniqueTags.ToImmutableSortedDictionary().Keys.ToList();
Metadata.CloudTargets = CloudTargets.ToImmutableSortedDictionary().Keys.ToList();
Metadata.PackageTypes = PackageTypes.ToImmutableSortedDictionary().Keys.ToList();
Metadata.FileExtensions = FileExtensions.ToImmutableSortedDictionary().Keys.ToList();
Metadata.Outputs = Outputs.ToImmutableSortedDictionary().Keys.ToList();
Metadata.Targets = Targets.ToImmutableSortedDictionary().Keys.ToList();
Metadata.CPUTargets = CPUTargets.Keys.ToList();
Metadata.AppTypes = AppTypes.Keys.ToList();
Metadata.OSTargets = OSTargets.Keys.ToList();
Metadata.UniqueDependencies = UniqueDependencies.Keys.ToList();
Metadata.UniqueTags = UniqueTags.Keys.ToList();
Metadata.CloudTargets = CloudTargets.Keys.ToList();
Metadata.PackageTypes = PackageTypes.Keys.ToList();
Metadata.FileExtensions = FileExtensions.Keys.ToList();
Metadata.Outputs = Outputs.Keys.ToList();
Metadata.Targets = Targets.Keys.ToList();
Metadata.CPUTargets.Sort();
Metadata.AppTypes.Sort();
Metadata.OSTargets.Sort();
Metadata.UniqueDependencies.Sort();
Metadata.UniqueTags.Sort();
Metadata.CloudTargets.Sort();
Metadata.PackageTypes.Sort();
Metadata.FileExtensions.Sort();
Metadata.Outputs.Sort();
Metadata.Targets.Sort();
Metadata.Languages = Languages.ToImmutableSortedDictionary();
foreach (MetricTagCounter metricTagCounter in TagCounters.Values)
@ -209,7 +221,7 @@ namespace Microsoft.ApplicationInspector.Commands
public string DetectSolutionType(MatchRecord match)
{
string result = "";
if (match.Tags.Any(s => s.Contains("Application.Type")))
if (match.Tags is not null && match.Tags.Any(s => s.Contains("Application.Type")))
{
foreach (string tag in match.Tags ?? new string[] { })
{

Просмотреть файл

@ -73,7 +73,7 @@ namespace Microsoft.ApplicationInspector.Commands
{
_verified = true;
foreach (Rule rule in _rules.AsEnumerable())
foreach (Rule rule in _rules?.AsEnumerable() ?? Array.Empty<Rule>())
{
bool ruleVerified = CheckIntegrity(rule);
_ruleStatuses?.Add(new RuleStatus()
@ -104,8 +104,7 @@ namespace Microsoft.ApplicationInspector.Commands
else
{
// Check for same ID
Rule sameRule = _rules.FirstOrDefault(x => x.Id == rule.Id);
if (_rules.Count(x => x.Id == rule.Id) > 1)
if (_rules?.Count(x => x.Id == rule.Id) > 1)
{
_logger?.Error(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULES_DUPLICATEID_FAIL, rule.Id));
isValid = false;
@ -149,6 +148,10 @@ namespace Microsoft.ApplicationInspector.Commands
{
try
{
if (string.IsNullOrEmpty(searchPattern.Pattern))
{
throw new ArgumentException();
}
_ = new Regex(searchPattern.Pattern);
}
catch (Exception e)
@ -169,6 +172,7 @@ namespace Microsoft.ApplicationInspector.Commands
#region basicFileIO
private void LoadDirectory(string? path)
{
if (path is null) { return; }
foreach (string filename in Directory.EnumerateFileSystemEntries(path, "*.json", SearchOption.AllDirectories))
{
LoadFile(filename);

Просмотреть файл

@ -38,7 +38,7 @@ namespace Microsoft.ApplicationInspector.Commands
{
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
return fileVersionInfo.ProductVersion;
return fileVersionInfo.ProductVersion ?? string.Empty;
}
public static bool CLIExecutionContext { get; set; }

Просмотреть файл

@ -371,18 +371,11 @@ namespace Microsoft.ApplicationInspector.RulesEngine
minSpaces = (minSpaces == -1 || numPrefixSpaces < minSpaces) ? numPrefixSpaces : minSpaces;
}
var sb = new StringBuilder();
// We want to go from (start - 5) to (start + 5) (off by one?)
// LINE=10, len=5, we want 8..12, so N-(L-1)/2 to N+(L-1)/2
// But cap those values at 0/end
for (var i = excerptStartLine; i <= excerptEndLine; i++)
{
string line = lines[i].Substring(minSpaces).TrimEnd();
sb.AppendLine(line);
}
return sb.ToString();
return string.Join(Environment.NewLine, lines[excerptStartLine..(excerptEndLine + 1)].Select(x => x[minSpaces..].TrimEnd()));
}
/// <summary>

Просмотреть файл

@ -90,6 +90,10 @@ namespace Microsoft.ApplicationInspector.RulesEngine
/// <param name="collection"> Collection of rules </param>
public void AddRange(IEnumerable<Rule>? collection)
{
if (collection is null)
{
return;
}
foreach (var rule in collection.Select(AppInspectorRuleToOatRule))
{
if (rule != null)
@ -366,12 +370,12 @@ namespace Microsoft.ApplicationInspector.RulesEngine
else if (pattern.PatternType == PatternType.String)
{
pattern.PatternType = PatternType.Regex;
pattern.Pattern = string.Format(CultureInfo.InvariantCulture, @"\b{0}\b", Regex.Escape(pattern.Pattern));
pattern.Pattern = string.Format(CultureInfo.InvariantCulture, @"\b{0}\b", Regex.Escape(pattern.Pattern ?? string.Empty));
}
else if (pattern.PatternType == PatternType.Substring)
{
pattern.PatternType = PatternType.Regex;
pattern.Pattern = string.Format(CultureInfo.InvariantCulture, @"{0}", Regex.Escape(pattern.Pattern));
pattern.Pattern = string.Format(CultureInfo.InvariantCulture, @"{0}", Regex.Escape(pattern.Pattern ?? string.Empty));
}
}
}