schema.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #pragma once
  2. #include <memory>
  3. #include <type_traits>
  4. #include <unordered_map>
  5. #include <vector>
  6. #include <jvalidate/adapter.h>
  7. #include <jvalidate/constraint.h>
  8. #include <jvalidate/detail/anchor.h>
  9. #include <jvalidate/detail/expect.h>
  10. #include <jvalidate/detail/on_block_exit.h>
  11. #include <jvalidate/detail/parser_context.h>
  12. #include <jvalidate/detail/pointer.h>
  13. #include <jvalidate/detail/reference.h>
  14. #include <jvalidate/document_cache.h>
  15. #include <jvalidate/enum.h>
  16. #include <jvalidate/forward.h>
  17. namespace jvalidate::schema {
  18. class Node {
  19. private:
  20. std::string description_;
  21. std::unique_ptr<adapter::Const const> default_{nullptr};
  22. detail::Reference uri_;
  23. bool rejects_all_{false};
  24. std::optional<schema::Node const *> reference_{};
  25. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> constraints_{};
  26. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> post_constraints_{};
  27. protected:
  28. static Version schema_version(std::string_view url);
  29. static Version schema_version(Adapter auto const & json);
  30. static Version schema_version(Adapter auto const & json, Version default_version);
  31. public:
  32. Node(bool rejects_all = false) : rejects_all_(rejects_all) {}
  33. template <Adapter A> Node(detail::ParserContext<A> context);
  34. bool is_pure_reference() const {
  35. return reference_ && constraints_.empty() && post_constraints_.empty() && not default_;
  36. }
  37. bool rejects_all() const { return rejects_all_; }
  38. std::optional<schema::Node const *> reference_schema() const { return reference_; }
  39. bool requires_result_context() const { return not post_constraints_.empty(); }
  40. auto const & constraints() const { return constraints_; }
  41. auto const & post_constraints() const { return constraints_; }
  42. adapter::Const const * default_value() const { return default_.get(); }
  43. private:
  44. template <Adapter A> detail::OnBlockExit resolve_anchor(detail::ParserContext<A> & context);
  45. template <Adapter A> bool resolve_reference(detail::ParserContext<A> const & context);
  46. };
  47. inline Version Node::schema_version(std::string_view url) {
  48. static std::map<std::string_view, Version> const g_schema_ids{
  49. {"http://json-schema.org/draft-04/schema", Version::Draft04},
  50. {"http://json-schema.org/draft-06/schema", Version::Draft06},
  51. {"http://json-schema.org/draft-07/schema", Version::Draft07},
  52. {"http://json-schema.org/draft/2019-09/schema", Version::Draft2019_09},
  53. {"http://json-schema.org/draft/2020-12/schema", Version::Draft2020_12},
  54. };
  55. if (url.ends_with('#')) {
  56. url.remove_suffix(1);
  57. }
  58. auto it = g_schema_ids.find(url);
  59. EXPECT_T(it != g_schema_ids.end(), std::invalid_argument, url);
  60. return it->second;
  61. }
  62. Version Node::schema_version(Adapter auto const & json) {
  63. EXPECT(json.type() == adapter::Type::Object);
  64. EXPECT(json.as_object().contains("$schema"));
  65. auto const & schema = json.as_object()["$schema"];
  66. EXPECT(schema.type() == adapter::Type::String);
  67. return schema_version(schema.as_string());
  68. }
  69. Version Node::schema_version(Adapter auto const & json, Version default_version) {
  70. RETURN_UNLESS(json.type() == adapter::Type::Object, default_version);
  71. RETURN_UNLESS(json.as_object().contains("$schema"), default_version);
  72. auto const & schema = json.as_object()["$schema"];
  73. RETURN_UNLESS(schema.type() == adapter::Type::String, default_version);
  74. return schema_version(schema.as_string());
  75. }
  76. }
  77. namespace jvalidate {
  78. class Schema : public schema::Node {
  79. private:
  80. friend class schema::Node;
  81. template <Adapter A> friend class detail::ParserContext;
  82. struct DynamicRef {
  83. template <typename F>
  84. DynamicRef(detail::Reference const & where, F const & reconstruct)
  85. : where(where), reconstruct(reconstruct) {}
  86. detail::Reference where;
  87. std::function<schema::Node const *()> reconstruct;
  88. };
  89. private:
  90. schema::Node accept_{false};
  91. schema::Node reject_{true};
  92. // A map of (URI, Anchor) => (URI, Pointer), binding an anchor reference
  93. // to it's fully resolved path.
  94. std::map<detail::Reference, detail::Reference> anchors_;
  95. // A map of anchors to DynamicRef info - note that DynamicRef.reconstruct is
  96. // an unsafe object, because it holds an object which may hold references to
  97. // temporary objects.
  98. // Nothing should be added to this object except through calling
  99. // {@see Node::resolve_anchor}, which returns a scope(exit) construct that
  100. // cleans up the element.
  101. std::map<detail::Anchor, DynamicRef> dynamic_anchors_;
  102. // An owning cache of all created schemas. Avoids storing duplicates such as
  103. // the "always-true" schema, "always-false" schema, and schemas whose only
  104. // meaningful field is "$ref", "$recursiveRef", or "$dynamicRef".
  105. std::map<detail::Reference, schema::Node> cache_;
  106. // A non-owning cache of all schemas, including duplcates where multiple
  107. // References map to the same underlying schema.
  108. std::map<detail::Reference, schema::Node const *> alias_cache_;
  109. public:
  110. /**
  111. * @brief Construct a new schema. All other constructors of this type may be
  112. * considered syntactic sugar for this constructor.
  113. *
  114. * As such, the true signature of this class's contructor is:
  115. *
  116. * Schema(Adapter| JSON
  117. * [, schema::Version]
  118. * [, URIResolver<A> | DocumentCache<A> &]
  119. * [, ConstraintFactory<A> const &])
  120. *
  121. * as long as the order of arguments is preserved - the constructor will work
  122. * no matter which arguments are ignored. The only required argument being
  123. * the JSON object/Adapter.
  124. *
  125. * @param json An adapter to a json object
  126. *
  127. * @param version The json-schema draft version that all schemas will prefer
  128. *
  129. * @param external An object capable of resolving URIs, and turning them into
  130. * Adapter objects. Holds a cache and so must be mutable.
  131. *
  132. * @param factory An object that manuafactures constraints - allows the user
  133. * to provide custom extensions or even modify the behavior of existing
  134. * keywords by overridding the virtual accessor function(s).
  135. */
  136. template <Adapter A>
  137. Schema(A const & json, schema::Version version, DocumentCache<A> & external,
  138. ConstraintFactory<A> const & factory = {}) {
  139. detail::ParserContext<A> root{*this, json, version, factory, external};
  140. // Prevent unintialized data caches
  141. schema::Node::operator=(root);
  142. }
  143. /**
  144. * @param json An adapter to a json schema
  145. *
  146. * @param version The json-schema draft version that all schemas will prefer
  147. *
  148. * @param external An object capable of resolving URIs, and turning them into
  149. * Adapter objects. Holds a cache and so must be mutable. If this constructor
  150. * is called, then it means that the cache is a one-off object, and will not
  151. * be reused.
  152. */
  153. template <Adapter A, typename... Args>
  154. Schema(A const & json, schema::Version version, DocumentCache<A> && external, Args &&... args)
  155. : Schema(json, version, external, std::forward<Args>(args)...) {}
  156. /**
  157. * @param json An adapter to a json schema
  158. *
  159. * @param version The json-schema draft version that all schemas will prefer
  160. *
  161. * @param resolve A function capable of resolving URIs, and storing the
  162. * contents in a provided concrete JSON object.
  163. */
  164. template <Adapter A, typename... Args>
  165. Schema(A const & json, schema::Version version, URIResolver<A> resolve, Args &&... args)
  166. : Schema(json, version, DocumentCache<A>(resolve), std::forward<Args>(args)...) {}
  167. /**
  168. * @param json An adapter to a json schema
  169. *
  170. * @param version The json-schema draft version that all schemas will prefer
  171. */
  172. template <Adapter A, Not<DocumentCache<A>>... Args>
  173. Schema(A const & json, schema::Version version, Args &&... args)
  174. : Schema(json, version, DocumentCache<A>(), std::forward<Args>(args)...) {}
  175. /**
  176. * @param json An adapter to a json schema
  177. */
  178. template <Adapter A, Not<schema::Version>... Args>
  179. explicit Schema(A const & json, Args &&... args)
  180. : Schema(json, schema_version(json), std::forward<Args>(args)...) {}
  181. /**
  182. * @param json Any non-adapter (JSON) object. Will be immedately converted
  183. * into an Adapter object to allow us to walk through it w/o specialization.
  184. */
  185. template <typename JSON, typename... Args>
  186. explicit Schema(JSON const & json, Args &&... args)
  187. : Schema(adapter::AdapterFor<JSON const>(json), std::forward<Args>(args)...) {}
  188. private:
  189. /**
  190. * @brief Associate an anchor with its absolute path
  191. * @pre We should not already have an anchor associated with this anchor
  192. *
  193. * @param anchor A URI-Reference containing only a URI and Anchor
  194. * @param from A URI-Reference representing the absolute path to this Anchor
  195. */
  196. void anchor(detail::Reference const & anchor, detail::Reference const & from) {
  197. EXPECT_M(anchors_.try_emplace(anchor.root(), from).second,
  198. "more than one anchor found for uri " << anchor);
  199. }
  200. template <Adapter A>
  201. void dynamic_anchor(detail::Anchor const & anchor, detail::ParserContext<A> const & context) {
  202. dynamic_anchors_.try_emplace(anchor, context.where,
  203. [this, context]() { return fetch_schema(context); });
  204. }
  205. void remove_dynamic_anchor(detail::Anchor const & anchor, detail::Reference const & where) {
  206. if (auto it = dynamic_anchors_.find(anchor);
  207. it != dynamic_anchors_.end() && it->second.where == where) {
  208. dynamic_anchors_.erase(it);
  209. }
  210. }
  211. schema::Node const * alias(detail::Reference const & where, schema::Node const * schema) {
  212. EXPECT_M(alias_cache_.try_emplace(where, schema).second,
  213. "more than one schema found with uri " << where);
  214. return schema;
  215. }
  216. std::optional<schema::Node const *> from_cache(detail::Reference ref) {
  217. if (auto it = anchors_.find(ref.root()); it != anchors_.end()) {
  218. ref = it->second / ref.pointer();
  219. }
  220. if (auto it = alias_cache_.find(ref); it != alias_cache_.end()) {
  221. return it->second;
  222. }
  223. return std::nullopt;
  224. }
  225. template <Adapter A>
  226. schema::Node const * resolve(detail::Reference ref, detail::ParserContext<A> const & context) {
  227. // Special case if the root-level document does not have an $id property
  228. if (ref == detail::Reference() && ref.anchor() == context.where.anchor()) {
  229. return this;
  230. }
  231. if (std::optional cached = from_cache(ref)) {
  232. return *cached;
  233. }
  234. // SPECIAL RULE: Resolve this URI into the context of the calling URI
  235. if (ref.uri().scheme().empty()) {
  236. URI const & relative_to = context.where.uri();
  237. EXPECT_M(relative_to.resource().rfind('/') != std::string::npos,
  238. "Relative URIs require that the current context has a resolved URI");
  239. ref = detail::Reference(relative_to.parent() / ref.uri(), ref.anchor(), ref.pointer());
  240. }
  241. EXPECT_M(context.external, "Unable to resolve external reference(s) without a URIResolver");
  242. std::optional schema = context.external.try_load(ref.uri());
  243. EXPECT_M(schema.has_value(), "URIResolver could not resolve " << ref.uri());
  244. (void)fetch_schema(context.rebind(*schema, ref.uri()));
  245. std::optional referenced_node = from_cache(ref);
  246. EXPECT_M(referenced_node.has_value(),
  247. "Could not locate reference '" << ref << "' within external schema.");
  248. return *referenced_node;
  249. }
  250. schema::Node const * resolve_dynamic(detail::Anchor const & ref) {
  251. auto it = dynamic_anchors_.find(ref);
  252. EXPECT_M(it != dynamic_anchors_.end(), "Unmatched $dynamicRef '" << ref << "'");
  253. return it->second.reconstruct();
  254. }
  255. template <Adapter A> schema::Node const * fetch_schema(detail::ParserContext<A> const & context) {
  256. adapter::Type const type = context.schema.type();
  257. if (type == adapter::Type::Boolean && context.version >= schema::Version::Draft06) {
  258. return alias(context.where, context.schema.as_boolean() ? &accept_ : &reject_);
  259. }
  260. EXPECT(type == adapter::Type::Object);
  261. if (context.schema.object_size() == 0) {
  262. return alias(context.where, &accept_);
  263. }
  264. auto [it, created] = cache_.try_emplace(context.where, context);
  265. EXPECT_M(created, "more than one schema found with uri " << context.where);
  266. schema::Node const * node = &it->second;
  267. // Special Case - if the only is the reference constraint, then we don't need
  268. // to store it uniquely. Draft2019_09 supports directly extending a $ref schema
  269. // in the same schema, instead of requiring an allOf clause.
  270. if (node->is_pure_reference()) {
  271. node = *node->reference_schema();
  272. cache_.erase(it);
  273. return alias(context.where, node);
  274. }
  275. return alias(context.where, node);
  276. }
  277. };
  278. }
  279. namespace jvalidate::detail {
  280. template <Adapter A> schema::Node const * ParserContext<A>::node() const {
  281. return root.fetch_schema(*this);
  282. }
  283. template <Adapter A> schema::Node const * ParserContext<A>::always() const {
  284. return schema.as_boolean() ? &root.accept_ : &root.reject_;
  285. }
  286. }
  287. namespace jvalidate::schema {
  288. template <Adapter A> detail::OnBlockExit Node::resolve_anchor(detail::ParserContext<A> & context) {
  289. auto const schema = context.schema.as_object();
  290. if (schema.contains("$anchor")) {
  291. // Create an anchor mapping using the current document and the anchor
  292. // string. There's no need for special validation/chaining here, because
  293. // {@see Schema::resolve} will turn all $ref/$dynamicRef anchors into
  294. // their fully-qualified path.
  295. detail::Anchor anchor(schema["$anchor"].as_string());
  296. context.root.anchor(detail::Reference(context.where.uri(), anchor), context.where);
  297. return nullptr;
  298. }
  299. if (context.version == Version::Draft2019_09 && schema.contains("$recursiveAnchor")) {
  300. EXPECT_M(schema["$recursiveAnchor"].as_boolean(), "$recursiveAnchor MUST be 'true'");
  301. context.root.dynamic_anchor(detail::Anchor(), context);
  302. return [&context]() { context.root.remove_dynamic_anchor(detail::Anchor(), context.where); };
  303. }
  304. if (context.version > Version::Draft2019_09 && schema.contains("$dynamicAnchor")) {
  305. detail::Anchor anchor(schema["$dynamicAnchor"].as_string());
  306. context.root.dynamic_anchor(anchor, context);
  307. return [&context, anchor]() { context.root.remove_dynamic_anchor(anchor, context.where); };
  308. }
  309. return nullptr;
  310. }
  311. template <Adapter A> bool Node::resolve_reference(detail::ParserContext<A> const & context) {
  312. auto const schema = context.schema.as_object();
  313. if (schema.contains("$ref")) {
  314. detail::Reference ref(schema["$ref"].as_string());
  315. reference_ = context.root.resolve(ref, context);
  316. return true;
  317. }
  318. if (context.version < Version::Draft2019_09) {
  319. return false;
  320. }
  321. if (context.version == Version::Draft2019_09 && schema.contains("$recursiveRef")) {
  322. detail::Reference ref(schema["$recursiveRef"].as_string());
  323. EXPECT_M(ref == detail::Reference(), "Only the root schema is permitted as a $recursiveRef");
  324. reference_ = context.root.resolve_dynamic(detail::Anchor());
  325. return true;
  326. }
  327. if (context.version > Version::Draft2019_09 && schema.contains("$dynamicRef")) {
  328. detail::Reference ref(schema["$dynamicRef"].as_string());
  329. reference_ = context.root.resolve_dynamic(ref.anchor());
  330. return true;
  331. }
  332. return false;
  333. }
  334. template <Adapter A> Node::Node(detail::ParserContext<A> context) {
  335. EXPECT(context.schema.type() == adapter::Type::Object);
  336. auto const schema = context.schema.as_object();
  337. if (schema.contains("$schema")) {
  338. // At any point in the schema, we're allowed to change versions
  339. // This means that we're not version-locked to the latest grammar
  340. // (which is especially important for some breaking changes)
  341. context.version = schema_version(context.schema);
  342. }
  343. if (schema.contains("$id")) {
  344. context.root.alias(detail::Reference(schema["$id"].as_string(), false), this);
  345. }
  346. [[maybe_unused]] auto _ = resolve_anchor(context);
  347. bool const has_reference = resolve_reference(context);
  348. if (schema.contains("default")) {
  349. default_ = schema["default"].freeze();
  350. }
  351. if (schema.contains("description")) {
  352. description_ = schema["description"].as_string();
  353. }
  354. for (auto [key, subschema] : schema) {
  355. // Using a constraint store allows overriding certain rules, or the creation
  356. // of user-defined extention vocabularies.
  357. if (auto make_constraint = context.factory(key, context.version)) {
  358. EXPECT_M(not has_reference || context.version >= Version::Draft2019_09,
  359. "Cannot directly extend $ref schemas before Draft2019-09");
  360. // A constraint may return null if it is not applicable - but otherwise
  361. // well-formed. For example, before Draft-06 "exclusiveMaximum" was a
  362. // modifier property for "maximum", and not a unique constaint on its own.
  363. // Therefore, we parse it alongside parsing "maximum", and could return
  364. // nullptr when requesting a constraint pointer for "exclusiveMaximum".
  365. if (auto constraint = make_constraint(context.child(subschema, key))) {
  366. auto & into = context.factory.is_post_constraint(key) ? post_constraints_ : constraints_;
  367. into.emplace(key, std::move(constraint));
  368. }
  369. }
  370. }
  371. }
  372. }