schema.h 17 KB

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