From f472bcca1ee79b0447a69438b4eedc8d14040996 Mon Sep 17 00:00:00 2001 From: OpSocket Date: Fri, 19 Aug 2022 17:51:48 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9A=EF=B8=8F=20raise=20error=20when=20?= =?UTF-8?q?trying=20to=20change=20a=20read=20only=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/json-validator.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/json-validator.cpp b/src/json-validator.cpp index 3ffd087..89a28cf 100644 --- a/src/json-validator.cpp +++ b/src/json-validator.cpp @@ -457,6 +457,7 @@ class type_schema : public schema std::vector> type_; std::pair enum_, const_; std::vector> logic_; + bool read_only_ = false; static std::shared_ptr make(json &schema, json::value_t type, @@ -507,6 +508,13 @@ class type_schema : public schema else_->validate(ptr, instance, patch, e); } } + + // enforce default value if any read only values + if(read_only_) { + auto rod_value = default_value(ptr, instance, e); + if(rod_value != nullptr && instance != rod_value) + e.error(ptr, instance, "key is read-only"); + } } public: @@ -562,6 +570,12 @@ public: sch.erase(attr); } + attr = sch.find("readOnly"); + if (attr != sch.end()) { + read_only_ = attr.value().get(); + sch.erase(attr); + } + for (auto &key : known_keywords) sch.erase(key); @@ -1327,7 +1341,7 @@ class throwing_error_handler : public error_handler { void error(const json::json_pointer &ptr, const json &instance, const std::string &message) override { - throw std::invalid_argument(std::string("At ") + ptr.to_string() + " of " + instance.dump() + " - " + message + "\n"); + throw std::invalid_argument(std::string("At \"") + ptr.to_string() + "\" with a value of " + instance.dump() + " - " + message + "\n"); } }; @@ -1402,3 +1416,4 @@ json json_validator::validate(const json &instance, error_handler &err, const js } // namespace json_schema } // namespace nlohmann +