File: test_rest_connection_pool.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (355 lines) | stat: -rw-r--r-- 12,719 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
  Copyright (c) 2022, 2025, Oracle and/or its affiliates.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 2.0,
  as published by the Free Software Foundation.

  This program is designed to work with certain software (including
  but not limited to OpenSSL) that is licensed under separate terms,
  as designated in a particular file or component or in included license
  documentation.  The authors of MySQL hereby grant you an additional
  permission to link the program and your derivative works with the
  separately licensed software that they have either included with
  the program or referenced in the documentation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <array>
#include <thread>

#include <gmock/gmock.h>

#ifdef RAPIDJSON_NO_SIZETYPEDEFINE
#include "my_rapidjson_size_t.h"
#endif

#include <rapidjson/document.h>
#include <rapidjson/pointer.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/schema.h>
#include <rapidjson/stringbuffer.h>

#include "config_builder.h"
#include "dim.h"
#include "mysql/harness/utility/string.h"  // ::join
#include "mysqlrouter/mysql_session.h"
#include "process_launcher.h"
#include "rest_api_testutils.h"
#include "router_component_test.h"
#include "router_config.h"

#include "mysqlrouter/rest_client.h"

using namespace std::chrono_literals;

class RestConnectionPoolApiTest
    : public RestApiComponentTest,
      public ::testing::WithParamInterface<RestApiTestParams> {};

static const std::vector<SwaggerPath> kSwaggerPaths{
    {"/connection_pool/{connectionPoolName}/config", "Get config of a route",
     "config of a route", "route not found"},
    {"/connection_pool/{connectionPoolName}/status", "Get status of a route",
     "status of a route", "route not found"},
    {"/connection_pool", "Get list of the connection pools",
     "list of the connection pools", ""},
};

/**
 * @test check /connection_pool/main/status
 *
 * - start router with rest_connection_pool module loaded
 * - GET /connection_pool/main/status
 * - check response code is 200 and output matches openapi spec
 */
TEST_P(RestConnectionPoolApiTest, ensure_openapi) {
  const std::string http_hostname = "127.0.0.1";
  const std::string http_uri = GetParam().uri + GetParam().api_path;

  const std::string userfile = create_password_file();
  auto config_sections =
      get_restapi_config("rest_connection_pool", userfile, true);

  // add the default connection pool
  config_sections.emplace_back("[connection_pool]");

  const std::string conf_file{create_config_file(
      conf_dir_.name(), mysql_harness::join(config_sections, "\n"))};
  ProcessWrapper &http_server{launch_router({"-c", conf_file})};

  ASSERT_NO_FATAL_FAILURE(
      fetch_and_validate_schema_and_resource(GetParam(), http_server));
}

// ****************************************************************************
// Request the resource(s) using supported methods with authentication enabled
// and valid credentials
// ****************************************************************************
static const RestApiTestParams rest_api_valid_methods[]{
    {"connection_pool_status_get",
     std::string(rest_api_basepath) + "/connection_pool/main/status",
     "/connection_pool/{connectionPoolName}/status",
     HttpMethod::Get,
     HttpStatusCode::Ok,
     kContentTypeJson,
     kRestApiUsername,
     kRestApiPassword,
     /*request_authentication =*/true,
     {
         {"/idleServerConnections",
          [](const JsonValue *value) -> void {
            ASSERT_NE(value, nullptr);
            ASSERT_TRUE(value->IsInt());

            ASSERT_GE(value->GetInt(), 0);
          }},
     },
     kSwaggerPaths},

    {"connection_pool_config_get",
     std::string(rest_api_basepath) + "/connection_pool/main/config",
     "/connection_pool/{connectionPoolName}/config",
     HttpMethod::Get,
     HttpStatusCode::Ok,
     kContentTypeJson,
     kRestApiUsername,
     kRestApiPassword,
     /*request_authentication =*/true,
     {
         {"/maxIdleServerConnections",
          [](const JsonValue *value) -> void {
            ASSERT_NE(value, nullptr);
            ASSERT_TRUE(value->IsInt());

            ASSERT_GE(value->GetInt(), 0);
          }},
         {"/idleTimeoutInMs",
          [](const JsonValue *value) -> void {
            ASSERT_NE(value, nullptr);
            ASSERT_TRUE(value->IsInt());

            ASSERT_GE(value->GetInt(), 0);
          }},
     },
     kSwaggerPaths},
    {"connection_pool_list_get",
     std::string(rest_api_basepath) + "/connection_pool/",
     "/connection_pool",
     HttpMethod::Get,
     HttpStatusCode::Ok,
     kContentTypeJson,
     kRestApiUsername,
     kRestApiPassword,
     /*request_authentication =*/true,
     {
         {"/items",
          [](const JsonValue *value) {
            ASSERT_NE(value, nullptr);
            ASSERT_TRUE(value->IsArray());
            ASSERT_EQ(value->GetArray().Size(), 1);
          }},
         {"/items/0/name",
          [](const JsonValue *value) {
            ASSERT_TRUE(value != nullptr);
            ASSERT_TRUE(value->IsString());
            ASSERT_STREQ(value->GetString(), "main");
          }},
     },
     kSwaggerPaths},

    {"connection_pool_no_params",
     std::string(rest_api_basepath) + "/connection_pool/main/status?someparam",
     "/connection_pool/{connectionPoolName}/status",
     HttpMethod::Get,
     HttpStatusCode::BadRequest,
     kContentTypeJsonProblem,
     kRestApiUsername,
     kRestApiPassword,
     /*request_authentication =*/true,
     {},
     kSwaggerPaths},
};

INSTANTIATE_TEST_SUITE_P(
    ValidMethods, RestConnectionPoolApiTest,
    ::testing::ValuesIn(rest_api_valid_methods),
    [](const ::testing::TestParamInfo<RestApiTestParams> &info) {
      return info.param.test_name;
    });

// ****************************************************************************
// Request the resource(s) using supported methods with authentication enabled
// and invalid credentials
// ****************************************************************************

static const RestApiTestParams rest_api_valid_methods_invalid_auth_params[]{
    {"connection_pool_invalid_auth",
     std::string(rest_api_basepath) + "/connection_pool/main/status",
     "/connection_pool/main/status",
     HttpMethod::Get,
     HttpStatusCode::Unauthorized,
     kContentTypeHtmlCharset,
     kRestApiUsername,
     "invalid password",
     /*request_authentication =*/true,
     {},
     kSwaggerPaths},
};

INSTANTIATE_TEST_SUITE_P(
    ValidMethodsInvalidAuth, RestConnectionPoolApiTest,
    ::testing::ValuesIn(rest_api_valid_methods_invalid_auth_params),
    [](const ::testing::TestParamInfo<RestApiTestParams> &info) {
      return info.param.test_name;
    });

// ****************************************************************************
// Request the resource(s) using unsupported methods with authentication enabled
// and valid credentials
// ****************************************************************************
static const RestApiTestParams rest_api_invalid_methods_params[]{
    {"connection_pool_status_invalid_methods",
     std::string(rest_api_basepath) + "/connection_pool/main/status",
     "/connection_pool/main/status",
     HttpMethod::Post | HttpMethod::Delete | HttpMethod::Patch |
         HttpMethod::Head | HttpMethod::Trace | HttpMethod::Options,
     HttpStatusCode::MethodNotAllowed, kContentTypeJsonProblem,
     kRestApiUsername, kRestApiPassword,
     /*request_authentication =*/true,
     RestApiComponentTest::get_json_method_not_allowed_verifiers(),
     kSwaggerPaths},
};

INSTANTIATE_TEST_SUITE_P(
    InvalidMethods, RestConnectionPoolApiTest,
    ::testing::ValuesIn(rest_api_invalid_methods_params),
    [](const ::testing::TestParamInfo<RestApiTestParams> &info) {
      return info.param.test_name;
    });

// ****************************************************************************
// Configuration errors scenarios
// ****************************************************************************

/*
 * 1. Add [rest_connection_pool] twice to the configuration file.
 * 2. Start router.
 * 3. Expect router to fail providing an error about the duplicate section.
 */
TEST_F(RestConnectionPoolApiTest, section_twice) {
  const std::string userfile = create_password_file();
  auto config_sections = get_restapi_config("rest_connection_pool", userfile,
                                            /*request_authentication=*/true);

  // force [rest_connection_pool] twice in the config
  config_sections.push_back(
      mysql_harness::ConfigBuilder::build_section("rest_connection_pool", {}));

  const std::string conf_file{create_config_file(
      conf_dir_.name(), mysql_harness::join(config_sections, "\n"))};
  auto &router =
      launch_router({"-c", conf_file}, EXIT_FAILURE, true, false, -1s);

  check_exit_code(router, EXIT_FAILURE, 10s);

  const std::string router_output = router.get_full_output();
  EXPECT_NE(
      router_output.find(
          "Configuration error: Section 'rest_connection_pool' already exists"),
      router_output.npos)
      << router_output;
}

/*
 * 1. Enable [rest_connection_pool] using a section key such as
 *    [rest_connection_pool:A].
 * 2. Start router.
 * 3. Expect router to fail providing an error about the use of an unsupported
 *    section key.
 */
TEST_F(RestConnectionPoolApiTest, section_has_key) {
  const std::string userfile = create_password_file();
  auto config_sections = get_restapi_config("rest_connection_pool:A", userfile,
                                            /*request_authentication=*/true);

  const std::string conf_file{create_config_file(
      conf_dir_.name(), mysql_harness::join(config_sections, "\n"))};
  auto &router =
      launch_router({"-c", conf_file}, EXIT_FAILURE, true, false, -1s);

  check_exit_code(router, EXIT_FAILURE, 10s);

  const std::string router_output = router.get_logfile_content();
  EXPECT_THAT(
      router_output,
      ::testing::HasSubstr(
          "  init 'rest_connection_pool' failed: [rest_connection_pool] "
          "section does not expect a key, found 'A'"));
}

/**
 * @test Try to disable authentication although a REST API endpoint/plugin
 * defines authentication as a MUST.
 *
 */
TEST_F(RestConnectionPoolApiTest, no_auth) {
  const std::string userfile = create_password_file();
  auto config_sections = get_restapi_config("rest_connection_pool", userfile,
                                            /*request_authentication=*/false);

  const std::string conf_file{create_config_file(
      conf_dir_.name(), mysql_harness::join(config_sections, "\n"))};
  auto &router =
      launch_router({"-c", conf_file}, EXIT_FAILURE, true, false, -1s);

  check_exit_code(router, EXIT_FAILURE, 10s);

  const std::string router_output = router.get_logfile_content();
  EXPECT_THAT(router_output,
              ::testing::HasSubstr(
                  "  init 'rest_connection_pool' failed: option "
                  "require_realm in [rest_connection_pool] is required"))
      << router_output;
}

/**
 * @test Enable authentication for the plugin in question. Reference a realm
 * that does not exist in the configuration file.
 */
TEST_F(RestConnectionPoolApiTest, invalid_realm) {
  const std::string userfile = create_password_file();
  auto config_sections =
      get_restapi_config("rest_connection_pool", userfile,
                         /*request_authentication=*/true, "invalidrealm");

  const std::string conf_file{create_config_file(
      conf_dir_.name(), mysql_harness::join(config_sections, "\n"))};
  auto &router =
      launch_router({"-c", conf_file}, EXIT_FAILURE, true, false, -1s);

  check_exit_code(router, EXIT_FAILURE, 10s);

  const std::string router_output = router.get_logfile_content();
  EXPECT_THAT(
      router_output,
      ::testing::HasSubstr(
          "Configuration error: The option 'require_realm=invalidrealm' "
          "in [rest_connection_pool] does not match any http_auth_realm."))
      << router_output;
}

int main(int argc, char *argv[]) {
  init_windows_sockets();
  ProcessManager::set_origin(Path(argv[0]).dirname());
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}