Esempio n. 1
0
        private static string RunTransformationCore(string logFileContents, SarifVersion targetVersion)
        {
            const string LogFilePath         = @"c:\logs\mylog.sarif";
            var          transformedContents = new StringBuilder();

            // Complex: TransformCommand has code paths that use Create and OpenRead, but also ReadAllText and WriteAllText.
            var mockFileSystem = new Mock <IFileSystem>();

            mockFileSystem.Setup(x => x.ReadAllText(LogFilePath)).Returns(logFileContents);
            mockFileSystem.Setup(x => x.OpenRead(LogFilePath)).Returns(() => new MemoryStream(Encoding.UTF8.GetBytes(logFileContents)));
            mockFileSystem.Setup(x => x.Create(LogFilePath)).Returns(() => new MemoryStreamToStringBuilder(transformedContents));
            mockFileSystem.Setup(x => x.WriteAllText(LogFilePath, It.IsAny <string>())).Callback <string, string>((path, contents) => { transformedContents.Append(contents); });

            var transformCommand = new TransformCommand(mockFileSystem.Object);

            var options = new TransformOptions
            {
                Inline             = true,
                SarifOutputVersion = targetVersion,
                InputFilePath      = LogFilePath
            };

            int returnCode = transformCommand.Run(options);

            returnCode.Should().Be(0);

            return(transformedContents.ToString());
        }
Esempio n. 2
0
        public static bool TryParse(string version, out SarifVersion result)
        {
            if (version == null)
            {
                result = SarifVersion.Default;
                return(true);
            }

            switch (CaseInsensitiveComparison.ToLower(version))
            {
            case "default":
                result = SarifVersion.Default;
                return(true);

            case "latest":
                result = SarifVersion.Latest;
                return(true);

            case "1":
            case "1.0":
                result = SarifVersion.Sarif1;
                return(true);

            case "2":
            case "2.1":
                result = SarifVersion.Sarif2;
                return(true);

            default:
                result = SarifVersion.Default;
                return(false);
            }
        }
Esempio n. 3
0
        private static string RunTransformationCore(string logFileContents, SarifVersion targetVersion)
        {
            string logFilePath         = @"c:\logs\mylog.sarif";
            string transformedContents = null;

            var mockFileSystem = new Mock <IFileSystem>();

            mockFileSystem.Setup(x => x.ReadAllText(logFilePath)).Returns(logFileContents);
            mockFileSystem.Setup(x => x.WriteAllText(logFilePath, It.IsAny <string>())).Callback <string, string>((path, contents) => { transformedContents = contents; });

            var transformCommand = new TransformCommand(mockFileSystem.Object, testing: true);

            var options = new TransformOptions
            {
                Inline        = true,
                TargetVersion = targetVersion,
                InputFilePath = logFilePath
            };

            int returnCode = transformCommand.Run(options);

            returnCode.Should().Be(0);

            return(transformedContents);
        }
Esempio n. 4
0
        private void Init(Uri schemaUri, SarifVersion version, IEnumerable <Run> runs)
        {
            if (schemaUri != null)
            {
                SchemaUri = new Uri(schemaUri.OriginalString, schemaUri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative);
            }

            Version = version;
            if (runs != null)
            {
                var destination_0 = new List <Run>();
                foreach (var value_0 in runs)
                {
                    if (value_0 == null)
                    {
                        destination_0.Add(null);
                    }
                    else
                    {
                        destination_0.Add(new Run(value_0));
                    }
                }

                Runs = destination_0;
            }
        }
Esempio n. 5
0
        /// <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;
        }
Esempio n. 6
0
        /// <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;
        }
Esempio n. 7
0
        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));
        }
Esempio n. 8
0
 public static Uri ConvertToSchemaUri(this SarifVersion sarifVersion)
 {
     return(new Uri(
                SarifSchemaUriBase +
                sarifVersion.ConvertToText() +
                (sarifVersion == SarifVersion.Current ? VersionConstants.PackageVersionSuffix : ""), UriKind.Absolute));
 }
Esempio n. 9
0
 public static string ConvertToText(this SarifVersion sarifVersion)
 {
     switch (sarifVersion)
     {
     case SarifVersion.OneZeroZeroBetaFour: { return(V1_0_0_BETA_4); }
     }
     return("unknown");
 }
Esempio n. 10
0
        public ErrorLogOptions(string path, SarifVersion sarifVersion)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            Path         = path;
            SarifVersion = sarifVersion;
        }
Esempio n. 11
0
        public static string ConvertToText(this SarifVersion sarifVersion)
        {
            switch (sarifVersion)
            {
            case SarifVersion.OneZeroZero: { return(V1_0_0); }

            case SarifVersion.Current: { return(StableSarifVersion); }
            }
            return("unknown");
        }
Esempio n. 12
0
        public static string ConvertToText(this SarifVersion sarifVersion)
        {
            switch (sarifVersion)
            {
            case SarifVersion.OneZeroZeroBetaFive: { return(V1_0_0_BETA_5); }

            case SarifVersion.OneZeroZero: { return(V1_0_0); }

            case SarifVersion.TwoZeroZero: { return(V2_0_0); }
            }
            return("unknown");
        }
Esempio n. 13
0
        internal ErrorLogOptions?ParseErrorLogOptions(
            string arg,
            IList <Diagnostic> diagnostics,
            string?baseDirectory,
            out bool diagnosticAlreadyReported)
        {
            diagnosticAlreadyReported = false;

            IEnumerator <string> partsEnumerator = ParseSeparatedStrings(arg, s_pathSeparators, StringSplitOptions.RemoveEmptyEntries).GetEnumerator();

            if (!partsEnumerator.MoveNext() || string.IsNullOrEmpty(partsEnumerator.Current))
            {
                return(null);
            }

            string?path = ParseGenericPathToFile(partsEnumerator.Current, diagnostics, baseDirectory);

            if (path is null)
            {
                // ParseGenericPathToFile already reported the failure, so the caller should not
                // report its own failure.
                diagnosticAlreadyReported = true;
                return(null);
            }

            const char   ParameterNameValueSeparator = '=';
            SarifVersion sarifVersion = SarifVersion.Default;

            if (partsEnumerator.MoveNext() && !string.IsNullOrEmpty(partsEnumerator.Current))
            {
                string part = partsEnumerator.Current;

                string versionParameterDesignator       = "version" + ParameterNameValueSeparator;
                int    versionParameterDesignatorLength = versionParameterDesignator.Length;

                if (!(
                        part.Length > versionParameterDesignatorLength &&
                        part.Substring(0, versionParameterDesignatorLength).Equals(versionParameterDesignator, StringComparison.OrdinalIgnoreCase) &&
                        SarifVersionFacts.TryParse(part.Substring(versionParameterDesignatorLength), out sarifVersion)
                        ))
                {
                    return(null);
                }
            }

            if (partsEnumerator.MoveNext())
            {
                return(null);
            }

            return(new ErrorLogOptions(path, sarifVersion));
        }
Esempio n. 14
0
        private void Init(Uri schemaUri, SarifVersion version, IEnumerable <Run> runs, IEnumerable <ExternalProperties> inlineExternalProperties, IDictionary <string, SerializedPropertyInfo> properties)
        {
            if (schemaUri != null)
            {
                SchemaUri = new Uri(schemaUri.OriginalString, schemaUri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative);
            }

            Version = version;
            if (runs != null)
            {
                var destination_0 = new List <Run>();
                foreach (var value_0 in runs)
                {
                    if (value_0 == null)
                    {
                        destination_0.Add(null);
                    }
                    else
                    {
                        destination_0.Add(new Run(value_0));
                    }
                }

                Runs = destination_0;
            }

            if (inlineExternalProperties != null)
            {
                var destination_1 = new List <ExternalProperties>();
                foreach (var value_1 in inlineExternalProperties)
                {
                    if (value_1 == null)
                    {
                        destination_1.Add(null);
                    }
                    else
                    {
                        destination_1.Add(new ExternalProperties(value_1));
                    }
                }

                InlineExternalProperties = destination_1;
            }

            if (properties != null)
            {
                Properties = new Dictionary <string, SerializedPropertyInfo>(properties);
            }
        }
Esempio n. 15
0
        private static (string transformedContents, int returnCode) RunTransformationCore(
            string logFileContents,
            SarifVersion targetVersion,
            RewriteOptions options = null)
        {
            const string LogFilePath = @"c:\logs\mylog.sarif";

            options ??= new RewriteOptions
            {
                Inline             = true,
                SarifOutputVersion = targetVersion,
                InputFilePath      = LogFilePath
            };

            if (options.SarifOutputVersion == SarifVersion.Unknown)
            {
                options.SarifOutputVersion = targetVersion;
            }

            if (options.InputFilePath == null)
            {
                options.Inline        = true;
                options.InputFilePath = LogFilePath;
            }

            var transformedContents = new StringBuilder();

            transformedContents.Append(logFileContents);

            var mockFileSystem = new Mock <IFileSystem>();

            //  This only works because we're testing "Inline"
            //  TODO: Verify a separate OutputFilePath works as expected
            mockFileSystem.Setup(x => x.FileReadAllText(options.InputFilePath)).Returns(transformedContents.ToString());
            mockFileSystem.Setup(x => x.FileOpenRead(options.InputFilePath)).Returns(() => new MemoryStream(Encoding.UTF8.GetBytes(transformedContents.ToString())));
            mockFileSystem.Setup(x => x.FileCreate(options.InputFilePath)).Returns(() => new MemoryStreamToStringBuilder(transformedContents));
            mockFileSystem.Setup(x => x.FileWriteAllText(options.InputFilePath, It.IsAny <string>())).Callback <string, string>((path, contents) =>
            {
                transformedContents.Clear();
                transformedContents.Append(contents);
            });

            var rewriteCommand = new RewriteCommand(mockFileSystem.Object);

            int returnCode = rewriteCommand.Run(options);

            return(transformedContents.ToString(), returnCode);
        }
        public static IOutputBuilder CreateOutputBuilder(OutputFormat format)
        {
            switch (format)
            {
            case OutputFormat.none:
                return(new NoneOutputBuilder());

            case OutputFormat.sarifv1:
            case OutputFormat.sarifv2:
                SarifVersion version = format == OutputFormat.sarifv1 ? SarifVersion.OneZeroZero : SarifVersion.Current;
                return(new SarifOutputBuilder(version));

            case OutputFormat.text:
            default:
                return(new StringOutputBuilder());
            }
        }
Esempio n. 17
0
        private void Init(SarifVersion version, IEnumerable <Run> runs)
        {
            Version = version;
            if (runs != null)
            {
                var destination_0 = new List <Run>();
                foreach (var value_0 in runs)
                {
                    if (value_0 == null)
                    {
                        destination_0.Add(null);
                    }
                    else
                    {
                        destination_0.Add(new Run(value_0));
                    }
                }

                Runs = destination_0;
            }
        }
        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));
        }
Esempio n. 19
0
 public static Uri ConvertToSchemaUri(this SarifVersion sarifVersion)
 {
     return(new Uri(
                SarifSchemaUriBase +
                (sarifVersion == SarifVersion.Current ? VersionConstants.SchemaVersionAsPublishedToSchemaStoreOrg : sarifVersion.ConvertToText()) + ".json", UriKind.Absolute));
 }
Esempio n. 20
0
        private void Init(Uri schema, SarifVersion version, string guid, string runGuid, Conversion conversion, object graphs, PropertyBag externalizedProperties, IEnumerable <Artifact> artifacts, IEnumerable <Invocation> invocations, IEnumerable <LogicalLocation> logicalLocations, IEnumerable <ThreadFlowLocation> threadFlowLocations, IEnumerable <Result> results, IEnumerable <ReportingDescriptor> taxonomies, ToolComponent driver, IEnumerable <ToolComponent> extensions, IDictionary <string, SerializedPropertyInfo> properties)
        {
            if (schema != null)
            {
                Schema = new Uri(schema.OriginalString, schema.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative);
            }

            Version = version;
            Guid    = guid;
            RunGuid = runGuid;
            if (conversion != null)
            {
                Conversion = new Conversion(conversion);
            }

            Graphs = graphs;
            if (externalizedProperties != null)
            {
                ExternalizedProperties = new PropertyBag(externalizedProperties);
            }

            if (artifacts != null)
            {
                var destination_0 = new List <Artifact>();
                foreach (var value_0 in artifacts)
                {
                    if (value_0 == null)
                    {
                        destination_0.Add(null);
                    }
                    else
                    {
                        destination_0.Add(new Artifact(value_0));
                    }
                }

                Artifacts = destination_0;
            }

            if (invocations != null)
            {
                var destination_1 = new List <Invocation>();
                foreach (var value_1 in invocations)
                {
                    if (value_1 == null)
                    {
                        destination_1.Add(null);
                    }
                    else
                    {
                        destination_1.Add(new Invocation(value_1));
                    }
                }

                Invocations = destination_1;
            }

            if (logicalLocations != null)
            {
                var destination_2 = new List <LogicalLocation>();
                foreach (var value_2 in logicalLocations)
                {
                    if (value_2 == null)
                    {
                        destination_2.Add(null);
                    }
                    else
                    {
                        destination_2.Add(new LogicalLocation(value_2));
                    }
                }

                LogicalLocations = destination_2;
            }

            if (threadFlowLocations != null)
            {
                var destination_3 = new List <ThreadFlowLocation>();
                foreach (var value_3 in threadFlowLocations)
                {
                    if (value_3 == null)
                    {
                        destination_3.Add(null);
                    }
                    else
                    {
                        destination_3.Add(new ThreadFlowLocation(value_3));
                    }
                }

                ThreadFlowLocations = destination_3;
            }

            if (results != null)
            {
                var destination_4 = new List <Result>();
                foreach (var value_4 in results)
                {
                    if (value_4 == null)
                    {
                        destination_4.Add(null);
                    }
                    else
                    {
                        destination_4.Add(new Result(value_4));
                    }
                }

                Results = destination_4;
            }

            if (taxonomies != null)
            {
                var destination_5 = new List <ReportingDescriptor>();
                foreach (var value_5 in taxonomies)
                {
                    if (value_5 == null)
                    {
                        destination_5.Add(null);
                    }
                    else
                    {
                        destination_5.Add(new ReportingDescriptor(value_5));
                    }
                }

                Taxonomies = destination_5;
            }

            if (driver != null)
            {
                Driver = new ToolComponent(driver);
            }

            if (extensions != null)
            {
                var destination_6 = new List <ToolComponent>();
                foreach (var value_6 in extensions)
                {
                    if (value_6 == null)
                    {
                        destination_6.Add(null);
                    }
                    else
                    {
                        destination_6.Add(new ToolComponent(value_6));
                    }
                }

                Extensions = destination_6;
            }

            if (properties != null)
            {
                Properties = new Dictionary <string, SerializedPropertyInfo>(properties);
            }
        }
Esempio n. 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExternalProperties" /> class from the supplied values.
 /// </summary>
 /// <param name="schema">
 /// An initialization value for the <see cref="P:Schema" /> property.
 /// </param>
 /// <param name="version">
 /// An initialization value for the <see cref="P:Version" /> property.
 /// </param>
 /// <param name="guid">
 /// An initialization value for the <see cref="P:Guid" /> property.
 /// </param>
 /// <param name="runGuid">
 /// An initialization value for the <see cref="P:RunGuid" /> property.
 /// </param>
 /// <param name="conversion">
 /// An initialization value for the <see cref="P:Conversion" /> property.
 /// </param>
 /// <param name="graphs">
 /// An initialization value for the <see cref="P:Graphs" /> property.
 /// </param>
 /// <param name="externalizedProperties">
 /// An initialization value for the <see cref="P:ExternalizedProperties" /> property.
 /// </param>
 /// <param name="artifacts">
 /// An initialization value for the <see cref="P:Artifacts" /> property.
 /// </param>
 /// <param name="invocations">
 /// An initialization value for the <see cref="P:Invocations" /> property.
 /// </param>
 /// <param name="logicalLocations">
 /// An initialization value for the <see cref="P:LogicalLocations" /> property.
 /// </param>
 /// <param name="threadFlowLocations">
 /// An initialization value for the <see cref="P:ThreadFlowLocations" /> property.
 /// </param>
 /// <param name="results">
 /// An initialization value for the <see cref="P:Results" /> property.
 /// </param>
 /// <param name="taxonomies">
 /// An initialization value for the <see cref="P:Taxonomies" /> property.
 /// </param>
 /// <param name="driver">
 /// An initialization value for the <see cref="P:Driver" /> property.
 /// </param>
 /// <param name="extensions">
 /// An initialization value for the <see cref="P:Extensions" /> property.
 /// </param>
 /// <param name="properties">
 /// An initialization value for the <see cref="P:Properties" /> property.
 /// </param>
 public ExternalProperties(Uri schema, SarifVersion version, string guid, string runGuid, Conversion conversion, object graphs, PropertyBag externalizedProperties, IEnumerable <Artifact> artifacts, IEnumerable <Invocation> invocations, IEnumerable <LogicalLocation> logicalLocations, IEnumerable <ThreadFlowLocation> threadFlowLocations, IEnumerable <Result> results, IEnumerable <ReportingDescriptor> taxonomies, ToolComponent driver, IEnumerable <ToolComponent> extensions, IDictionary <string, SerializedPropertyInfo> properties)
 {
     Init(schema, version, guid, runGuid, conversion, graphs, externalizedProperties, artifacts, invocations, logicalLocations, threadFlowLocations, results, taxonomies, driver, extensions, properties);
 }
Esempio n. 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SarifLog" /> class from the supplied values.
 /// </summary>
 /// <param name="schemaUri">
 /// An initialization value for the <see cref="P: SchemaUri" /> property.
 /// </param>
 /// <param name="version">
 /// An initialization value for the <see cref="P: Version" /> property.
 /// </param>
 /// <param name="runs">
 /// An initialization value for the <see cref="P: Runs" /> property.
 /// </param>
 public SarifLog(Uri schemaUri, SarifVersion version, IEnumerable <Run> runs)
 {
     Init(schemaUri, version, runs);
 }
Esempio n. 23
0
 public static Uri ConvertToSchemaUri(this SarifVersion sarifVersion)
 {
     return(new Uri(SarifSchemaUriBase + sarifVersion.ConvertToText(), UriKind.Absolute));
 }
Esempio n. 24
0
        /// <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));
            }
        }
Esempio n. 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExternalProperties" /> class from the supplied values.
 /// </summary>
 /// <param name="schema">
 /// An initialization value for the <see cref="P:Schema" /> property.
 /// </param>
 /// <param name="version">
 /// An initialization value for the <see cref="P:Version" /> property.
 /// </param>
 /// <param name="guid">
 /// An initialization value for the <see cref="P:Guid" /> property.
 /// </param>
 /// <param name="runGuid">
 /// An initialization value for the <see cref="P:RunGuid" /> property.
 /// </param>
 /// <param name="conversion">
 /// An initialization value for the <see cref="P:Conversion" /> property.
 /// </param>
 /// <param name="graphs">
 /// An initialization value for the <see cref="P:Graphs" /> property.
 /// </param>
 /// <param name="externalizedProperties">
 /// An initialization value for the <see cref="P:ExternalizedProperties" /> property.
 /// </param>
 /// <param name="artifacts">
 /// An initialization value for the <see cref="P:Artifacts" /> property.
 /// </param>
 /// <param name="invocations">
 /// An initialization value for the <see cref="P:Invocations" /> property.
 /// </param>
 /// <param name="logicalLocations">
 /// An initialization value for the <see cref="P:LogicalLocations" /> property.
 /// </param>
 /// <param name="threadFlowLocations">
 /// An initialization value for the <see cref="P:ThreadFlowLocations" /> property.
 /// </param>
 /// <param name="results">
 /// An initialization value for the <see cref="P:Results" /> property.
 /// </param>
 /// <param name="taxonomies">
 /// An initialization value for the <see cref="P:Taxonomies" /> property.
 /// </param>
 /// <param name="driver">
 /// An initialization value for the <see cref="P:Driver" /> property.
 /// </param>
 /// <param name="extensions">
 /// An initialization value for the <see cref="P:Extensions" /> property.
 /// </param>
 /// <param name="policies">
 /// An initialization value for the <see cref="P:Policies" /> property.
 /// </param>
 /// <param name="translations">
 /// An initialization value for the <see cref="P:Translations" /> property.
 /// </param>
 /// <param name="addresses">
 /// An initialization value for the <see cref="P:Addresses" /> property.
 /// </param>
 /// <param name="webRequests">
 /// An initialization value for the <see cref="P:WebRequests" /> property.
 /// </param>
 /// <param name="webResponses">
 /// An initialization value for the <see cref="P:WebResponses" /> property.
 /// </param>
 /// <param name="properties">
 /// An initialization value for the <see cref="P:Properties" /> property.
 /// </param>
 public ExternalProperties(Uri schema, SarifVersion version, string guid, string runGuid, Conversion conversion, IEnumerable <Graph> graphs, PropertyBag externalizedProperties, IEnumerable <Artifact> artifacts, IEnumerable <Invocation> invocations, IEnumerable <LogicalLocation> logicalLocations, IEnumerable <ThreadFlowLocation> threadFlowLocations, IEnumerable <Result> results, IEnumerable <ToolComponent> taxonomies, ToolComponent driver, IEnumerable <ToolComponent> extensions, IEnumerable <ToolComponent> policies, IEnumerable <ToolComponent> translations, IEnumerable <Address> addresses, IEnumerable <WebRequest> webRequests, IEnumerable <WebResponse> webResponses, IDictionary <string, SerializedPropertyInfo> properties)
 {
     Init(schema, version, guid, runGuid, conversion, graphs, externalizedProperties, artifacts, invocations, logicalLocations, threadFlowLocations, results, taxonomies, driver, extensions, policies, translations, addresses, webRequests, webResponses, properties);
 }
Esempio n. 27
0
        private void Init(Uri schemaUri, SarifVersion version, IEnumerable<Run> runs)
        {
            if (schemaUri != null)
            {
                SchemaUri = new Uri(schemaUri.OriginalString, schemaUri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative);
            }

            Version = version;
            if (runs != null)
            {
                var destination_0 = new List<Run>();
                foreach (var value_0 in runs)
                {
                    if (value_0 == null)
                    {
                        destination_0.Add(null);
                    }
                    else
                    {
                        destination_0.Add(new Run(value_0));
                    }
                }

                Runs = destination_0;
            }
        }
Esempio n. 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SarifLog" /> class from the supplied values.
 /// </summary>
 /// <param name="version">
 /// An initialization value for the <see cref="P: Version" /> property.
 /// </param>
 /// <param name="runs">
 /// An initialization value for the <see cref="P: Runs" /> property.
 /// </param>
 public SarifLog(SarifVersion version, IEnumerable <Run> runs)
 {
     Init(version, runs);
 }
Esempio n. 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SarifLog" /> class from the supplied values.
 /// </summary>
 /// <param name="schemaUri">
 /// An initialization value for the <see cref="P: SchemaUri" /> property.
 /// </param>
 /// <param name="version">
 /// An initialization value for the <see cref="P: Version" /> property.
 /// </param>
 /// <param name="runs">
 /// An initialization value for the <see cref="P: Runs" /> property.
 /// </param>
 public SarifLog(Uri schemaUri, SarifVersion version, IEnumerable<Run> runs)
 {
     Init(schemaUri, version, runs);
 }
Esempio n. 30
0
 public static Uri ConvertToSchemaUri(this SarifVersion sarifVersion)
 {
     return(new Uri("http://json.schemastore.org/sarif-" + sarifVersion.ConvertToText(), UriKind.Absolute));
 }
Esempio n. 31
0
        protected virtual void Init(Uri schema, SarifVersion version, string guid, string runGuid, Conversion conversion, IEnumerable <Graph> graphs, PropertyBag externalizedProperties, IEnumerable <Artifact> artifacts, IEnumerable <Invocation> invocations, IEnumerable <LogicalLocation> logicalLocations, IEnumerable <ThreadFlowLocation> threadFlowLocations, IEnumerable <Result> results, IEnumerable <ToolComponent> taxonomies, ToolComponent driver, IEnumerable <ToolComponent> extensions, IEnumerable <ToolComponent> policies, IEnumerable <ToolComponent> translations, IEnumerable <Address> addresses, IEnumerable <WebRequest> webRequests, IEnumerable <WebResponse> webResponses, IDictionary <string, SerializedPropertyInfo> properties)
        {
            if (schema != null)
            {
                Schema = new Uri(schema.OriginalString, schema.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative);
            }

            Version = version;
            Guid    = guid;
            RunGuid = runGuid;
            if (conversion != null)
            {
                Conversion = new Conversion(conversion);
            }

            if (graphs != null)
            {
                var destination_0 = new List <Graph>();
                foreach (var value_0 in graphs)
                {
                    if (value_0 == null)
                    {
                        destination_0.Add(null);
                    }
                    else
                    {
                        destination_0.Add(new Graph(value_0));
                    }
                }

                Graphs = destination_0;
            }

            if (externalizedProperties != null)
            {
                ExternalizedProperties = new PropertyBag(externalizedProperties);
            }

            if (artifacts != null)
            {
                var destination_1 = new List <Artifact>();
                foreach (var value_1 in artifacts)
                {
                    if (value_1 == null)
                    {
                        destination_1.Add(null);
                    }
                    else
                    {
                        destination_1.Add(new Artifact(value_1));
                    }
                }

                Artifacts = destination_1;
            }

            if (invocations != null)
            {
                var destination_2 = new List <Invocation>();
                foreach (var value_2 in invocations)
                {
                    if (value_2 == null)
                    {
                        destination_2.Add(null);
                    }
                    else
                    {
                        destination_2.Add(new Invocation(value_2));
                    }
                }

                Invocations = destination_2;
            }

            if (logicalLocations != null)
            {
                var destination_3 = new List <LogicalLocation>();
                foreach (var value_3 in logicalLocations)
                {
                    if (value_3 == null)
                    {
                        destination_3.Add(null);
                    }
                    else
                    {
                        destination_3.Add(new LogicalLocation(value_3));
                    }
                }

                LogicalLocations = destination_3;
            }

            if (threadFlowLocations != null)
            {
                var destination_4 = new List <ThreadFlowLocation>();
                foreach (var value_4 in threadFlowLocations)
                {
                    if (value_4 == null)
                    {
                        destination_4.Add(null);
                    }
                    else
                    {
                        destination_4.Add(new ThreadFlowLocation(value_4));
                    }
                }

                ThreadFlowLocations = destination_4;
            }

            if (results != null)
            {
                var destination_5 = new List <Result>();
                foreach (var value_5 in results)
                {
                    if (value_5 == null)
                    {
                        destination_5.Add(null);
                    }
                    else
                    {
                        destination_5.Add(new Result(value_5));
                    }
                }

                Results = destination_5;
            }

            if (taxonomies != null)
            {
                var destination_6 = new List <ToolComponent>();
                foreach (var value_6 in taxonomies)
                {
                    if (value_6 == null)
                    {
                        destination_6.Add(null);
                    }
                    else
                    {
                        destination_6.Add(new ToolComponent(value_6));
                    }
                }

                Taxonomies = destination_6;
            }

            if (driver != null)
            {
                Driver = new ToolComponent(driver);
            }

            if (extensions != null)
            {
                var destination_7 = new List <ToolComponent>();
                foreach (var value_7 in extensions)
                {
                    if (value_7 == null)
                    {
                        destination_7.Add(null);
                    }
                    else
                    {
                        destination_7.Add(new ToolComponent(value_7));
                    }
                }

                Extensions = destination_7;
            }

            if (policies != null)
            {
                var destination_8 = new List <ToolComponent>();
                foreach (var value_8 in policies)
                {
                    if (value_8 == null)
                    {
                        destination_8.Add(null);
                    }
                    else
                    {
                        destination_8.Add(new ToolComponent(value_8));
                    }
                }

                Policies = destination_8;
            }

            if (translations != null)
            {
                var destination_9 = new List <ToolComponent>();
                foreach (var value_9 in translations)
                {
                    if (value_9 == null)
                    {
                        destination_9.Add(null);
                    }
                    else
                    {
                        destination_9.Add(new ToolComponent(value_9));
                    }
                }

                Translations = destination_9;
            }

            if (addresses != null)
            {
                var destination_10 = new List <Address>();
                foreach (var value_10 in addresses)
                {
                    if (value_10 == null)
                    {
                        destination_10.Add(null);
                    }
                    else
                    {
                        destination_10.Add(new Address(value_10));
                    }
                }

                Addresses = destination_10;
            }

            if (webRequests != null)
            {
                var destination_11 = new List <WebRequest>();
                foreach (var value_11 in webRequests)
                {
                    if (value_11 == null)
                    {
                        destination_11.Add(null);
                    }
                    else
                    {
                        destination_11.Add(new WebRequest(value_11));
                    }
                }

                WebRequests = destination_11;
            }

            if (webResponses != null)
            {
                var destination_12 = new List <WebResponse>();
                foreach (var value_12 in webResponses)
                {
                    if (value_12 == null)
                    {
                        destination_12.Add(null);
                    }
                    else
                    {
                        destination_12.Add(new WebResponse(value_12));
                    }
                }

                WebResponses = destination_12;
            }

            if (properties != null)
            {
                Properties = new Dictionary <string, SerializedPropertyInfo>(properties);
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SarifLog" /> class from the supplied values.
 /// </summary>
 /// <param name="schemaUri">
 /// An initialization value for the <see cref="P:SchemaUri" /> property.
 /// </param>
 /// <param name="version">
 /// An initialization value for the <see cref="P:Version" /> property.
 /// </param>
 /// <param name="runs">
 /// An initialization value for the <see cref="P:Runs" /> property.
 /// </param>
 /// <param name="inlineExternalProperties">
 /// An initialization value for the <see cref="P:InlineExternalProperties" /> property.
 /// </param>
 /// <param name="properties">
 /// An initialization value for the <see cref="P:Properties" /> property.
 /// </param>
 public SarifLog(Uri schemaUri, SarifVersion version, IEnumerable <Run> runs, IEnumerable <ExternalProperties> inlineExternalProperties, IDictionary <string, SerializedPropertyInfo> properties)
 {
     Init(schemaUri, version, runs, inlineExternalProperties, properties);
 }