userver: /data/code/userver/libraries/s3api/tools/cli/tests/cli_test.cpp Source File
Loading...
Searching...
No Matches
cli_test.cpp
1#include "../cli.hpp"
2
3#include <array>
4#include <chrono>
5#include <stdexcept>
6#include <string>
7#include <string_view>
8#include <vector>
9
10#include <userver/clients/http/error.hpp>
11#include <userver/clients/http/standalone_client.hpp>
12#include <userver/engine/task/current_task.hpp>
13#include <userver/fs/blocking/read.hpp>
14#include <userver/fs/blocking/temp_directory.hpp>
15#include <userver/http/common_headers.hpp>
16#include <userver/http/header_map.hpp>
17#include <userver/utest/http_client.hpp>
18#include <userver/utest/http_server_mock.hpp>
19#include <userver/utest/utest.hpp>
20
21USERVER_NAMESPACE_BEGIN
22
23namespace s3api::cli {
24namespace {
25
26constexpr http::headers::PredefinedHeader kAmzDate{"X-Amz-Date"};
27constexpr http::headers::PredefinedHeader kAmzContentSha256{"X-Amz-Content-Sha256"};
28
29std::vector<std::string> BaseArguments() {
30 return {
31 "--endpoint-url",
32 "https://s3.example.com",
33 "--bucket",
34 "bucket",
35 "--key",
36 "object",
37 "--credentials-file",
38 "credentials.json",
39 "--region",
40 "ru-3"
41 };
42}
43
44Options OptionsForServer(const utest::HttpServerMock& server) {
45 Options options;
46 options.endpoint = "http://localhost:" + std::to_string(server.GetPort());
47 options.bucket = "bucket";
48 options.key = "folder/test object";
49 options.region = "ru-3";
50 options.timeout_ms = std::chrono::duration_cast<std::chrono::milliseconds>(utest::kMaxTestWaitTime).count();
51 return options;
52}
53
54TEST(S3Cli, ParsesAwsStyleCommandsAndDefaults) {
55 auto arguments = BaseArguments();
56 arguments.insert(arguments.end(), {"get-object", "output.bin"});
57 const auto get = ParseOptions(arguments);
58 EXPECT_EQ(get.command, Command::kGetObject);
59 EXPECT_EQ(get.output_file, "output.bin");
60 EXPECT_EQ(get.signature_version, "v4");
61 EXPECT_EQ(get.timeout_ms, kDefaultTimeoutMs);
62 EXPECT_EQ(get.retries, kDefaultRetries);
63
64 arguments = BaseArguments();
65 arguments.insert(arguments.end(), {"put-object", "--body", "input.bin", "--if-none-match", "*"});
66 const auto put = ParseOptions(arguments);
67 EXPECT_EQ(put.body_file, "input.bin");
68 EXPECT_EQ(put.command, Command::kPutObjectConditional);
69 EXPECT_TRUE(put.if_none_match);
70 EXPECT_FALSE(put.if_match);
71
72 EXPECT_TRUE(ParseOptions({"--help"}).help);
73 const auto v2 = ParseOptions(
74 {"put-object",
75 "--endpoint-url",
76 "https://s3.example.com/",
77 "--bucket",
78 "bucket",
79 "--key",
80 "object",
81 "--credentials-file",
82 "credentials.json",
83 "--signature-version",
84 "v2",
85 "--body",
86 "input.bin",
87 "--if-match",
88 "\"previous\""}
89 );
90 EXPECT_EQ(v2.command, Command::kPutObjectConditional);
91 EXPECT_EQ(v2.signature_version, "v2");
92 EXPECT_EQ(v2.endpoint, "https://s3.example.com");
93 EXPECT_EQ(v2.if_match, "\"previous\"");
94}
95
96TEST(S3Cli, RejectsUnsupportedOrAmbiguousOperationsBeforeRequests) {
97 const std::vector<std::vector<std::string>> invalid_suffixes{
98 {"get-object"},
99 {"put-object"},
100 {"delete-object"},
101 {"get-object", "out", "--if-match", "etag"},
102 {"get-object", "out", "--body", "in"},
103 {"put-object", "--body", "in", "out"},
104 {"put-object", "--body", "in", "--if-none-match", "etag"},
105 {"put-object", "--body", "in", "--if-none-match", "*", "--if-match", "etag"},
106 {"put-object", "--body", "in", "--if-match", ""},
107 {"get-object", "out", "--timeout-ms", "0"},
108 {"get-object", "out", "--retries", "0"},
109 {"get-object", "out", "--signature-version", "v2"},
110 {"get-object", "out", "--signature-version", "v3"}
111 };
112 for (const auto& suffix : invalid_suffixes) {
113 auto arguments = BaseArguments();
114 arguments.insert(arguments.end(), suffix.begin(), suffix.end());
115 EXPECT_THROW(ParseOptions(arguments), std::exception);
116 }
117 EXPECT_THROW(
118 ParseOptions(
119 {"get-object",
120 "out",
121 "--endpoint-url",
122 "https://s3.example.com",
123 "--bucket",
124 "bucket",
125 "--key",
126 "object",
127 "--credentials-file",
128 "credentials.json"}
129 ),
130 std::invalid_argument
131 );
132}
133
134TEST(S3Cli, InvalidCredentialsNeverExposeTheirContents) {
135 const auto credentials = ParseCredentials(R"({"access_key_id":"test-access","secret_key":"test-secret"})");
136 EXPECT_EQ(credentials.access_key, "test-access");
137 for (const auto& contents :
138 {"test-secret",
139 R"({"access_key_id":"test-access","secret_key":123})",
140 R"({"access_key_id":"test-access","secret_key":""})",
141 R"({"secret_key":"test-secret"})"})
142 {
143 try {
144 static_cast<void>(ParseCredentials(contents));
145 FAIL() << "Invalid credentials were accepted";
146 } catch (const std::invalid_argument& error) {
147 EXPECT_EQ(std::string(error.what()).find("test-secret"), std::string::npos);
148 EXPECT_EQ(std::string(error.what()).find("test-access"), std::string::npos);
149 }
150 }
151}
152
153TEST(S3Cli, CredentialsReadFailurePreservesOriginalError) {
154 const auto directory = fs::blocking::TempDirectory::Create();
155 const auto path = directory.GetPath() + "/missing-credentials.json";
156 std::string original_error;
157 try {
158 static_cast<void>(fs::blocking::ReadFileContents(path));
159 FAIL() << "Reading a missing file succeeded";
160 } catch (const std::runtime_error& error) {
161 original_error = error.what();
162 }
163 ASSERT_FALSE(original_error.empty());
164 try {
165 static_cast<void>(ReadCredentials(path));
166 FAIL() << "Reading missing credentials succeeded";
167 } catch (const std::invalid_argument& error) {
168 const std::string message = error.what();
169 EXPECT_NE(message.find(original_error), std::string::npos);
170 EXPECT_NE(message.find("--credentials-file"), std::string::npos);
171 EXPECT_NE(message.find("check the path and permissions"), std::string::npos);
172 }
173}
174
175UTEST(S3Cli, SendsProcessingCompatibleRequestsWithBothAuthenticators) {
176 constexpr std::string_view kEtag = "\"object-etag\"";
177 const std::string payload{"binary\0payload", 14};
178 for (const auto* signature_version : std::array{"v2", "v4"}) {
179 std::vector<utest::HttpServerMock::HttpRequest> requests;
180 const utest::HttpServerMock server([&](const auto& request) {
181 requests.push_back(request);
182 return utest::HttpServerMock::HttpResponse{200, {{"ETag", std::string(kEtag)}}, payload};
183 });
184 auto options = OptionsForServer(server);
185 options.signature_version = signature_version;
186 const auto credentials = ParseCredentials(R"({"access_key_id":"test-access","secret_key":"test-secret"})");
187 auto http_client = clients::http::CreateStandaloneHttpClient(
188 {"s3-cli-test", 1},
189 {},
190 engine::current_task::GetBlockingTaskProcessor()
191 );
192 const auto client = MakeClient(*http_client, options, credentials);
193
194 options.command = Command::kGetObject;
195 const auto result = Execute(*client, options, {});
196 EXPECT_EQ(result.body, payload);
197 EXPECT_EQ(result.etag, kEtag);
198
199 options.command = Command::kPutObject;
200 EXPECT_FALSE(Execute(*client, options, payload).etag);
201 options.command = Command::kPutObjectConditional;
202 options.if_none_match = true;
203 Execute(*client, options, payload);
204 options.if_none_match = false;
205 options.if_match = kEtag;
206 Execute(*client, options, payload);
207
208 ASSERT_EQ(requests.size(), 4);
209 EXPECT_EQ(requests[0].method, clients::http::HttpMethod::kGet);
210 for (const auto& request : requests) {
211 EXPECT_EQ(request.path, "/folder/test%20object");
212 EXPECT_EQ(request.headers.at(http::headers::kHost), "bucket.localhost:" + std::to_string(server.GetPort()));
213 const auto& authorization = request.headers.at(http::headers::kAuthorization);
214 if (options.signature_version == "v2") {
215 EXPECT_TRUE(authorization.starts_with("AWS test-access:"));
216 EXPECT_TRUE(request.headers.contains(http::headers::kDate));
217 EXPECT_FALSE(request.headers.contains(kAmzContentSha256));
218 } else {
219 EXPECT_TRUE(authorization.starts_with("AWS4-HMAC-SHA256 Credential=test-access/"));
220 EXPECT_NE(authorization.find("/ru-3/s3/aws4_request"), std::string::npos);
221 EXPECT_TRUE(request.headers.contains(kAmzDate));
222 EXPECT_TRUE(request.headers.contains(kAmzContentSha256));
223 }
224 }
225 for (std::size_t index = 1; index < requests.size(); ++index) {
226 EXPECT_EQ(requests[index].method, clients::http::HttpMethod::kPut);
227 EXPECT_EQ(requests[index].body, payload);
228 }
229 EXPECT_EQ(requests[1].headers.at(http::headers::kContentType), "text/plain");
230 EXPECT_FALSE(requests[1].headers.contains(http::headers::kIfMatch));
231 EXPECT_FALSE(requests[1].headers.contains(http::headers::kIfNoneMatch));
232 EXPECT_EQ(requests[2].headers.at(http::headers::kContentType), "application/json");
233 EXPECT_EQ(requests[2].headers.at(http::headers::kIfNoneMatch), "*");
234 EXPECT_EQ(requests[3].headers.at(http::headers::kIfMatch), kEtag);
235 EXPECT_FALSE(requests[3].headers.contains(http::headers::kIfNoneMatch));
236 }
237}
238
239UTEST(S3Cli, PreservesHttpFailuresWithoutExtraRequests) {
240 for (const auto status : std::array{404, 409, 412, 403}) {
241 std::size_t requests = 0;
242 const utest::HttpServerMock server([&](const auto&) {
243 ++requests;
244 return utest::HttpServerMock::HttpResponse{status, {}, "failure"};
245 });
246 auto options = OptionsForServer(server);
247 options.command = status == 404 ? Command::kGetObject : Command::kPutObjectConditional;
248 options.if_match = "\"previous\"";
249 const auto credentials = ParseCredentials(R"({"access_key_id":"test-access","secret_key":"test-secret"})");
250 auto http_client = utest::CreateHttpClient();
251 const auto client = MakeClient(*http_client, options, credentials);
252 try {
253 Execute(*client, options, "data");
254 FAIL() << "HTTP failure was accepted";
255 } catch (const clients::http::HttpException& error) {
256 EXPECT_EQ(error.code(), status);
257 }
258 EXPECT_EQ(requests, 1);
259 }
260}
261
262UTEST(S3Cli, RequiresEtagForGetWithoutSendingHead) {
263 std::size_t requests = 0;
264 const utest::HttpServerMock server([&](const auto&) {
265 ++requests;
266 return utest::HttpServerMock::HttpResponse{200, {}, "data"};
267 });
268 auto options = OptionsForServer(server);
269 options.command = Command::kGetObject;
270 const auto credentials = ParseCredentials(R"({"access_key_id":"test-access","secret_key":"test-secret"})");
271 auto http_client = utest::CreateHttpClient();
272 const auto client = MakeClient(*http_client, options, credentials);
273 EXPECT_THROW(Execute(*client, options, {}), std::runtime_error);
274 EXPECT_EQ(requests, 1);
275}
276
277} // namespace
278} // namespace s3api::cli
279
280USERVER_NAMESPACE_END