From cbfef4fece30438d9f7081925b35fce46aa731e2 Mon Sep 17 00:00:00 2001 From: Nate Heydt Date: Tue, 16 Nov 2021 17:07:04 -0800 Subject: [PATCH] Fix bug when validating schemas that specify an explicit metaschema Schema.assert_valid_schema/1 was checking whether an input schema was one of the JSON Schema draft metaschemas, and if so, automatically marking it as valid. The problem, though, is that it was checking the $schema field instead of the $id field. This meant that any schema which specified that it's supposed to be checked against a JSON Schema draft would automatically pass even if it wasn't valid. --- lib/ex_json_schema/schema.ex | 6 +++--- test/ex_json_schema/schema_test.exs | 9 +++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/ex_json_schema/schema.ex b/lib/ex_json_schema/schema.ex index 6a01144..e0551f6 100644 --- a/lib/ex_json_schema/schema.ex +++ b/lib/ex_json_schema/schema.ex @@ -373,13 +373,13 @@ defmodule ExJsonSchema.Schema do end) end - defp meta04?(%{"$schema" => @draft4_schema_url <> _}), do: true + defp meta04?(%{"$id" => @draft4_schema_url <> _}), do: true defp meta04?(_), do: false - defp meta06?(%{"$schema" => @draft6_schema_url <> _}), do: true + defp meta06?(%{"$id" => @draft6_schema_url <> _}), do: true defp meta06?(_), do: false - defp meta07?(%{"$schema" => @draft7_schema_url <> _}), do: true + defp meta07?(%{"$id" => @draft7_schema_url <> _}), do: true defp meta07?(_), do: false defp do_get_fragment(nil, _, _ref), do: {:error, :invalid_reference} diff --git a/test/ex_json_schema/schema_test.exs b/test/ex_json_schema/schema_test.exs index d28569e..bf10651 100644 --- a/test/ex_json_schema/schema_test.exs +++ b/test/ex_json_schema/schema_test.exs @@ -34,9 +34,18 @@ defmodule ExJsonSchema.SchemaTest do test "schema is validated against its meta-schema" do schema = %{"properties" => "foo"} + schema_meta_draft7 = %{ + "$schema" => "http://json-schema.org/draft-07/schema#", + "properties" => "foo" + } + assert_raise ExJsonSchema.Schema.InvalidSchemaError, ~s(schema did not pass validation against its meta-schema: [%ExJsonSchema.Validator.Error{error: %ExJsonSchema.Validator.Error.Type{actual: "string", expected: ["object"]}, path: "#/properties"}]), fn -> resolve(schema) end + + assert_raise ExJsonSchema.Schema.InvalidSchemaError, + ~s(schema did not pass validation against its meta-schema: [%ExJsonSchema.Validator.Error{error: %ExJsonSchema.Validator.Error.Type{actual: "string", expected: ["object"]}, path: "#/properties"}]), + fn -> resolve(schema_meta_draft7) end end test "resolving an absolute reference in a scoped schema" do