schema.h 16 KB

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