Skip to content

Commit

Permalink
Validate that parsed string is a JSON Object.
Browse files Browse the repository at this point in the history
Without this, parsing may crash if the input is a valid JSON value, but not a JSON Object.

PiperOrigin-RevId: 621489078
Change-Id: I0531ebf0a7c1710ddb1d03c160fd9a8580793159
(cherry picked from commit 967a769)
  • Loading branch information
juergw authored and morambro committed Apr 4, 2024
1 parent 89755d3 commit da091f8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
7 changes: 4 additions & 3 deletions tink/core/json_keyset_reader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
#include <iostream>
#include <istream>
#include <memory>
#include <sstream>
#include <string>
#include <utility>

Expand All @@ -30,8 +29,6 @@
#include "include/rapidjson/document.h"
#include "include/rapidjson/error/en.h"
#include "tink/util/enums.h"
#include "tink/util/errors.h"
#include "tink/util/protobuf_helper.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "proto/tink.pb.h"
Expand Down Expand Up @@ -262,6 +259,10 @@ util::StatusOr<std::unique_ptr<Keyset>> JsonKeysetReader::Read() {
"Invalid JSON Keyset: Error (offset ", json_doc.GetErrorOffset(),
"): ", rapidjson::GetParseError_En(json_doc.GetParseError())));
}
if (!json_doc.IsObject()) {
return util::Status(absl::StatusCode::kInvalidArgument,
"Invalid JSON Keyset: Expected object.");
}
return KeysetFromJson(json_doc);
}

Expand Down
9 changes: 9 additions & 0 deletions tink/core/json_keyset_reader_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,15 @@ TEST_F(JsonKeysetReaderTest, testReadFromString) {
EXPECT_FALSE(read_result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, read_result.status().code());
}

{ // A valid JSON value, but not a JSON object.
auto reader_result = JsonKeysetReader::New("124");
EXPECT_TRUE(reader_result.ok()) << reader_result.status();
auto reader = std::move(reader_result.value());
auto read_result = reader->Read();
EXPECT_FALSE(read_result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, read_result.status().code());
}
}

TEST_F(JsonKeysetReaderTest, testReadFromStream) {
Expand Down

0 comments on commit da091f8

Please sign in to comment.