From 7c4d935f4c6c89d6e5448ba8c578b88ddc406778 Mon Sep 17 00:00:00 2001 From: Tristan Penman Date: Fri, 19 Jun 2015 08:54:49 +1000 Subject: [PATCH] Add check for hyphen used as array index in JSON Pointer --- include/valijson/internal/json_pointer.hpp | 5 ++++ tests/test_json_pointer.cpp | 30 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/include/valijson/internal/json_pointer.hpp b/include/valijson/internal/json_pointer.hpp index 0a8bdef..59643d3 100644 --- a/include/valijson/internal/json_pointer.hpp +++ b/include/valijson/internal/json_pointer.hpp @@ -114,6 +114,11 @@ inline AdapterType resolveJsonPointer( return resolveJsonPointer(node, jsonPointer, jsonPointerNext); } else if (node.isArray()) { + if (referenceToken.compare("-") == 0) { + throw std::runtime_error("Hyphens cannot be used as array indices " + "since the requested array element does not yet exist"); + } + try { // Fragment must be non-negative integer const uint64_t index = boost::lexical_cast( diff --git a/tests/test_json_pointer.cpp b/tests/test_json_pointer.cpp index 9d23d0f..e01f2f6 100644 --- a/tests/test_json_pointer.cpp +++ b/tests/test_json_pointer.cpp @@ -172,6 +172,36 @@ std::vector > testCases.push_back(testCase); } + // + // Allow the "-" character is not useful within the context of this library, + // there is an explicit check for it, so that a custom error message can + // be included in the exception that is thrown. + // + // From the JSON Pointer specification (RFC 6901, April 2013): + // + // Note that the use of the "-" character to index an array will always + // result in such an error condition because by definition it refers to + // a nonexistent array element. Thus, applications of JSON Pointer need + // to specify how that character is to be handled, if it is to be + // useful. + // + + { + rapidjson::Value testArray; + testArray.SetArray(); + testArray.PushBack("test0", allocator); + testArray.PushBack("test1", allocator); + testArray.PushBack("test2", allocator); + + testCase = boost::make_shared( + "Resolving '/test/-' in object containing one member containing " + "an array with 3 elements should throw an exception"); + testCase->value.SetNull(); + testCase->jsonPointer = "/test/-"; + testCase->expectedValue = NULL; + testCases.push_back(testCase); + } + // // The following tests ensure that escape sequences are handled correctly. //