reference_manager.h 18 KB

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