コード例 #1
0
        public async static Task <JsonSchema> LoadDataFromEmbeddedResourceAsJsonSchema(string resourceName)
        {
            var resourceStream = LoadDataFromEmbeddedResource(resourceName);

            var jsonSchema = await JsonSchema.FromStream(resourceStream);

            return(jsonSchema);
        }
コード例 #2
0
        /// <summary>
        /// Validate the stream contents represent a valid SPDX JSON document.
        /// </summary>
        /// <param name="jsonStream"></param>
        /// <param name="schemaVersion"></param>
        /// <returns></returns>
        public static async Task <ValidationResult> ValidateAsync(Stream jsonStream)
        {
            var assembly = typeof(JsonValidator).GetTypeInfo().Assembly;

            using (var schemaStream = assembly.GetManifestResourceStream($"CycloneDX.Spdx.Schemas.spdx-2.2.schema.json"))
            {
                var jsonSchema = await JsonSchema.FromStream(schemaStream).ConfigureAwait(false);

                var jsonDocument = await JsonDocument.ParseAsync(jsonStream).ConfigureAwait(false);

                return(Validate(jsonSchema, jsonDocument));
            }
        }
コード例 #3
0
        public async Task FromStream()
        {
            var text = "{\"$id\":\"http://my.schema/test1\",\"minimum\":5}";

            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(text));

            var schema = await JsonSchema.FromStream(stream);

            using var json = JsonDocument.Parse("10");

            var results = schema.Validate(json.RootElement);

            Assert.True(results.IsValid);
        }
コード例 #4
0
        /// <summary>
        /// Validate the stream contents represent a valid CycloneDX JSON document.
        /// </summary>
        /// <param name="jsonStream"></param>
        /// <param name="specificationVersion"></param>
        /// <returns></returns>
        public static async Task <ValidationResult> ValidateAsync(Stream jsonStream, SpecificationVersion specificationVersion)
        {
            if (specificationVersion < SpecificationVersion.v1_2)
            {
                throw new Exceptions.UnsupportedFormatSpecificationVersionException($"JSON format is not supported by schema version {specificationVersion}");
            }

            var schemaVersionString = SchemaVersionResourceFilenameString(specificationVersion);
            var assembly            = typeof(Validator).GetTypeInfo().Assembly;

            using (var schemaStream = assembly.GetManifestResourceStream($"CycloneDX.Core.Schemas.bom-{schemaVersionString}.schema.json"))
            {
                var jsonSchema = await JsonSchema.FromStream(schemaStream).ConfigureAwait(false);

                var jsonDocument = await JsonDocument.ParseAsync(jsonStream).ConfigureAwait(false);

                return(Validate(jsonSchema, jsonDocument, schemaVersionString));
            }
        }
コード例 #5
0
        public static async Task <ValidationResult> Validate(string sbom, SchemaVersion schemaVersion)
        {
            if (schemaVersion == SchemaVersion.v1_0 || schemaVersion == SchemaVersion.v1_1)
            {
                throw new UnsupportedSchemaVersionException($"JSON format is not supported by schema {schemaVersion}");
            }

            var validationMessages = new List <string>();

            var schemaVersionString = schemaVersion.ToString().Substring(1).Replace('_', '.');
            var assembly            = typeof(JsonBomValidator).GetTypeInfo().Assembly;

            using (var schemaStream = assembly.GetManifestResourceStream($"CycloneDX.Json.Schemas.bom-{schemaVersionString}.schema.json"))
                using (var spdxStream = assembly.GetManifestResourceStream("CycloneDX.Json.Schemas.spdx.schema.json"))
                {
                    var schema = await JsonSchema.FromStream(schemaStream);

                    var spdxSchema = await JsonSchema.FromStream(spdxStream);

                    SchemaRegistry.Global.Register(new Uri("file://spdx.schema.json"), spdxSchema);

                    var jsonDocument      = JsonDocument.Parse(sbom);
                    var validationOptions = new ValidationOptions
                    {
                        OutputFormat            = OutputFormat.Detailed,
                        RequireFormatValidation = true
                    };

                    var result = schema.Validate(jsonDocument.RootElement, validationOptions);

                    if (result.IsValid)
                    {
                        foreach (var properties in jsonDocument.RootElement.EnumerateObject())
                        {
                            if (properties.Name == "specVersion")
                            {
                                var specVersion = properties.Value.GetString();
                                if (specVersion != schemaVersionString)
                                {
                                    validationMessages.Add($"Incorrect schema version: expected {schemaVersionString} actual {specVersion}");
                                }
                            }
                        }
                    }
                    else
                    {
                        validationMessages.Add($"Validation failed: {result.Message}");
                        validationMessages.Add(result.SchemaLocation.ToString());

                        if (result.NestedResults != null)
                        {
                            var nestedResults = new Queue <ValidationResults>(result.NestedResults);

                            while (nestedResults.Count > 0)
                            {
                                var nestedResult = nestedResults.Dequeue();

                                if (
                                    !string.IsNullOrEmpty(nestedResult.Message) &&
                                    nestedResult.NestedResults != null &&
                                    nestedResult.NestedResults.Count > 0)
                                {
                                    validationMessages.Add($"{nestedResult.InstanceLocation}: {nestedResult.Message}");
                                }

                                if (nestedResult.NestedResults != null)
                                {
                                    foreach (var newNestedResult in nestedResult.NestedResults)
                                    {
                                        nestedResults.Enqueue(newNestedResult);
                                    }
                                }
                            }
                        }
                    }
                }

            return(new ValidationResult
            {
                Valid = validationMessages.Count == 0,
                Messages = validationMessages
            });
        }
コード例 #6
0
        public async Task ExecuteAsync(TestCaseContext testCaseContext)
        {
            var effectiveSourceKey = testCaseContext.GetEffectiveItemKey(_sourceKey);
            var effectiveTargetKey = testCaseContext.GetEffectiveItemKey(_targetKey);

            testCaseContext.DescriptionWriter.AddNote("JsonValidate", $"{effectiveSourceKey}");
            var itemToken = testCaseContext.GetRequiredItemAsJToken(effectiveSourceKey);

            var schema = await testCaseContext.TestCase.UsingReadStream(_schemaPath, stream => JsonSchema.FromStream(stream));

            var doc = JsonDocument.Parse(itemToken.ToString());

            var validationResult = schema.Validate(doc.RootElement, new ValidationOptions {
                OutputFormat = OutputFormat.Basic
            });

            testCaseContext.Logger.LogDebug("Document is valid agains schema: {result}", validationResult.IsValid);

            var res = validationResult.NestedResults.Select(r => new { r.Message, InstanceLocation = r.InstanceLocation.Source, SchemaLocation = r.SchemaLocation.Source }).ToIndentedJson();

            testCaseContext.SetItem(effectiveTargetKey, res);
        }