validation_visitor.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. #pragma once
  2. #include <algorithm>
  3. #include <tuple>
  4. #include <type_traits>
  5. #include <vector>
  6. #include <jvalidate/compat/enumerate.h>
  7. #include <jvalidate/constraint/array_constraint.h>
  8. #include <jvalidate/constraint/general_constraint.h>
  9. #include <jvalidate/constraint/number_constraint.h>
  10. #include <jvalidate/constraint/object_constraint.h>
  11. #include <jvalidate/constraint/string_constraint.h>
  12. #include <jvalidate/detail/expect.h>
  13. #include <jvalidate/detail/iostream.h>
  14. #include <jvalidate/detail/number.h>
  15. #include <jvalidate/detail/pointer.h>
  16. #include <jvalidate/detail/scoped_state.h>
  17. #include <jvalidate/detail/string_adapter.h>
  18. #include <jvalidate/forward.h>
  19. #include <jvalidate/schema.h>
  20. #include <jvalidate/status.h>
  21. #include <jvalidate/validation_config.h>
  22. #include <jvalidate/validation_result.h>
  23. #define VISITED(type) std::get<std::unordered_set<type>>(*visited_)
  24. #define VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(subschema, subinstance, path, local_visited, ...) \
  25. do { \
  26. Status const partial = \
  27. validate_subschema_on(subschema, subinstance, path __VA_OPT__(, ) __VA_ARGS__); \
  28. rval &= partial; \
  29. if (result_ and partial != Status::Noop) { \
  30. local_visited.insert(local_visited.end(), path); \
  31. } \
  32. } while (false)
  33. #define NOOP_UNLESS_TYPE(etype) \
  34. JVALIDATE_RETURN_UNLESS(adapter::Type::etype == document.type(), Status::Noop)
  35. #define BREAK_EARLY_IF_NO_RESULT_TREE() \
  36. do { \
  37. if (rval == Status::Reject and not result_ and not visited_) { \
  38. break; \
  39. } \
  40. } while (false)
  41. #define ANNOTATION_HELPER(name, ADD, FMT) \
  42. void name(auto const &... args) const { \
  43. if (not result_) { \
  44. /* do nothing if there's no result object to append to */ \
  45. } else if (schema_path_.empty()) { \
  46. result_->ADD(where_, schema_path_, "", FMT(args...)); \
  47. } else { \
  48. result_->ADD(where_, schema_path_.parent(), schema_path_.back(), FMT(args...)); \
  49. } \
  50. }
  51. namespace jvalidate {
  52. JVALIDATE_TRIBOOL_TYPE(StoreResults, ForValid, ForInvalid, ForAnything);
  53. template <Adapter Root, RegexEngine RE, typename ExtensionVisitor> class ValidationVisitor {
  54. private:
  55. using VisitedAnnotation = std::tuple<std::unordered_set<size_t>, std::unordered_set<std::string>>;
  56. friend class ValidationVisitorTest;
  57. private:
  58. detail::Pointer where_;
  59. detail::Pointer schema_path_;
  60. schema::Node const * schema_;
  61. Root const * root_;
  62. ValidationResult * result_;
  63. ValidationConfig const & cfg_;
  64. ExtensionVisitor extension_;
  65. RE & regex_;
  66. mutable VisitedAnnotation * visited_ = nullptr;
  67. mutable StoreResults tracking_ = StoreResults::ForInvalid;
  68. public:
  69. /**
  70. * @brief Construct a new ValidationVisitor
  71. *
  72. * @param schema The parsed JSON Schema
  73. * @param cfg General configuration settings for how the run is executed
  74. * @param regex A cache of string regular expressions to compiled
  75. * regular expressions
  76. * @param[optional] extension A special visitor for extension constraints.
  77. * @param[optional] result A cache of result/annotation info for the user to
  78. * receive a detailed summary of why a document is supported/unsupported.
  79. */
  80. ValidationVisitor(schema::Node const & schema, Root const & root, ValidationConfig const & cfg,
  81. RE & regex, ExtensionVisitor extension, ValidationResult * result)
  82. : schema_(&schema), root_(&root), result_(result), cfg_(cfg), extension_(extension),
  83. regex_(regex) {}
  84. private:
  85. Status visit(constraint::ExtensionConstraint const & cons, Adapter auto const & document) const {
  86. // Because we don't provide any contract constraint on our ExtensionVisitor,
  87. // we instead defer it to here where we validate that the extension can be
  88. // validated given the input document.
  89. // This covers a case where we write the extension around a specific adapter
  90. // instead of generically.
  91. if constexpr (std::is_invocable_r_v<Status, ExtensionVisitor, decltype(cons),
  92. decltype(document), ValidationVisitor const &>) {
  93. return extension_(cons, document, *this);
  94. }
  95. annotate("unsupported extension");
  96. return Status::Noop;
  97. }
  98. Status visit(constraint::TypeConstraint const & cons, Adapter auto const & document) const {
  99. adapter::Type const type = document.type();
  100. for (adapter::Type const accept : cons.types) {
  101. if (type == accept) { // Simple case, types are equal
  102. return result(Status::Accept, type, " is in types [", cons.types, "]");
  103. }
  104. if (accept == adapter::Type::Number && type == adapter::Type::Integer) {
  105. // Number is a super-type of Integer, therefore all Integer values are
  106. // accepted by a `"type": "number"` schema.
  107. return result(Status::Accept, type, " is in types [", cons.types, "]");
  108. }
  109. if (accept == adapter::Type::Integer && type == adapter::Type::Number &&
  110. detail::is_json_integer(document.as_number())) {
  111. // Since the JSON specification does not distinguish between Number
  112. // and Integer, but JSON Schema does, we need to check that the number
  113. // is a whole integer that is representable within the system (64-bit).
  114. return result(Status::Accept, type, " is in types [", cons.types, "]");
  115. }
  116. }
  117. return result(Status::Reject, type, " is not in types [", cons.types, "]");
  118. }
  119. Status visit(constraint::ConstConstraint const & cons, Adapter auto const & document) const {
  120. auto is_equal = [this, &document](auto const & frozen) {
  121. return document.equals(frozen, cfg_.strict_equality);
  122. };
  123. if (cons.value->apply(is_equal)) {
  124. return result(Status::Accept, "matches value");
  125. }
  126. return result(Status::Reject, cons.value, " was expected");
  127. }
  128. Status visit(constraint::EnumConstraint const & cons, Adapter auto const & document) const {
  129. auto is_equal = [this, &document](auto const & frozen) {
  130. return document.equals(frozen, cfg_.strict_equality);
  131. };
  132. for (auto const & [index, option] : detail::enumerate(cons.enumeration)) {
  133. if (option->apply(is_equal)) {
  134. return result(Status::Accept, index);
  135. }
  136. }
  137. return result(Status::Reject, document, " value is not one of ", cons.enumeration);
  138. }
  139. Status visit(constraint::AllOfConstraint const & cons, Adapter auto const & document) const {
  140. Status rval = Status::Accept;
  141. std::set<size_t> unmatched;
  142. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  143. if (auto stat = validate_subschema(subschema, document, index); stat == Status::Reject) {
  144. rval = Status::Reject;
  145. unmatched.insert(index);
  146. }
  147. BREAK_EARLY_IF_NO_RESULT_TREE();
  148. }
  149. if (rval == Status::Reject) {
  150. return result(rval, "does not validate subschemas ", unmatched);
  151. }
  152. return result(rval, "validates all subschemas");
  153. }
  154. Status visit(constraint::AnyOfConstraint const & cons, Adapter auto const & document) const {
  155. std::optional<size_t> first_validated;
  156. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  157. if (validate_subschema(subschema, document, index)) {
  158. // This technically will produce different results when we're tracking
  159. // visited nodes, but in practice it doesn't actually matter which
  160. // subschema index we record in the annotation.
  161. first_validated = index;
  162. }
  163. if (not visited_ && first_validated.has_value()) {
  164. break;
  165. }
  166. }
  167. if (first_validated.has_value()) {
  168. return result(Status::Accept, "validates subschema ", *first_validated);
  169. }
  170. return result(Status::Reject, "validates none of the subschemas");
  171. }
  172. Status visit(constraint::OneOfConstraint const & cons, Adapter auto const & document) const {
  173. std::set<size_t> matches;
  174. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  175. scoped_state(tracking_, StoreResults::ForAnything);
  176. if (validate_subschema(subschema, document, index)) {
  177. matches.insert(index);
  178. }
  179. }
  180. if (matches.empty()) {
  181. return result(Status::Reject, "validates no subschemas");
  182. }
  183. if (matches.size() > 1) {
  184. return result(Status::Reject, "validates multiple subschemas ", matches);
  185. }
  186. size_t const match = *matches.begin();
  187. for (size_t i = 0; result_ and i < cons.children.size(); ++i) {
  188. if (i != match) {
  189. result_->unannotate(where_, schema_path_ / i);
  190. }
  191. }
  192. return result(Status::Accept, "validates subschema ", match);
  193. }
  194. Status visit(constraint::NotConstraint const & cons, Adapter auto const & document) const {
  195. scoped_state(visited_, nullptr);
  196. scoped_state(tracking_, !tracking_);
  197. bool const rejected = validate_subschema(cons.child, document) == Status::Reject;
  198. return rejected;
  199. }
  200. Status visit(constraint::ConditionalConstraint const & cons,
  201. Adapter auto const & document) const {
  202. Status const if_true = [this, &cons, &document]() {
  203. scoped_state(tracking_, StoreResults::ForAnything);
  204. return validate_subschema(cons.if_constraint, document);
  205. }();
  206. annotate(if_true ? "valid" : "invalid");
  207. if (if_true) {
  208. return validate_subschema(cons.then_constraint, document, detail::parent, "then");
  209. }
  210. return validate_subschema(cons.else_constraint, document, detail::parent, "else");
  211. }
  212. Status visit(constraint::MaximumConstraint const & cons, Adapter auto const & document) const {
  213. switch (document.type()) {
  214. case adapter::Type::Integer:
  215. if (int64_t value = document.as_integer(); not cons(value)) {
  216. return result(Status::Reject, value, cons.exclusive ? " >= " : " > ", cons.value);
  217. } else {
  218. return result(Status::Accept, value, cons.exclusive ? " < " : " <= ", cons.value);
  219. }
  220. case adapter::Type::Number:
  221. if (double value = document.as_number(); not cons(value)) {
  222. return result(Status::Reject, value, cons.exclusive ? " >= " : " > ", cons.value);
  223. } else {
  224. return result(Status::Accept, value, cons.exclusive ? " < " : " <= ", cons.value);
  225. }
  226. default:
  227. return Status::Noop;
  228. }
  229. }
  230. Status visit(constraint::MinimumConstraint const & cons, Adapter auto const & document) const {
  231. switch (document.type()) {
  232. case adapter::Type::Integer:
  233. if (int64_t value = document.as_integer(); not cons(value)) {
  234. return result(Status::Reject, value, cons.exclusive ? " <= " : " < ", cons.value);
  235. } else {
  236. return result(Status::Accept, value, cons.exclusive ? " > " : " >= ", cons.value);
  237. }
  238. case adapter::Type::Number:
  239. if (double value = document.as_number(); not cons(value)) {
  240. return result(Status::Reject, value, cons.exclusive ? " <= " : " < ", cons.value);
  241. } else {
  242. return result(Status::Accept, value, cons.exclusive ? " > " : " >= ", cons.value);
  243. }
  244. default:
  245. return Status::Noop;
  246. }
  247. }
  248. Status visit(constraint::MultipleOfConstraint const & cons, Adapter auto const & document) const {
  249. adapter::Type const type = document.type();
  250. JVALIDATE_RETURN_UNLESS(type == adapter::Type::Number || type == adapter::Type::Integer,
  251. Status::Noop);
  252. if (double value = document.as_number(); not cons(value)) {
  253. return result(Status::Reject, value, " is not a multiple of ", cons.value);
  254. } else {
  255. return result(Status::Accept, value, " is a multiple of ", cons.value);
  256. }
  257. }
  258. Status visit(constraint::MaxLengthConstraint const & cons, Adapter auto const & document) const {
  259. NOOP_UNLESS_TYPE(String);
  260. std::string const str = document.as_string();
  261. if (int64_t len = detail::length(str); len > cons.value) {
  262. return result(Status::Reject, "string of length ", len, " is >", cons.value);
  263. } else {
  264. return result(Status::Accept, "string of length ", len, " is <=", cons.value);
  265. }
  266. }
  267. Status visit(constraint::MinLengthConstraint const & cons, Adapter auto const & document) const {
  268. NOOP_UNLESS_TYPE(String);
  269. std::string const str = document.as_string();
  270. if (int64_t len = detail::length(str); len < cons.value) {
  271. return result(Status::Reject, "string of length ", len, " is <", cons.value);
  272. } else {
  273. return result(Status::Accept, "string of length ", len, " is >=", cons.value);
  274. }
  275. }
  276. Status visit(constraint::PatternConstraint const & cons, Adapter auto const & document) const {
  277. NOOP_UNLESS_TYPE(String);
  278. std::string const str = document.as_string();
  279. annotate(regex_.engine_name());
  280. if (regex_.search(cons.regex, str)) {
  281. return result(Status::Accept, "string matches pattern /", cons.regex, "/");
  282. }
  283. return result(Status::Reject, "string does not match pattern /", cons.regex, "/");
  284. }
  285. Status visit(constraint::FormatConstraint const & cons, Adapter auto const & document) const {
  286. // https://json-schema.org/draft/2020-12/json-schema-validation#name-defined-formats
  287. NOOP_UNLESS_TYPE(String);
  288. annotate(cons.format);
  289. if (not cfg_.validate_format && not cons.is_assertion) {
  290. // Don't both validating formats if we're not in assertion mode
  291. // Assertion mode is specified either by using the appropriate "$vocab"
  292. // meta-schema or by requesting it in the ValidationConfig.
  293. return true; // TODO: I think this can be made into Noop
  294. }
  295. return result(Status::Reject, cons.format, " is unimplemented");
  296. }
  297. Status visit(constraint::AdditionalItemsConstraint const & cons,
  298. Adapter auto const & document) const {
  299. NOOP_UNLESS_TYPE(Array);
  300. auto array = document.as_array();
  301. Status rval = Status::Accept;
  302. std::vector<size_t> items;
  303. for (size_t i = cons.applies_after_nth; i < array.size(); ++i) {
  304. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, array[i], i, items);
  305. BREAK_EARLY_IF_NO_RESULT_TREE();
  306. }
  307. annotate_list(items);
  308. return rval;
  309. }
  310. Status visit(constraint::ContainsConstraint const & cons, Adapter auto const & document) const {
  311. NOOP_UNLESS_TYPE(Array);
  312. auto array = document.as_array();
  313. size_t const minimum = cons.minimum.value_or(1);
  314. size_t const maximum = cons.maximum.value_or(array.size());
  315. size_t matches = 0;
  316. for (size_t i = 0; i < array.size(); ++i) {
  317. if (validate_subschema_on(cons.subschema, array[i], i)) {
  318. ++matches;
  319. }
  320. }
  321. if (matches < minimum) {
  322. return result(Status::Reject, "array contains <", minimum, " matching items");
  323. }
  324. if (matches > maximum) {
  325. return result(Status::Reject, "array contains >", maximum, " matching items");
  326. }
  327. return result(Status::Accept, "array contains ", matches, " matching items");
  328. }
  329. Status visit(constraint::MaxItemsConstraint const & cons, Adapter auto const & document) const {
  330. NOOP_UNLESS_TYPE(Array);
  331. if (size_t size = document.array_size(); size > cons.value) {
  332. return result(Status::Reject, "array of size ", size, " is >", cons.value);
  333. } else {
  334. return result(Status::Accept, "array of size ", size, " is <=", cons.value);
  335. }
  336. }
  337. Status visit(constraint::MinItemsConstraint const & cons, Adapter auto const & document) const {
  338. NOOP_UNLESS_TYPE(Array);
  339. if (size_t size = document.array_size(); size < cons.value) {
  340. return result(Status::Reject, "array of size ", size, " is <", cons.value);
  341. } else {
  342. return result(Status::Accept, "array of size ", size, " is >=", cons.value);
  343. }
  344. }
  345. Status visit(constraint::TupleConstraint const & cons, Adapter auto const & document) const {
  346. NOOP_UNLESS_TYPE(Array);
  347. Status rval = Status::Accept;
  348. std::vector<size_t> items;
  349. for (auto const & [index, item] : detail::enumerate(document.as_array())) {
  350. if (index >= cons.items.size()) {
  351. break;
  352. }
  353. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.items[index], item, index, items);
  354. BREAK_EARLY_IF_NO_RESULT_TREE();
  355. }
  356. annotate_list(items);
  357. return rval;
  358. }
  359. template <Adapter A>
  360. Status visit(constraint::UniqueItemsConstraint const & cons, A const & document) const {
  361. NOOP_UNLESS_TYPE(Array);
  362. if constexpr (std::totally_ordered<A>) {
  363. // If the adapter defines comparison operators, then it becomes possible
  364. // to compute uniqueness in O(n*log(n)) checks.
  365. std::map<A, size_t> cache;
  366. for (auto const & [index, elem] : detail::enumerate(document.as_array())) {
  367. if (auto [it, created] = cache.emplace(elem, index); not created) {
  368. return result(Status::Reject, "items ", it->second, " and ", index, " are equal");
  369. }
  370. }
  371. } else {
  372. // Otherwise, we need to run an O(n^2) triangular array search comparing
  373. // equality for each element. This still guarantees that each element is
  374. // compared against each other element no more than once.
  375. auto array = document.as_array();
  376. for (size_t i = 0; i < array.size(); ++i) {
  377. for (size_t j = i + 1; j < array.size(); ++j) {
  378. if (array[i].equals(array[j], true)) {
  379. return result(Status::Reject, "items ", i, " and ", j, " are equal");
  380. }
  381. }
  382. }
  383. }
  384. return result(Status::Accept, "all array items are unique");
  385. }
  386. Status visit(constraint::AdditionalPropertiesConstraint const & cons,
  387. Adapter auto const & document) const {
  388. NOOP_UNLESS_TYPE(Object);
  389. auto matches_any_pattern = [this, &cons](std::string const & key) {
  390. return std::ranges::any_of(cons.patterns, [this, &key](auto const & pattern) {
  391. return regex_.search(pattern, key);
  392. });
  393. };
  394. Status rval = Status::Accept;
  395. std::vector<std::string> properties;
  396. for (auto const & [key, elem] : document.as_object()) {
  397. if (not cons.properties.contains(key) && not matches_any_pattern(key)) {
  398. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, elem, key, properties);
  399. }
  400. BREAK_EARLY_IF_NO_RESULT_TREE();
  401. }
  402. annotate_list(properties);
  403. return rval;
  404. }
  405. Status visit(constraint::DependenciesConstraint const & cons,
  406. Adapter auto const & document) const {
  407. NOOP_UNLESS_TYPE(Object);
  408. auto object = document.as_object();
  409. Status rval = Status::Accept;
  410. for (auto const & [key, subschema] : cons.subschemas) {
  411. if (not object.contains(key)) {
  412. continue;
  413. }
  414. rval &= validate_subschema(subschema, document, key);
  415. BREAK_EARLY_IF_NO_RESULT_TREE();
  416. }
  417. for (auto [key, required] : cons.required) {
  418. if (not object.contains(key)) {
  419. continue;
  420. }
  421. for (auto const & [key, _] : object) {
  422. required.erase(key);
  423. }
  424. rval &= required.empty();
  425. BREAK_EARLY_IF_NO_RESULT_TREE();
  426. }
  427. return rval;
  428. }
  429. Status visit(constraint::MaxPropertiesConstraint const & cons,
  430. Adapter auto const & document) const {
  431. NOOP_UNLESS_TYPE(Object);
  432. if (size_t size = document.object_size(); size > cons.value) {
  433. return result(Status::Reject, "object of size ", size, " is >", cons.value);
  434. } else {
  435. return result(Status::Accept, "object of size ", size, " is <=", cons.value);
  436. }
  437. }
  438. Status visit(constraint::MinPropertiesConstraint const & cons,
  439. Adapter auto const & document) const {
  440. NOOP_UNLESS_TYPE(Object);
  441. if (size_t size = document.object_size(); size < cons.value) {
  442. return result(Status::Reject, "object of size ", size, " is <", cons.value);
  443. } else {
  444. return result(Status::Accept, "object of size ", size, " is >=", cons.value);
  445. }
  446. }
  447. Status visit(constraint::PatternPropertiesConstraint const & cons,
  448. Adapter auto const & document) const {
  449. NOOP_UNLESS_TYPE(Object);
  450. std::vector<std::string> properties;
  451. Status rval = Status::Accept;
  452. for (auto const & [pattern, subschema] : cons.properties) {
  453. for (auto const & [key, elem] : document.as_object()) {
  454. if (not regex_.search(pattern, key)) {
  455. continue;
  456. }
  457. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(subschema, elem, key, properties);
  458. BREAK_EARLY_IF_NO_RESULT_TREE();
  459. }
  460. }
  461. annotate_list(properties);
  462. return rval;
  463. }
  464. template <Adapter A>
  465. Status visit(constraint::PropertiesConstraint const & cons, A const & document) const {
  466. NOOP_UNLESS_TYPE(Object);
  467. Status rval = Status::Accept;
  468. auto object = document.as_object();
  469. if constexpr (MutableAdapter<A>) {
  470. // Special Rule - if the adapter is of a mutable json document (wraps a
  471. // non-const reference and exposes the assign function) we will process
  472. // the "default" annotation will be applied.
  473. // https://json-schema.org/draft/2020-12/json-schema-validation#section-9.2
  474. //
  475. // Although the JSON Schema draft only says the the default value ought be
  476. // valid against the schema, this implementation will assure that it is
  477. // valid against this PropertiesConstraint, and any other constraints that
  478. // are run after this one.
  479. for (auto const & [key, subschema] : cons.properties) {
  480. auto const * default_value = subschema->default_value();
  481. if (default_value && not object.contains(key)) {
  482. object.assign(key, *default_value);
  483. }
  484. }
  485. }
  486. std::vector<std::string> properties;
  487. for (auto const & [key, elem] : object) {
  488. if (auto it = cons.properties.find(key); it != cons.properties.end()) {
  489. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(it->second, elem, key, properties, key);
  490. }
  491. BREAK_EARLY_IF_NO_RESULT_TREE();
  492. }
  493. annotate_list(properties);
  494. return rval;
  495. }
  496. Status visit(constraint::PropertyNamesConstraint const & cons,
  497. Adapter auto const & document) const {
  498. NOOP_UNLESS_TYPE(Object);
  499. Status rval = Status::Accept;
  500. for (auto const & [key, _] : document.as_object()) {
  501. rval &=
  502. validate_subschema_on(cons.key_schema, detail::StringAdapter(key), std::string("$$key"));
  503. }
  504. return rval;
  505. }
  506. Status visit(constraint::RequiredConstraint const & cons, Adapter auto const & document) const {
  507. NOOP_UNLESS_TYPE(Object);
  508. auto required = cons.properties;
  509. for (auto const & [key, _] : document.as_object()) {
  510. required.erase(key);
  511. }
  512. if (required.empty()) {
  513. return result(Status::Accept, "contains all required properties ", cons.properties);
  514. }
  515. return result(Status::Reject, "missing required properties ", required);
  516. }
  517. Status visit(constraint::UnevaluatedItemsConstraint const & cons,
  518. Adapter auto const & document) const {
  519. NOOP_UNLESS_TYPE(Array);
  520. if (not visited_) {
  521. return Status::Reject;
  522. }
  523. Status rval = Status::Accept;
  524. std::vector<size_t> items;
  525. for (auto const & [index, item] : detail::enumerate(document.as_array())) {
  526. if (not VISITED(size_t).contains(index)) {
  527. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, item, index, items);
  528. }
  529. BREAK_EARLY_IF_NO_RESULT_TREE();
  530. }
  531. annotate_list(items);
  532. return rval;
  533. }
  534. Status visit(constraint::UnevaluatedPropertiesConstraint const & cons,
  535. Adapter auto const & document) const {
  536. NOOP_UNLESS_TYPE(Object);
  537. if (not visited_) {
  538. return Status::Reject;
  539. }
  540. Status rval = Status::Accept;
  541. std::vector<std::string> properties;
  542. for (auto const & [key, elem] : document.as_object()) {
  543. if (not VISITED(std::string).contains(key)) {
  544. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, elem, key, properties);
  545. }
  546. BREAK_EARLY_IF_NO_RESULT_TREE();
  547. }
  548. annotate_list(properties);
  549. return rval;
  550. }
  551. public:
  552. /**
  553. * @brief The main entry point into the validator. Validates the provided
  554. * document according to the schema. This function should only be called
  555. * internally (validate_subschema/validate_subschema_on) or via the Validator
  556. * class.
  557. */
  558. Status validate(Adapter auto const & document) {
  559. // Step 1) Check if this is an always-false schema. Sometimes, this will
  560. // have a custom message.
  561. if (std::optional<std::string> const & reject = schema_->rejects_all()) {
  562. if (should_annotate(Status::Reject)) {
  563. // This will only be run if we are interested in why something is
  564. // rejected. For example - `{ "not": false }` doesn't produce a
  565. // meaningful annotation...
  566. result_->error(where_, schema_path_, "", *reject);
  567. }
  568. // ...We do always record the result if a result object is present.
  569. (result_ ? result_->valid(where_, schema_path_, false) : void());
  570. return Status::Reject;
  571. }
  572. if (schema_->accepts_all()) {
  573. // An accept-all schema is not No-Op for the purpose of unevaluated*
  574. (result_ ? result_->valid(where_, schema_path_, true) : void());
  575. return Status::Accept;
  576. }
  577. // Begin tracking evaluations for unevaluated* keywords. The annotation
  578. // object is passed down from parent visitor to child visitor to allow all
  579. // schemas to mark whether they visited a certain item or property.
  580. VisitedAnnotation annotate;
  581. if (schema_->requires_result_context() and not visited_) {
  582. visited_ = &annotate;
  583. }
  584. Status rval = Status::Noop;
  585. // Before Draft2019_09, reference schemas could not coexist with other
  586. // constraints. This is enforced in the parsing of the schema, rather than
  587. // during validation {@see jvalidate::schema::Node::construct}.
  588. if (std::optional<schema::Node const *> ref = schema_->reference_schema()) {
  589. // TODO: Investigate why this seems to produce .../$ref/$ref pointers
  590. rval = validate_subschema(*ref, document, "$ref");
  591. }
  592. if (result_ && !schema_->description().empty()) {
  593. result_->annotate(where_, schema_path_, "description", schema_->description());
  594. }
  595. detail::Pointer const current_schema = schema_path_;
  596. for (auto const & [key, p_constraint] : schema_->constraints()) {
  597. BREAK_EARLY_IF_NO_RESULT_TREE();
  598. schema_path_ = current_schema / key;
  599. rval &= std::visit([this, &document](auto & c) { return this->visit(c, document); },
  600. *p_constraint);
  601. }
  602. // Post Constraints represent the unevaluatedItems and unevaluatedProperties
  603. // keywords.
  604. for (auto const & [key, p_constraint] : schema_->post_constraints()) {
  605. BREAK_EARLY_IF_NO_RESULT_TREE();
  606. schema_path_ = current_schema / key;
  607. rval &= std::visit([this, &document](auto & c) { return this->visit(c, document); },
  608. *p_constraint);
  609. }
  610. (result_ ? result_->valid(where_, current_schema, static_cast<bool>(rval)) : void());
  611. return rval;
  612. }
  613. // Functions to grant access to some, but not all of the internals of the
  614. // ValidationVisitor for the purposes of implementing ExtensionVisitor
  615. // validators.
  616. detail::Pointer const & where() const { return where_; }
  617. Root const & root() const { return *root_; }
  618. ValidationConfig const & config() const { return cfg_; }
  619. RE & regex() const { return regex_; }
  620. /**
  621. * @brief Allow ExtensionVisitor to enter a state similar to a NotConstraint
  622. * when calling sub-requests.
  623. *
  624. * @return A ScopedState object that will restore the tracking mode once it
  625. * is destroyed.
  626. */
  627. [[nodiscard]] detail::ScopedState invert_tracking() const {
  628. return detail::ScopedState(tracking_, !tracking_);
  629. }
  630. /**
  631. * @brief Allow ExtensionVisitor to enable tracking of all results in child
  632. * constraints.
  633. *
  634. * @return A ScopedState object that will restore the tracking mode once it
  635. * is destroyed.
  636. */
  637. [[nodiscard]] detail::ScopedState track_everything() const {
  638. return detail::ScopedState(tracking_, StoreResults::ForAnything);
  639. }
  640. ANNOTATION_HELPER(error, error, jvalidate::to_string)
  641. ANNOTATION_HELPER(annotate, annotate, jvalidate::to_string)
  642. ANNOTATION_HELPER(annotate_list, annotate, jvalidate::to_string_list)
  643. bool should_annotate(Status stat) const {
  644. if (not result_) {
  645. return false;
  646. }
  647. switch (*tracking_) {
  648. case StoreResults::ForAnything:
  649. return stat != Status::Noop;
  650. case StoreResults::ForValid:
  651. return stat == Status::Accept;
  652. case StoreResults::ForInvalid:
  653. return stat == Status::Reject;
  654. }
  655. }
  656. Status result(Status stat, auto const &... args) const {
  657. return (should_annotate(stat) ? error(args...) : void(), stat);
  658. }
  659. /**
  660. * @brief Walking function for entering a subschema.
  661. *
  662. * @param subschema The "subschema" being validated. This is either another
  663. * schema object (jvalidate::schema::Node), or a constraint.
  664. * @param keys... The path to this subschema, relative to the current schema
  665. * evaluation.
  666. *
  667. * @return The status of validating the current instance against the
  668. * subschema.
  669. */
  670. template <typename... K>
  671. Status validate_subschema(constraint::SubConstraint const & subschema,
  672. Adapter auto const & document, K const &... keys) const {
  673. if (schema::Node const * const * ppschema = std::get_if<0>(&subschema)) {
  674. return validate_subschema(*ppschema, document, keys...);
  675. } else {
  676. return std::visit([this, &document](auto & c) { return this->visit(c, document); },
  677. *std::get<1>(subschema));
  678. }
  679. }
  680. /**
  681. * @brief Walking function for entering a subschema. Creates a new validation
  682. * visitor in order to continue evaluation.
  683. *
  684. * @param subschema The subschema being validated.
  685. * @param keys... The path to this subschema, relative to the current schema
  686. * evaluation.
  687. *
  688. * @return The status of validating the current instance against the
  689. * subschema.
  690. */
  691. template <typename... K>
  692. Status validate_subschema(schema::Node const * subschema, Adapter auto const & document,
  693. K const &... keys) const {
  694. VisitedAnnotation annotate;
  695. ValidationVisitor next = *this;
  696. ((next.schema_path_ /= keys), ...);
  697. std::tie(next.schema_, next.visited_) =
  698. std::forward_as_tuple(subschema, visited_ ? &annotate : nullptr);
  699. Status rval = next.validate(document);
  700. // Only update the visited annotation of the current context if the
  701. // subschema validates as Accepted.
  702. if (rval == Status::Accept and visited_) {
  703. std::get<0>(*visited_).merge(std::get<0>(annotate));
  704. std::get<1>(*visited_).merge(std::get<1>(annotate));
  705. }
  706. return rval;
  707. }
  708. /**
  709. * @brief Walking function for entering a subschema and child document.
  710. * Creates a new validation visitor in order to continue evaluation.
  711. *
  712. * @param subschema The subschema being validated.
  713. * @param document The child document being evaluated.
  714. * @param key The path to this document instance.
  715. * @param schema_keys... The path to this subschema, relative to the current
  716. * schema evaluation.
  717. *
  718. * @return The status of validating the current instance against the
  719. * subschema.
  720. */
  721. template <typename K>
  722. Status validate_subschema_on(schema::Node const * subschema, Adapter auto const & document,
  723. K const & key, auto const &... schema_keys) const {
  724. ValidationResult result;
  725. ValidationVisitor next = *this;
  726. next.where_ /= key;
  727. ((next.schema_path_ /= schema_keys), ...);
  728. std::tie(next.schema_, next.result_, next.visited_) =
  729. std::forward_as_tuple(subschema, result_ ? &result : nullptr, nullptr);
  730. Status rval = next.validate(document);
  731. // Only update the visited annotation of the current context if the
  732. // subschema validates as Accepted.
  733. if (rval == Status::Accept and visited_) {
  734. VISITED(K).insert(key);
  735. }
  736. // Update the annotation/error content only if a failure is being reported,
  737. // or if we are in an "if" schema.
  738. if (should_annotate(rval)) {
  739. result_->merge(std::move(result));
  740. }
  741. return rval;
  742. }
  743. };
  744. }
  745. #undef ANNOTATION_HELPER
  746. #undef BREAK_EARLY_IF_NO_RESULT_TREE
  747. #undef NOOP_UNLESS_TYPE
  748. #undef VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT
  749. #undef VISITED