private void OutputSarifRulesMetada(string outputFilePath, ImmutableArray <IRule> skimmers, ImmutableArray <IOptionsProvider> options) { var log = new SarifLog(); SarifVersion sarifVersion = SarifVersion.OneZeroZeroBetaFive; log.SchemaUri = sarifVersion.ConvertToSchemaUri(); log.Version = sarifVersion; // The SARIF spec currently requires an array // of run logs with at least one member log.Runs = new List <Run>(); var run = new Run(); run.Tool = new Tool(); run.Tool.InitializeFromAssembly(this.GetType().Assembly, Prerelease); run.Results = new List <Result>(); log.Runs.Add(run); run.Rules = new Dictionary <string, Rule>(); SortedDictionary <int, Rule> sortedRules = new SortedDictionary <int, Rule>(); foreach (IRule rule in skimmers) { var newRule = new Rule(); newRule.Id = rule.Id; newRule.Name = rule.Name; newRule.HelpUri = rule.HelpUri; newRule.FullDescription = rule.FullDescription; newRule.MessageFormats = rule.MessageFormats; newRule.ShortDescription = rule.ShortDescription; foreach (string propertyName in rule.PropertyNames) { newRule.SetProperty(propertyName, rule.GetProperty(propertyName)); } int numericId = GetIdIntegerSuffix(newRule.Id); sortedRules[numericId] = newRule; } foreach (Rule rule in sortedRules.Values) { run.Rules[rule.Id] = rule; } var settings = new JsonSerializerSettings() { ContractResolver = SarifContractResolver.Instance, Formatting = Newtonsoft.Json.Formatting.Indented, }; File.WriteAllText(outputFilePath, JsonConvert.SerializeObject(log, settings)); }
/// <summary> /// Initializes the SARIF log by emitting properties and other constructs /// sufficient to being populating a run with results. /// </summary> /// <param name="id">A string that uniquely identifies a run.</param> /// <param name="automationId">A global identifier for a run that permits correlation with a larger automation process.</param> public void Initialize(string id, string automationId) { this.EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.Initialized); SarifVersion sarifVersion = SarifVersion.OneZeroZero; _jsonWriter.WriteStartObject(); // Begin: sarifLog _jsonWriter.WritePropertyName("$schema"); _jsonWriter.WriteValue(sarifVersion.ConvertToSchemaUri().OriginalString); _jsonWriter.WritePropertyName("version"); _jsonWriter.WriteValue(sarifVersion.ConvertToText()); _jsonWriter.WritePropertyName("runs"); _jsonWriter.WriteStartArray(); // Begin: runs _jsonWriter.WriteStartObject(); // Begin: run if (!string.IsNullOrEmpty(id)) { _jsonWriter.WritePropertyName("id"); _serializer.Serialize(_jsonWriter, id, typeof(string)); } if (!string.IsNullOrEmpty(automationId)) { _jsonWriter.WritePropertyName("automationId"); _serializer.Serialize(_jsonWriter, automationId, typeof(string)); } _writeConditions |= Conditions.Initialized; }
/// <summary> /// Initializes the SARIF log by emitting properties and other constructs /// sufficient to being populating a run with results. /// </summary> /// <param name="id">A string that uniquely identifies a run.</param> /// <param name="automationId">A global identifier for a run that permits correlation with a larger automation process.</param> public void Initialize(Run run) { if (run == null) { throw new ArgumentNullException(nameof(run)); } _run = run; this.EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.RunInitialized); SarifVersion sarifVersion = SarifVersion.Current; _jsonWriter.WriteStartObject(); // Begin: sarifLog _jsonWriter.WritePropertyName("$schema"); _jsonWriter.WriteValue(sarifVersion.ConvertToSchemaUri().OriginalString); _jsonWriter.WritePropertyName("version"); _jsonWriter.WriteValue(sarifVersion.ConvertToText()); _jsonWriter.WritePropertyName("runs"); _jsonWriter.WriteStartArray(); // Begin: runs _jsonWriter.WriteStartObject(); // Begin: run _writeConditions |= Conditions.RunInitialized; }
private void OutputSarifRulesMetada(string outputFilePath, ImmutableArray <ReportingDescriptor> skimmers) { var log = new SarifLog(); SarifVersion sarifVersion = SarifVersion.Current; log.SchemaUri = sarifVersion.ConvertToSchemaUri(); log.Version = sarifVersion; // The SARIF spec currently requires an array // of run logs with at least one member log.Runs = new List <Run>(); var run = new Run(); run.Tool = new Tool(); run.Tool = Tool.CreateFromAssemblyData(this.GetType().Assembly); run.Results = new List <Result>(); log.Runs.Add(run); SortedDictionary <int, ReportingDescriptor> sortedRules = new SortedDictionary <int, ReportingDescriptor>(); foreach (ReportingDescriptor rule in skimmers) { int numericId = GetIdIntegerSuffix(rule.Id); sortedRules[numericId] = rule; } run.Tool.Driver.Rules = new List <ReportingDescriptor>(sortedRules.Values); var settings = new JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.Indented, }; File.WriteAllText(outputFilePath, JsonConvert.SerializeObject(log, settings)); }
/// <summary> /// Initializes the SARIF log by emitting properties and other constructs /// sufficient to being populating a run with results. /// </summary> /// <param name="id">A string that uniquely identifies a run.</param> /// <param name="automationId">A global identifier for a run that permits correlation with a larger automation process.</param> public void Initialize(Run run) { if (run == null) { throw new ArgumentNullException(nameof(run)); } this.EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.RunInitialized); SarifVersion sarifVersion = SarifVersion.Current; _jsonWriter.WriteStartObject(); // Begin: sarifLog _jsonWriter.WritePropertyName("$schema"); _jsonWriter.WriteValue(sarifVersion.ConvertToSchemaUri().OriginalString); _jsonWriter.WritePropertyName("version"); _jsonWriter.WriteValue(sarifVersion.ConvertToText()); _jsonWriter.WritePropertyName("runs"); _jsonWriter.WriteStartArray(); // Begin: runs _jsonWriter.WriteStartObject(); // Begin: run if (run.Id != null) { _jsonWriter.WritePropertyName("id"); _serializer.Serialize(_jsonWriter, run.Id); } if (!string.IsNullOrEmpty(run.BaselineInstanceGuid)) { _jsonWriter.WritePropertyName("baselineInstanceGuid"); _serializer.Serialize(_jsonWriter, run.BaselineInstanceGuid); } if (run.AggregateIds != null) { _jsonWriter.WritePropertyName("aggregateIds"); _serializer.Serialize(_jsonWriter, run.AggregateIds); } if (run.Conversion != null) { _jsonWriter.WritePropertyName("conversion"); _serializer.Serialize(_jsonWriter, run.Conversion); } if (run.VersionControlProvenance != null) { _jsonWriter.WritePropertyName("versionControlProvenance"); _serializer.Serialize(_jsonWriter, run.VersionControlProvenance); } if (run.OriginalUriBaseIds != null) { _jsonWriter.WritePropertyName("originalUriBaseIds"); _serializer.Serialize(_jsonWriter, run.OriginalUriBaseIds); } if (run.DefaultFileEncoding != null) { _jsonWriter.WritePropertyName("defaultFileEncoding"); _serializer.Serialize(_jsonWriter, run.DefaultFileEncoding); } if (run.MarkdownMessageMimeType != null && run.MarkdownMessageMimeType != "text/markdown;variant=GFM") { _jsonWriter.WritePropertyName("markdownMessageMimeType"); _serializer.Serialize(_jsonWriter, run.MarkdownMessageMimeType); } if (run.RedactionToken != null) { _jsonWriter.WritePropertyName("redactionToken"); _serializer.Serialize(_jsonWriter, run.RedactionToken); } // For this Windows-relevant SDK, if the column kind isn't explicitly set, // we will set it to Utf16CodeUnits. Our jschema-generated OM is tweaked to // always persist this property. _jsonWriter.WritePropertyName("columnKind"); _jsonWriter.WriteValue(run.ColumnKind == ColumnKind.UnicodeCodePoints ? "unicodeCodePoints" : "utf16CodeUnits"); _writeConditions |= Conditions.RunInitialized; _run = run; }
public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true) { if (TextWriter is null) { throw new ArgumentNullException(nameof(TextWriter)); } string?basePath = null; if (commandOptions is CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions) { basePath = cLIAnalyzeCmdOptions.BasePath; if (result is AnalyzeResult analyzeResult) { SarifLog log = new(); SarifVersion sarifVersion = SarifVersion.Current; log.SchemaUri = sarifVersion.ConvertToSchemaUri(); log.Version = sarifVersion; log.Runs = new List <Run>(); var run = new Run(); if (Uri.TryCreate(cLIAnalyzeCmdOptions.RepositoryUri, UriKind.RelativeOrAbsolute, out Uri? uri)) { run.VersionControlProvenance = new List <VersionControlDetails>() { new VersionControlDetails() { RepositoryUri = uri, RevisionId = cLIAnalyzeCmdOptions.CommitHash } }; } var artifacts = new List <Artifact>(); run.Tool = new Tool { Driver = new ToolComponent { Name = $"Application Inspector", InformationUri = new Uri("https://github.com/microsoft/ApplicationInspector/"), Organization = "Microsoft", Version = Helpers.GetVersionString(), } }; var reportingDescriptors = new List <ReportingDescriptor>(); run.Results = new List <CodeAnalysis.Sarif.Result>(); foreach (var match in analyzeResult.Metadata.Matches) { var sarifResult = new CodeAnalysis.Sarif.Result(); if (match.Rule is not null) { if (!reportingDescriptors.Any(r => r.Id == match.Rule.Id)) { ReportingDescriptor reportingDescriptor = new() { FullDescription = new MultiformatMessageString() { Text = match.Rule.Description }, Id = match.Rule.Id, Name = match.Rule.Name, DefaultConfiguration = new ReportingConfiguration() { Level = GetSarifFailureLevel(match.Rule.Severity) } }; reportingDescriptor.Tags.AddRange(match.Rule.Tags); reportingDescriptors.Add(reportingDescriptor); } sarifResult.Level = GetSarifFailureLevel(match.Rule.Severity); sarifResult.RuleId = match.Rule.Id; sarifResult.Tags.AddRange(match.Rule.Tags); sarifResult.Message = new Message() { Text = match.Rule.Description }; if (match.FileName is not null) { string fileName = match.FileName; if (basePath is not null) { fileName = Path.GetRelativePath(basePath, fileName); } if (Uri.TryCreate(fileName, UriKind.RelativeOrAbsolute, out Uri? outUri)) { int artifactIndex = artifacts.FindIndex(a => a.Location.Uri.Equals(outUri)); if (artifactIndex == -1) { Artifact artifact = new() { Location = new ArtifactLocation() { Index = artifacts.Count, Uri = outUri }, }; artifactIndex = artifact.Location.Index; artifact.Tags.AddRange(match.Rule.Tags); if (Language.FromFileNameOut(fileName, out LanguageInfo languageInfo)) { artifact.SourceLanguage = languageInfo.Name; } artifacts.Add(artifact); } else { artifacts[artifactIndex].Tags.AddRange(match.Rule.Tags); } sarifResult.Locations = new List <Location>() { new Location() { PhysicalLocation = new PhysicalLocation() { ArtifactLocation = new ArtifactLocation() { Index = artifactIndex }, Region = new Region() { StartLine = match.StartLocationLine, StartColumn = match.StartLocationColumn, EndLine = match.EndLocationLine, EndColumn = match.EndLocationColumn, Snippet = new ArtifactContent() { Text = match.Sample } } } } }; } } } run.Artifacts = artifacts; run.Tool.Driver.Rules = reportingDescriptors; run.Results.Add(sarifResult); } log.Runs.Add(run); JsonSerializerSettings serializerSettings = new(); var serializer = new JsonSerializer(); serializer.Serialize(TextWriter, log); FlushAndClose(); } else { throw new ArgumentException("This writer can only write Analyze results.", nameof(result)); } } else { throw new ArgumentException("This writer requires a CLIAnalyzeCmdOptions options argument.", nameof(commandOptions)); } }
/// <summary> /// Initializes the SARIF log by emitting properties and other constructs /// sufficient to being populating a run with results. /// </summary> /// <param name="id">A string that uniquely identifies a run.</param> /// <param name="automationId">A global identifier for a run that permits correlation with a larger automation process.</param> public void Initialize(Run run) { if (run == null) { throw new ArgumentNullException(nameof(run)); } if (run.Tool == null) { throw new ArgumentNullException(nameof(run.Tool)); } this.EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.RunInitialized); SarifVersion sarifVersion = SarifVersion.TwoZeroZero; _jsonWriter.WriteStartObject(); // Begin: sarifLog _jsonWriter.WritePropertyName("$schema"); _jsonWriter.WriteValue(sarifVersion.ConvertToSchemaUri().OriginalString); _jsonWriter.WritePropertyName("version"); _jsonWriter.WriteValue(sarifVersion.ConvertToText()); _jsonWriter.WritePropertyName("runs"); _jsonWriter.WriteStartArray(); // Begin: runs _jsonWriter.WriteStartObject(); // Begin: run if (!string.IsNullOrEmpty(run.InstanceGuid)) { _jsonWriter.WritePropertyName("instanceGuid"); _serializer.Serialize(_jsonWriter, run.InstanceGuid); } if (!string.IsNullOrEmpty(run.BaselineInstanceGuid)) { _jsonWriter.WritePropertyName("baselineInstanceGuid"); _serializer.Serialize(_jsonWriter, run.BaselineInstanceGuid); } if (!string.IsNullOrEmpty(run.AutomationLogicalId)) { _jsonWriter.WritePropertyName("automationLogicalId"); _serializer.Serialize(_jsonWriter, run.AutomationLogicalId); } if (!string.IsNullOrEmpty(run.LogicalId)) { _jsonWriter.WritePropertyName("logicalId"); _serializer.Serialize(_jsonWriter, run.LogicalId); } if (!string.IsNullOrEmpty(run.Architecture)) { _jsonWriter.WritePropertyName("architecture"); _serializer.Serialize(_jsonWriter, run.Architecture); } if (run.Description != null) { _jsonWriter.WritePropertyName("description"); _serializer.Serialize(_jsonWriter, run.Description); } if (run.Tool != null) { _jsonWriter.WritePropertyName("tool"); _serializer.Serialize(_jsonWriter, run.Tool); } if (run.Conversion != null) { _jsonWriter.WritePropertyName("conversion"); _serializer.Serialize(_jsonWriter, run.Conversion); } if (run.VersionControlProvenance != null) { _jsonWriter.WritePropertyName("versionControlProvenance"); _serializer.Serialize(_jsonWriter, run.VersionControlProvenance); } if (run.OriginalUriBaseIds != null) { _jsonWriter.WritePropertyName("originalUriBaseIds"); _serializer.Serialize(_jsonWriter, run.OriginalUriBaseIds); } if (run.DefaultFileEncoding != null) { _jsonWriter.WritePropertyName("defaultFileEncoding"); _serializer.Serialize(_jsonWriter, run.DefaultFileEncoding); } if (run.RichMessageMimeType != null) { _jsonWriter.WritePropertyName("richMessageMimeType"); _serializer.Serialize(_jsonWriter, run.RichMessageMimeType); } if (run.RedactionToken != null) { _jsonWriter.WritePropertyName("redactionToken"); _serializer.Serialize(_jsonWriter, run.RedactionToken); } _writeConditions |= Conditions.RunInitialized; }