schema.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #pragma once
  2. #include <memory>
  3. #include <unordered_map>
  4. #include <jvalidate/adapter.h>
  5. #include <jvalidate/constraint.h>
  6. #include <jvalidate/detail/anchor.h>
  7. #include <jvalidate/detail/expect.h>
  8. #include <jvalidate/detail/on_block_exit.h>
  9. #include <jvalidate/detail/parser_context.h>
  10. #include <jvalidate/detail/pointer.h>
  11. #include <jvalidate/detail/reference.h>
  12. #include <jvalidate/detail/reference_manager.h>
  13. #include <jvalidate/document_cache.h>
  14. #include <jvalidate/enum.h>
  15. #include <jvalidate/forward.h>
  16. namespace jvalidate::schema {
  17. /**
  18. * @brief The real "Schema" class, representing a resolved node in a schema
  19. * object. Each node is analogous to one layer of the schema json, and can
  20. * represent either a "rejects all" schema, an "accepts all" schema, or a
  21. * schema that has some selection of constraints and other features.
  22. */
  23. class Node {
  24. private:
  25. // Annotations for this schema...
  26. std::string description_;
  27. // The default value to apply to an object if if does not exist - is invoked
  28. // by the parent schema node, rather than this node itself.
  29. std::unique_ptr<adapter::Const const> default_{nullptr};
  30. // Rejects-all can provide a custom reason under some circumstances.
  31. std::optional<std::string> rejects_all_;
  32. // Actual constraint information
  33. std::optional<schema::Node const *> reference_{};
  34. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> constraints_{};
  35. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> post_constraints_{};
  36. public:
  37. Node() = default;
  38. /**
  39. * @brief Construct a schema that rejects all values, with a custom reason
  40. *
  41. * @param A user-safe justification of why this schema rejects everything.
  42. * Depending on the compiler settings, this might be used to indicate things
  43. * such as attempting to load a non-existant schema.
  44. */
  45. Node(std::string const & rejection_reason) : rejects_all_(rejection_reason) {}
  46. /**
  47. * @brief Actually initialize this schema node. Unfortunately, we cannot use
  48. * RAII for initializing this object because of certain optimizations and
  49. * guardrails make reference captures breakable.
  50. *
  51. * @param context The currently operating context, including the actual JSON
  52. * document being parsed at this moment.
  53. */
  54. template <Adapter A> void construct(detail::ParserContext<A> context);
  55. bool is_pure_reference() const {
  56. return reference_ && constraints_.empty() && post_constraints_.empty() && not default_;
  57. }
  58. bool accepts_all() const {
  59. return not reference_ && constraints_.empty() && post_constraints_.empty();
  60. }
  61. std::optional<std::string> const & rejects_all() const { return rejects_all_; }
  62. std::optional<schema::Node const *> reference_schema() const { return reference_; }
  63. std::string const & description() const { return description_; }
  64. bool requires_result_context() const { return not post_constraints_.empty(); }
  65. auto const & constraints() const { return constraints_; }
  66. auto const & post_constraints() const { return post_constraints_; }
  67. adapter::Const const * default_value() const { return default_.get(); }
  68. private:
  69. /**
  70. * @brief Resolve any dynamic anchors that are children of the current schema
  71. * (if this is the root node of a schema). If it is not a root node (does not
  72. * define "$id"), then this function does nothing.
  73. *
  74. * @tparam A The Adapter type for the JSON being worked with.
  75. *
  76. * @param context The currently operating context, including the actual JSON
  77. * document being parsed at this moment.
  78. *
  79. * @returns If this is a root schema - a scope object to pop the dynamic scope
  80. */
  81. template <Adapter A> detail::OnBlockExit resolve_anchor(detail::ParserContext<A> const & context);
  82. /**
  83. * @brief Resolves/embeds referenced schema information into this schema node.
  84. *
  85. * @tparam A The Adapter type for the JSON being worked with.
  86. *
  87. * @param context The currently operating context, including the actual JSON
  88. * document being parsed at this moment.
  89. *
  90. * @returns true iff there was a reference tag to follow
  91. */
  92. template <Adapter A> bool resolve_reference(detail::ParserContext<A> const & context);
  93. };
  94. }
  95. namespace jvalidate {
  96. class Schema : public schema::Node {
  97. private:
  98. friend class schema::Node;
  99. template <Adapter A> friend struct detail::ParserContext;
  100. private:
  101. schema::Node accept_;
  102. schema::Node reject_{"always false"};
  103. // An owning cache of all created schemas. Avoids storing duplicates such as
  104. // the "always-true" schema, "always-false" schema, and schemas whose only
  105. // meaningful field is "$ref", "$recursiveRef", or "$dynamicRef".
  106. std::map<detail::Reference, schema::Node> cache_;
  107. // A non-owning cache of all schemas, including duplcates where multiple
  108. // References map to the same underlying schema.
  109. std::map<detail::Reference, schema::Node const *> alias_cache_;
  110. public:
  111. /**
  112. * @brief Construct a new schema. All other constructors of this type may be
  113. * considered syntactic sugar for this constructor.
  114. *
  115. * As such, the true signature of this class's contructor is:
  116. *
  117. * Schema(Adapter| JSON
  118. * [, schema::Version]
  119. * [, URIResolver<A> | DocumentCache<A> &]
  120. * [, ConstraintFactory<A> const &])
  121. *
  122. * as long as the order of arguments is preserved - the constructor will work
  123. * no matter which arguments are ignored. The only required argument being
  124. * the JSON object/Adapter.
  125. *
  126. * @param json An adapter to a json object
  127. *
  128. * @param version The json-schema draft version that all schemas will prefer
  129. *
  130. * @param external An object capable of resolving URIs, and turning them into
  131. * Adapter objects. Holds a cache and so must be mutable.
  132. *
  133. * @param factory An object that manuafactures constraints - allows the user
  134. * to provide custom extensions or even modify the behavior of existing
  135. * keywords by overridding the virtual accessor function(s).
  136. */
  137. template <Adapter A>
  138. Schema(A const & json, schema::Version version, DocumentCache<A> & external,
  139. ConstraintFactory<A> const & factory = {}) {
  140. // Prevent unintialized data caches
  141. if (version >= schema::Version::Draft06 && json.type() == adapter::Type::Boolean) {
  142. schema::Node::operator=(std::move(json.as_boolean() ? accept_ : reject_));
  143. return;
  144. }
  145. detail::ReferenceManager<A> ref(external, json, version, factory);
  146. detail::ParserContext<A> root{*this, json, &ref.vocab(version), ref};
  147. root.where = root.dynamic_where = ref.canonicalize({}, {}, false);
  148. construct(root);
  149. }
  150. /**
  151. * @param json An adapter to a json schema
  152. *
  153. * @param version The json-schema draft version that all schemas will prefer
  154. *
  155. * @param external An object capable of resolving URIs, and turning them into
  156. * Adapter objects. Holds a cache and so must be mutable. If this constructor
  157. * is called, then it means that the cache is a one-off object, and will not
  158. * be reused.
  159. */
  160. template <Adapter A, typename... Args>
  161. Schema(A const & json, schema::Version version, DocumentCache<A> && external, Args &&... args)
  162. : Schema(json, version, external, std::forward<Args>(args)...) {}
  163. /**
  164. * @param json An adapter to a json schema
  165. *
  166. * @param version The json-schema draft version that all schemas will prefer
  167. *
  168. * @param resolve A function capable of resolving URIs, and storing the
  169. * contents in a provided concrete JSON object.
  170. */
  171. template <Adapter A, typename... Args>
  172. Schema(A const & json, schema::Version version, URIResolver<A> resolve, Args &&... args)
  173. : Schema(json, version, DocumentCache<A>(resolve), std::forward<Args>(args)...) {}
  174. /**
  175. * @param json An adapter to a json schema
  176. *
  177. * @param version The json-schema draft version that all schemas will prefer
  178. */
  179. template <Adapter A, Not<DocumentCache<A>>... Args>
  180. Schema(A const & json, schema::Version version, Args &&... args)
  181. : Schema(json, version, DocumentCache<A>(), std::forward<Args>(args)...) {}
  182. /**
  183. * @param json Any non-adapter (JSON) object. Will be immedately converted
  184. * into an Adapter object to allow us to walk through it w/o specialization.
  185. */
  186. template <typename JSON, typename... Args>
  187. requires(not Adapter<JSON>)
  188. explicit Schema(JSON const & json, Args &&... args)
  189. : Schema(adapter::AdapterFor<JSON const>(json), std::forward<Args>(args)...) {}
  190. private:
  191. /**
  192. * @brief Cache an alias to a given schema, without ownership. alias_cache_ is
  193. * a many-to-one association.
  194. * Syntactic sugar for "add pointer to map and return".
  195. *
  196. * @param where The key aliasing the schema, which may also be the original
  197. * lexical key.
  198. *
  199. * @param schema The pointer to a schema being stored
  200. */
  201. schema::Node const * alias(detail::Reference const & where, schema::Node const * schema) {
  202. alias_cache_.emplace(where, schema);
  203. return schema;
  204. }
  205. /**
  206. * @brief Syntactic sugar for finding a map value as an optional instead of an
  207. * iterator that may be "end".
  208. *
  209. * @param ref The key being looked up
  210. */
  211. std::optional<schema::Node const *> from_cache(detail::Reference const & ref) {
  212. if (auto it = alias_cache_.find(ref); it != alias_cache_.end()) {
  213. return it->second;
  214. }
  215. return std::nullopt;
  216. }
  217. /**
  218. * @brief Resolve a $ref/$dynamicRef tag and construct or load from cache the
  219. * schema that is being pointed to.
  220. *
  221. * @param context All of the context information about the schema, importantly
  222. * the location information, {@see jvalidate::detail::ReferenceManager}, and
  223. * {@see jvalidate::detail::Vocabulary}.
  224. *
  225. * @param dynamic_reference Is this request coming from a "$dynamicRef"/
  226. * "$recursiveRef" tag, or a regular "$ref" tag.
  227. *
  228. * @returns A schema node, that will also be stored in a local cache.
  229. *
  230. * @throws std::runtime_error if the reference is to an unloaded URI, and we
  231. * fail to load it. If the preprocessor definition
  232. * JVALIDATE_LOAD_FAILURE_AS_FALSE_SCHEMA is set, then we instead return an
  233. * always-false schema with a custom error message. This is primarily for use
  234. * in writing tests for JSON-Schema's selfvalidation test cases.
  235. */
  236. template <Adapter A>
  237. schema::Node const * resolve(detail::Reference const & ref,
  238. detail::ParserContext<A> const & context, bool dynamic_reference) {
  239. detail::Reference lexical = context.ref.canonicalize(ref, context.where, dynamic_reference);
  240. detail::Reference dynamic = dynamic_reference ? lexical : context.dynamic_where / "$ref";
  241. detail::OnBlockExit scope;
  242. if (lexical.uri() != context.where.uri()) {
  243. // Whenever we change base URIs, we need to recalculate our dynamic_scope.
  244. // Otherwise, it is possible for a chain of $ref statements to
  245. // accidentally leave us ignoring $dynamicAnchor contexts.
  246. // This is demonstrated by the test descriptor in JSON-Schema-Test-Suite:
  247. // "$dynamicRef avoids the root of each schema, but scopes are still registered"
  248. scope = context.ref.dynamic_scope(lexical);
  249. }
  250. if (std::optional cached = from_cache(dynamic)) {
  251. return *cached;
  252. }
  253. std::string error;
  254. if (std::optional root = context.ref.load(lexical, context.vocab, error)) {
  255. return fetch_schema(context.rebind(*root, lexical, dynamic));
  256. }
  257. constexpr char const * prelude = "URIResolver could not find ";
  258. #ifdef JVALIDATE_LOAD_FAILURE_AS_FALSE_SCHEMA
  259. return alias(dynamic,
  260. &cache_.try_emplace(dynamic, prelude + std::string(lexical.uri())).first->second);
  261. #else
  262. JVALIDATE_THROW(std::runtime_error, prelude << lexical.uri() << ": " << error);
  263. #endif
  264. }
  265. /**
  266. * @brief Fetch from cache or create a new schema node from the given context,
  267. * which may be the result of resolving a reference {@see Schema::resolve}, or
  268. * simply loading a child schema via {@see ParserContext::node}.
  269. *
  270. * @param context The current operating context of the schema
  271. */
  272. template <Adapter A> schema::Node const * fetch_schema(detail::ParserContext<A> const & context) {
  273. // TODO(samjaffe): No longer promises uniqueness - instead track unique URI's
  274. if (std::optional cached = from_cache(context.dynamic_where)) {
  275. return *cached;
  276. }
  277. adapter::Type const type = context.schema.type();
  278. // Boolean schemas were made universally permitted in Draft06. Before then,
  279. // you could only use them for specific keywords, like additionalProperties.
  280. if (type == adapter::Type::Boolean && context.vocab->version() >= schema::Version::Draft06) {
  281. return alias(context.dynamic_where, context.schema.as_boolean() ? &accept_ : &reject_);
  282. }
  283. // If the schema is not universal accept/reject, then it MUST be an object
  284. EXPECT_M(type == adapter::Type::Object, "invalid schema at " << context.dynamic_where);
  285. // The empty object is equivalent to true, but is permitted in prior drafts
  286. if (context.schema.object_size() == 0) {
  287. return alias(context.dynamic_where, &accept_);
  288. }
  289. // Because of the below alias() expression, and the above from_cache
  290. // expression, it shouldn't be possible for try_emplace to not create a new
  291. // schema node. We keep the check in anyway just in case somehow things have
  292. // gotten into a malformed state.
  293. auto [it, created] = cache_.try_emplace(context.dynamic_where);
  294. EXPECT_M(created, "creating duplicate schema at... " << context.dynamic_where);
  295. // Do this here first in order to protect from infinite loops
  296. alias(context.dynamic_where, &it->second);
  297. it->second.construct(context);
  298. return &it->second;
  299. }
  300. };
  301. }
  302. namespace jvalidate::detail {
  303. template <Adapter A> schema::Node const * ParserContext<A>::node() const {
  304. return root.fetch_schema(*this);
  305. }
  306. template <Adapter A> schema::Node const * ParserContext<A>::always() const {
  307. return fixed_schema(schema.as_boolean());
  308. }
  309. template <Adapter A> schema::Node const * ParserContext<A>::fixed_schema(bool accept) const {
  310. return accept ? &root.accept_ : &root.reject_;
  311. }
  312. }
  313. namespace jvalidate::schema {
  314. template <Adapter A>
  315. detail::OnBlockExit Node::resolve_anchor(detail::ParserContext<A> const & context) {
  316. auto const schema = context.schema.as_object();
  317. if (context.vocab->version() < schema::Version::Draft2019_09 || not schema.contains("$id")) {
  318. return nullptr;
  319. }
  320. return context.ref.dynamic_scope(context.where);
  321. }
  322. template <Adapter A> bool Node::resolve_reference(detail::ParserContext<A> const & context) {
  323. auto const schema = context.schema.as_object();
  324. if (schema.contains("$ref")) {
  325. detail::Reference ref(schema["$ref"].as_string());
  326. reference_ = context.root.resolve(ref, context, false);
  327. return true;
  328. }
  329. // Prior to Draft2019-09, "$ref" was the only way to reference another
  330. // schema (ignoring Draft03's extends keyword, which was more like allOf)
  331. if (context.vocab->version() < Version::Draft2019_09) {
  332. return false;
  333. }
  334. std::string const dyn_ref =
  335. context.vocab->version() > schema::Version::Draft2019_09 ? "$dynamicRef" : "$recursiveRef";
  336. if (schema.contains(dyn_ref)) {
  337. detail::Reference ref(schema[dyn_ref].as_string());
  338. reference_ = context.root.resolve(ref, context, true);
  339. return true;
  340. }
  341. return false;
  342. }
  343. template <Adapter A> void Node::construct(detail::ParserContext<A> context) {
  344. EXPECT(context.schema.type() == adapter::Type::Object);
  345. auto const schema = context.schema.as_object();
  346. if (schema.contains("$schema")) {
  347. // At any point in the schema, we're allowed to change versions
  348. // This means that we're not version-locked to the latest grammar
  349. // (which is especially important for some breaking changes)
  350. context.vocab = &context.ref.vocab(URI(schema["$schema"].as_string()));
  351. }
  352. auto _ = resolve_anchor(context);
  353. bool const has_reference = resolve_reference(context);
  354. if (schema.contains("default")) {
  355. default_ = schema["default"].freeze();
  356. }
  357. if (schema.contains("description")) {
  358. description_ = schema["description"].as_string();
  359. }
  360. // Prior to Draft 2019-09, reference keywords take precedence over everything
  361. // else (instead of allowing direct extensions).
  362. if (has_reference && context.vocab->version() < Version::Draft2019_09) {
  363. return;
  364. }
  365. for (auto const & [key, subschema] : schema) {
  366. // Using a constraint store allows overriding certain rules, or the creation
  367. // of user-defined extention vocabularies.
  368. if (not context.vocab->is_constraint(key)) {
  369. continue;
  370. }
  371. // A constraint may return null if it is not applicable - but otherwise
  372. // well-formed. For example, before Draft-06 "exclusiveMaximum" was a
  373. // modifier property for "maximum", and not a unique constaint on its own.
  374. // Therefore, we parse it alongside parsing "maximum", and could return
  375. // nullptr when requesting a constraint pointer for "exclusiveMaximum".
  376. auto [constraint, post] = context.vocab->constraint(key, context.child(subschema, key));
  377. if (not constraint) {
  378. continue;
  379. }
  380. if (post) {
  381. post_constraints_.emplace(key, std::move(constraint));
  382. } else {
  383. constraints_.emplace(key, std::move(constraint));
  384. }
  385. }
  386. }
  387. }