reference_manager.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. #pragma once
  2. #include <cstdlib>
  3. #include <optional>
  4. #include <string>
  5. #include <string_view>
  6. #include <unordered_map>
  7. #include <unordered_set>
  8. #include <utility>
  9. #include <jvalidate/compat/enumerate.h>
  10. #include <jvalidate/detail/anchor.h>
  11. #include <jvalidate/detail/dynamic_reference_context.h>
  12. #include <jvalidate/detail/expect.h>
  13. #include <jvalidate/detail/on_block_exit.h>
  14. #include <jvalidate/detail/out.h>
  15. #include <jvalidate/detail/parser_context.h>
  16. #include <jvalidate/detail/pointer.h>
  17. #include <jvalidate/detail/reference.h>
  18. #include <jvalidate/detail/reference_cache.h>
  19. #include <jvalidate/detail/vocabulary.h>
  20. #include <jvalidate/document_cache.h>
  21. #include <jvalidate/enum.h>
  22. #include <jvalidate/forward.h>
  23. #include <jvalidate/uri.h>
  24. namespace jvalidate::detail {
  25. /**
  26. * @brief An object responsible for owning/managing the various documents,
  27. * references, and related functionality for ensuring that we properly construct
  28. * things.
  29. *
  30. * In order to support this we store information on:
  31. * - A {@see jvalidate::detail::ReferenceCache} that maps various absolute
  32. * Reference paths to their Canonical forms.
  33. * - "Vocabularies", which describe the the set of legal keywords for
  34. * constraint parsing.
  35. * - "Anchor Locations", a non-owning store of the Adapters associated with
  36. * "$id"/"$anchor" tags to allow quick lookups without having to re-walk the
  37. * document.
  38. * - "Dynamic Anchors", a list of all of the "$dynamicAnchor" tags that exist
  39. * under a given "$id" tag, and those bindings which are active in the current
  40. * scope.
  41. *
  42. * @tparam A The adapter type being operated upon
  43. */
  44. template <Adapter A> class ReferenceManager {
  45. private:
  46. ConstraintFactory<A> const & constraints_;
  47. DocumentCache<A> & external_;
  48. ReferenceCache references_;
  49. std::unordered_map<schema::Version, Vocabulary<A>> vocabularies_;
  50. std::unordered_map<URI, Vocabulary<A>> user_vocabularies_;
  51. std::unordered_map<RootReference, A> roots_;
  52. std::unordered_map<URI, std::unordered_map<Anchor, Reference>> dynamic_anchors_;
  53. DynamicReferenceContext active_dynamic_anchors_;
  54. public:
  55. /**
  56. * @brief Construct a new ReferenceManager around a given root schema
  57. *
  58. * @param external A cache/loader of external documents. Due to the way that
  59. * {@see jvalidate::Schema} is implemented, the cache may have the same
  60. * lifetime as this object, despite being owned by mutable reference.
  61. *
  62. * @param root The root schema being operated on.
  63. *
  64. * @param version The version of the schema being used for determining the
  65. * base vocabulary to work with (see the definition of schema::Version for
  66. * more details on how the base vocabulary changes).
  67. *
  68. * @param constraints A factory for turning JSON schema information into
  69. * constraints.
  70. */
  71. ReferenceManager(DocumentCache<A> & external, A const & root, schema::Version version,
  72. ConstraintFactory<A> const & constraints)
  73. : constraints_(constraints), external_(external), roots_{{{}, root}} {
  74. prime(root, {}, &vocab(version));
  75. }
  76. /**
  77. * @brief Turn a schema version into a vocabulary, ignoring user-defined
  78. * vocabularies
  79. *
  80. * @param version The schema version
  81. *
  82. * @returns The default vocabulary for a given draft version
  83. */
  84. Vocabulary<A> const & vocab(schema::Version version) {
  85. if (not vocabularies_.contains(version)) {
  86. vocabularies_.emplace(version, constraints_.keywords(version));
  87. }
  88. return vocabularies_.at(version);
  89. }
  90. /**
  91. * @brief Fetch the vocabulary information associated with a given "$schema"
  92. * tag. Unlike the enum version of this function, we can also load
  93. * user-defined schemas using the ReferenceCache object, if supported. This
  94. * allows us to define custom constraints or remove some that we want to
  95. * forbid.
  96. *
  97. * @param schema The location of the schema being fetched
  98. *
  99. * @returns If schema is a draft version - then one of the default
  100. * vocabularies, else a user-schema is loaded.
  101. */
  102. Vocabulary<A> const & vocab(URI const & schema) {
  103. static std::unordered_map<std::string_view, schema::Version> const schema_ids{
  104. {"json-schema.org/draft-03/schema", schema::Version::Draft03},
  105. {"json-schema.org/draft-04/schema", schema::Version::Draft04},
  106. {"json-schema.org/draft-06/schema", schema::Version::Draft06},
  107. {"json-schema.org/draft-07/schema", schema::Version::Draft07},
  108. {"json-schema.org/draft/2019-09/schema", schema::Version::Draft2019_09},
  109. {"json-schema.org/draft/2020-12/schema", schema::Version::Draft2020_12},
  110. };
  111. if (auto it = schema_ids.find(schema.resource()); it != schema_ids.end()) {
  112. return vocab(it->second);
  113. }
  114. if (auto it = user_vocabularies_.find(schema); it != user_vocabularies_.end()) {
  115. return it->second;
  116. }
  117. std::string error;
  118. std::optional<A> external = external_.try_load(schema, error);
  119. EXPECT_M(external.has_value(),
  120. "Unable to load external meta-schema " << schema << ": " << error);
  121. EXPECT_M(external->type() == adapter::Type::Object, "meta-schema must be an object");
  122. auto metaschema = external->as_object();
  123. // All user-defined schemas MUST have a parent schema they point to
  124. // Furthermore - in order to be well-formed, the schema chain must
  125. // eventually point to one of the draft schemas. However - if a metaschema
  126. // ends up in a recusive situation (e.g. A -> B -> A), it will not fail in
  127. // the parsing step, but instead produce a malformed Schema object for
  128. // validation.
  129. EXPECT_M(metaschema.contains("$schema"),
  130. "user-defined meta-schema must reference a base schema");
  131. // Initialize first to prevent recursion
  132. Vocabulary<A> & parent = user_vocabularies_[schema];
  133. parent = vocab(URI(metaschema["$schema"].as_string()));
  134. if (metaschema.contains("$vocabulary")) {
  135. // This is a silly thing we have to do because rather than have some kind
  136. // of annotation/assertion divide marker for the format constraint, we
  137. // instead use true/false in Draft2019-09, and have format-assertion/
  138. // format-annotation vocabularies in Draft2020-12.
  139. auto [keywords, vocabularies] = extract_keywords(metaschema["$vocabulary"].as_object());
  140. parent.restrict(keywords, vocabularies);
  141. }
  142. return parent;
  143. }
  144. /**
  145. * @brief Load the current location into the stack of dynamic ref/anchors so
  146. * that we are able to properly resolve them (e.g. because an anchor got
  147. * disabled).
  148. *
  149. * @param ref The current parsing location in the schema, which should
  150. * correspond with an "$id" tag.
  151. *
  152. * @returns A scope object that will remove this set of dynamic ref/anchor
  153. * resolutions from the stack when it exits scope.
  154. */
  155. auto dynamic_scope(Reference const & ref) {
  156. URI const uri =
  157. ref.pointer().empty() ? ref.uri() : references_.relative_to_nearest_anchor(ref).uri();
  158. return active_dynamic_anchors_.scope(uri, dynamic_anchors_[uri]);
  159. }
  160. /**
  161. * @breif "Load" a requested document reference, which may exist in the
  162. * current document, or in an external one.
  163. *
  164. * @param ref The location to load. Since there is no guarantee of direct
  165. * relation between the current scope and this reference, we treat this like a
  166. * jump.
  167. *
  168. * @param vocab The current vocabulary being used for parsing. It may be
  169. * changed when loading the new reference if there is a "$schema" tag at the
  170. * root.
  171. *
  172. * @returns The schema corresponding to the reference, if it can be located.
  173. * As long as ref contains a valid URI/Anchor, we will return an Adapter, even
  174. * if that adapter might point to a null JSON.
  175. */
  176. std::optional<A> load(Reference const & ref, Vocabulary<A> const * vocab, std::string & error) {
  177. if (auto it = roots_.find(ref.root()); it != roots_.end()) {
  178. return ref.pointer().walk(it->second);
  179. }
  180. std::optional<A> external = external_.try_load(ref.uri(), error);
  181. if (not external) {
  182. return std::nullopt;
  183. }
  184. references_.emplace(ref.uri());
  185. prime(*external, ref, vocab);
  186. // May have a sub-id that we map to
  187. if (auto it = roots_.find(ref.root()); it != roots_.end()) {
  188. return ref.pointer().walk(it->second);
  189. }
  190. // Will get called if the external schema does not declare a root id?
  191. return ref.pointer().walk(*external);
  192. }
  193. /**
  194. * @brief Transform a reference into its "canonical" form, in the context of
  195. * the calling context (parent).
  196. *
  197. * @param ref The value of a "$ref" or "$dynamicRef" token, that is being
  198. * looked up.
  199. *
  200. * @param parent The current lexical scope being operated in.
  201. *
  202. * @param dynamic_reference As an input, indicates that we are requesting a
  203. * dynamic reference instead of a normal $ref.
  204. * As an output, indicates that we effectively did resolve a dynamicRef and
  205. * therefore should alter the dynamic scope in order to prevent infinite
  206. * recursions in schema parsing.
  207. *
  208. * @returns ref, but in its canonical/lexical form.
  209. */
  210. Reference canonicalize(Reference const & ref, Reference const & parent,
  211. inout<bool> dynamic_reference) {
  212. URI const uri = [this, &ref, &parent]() {
  213. // If there are no URIs involed (root schema does not set "$id")
  214. // then we don't need to do anything clever
  215. if (ref.uri().empty() && parent.uri().empty()) {
  216. return references_.actual_parent_uri(parent);
  217. }
  218. // At least one of ref and parent have a real URI/"$id" value. If it has a
  219. // "root" (e.g. file:// or http://), then we don't need to do any clever
  220. // alterations to identify the root.
  221. URI uri = ref.uri().empty() ? parent.uri() : ref.uri();
  222. if (not uri.is_rootless()) {
  223. return uri;
  224. }
  225. // Now we need to compute that URI into the context of its parent, such
  226. // as if ref := "file.json" and
  227. // parent := "http://localhost:8000/schemas/root.json"
  228. URI base = references_.actual_parent_uri(parent);
  229. EXPECT_M(base.resource().rfind('/') != std::string::npos,
  230. "Unable to deduce root for relative uri " << uri << " (" << base << ")");
  231. if (not uri.is_relative()) {
  232. return base.root() / uri;
  233. }
  234. if (auto base_rsrc = base.resource(), u_rsrc = uri.resource();
  235. base_rsrc.ends_with(u_rsrc) && base_rsrc[base_rsrc.size() - u_rsrc.size() - 1] == '/') {
  236. return base;
  237. }
  238. return base.parent() / uri;
  239. }();
  240. // This seems unintuitive, but we generally want to avoid providing a URI
  241. // when looking up dynamic references, unless they are explicitly asked for.
  242. URI const dyn_uri = ref.uri().empty() ? URI() : uri;
  243. if (std::optional dynref = dynamic(dyn_uri, ref, dynamic_reference)) {
  244. return *dynref;
  245. }
  246. dynamic_reference = dynamic_reference || active_dynamic_anchors_.empty();
  247. // Relative URI, not in the HEREDOC (or we set an $id)
  248. if (ref.uri().empty() and ref.anchor().empty()) {
  249. return Reference(references_.relative_to_nearest_anchor(parent).root(), ref.pointer());
  250. }
  251. return Reference(uri, ref.anchor(), ref.pointer());
  252. }
  253. private:
  254. /**
  255. * @brief Locate the dynamic reference being requested (if it is being
  256. * requested).
  257. *
  258. * @param uri The dynamic reference uri being requested, generally empty.
  259. *
  260. * @param ref The value of a "$ref" or "$dynamicRef" token, that is being
  261. * looked up. Primarily used for the anchor value, which is relevant for
  262. * $dynamicRef/$dynamicAnchor.
  263. *
  264. * @param dynamic_reference As an input, indicates that we are requesting a
  265. * dynamic reference instead of a normal $ref.
  266. * As an output, indicates that we effectively did resolve a dynamicRef and
  267. * therefore should alter the dynamic scope in order to prevent infinite
  268. * recursions in schema parsing.
  269. *
  270. * @returns If there is a dynamic reference for the requested anchor, we
  271. * return it.
  272. */
  273. std::optional<Reference> dynamic(URI const & uri, Reference const & ref,
  274. inout<bool> dynamic_reference) {
  275. bool const anchor_is_dynamic = active_dynamic_anchors_.contains(ref.anchor());
  276. if (not dynamic_reference) {
  277. // A normal $ref to an $anchor that matches a $dynamicAnchor breaks the
  278. // dynamic recursion pattern. This requires that we are not looking for a
  279. // subschema of the anchor AND that we are not targetting an anchor in a
  280. // different root document.
  281. dynamic_reference = (anchor_is_dynamic && ref.uri().empty() && ref.pointer().empty());
  282. return std::nullopt;
  283. }
  284. OnBlockExit scope;
  285. if (not ref.uri().empty() && anchor_is_dynamic) {
  286. // Register the scope of this (potential) $dynamicAnchor BEFORE we attempt
  287. // to enter the reference, in case we end up pointing to an otherwise
  288. // suppressed $dynamicAnchor in a higher scope.
  289. scope = dynamic_scope(Reference(uri));
  290. }
  291. return active_dynamic_anchors_.lookup(uri, ref.anchor());
  292. }
  293. /**
  294. * @brief Prepare a newly loaded document, importing schema information,
  295. * ids, anchors, and dynamic anchors recursively.
  296. *
  297. * @param json The document being loaded
  298. *
  299. * @param vocab The vocabulary of legitimate keywords to iterate through to
  300. * locate ids etc.
  301. */
  302. void prime(Adapter auto const & json, Reference where, Vocabulary<A> const * vocab) {
  303. if (json.type() != adapter::Type::Object) {
  304. return;
  305. }
  306. auto schema = json.as_object();
  307. // Update vocabulary to the latest form
  308. if (schema.contains("$schema")) {
  309. vocab = &this->vocab(URI(schema["$schema"].as_string()));
  310. }
  311. // Load ids, anchors, etc.
  312. prime_roots(where, vocab->version(), json);
  313. // Recurse through the document
  314. for (auto const & [key, value] : schema) {
  315. if (not vocab->is_keyword(key)) {
  316. continue;
  317. }
  318. switch (value.type()) {
  319. case adapter::Type::Array: {
  320. // Recurse through array-type schemas, such as anyOf, allOf, and oneOf
  321. // we don't actually check that the key is one of those, because if we
  322. // do something stupid like "not": [] then the parsing phase will return
  323. // an error.
  324. for (auto const & [index, elem] : detail::enumerate(value.as_array())) {
  325. prime(elem, where / key / index, vocab);
  326. }
  327. break;
  328. }
  329. case adapter::Type::Object:
  330. // Normal schema-type data such as not, additionalItems, etc. hold a
  331. // schema as their immidiate child.
  332. if (not vocab->is_property_keyword(key)) {
  333. prime(value, where / key, vocab);
  334. break;
  335. }
  336. // Special schemas are key-value stores, where the key is arbitrary and
  337. // the value is the schema. Therefore we need to skip over the props.
  338. for (auto const & [prop, elem] : value.as_object()) {
  339. prime(elem, where / key / prop, vocab);
  340. }
  341. default:
  342. break;
  343. }
  344. }
  345. }
  346. /**
  347. * @brief Optionally register any root document at this location, as
  348. * designated by things like the "$id" and "$anchor" tags.
  349. *
  350. * @param where The current lexical location in the schema - if there is an
  351. * id/anchor tag, then we overwrite this value with the newly indicated root.
  352. *
  353. * @param version The current schema version - used to denote the name of the
  354. * id tag, whether anchors are available, and how dynamic anchors function
  355. * (Draft2019-09's recursiveAnchor vs. Draft2020-12's dynamicAnchor).
  356. *
  357. * @param json The document being primed.
  358. */
  359. void prime_roots(Reference & where, schema::Version version, A const & json) {
  360. std::string const id_token = version <= schema::Version::Draft04 ? "id" : "$id";
  361. auto const schema = json.as_object();
  362. RootReference root = where.root();
  363. if (schema.contains(id_token)) {
  364. root = RootReference(schema[id_token].as_string());
  365. if (root.uri().empty()) {
  366. root = RootReference(where.uri(), root.anchor());
  367. } else if (not root.uri().is_rootless() || where.uri().empty()) {
  368. // By definition - rooted URIs cannot be relative
  369. } else if (root.uri().is_relative()) {
  370. root = RootReference(where.uri().parent() / root.uri(), root.anchor());
  371. } else {
  372. root = RootReference(where.uri().root() / root.uri(), root.anchor());
  373. }
  374. roots_.emplace(root, json);
  375. where = references_.emplace(where, root);
  376. }
  377. // $anchor and its related keywords were introduced in Draft 2019-09
  378. if (version < schema::Version::Draft2019_09) {
  379. return;
  380. }
  381. if (schema.contains("$anchor")) {
  382. root = RootReference(root.uri(), Anchor(schema["$anchor"].as_string()));
  383. roots_.emplace(root, json);
  384. where = references_.emplace(where, root);
  385. }
  386. // Unfortunately - $recursiveAnchor and $dynamicAnchor use very different
  387. // handling mechanisms, so it is not convenient to merge together
  388. if (version == schema::Version::Draft2019_09 && schema.contains("$recursiveAnchor") &&
  389. schema["$recursiveAnchor"].as_boolean()) {
  390. Anchor const anchor;
  391. root = RootReference(root.uri(), anchor);
  392. roots_.emplace(root, json);
  393. where = references_.emplace(where, root);
  394. if (Reference & dynamic = dynamic_anchors_[root.uri()][anchor];
  395. dynamic == Reference() || where < dynamic) {
  396. dynamic = where;
  397. }
  398. }
  399. if (schema.contains("$dynamicAnchor") && version > schema::Version::Draft2019_09) {
  400. Anchor const anchor(schema["$dynamicAnchor"].as_string());
  401. root = RootReference(root.uri(), anchor);
  402. roots_.emplace(root, json);
  403. where = references_.emplace(where, root);
  404. if (Reference & dynamic = dynamic_anchors_[root.uri()][anchor];
  405. dynamic == Reference() || where < dynamic) {
  406. dynamic = where;
  407. }
  408. }
  409. }
  410. /**
  411. * @brief Extract the supported keywords of a given selection of vocabularies
  412. *
  413. * @param vocabularies A map of the form (VocabularyURI => Enabled)
  414. *
  415. * @returns A pair containing:
  416. * - All of the enabled keywords in the vocabulary
  417. * - The list of enabled vocabulary metaschema (used for is_format_assertion)
  418. */
  419. auto extract_keywords(ObjectAdapter<A> auto const & vocabularies) const
  420. -> std::pair<std::unordered_map<std::string, bool>, std::unordered_set<std::string>> {
  421. std::unordered_map<std::string, bool> keywords;
  422. std::unordered_set<std::string> vocab_docs;
  423. for (auto [vocab, required] : vocabularies) {
  424. constexpr std::string_view vocab_div = "/vocab/";
  425. size_t const pos = vocab.find(vocab_div);
  426. vocab_docs.emplace(vocab.substr(pos));
  427. vocab.replace(pos, vocab_div.size(), "/meta/");
  428. std::string error;
  429. auto vocab_object = external_.try_load(URI(vocab), error);
  430. if (!vocab_object.has_value()) {
  431. continue;
  432. }
  433. auto it = vocab_object->as_object().find("properties");
  434. if (it == vocab_object->as_object().end()) {
  435. continue;
  436. }
  437. for (auto const & [keyword, _] : it->second.as_object()) {
  438. keywords.emplace(keyword, required.as_boolean());
  439. }
  440. }
  441. return std::make_pair(keywords, vocab_docs);
  442. }
  443. };
  444. }