File: test_routing_connection_errors.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 (930 lines) | stat: -rw-r--r-- 32,711 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/*
  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 <chrono>
#include <cstdint>
#include <thread>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include "mysql/harness/net_ts/buffer.h"
#include "mysql/harness/net_ts/internet.h"
#include "mysql/harness/net_ts/io_context.h"
#include "mysql/harness/stdx/expected.h"
#include "mysql/harness/stdx/expected_ostream.h"
#include "mysql/harness/string_utils.h"  // split_string
#include "mysqlrouter/http_client.h"
#include "mysqlrouter/http_request.h"
#include "mysqlrouter/rest_client.h"
#include "rest_api_testutils.h"
#include "router/src/routing/tests/mysql_client.h"
#include "router_component_test.h"
#include "router_component_testutils.h"  // make_bad_connection
#include "stdx_expected_no_error.h"      // EXPECT_NO_ERROR

using namespace std::chrono_literals;

using testing::AllOf;
using testing::AnyOf;
using testing::HasSubstr;
using testing::Not;

std::ostream &operator<<(std::ostream &os, MysqlError e) {
  os << e.sql_state() << " (" << e.value() << ") " << e.message();
  return os;
}

struct Route {
  std::string_view client_ssl_mode;
  std::string_view server_ssl_mode;
  uint16_t bind_port;

  std::string route_name() const {
    return std::string(client_ssl_mode) + "__" + std::string(server_ssl_mode);
  }
};

class RoutingConnectionErrorTest : public RestApiComponentTest {
 protected:
  static std::string router_host() { return "127.0.0.1"; }
};

TEST_F(RoutingConnectionErrorTest, connect_successful) {
  auto rest_port = port_pool_.get_next_available();
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  auto pwfile = create_password_file();

  auto writer = config_writer(conf_dir_.name());
  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"protocol", "classic"},
            {"max_connect_errors", "1"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  writer
      .section("rest_routing",
               {
                   {"require_realm", "somerealm"},
               })
      .section("http_auth_realm:somerealm",
               {
                   {"backend", "somebackend"},
                   {"method", "basic"},
                   {"name", "Some Realm"},
               })
      .section("http_auth_backend:somebackend",
               {
                   {"backend", "file"},
                   {"filename", pwfile},
               })
      .section("http_server", {
                                  {"port", std::to_string(rest_port)},
                              });
  auto &r = router_spawner().spawn({"-c", writer.write()});

  // check for connect errors via REST API
  IOContext io_ctx;
  RestClient rest_cli(io_ctx, router_host(), rest_port, kRestApiUsername,
                      kRestApiPassword);

  for (auto route : routes) {
    {
      MysqlClient cli;
      cli.username("username");
      cli.password("password");

      auto connect_res = cli.connect(router_host(), route.bind_port);
      EXPECT_NO_ERROR(connect_res);
    }

    // check for connect errors via REST API
    auto resp = rest_cli.request_sync(
        HttpMethod::Get,
        rest_api_basepath + "/routes/" + route.route_name() + "/status");

    EXPECT_EQ(resp.get_response_code(), 200) << resp.get_response_code_line();
    if (resp.get_response_code() == 200) {
      auto http_buf = resp.get_input_buffer();
      auto buf = http_buf.pop_front(http_buf.length());

      rapidjson::Document json_doc;

      std::string_view sv(reinterpret_cast<char *>(buf.data()), buf.size());

      json_doc.Parse(sv.data(), sv.size());

      auto *blocked_hosts = rapidjson::Pointer("/blockedHosts").Get(json_doc);
      ASSERT_NE(blocked_hosts, nullptr);

      EXPECT_EQ(blocked_hosts->GetInt(), 0);
    }
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  // the log should not contain "closed connection before ..."
  EXPECT_THAT(r.get_logfile_content(),
              Not(AnyOf(HasSubstr("closed connection before"),
                        HasSubstr("blocking client host for"),
                        HasSubstr("incrementing"))));
}

TEST_F(RoutingConnectionErrorTest, connect_backend_not_reachable) {
  auto server_port = port_pool_.get_next_available();
  auto rest_port = port_pool_.get_next_available();

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  auto pwfile = create_password_file();

  SCOPED_TRACE("// start router");
  auto writer = config_writer(conf_dir_.name());
  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"max_connect_errors", "1"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }
  writer
      .section("rest_routing",
               {
                   {"require_realm", "somerealm"},
               })
      .section("http_auth_realm:somerealm",
               {
                   {"backend", "somebackend"},
                   {"method", "basic"},
                   {"name", "Some Realm"},
               })
      .section("http_auth_backend:somebackend",
               {
                   {"backend", "file"},
                   {"filename", pwfile},
               })
      .section("http_server", {
                                  {"port", std::to_string(rest_port)},
                              });
  auto &r = router_spawner().spawn({"-c", writer.write()});

  IOContext io_ctx;
  RestClient rest_cli(io_ctx, router_host(), rest_port, kRestApiUsername,
                      kRestApiPassword);

  SCOPED_TRACE("// connect should fail as we have no backend.");
  for (auto route : routes) {
    {
      MysqlClient cli;

      auto connect_res = cli.connect(router_host(), route.bind_port);
      EXPECT_ERROR(connect_res);
    }

    SCOPED_TRACE("// check for connect errors via REST API");

    auto resp = rest_cli.request_sync(
        HttpMethod::Get,
        rest_api_basepath + "/routes/" + route.route_name() + "/status");

    EXPECT_EQ(resp.get_response_code(), 200) << resp.get_response_code_line();

    if (resp.get_response_code() == 200) {
      auto http_buf = resp.get_input_buffer();
      auto buf = http_buf.pop_front(http_buf.length());

      rapidjson::Document json_doc;

      std::string_view sv(reinterpret_cast<char *>(buf.data()), buf.size());

      json_doc.Parse(sv.data(), sv.size());

      auto *blocked_hosts = rapidjson::Pointer("/blockedHosts").Get(json_doc);
      ASSERT_NE(blocked_hosts, nullptr) << sv;

      EXPECT_EQ(blocked_hosts->GetInt(), 0);
    }
  }
  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  // the log should not contain "closed connection before ..."
  EXPECT_THAT(r.get_logfile_content(),
              AllOf(HasSubstr("connecting to backend(s) for client"),
                    Not(AnyOf(HasSubstr("closed connection before"),
                              HasSubstr("blocking client host for"),
                              HasSubstr("incrementing")))));
}

TEST_F(RoutingConnectionErrorTest, connect_from_connection_pool) {
  auto router_port = port_pool_.get_next_available();
  auto rest_port = port_pool_.get_next_available();
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::string route_name = "under_test";

  auto pwfile = create_password_file();

  auto writer = config_writer(conf_dir_.name());
  writer
      .section("routing:" + route_name,
               {
                   {"bind_port", std::to_string(router_port)},
                   {"destinations", "127.0.0.1:" + std::to_string(server_port)},
                   {"routing_strategy", "round-robin"},
                   {"protocol", "classic"},
                   {"max_connect_errors", "1"},
                   {"client_ssl_mode", "DISABLED"},
                   {"server_ssl_mode", "DISABLED"},
               })
      .section("connection_pool",
               {
                   {"max_idle_server_connections", "1"},
               })
      .section("rest_routing",
               {
                   {"require_realm", "somerealm"},
               })
      .section("http_auth_realm:somerealm",
               {
                   {"backend", "somebackend"},
                   {"method", "basic"},
                   {"name", "Some Realm"},
               })
      .section("http_auth_backend:somebackend",
               {
                   {"backend", "file"},
                   {"filename", pwfile},
               })
      .section("http_server", {
                                  {"port", std::to_string(rest_port)},
                              });
  auto &r = router_spawner().spawn({"-c", writer.write()});

  {
    MysqlClient cli;  // first connection.

    auto connect_res = cli.connect(router_host(), router_port);
    EXPECT_NO_ERROR(connect_res);
  }

  using namespace std::chrono_literals;

  std::this_thread::sleep_for(100ms);

  {
    MysqlClient cli;  // from connection pool

    auto connect_res = cli.connect(router_host(), router_port);

    EXPECT_FALSE(connect_res);
    if (connect_res) {
      // change-user is issued by the router when it takes the connection from
      // the pool.
      //
      // the mock server doesn't support change-user (command 17) yet.
      EXPECT_EQ(connect_res.error().message(), "Unsupported command: 17");
    }
  }

  // check for connect errors via REST API
  IOContext io_ctx;
  RestClient rest_cli(io_ctx, router_host(), rest_port, kRestApiUsername,
                      kRestApiPassword);

  auto resp = rest_cli.request_sync(
      HttpMethod::Get, rest_api_basepath + "/routes/" + route_name + "/status");

  EXPECT_EQ(resp.get_response_code(), 200) << resp.get_response_code_line();

  if (resp.get_response_code() == 200) {
    auto http_buf = resp.get_input_buffer();
    auto buf = http_buf.pop_front(http_buf.length());

    rapidjson::Document json_doc;

    std::string_view sv(reinterpret_cast<char *>(buf.data()), buf.size());

    json_doc.Parse(sv.data(), sv.size());

    auto *blocked_hosts = rapidjson::Pointer("/blockedHosts").Get(json_doc);
    ASSERT_NE(blocked_hosts, nullptr);

    EXPECT_EQ(blocked_hosts->GetInt(), 0);
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  // the log should not contain "closed connection before ..."
  EXPECT_THAT(r.get_logfile_content(),
              Not(AnyOf(HasSubstr("closed connection before"),
                        HasSubstr("blocking client host for"),
                        HasSubstr("incrementing"))));
}

TEST_F(RoutingConnectionErrorTest, connect_close_is_not_an_error) {
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  SCOPED_TRACE("// start router");
  auto writer = config_writer(conf_dir_.name());
  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_address", "127.0.0.1"},
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }
  auto &r = router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE("// connect+close should not cause a connect-error.");
  net::io_context io_ctx;
  for (auto route : routes) {
    net::ip::tcp::socket sock(io_ctx);

    net::ip::tcp::endpoint ep(net::ip::address_v4::loopback(), route.bind_port);
    EXPECT_NO_ERROR(sock.connect(ep));
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  // the log should not contain "closed connection before ..."
  EXPECT_THAT(r.get_logfile_content(),
              Not(AnyOf(HasSubstr("closed connection before"),
                        HasSubstr("blocking client host for"),
                        HasSubstr("incrementing"))));
}

TEST_F(RoutingConnectionErrorTest, connect_recv_close_is_not_an_error) {
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  SCOPED_TRACE("// start router");
  auto writer = config_writer(conf_dir_.name());

  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_address", "127.0.0.1"},
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  auto &r = router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE("// connect+wait+close should not cause a connect-error.");
  net::io_context io_ctx;
  for (auto route : routes) {
    net::ip::tcp::socket sock(io_ctx);

    net::ip::tcp::endpoint ep(net::ip::address_v4::loopback(), route.bind_port);
    EXPECT_NO_ERROR(sock.connect(ep));

    // recv the server-greeting
    std::array<char, 1024> buf;
    EXPECT_NO_ERROR(
        net::read(sock, net::buffer(buf), net::transfer_at_least(1)));

    // and drop the connection.
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  // the log should not contain "closed connection before ..."
  EXPECT_THAT(r.get_logfile_content(),
              Not(AnyOf(HasSubstr("closed connection before"),
                        HasSubstr("blocking client host for"),
                        HasSubstr("incrementing"))));
}

TEST_F(RoutingConnectionErrorTest, broken_client_greeting_is_an_error) {
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  SCOPED_TRACE("// start router");
  auto writer = config_writer(conf_dir_.name());

  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_address", "127.0.0.1"},
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  auto &r = router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE("// connect+wait+close should not cause a connect-error.");
  for (auto route : routes) {
    EXPECT_NO_FATAL_FAILURE(make_bad_connection(route.bind_port));
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  std::string expected_substr("incrementing error counter for host");
  auto lines = mysql_harness::split_string(r.get_logfile_content(), '\n');

  size_t matches{};
  for (const auto &line : lines) {
    if (line.find(expected_substr) != std::string::npos) {
      ++matches;
    }
  }

  SCOPED_TRACE(
      "// the log should contain the 'incrementing error-count' once per "
      "route");
  EXPECT_EQ(matches, routes.size()) << expected_substr;
}

TEST_F(RoutingConnectionErrorTest, broken_client_greeting_seq_id_is_an_error) {
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  SCOPED_TRACE("// start router");
  auto writer = config_writer(conf_dir_.name());

  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_address", "127.0.0.1"},
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  auto &r = router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE("// connect+wait+close should not cause a connect-error.");
  net::io_context io_ctx;
  for (auto route : routes) {
    net::ip::tcp::socket sock(io_ctx);

    net::ip::tcp::endpoint ep(net::ip::address_v4::loopback(), route.bind_port);
    EXPECT_NO_ERROR(sock.connect(ep));

    // recv the server-greeting
    {
      std::array<char, 1024> buf{};
      EXPECT_NO_ERROR(
          net::read(sock, net::buffer(buf), net::transfer_at_least(1)));
    }

    {
      // send a valid client-greeting, with the wrong sequence-id
      std::array<char, 23> buf{23 - 4, 0x00, 0x00, 0x00,     // frame header
                               0x0d,   0x24,                 // caps
                               0,      0,    0,              // max-packet-size
                               'r',    'o',  'o',  't',  0,  // username
                               'H',    ']',  '^',  'C',  'S',
                               'V',    'Y',  '[',  '\0'};
      EXPECT_NO_ERROR(net::write(sock, net::buffer(buf), net::transfer_all()));
    }

    // recv the error.
    {
      std::array<char, 1024> buf{};
      auto read_res =
          net::read(sock, net::buffer(buf), net::transfer_at_least(1));
      ASSERT_NO_ERROR(read_res);

      std::string msg(buf.data(), buf.data() + read_res.value());
      EXPECT_THAT(msg, testing::HasSubstr("Got packets out of order"));
    }

    // and drop the connection.
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  std::string expected_substr("incrementing error counter for host");
  auto lines = mysql_harness::split_string(r.get_logfile_content(), '\n');

  size_t matches{};
  for (const auto &line : lines) {
    if (line.find(expected_substr) != std::string::npos) {
      ++matches;
    }
  }

  SCOPED_TRACE(
      "// the log should contain the 'incrementing error-count' once per "
      "route");
  EXPECT_EQ(matches, routes.size()) << expected_substr;
}

TEST_F(RoutingConnectionErrorTest, auth_fail_is_not_an_connection_error) {
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("bootstrap_gr.js").str(),
                           server_port);

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  SCOPED_TRACE("// start router");
  auto writer = config_writer(conf_dir_.name());

  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_address", "127.0.0.1"},
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  auto &r = router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE("// failed auth should not cause a 'connect-error'.");
  net::io_context io_ctx;
  for (auto route : routes) {
    net::ip::tcp::socket sock(io_ctx);

    MysqlClient cli;  // first connection.
    cli.username("username");
    cli.password("wrong_password");

    auto connect_res = cli.connect(router_host(), route.bind_port);
    ASSERT_ERROR(connect_res);
    EXPECT_EQ(connect_res.error().value(), 1045) << connect_res.error();
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  EXPECT_THAT(r.get_logfile_content(),
              Not(AnyOf(HasSubstr("closed connection before"),
                        HasSubstr("blocking client host for"),
                        HasSubstr("incrementing"))));
}

TEST_F(RoutingConnectionErrorTest, ssl_fail_is_not_an_connection_error) {
  auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      Route{"REQUIRED", "PREFERRED", port_pool_.get_next_available()},
  };

  SCOPED_TRACE("// start router");
  auto writer = config_writer(conf_dir_.name());

  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_address", "127.0.0.1"},
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  auto &r = router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE("// connect+wait+close should not cause a connect-error.");
  for (auto route : routes) {
    MysqlClient cli;  // first connection.
    cli.username("username");
    cli.password("password");
    cli.set_option(MysqlClient::SslMode(SSL_MODE_DISABLED));

    auto connect_res = cli.connect(router_host(), route.bind_port);
    ASSERT_ERROR(connect_res);
    EXPECT_EQ(connect_res.error().value(), 2026) << connect_res.error();
  }

  SCOPED_TRACE("// shutdown router");
  r.send_shutdown_event();
  r.wait_for_exit();

  EXPECT_THAT(r.get_logfile_content(),
              Not(AnyOf(HasSubstr("closed connection before"),
                        HasSubstr("blocking client host for"),
                        HasSubstr("incrementing"))));
}

TEST_F(RoutingConnectionErrorTest, max_connect_errors) {
  const auto server_port = port_pool_.get_next_available();

  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  auto writer = config_writer(conf_dir_.name());
  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"protocol", "classic"},
            {"max_connect_errors", "1"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  // launch the router
  auto &router = router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE("// trigger a connection-error");
  net::io_context io_ctx;
  for (auto route : routes) {
    net::ip::tcp::socket sock(io_ctx);

    net::ip::tcp::endpoint ep(net::ip::address_v4::loopback(), route.bind_port);
    EXPECT_NO_ERROR(sock.connect(ep));

    // recv the server-greeting
    {
      std::array<char, 1024> buf{};
      EXPECT_NO_ERROR(
          net::read(sock, net::buffer(buf), net::transfer_at_least(1)));
    }

    {
      // send a broken client-greeting.
      std::array buf{0x01, 0x00, 0x00, 0x01, 0xff};

      EXPECT_NO_ERROR(net::write(sock, net::buffer(buf), net::transfer_all()));
    }

    // recv the error.
    {
      std::array<char, 1024> buf{};
      auto read_res =
          net::read(sock, net::buffer(buf), net::transfer_at_least(1));
      ASSERT_NO_ERROR(read_res);

      std::string msg(buf.data(), buf.data() + read_res.value());
      EXPECT_THAT(msg, testing::HasSubstr("Bad handshake"));
    }

    // and drop the connection.
  }

  SCOPED_TRACE("// wait until 'blocking client host' appears in the log");
  ASSERT_TRUE(wait_log_contains(router, "blocking client host", 5000ms));

  for (auto route : routes) {
    // for the next connection attempt we should get an error as the
    // max_connect_errors was exceeded
    MysqlClient cli;
    cli.username("root");
    cli.password("fake-pass");

    auto connect_res = cli.connect("127.0.0.1", route.bind_port);
    ASSERT_ERROR(connect_res);
    EXPECT_EQ(connect_res.error().value(), 1129) << connect_res.error();
    EXPECT_THAT(connect_res.error().message(),
                ::testing::HasSubstr("Too many connection errors"));
  }
}

/**
 * @test
 * This test verifies that:
 *   1. Router will block a misbehaving client after consecutive
 *      <max_connect_errors> connection errors
 *   2. Router will reset its connection error counter if client establishes a
 *      successful connection before <max_connect_errors> threshold is hit
 */
TEST_F(RoutingConnectionErrorTest, error_counters) {
  const uint16_t server_port = port_pool_.get_next_available();

  // launch the server mock
  launch_mysql_server_mock(get_data_dir().join("my_port.js").str(),
                           server_port);

  std::array routes{
      // Route{"PASSTHROUGH", "AS_CLIENT", port_pool_.get_next_available()},
      // Route{"PREFERRED", "AS_CLIENT", port_pool_.get_next_available()},
      Route{"PREFERRED", "PREFERRED", port_pool_.get_next_available()},
  };

  auto writer = config_writer(conf_dir_.name());
  for (auto route : routes) {
    writer.section(
        "routing:" + route.route_name(),
        {
            {"bind_port", std::to_string(route.bind_port)},
            {"destinations", "127.0.0.1:" + std::to_string(server_port)},
            {"routing_strategy", "round-robin"},
            {"protocol", "classic"},
            {"max_connect_errors", "3"},
            {"client_ssl_mode", std::string(route.client_ssl_mode)},
            {"server_ssl_mode", std::string(route.server_ssl_mode)},
            {"client_ssl_key", SSL_TEST_DATA_DIR "/server-key-sha512.pem"},
            {"client_ssl_cert", SSL_TEST_DATA_DIR "/server-cert-sha512.pem"},
        });
  }

  // launch the router
  router_spawner().spawn({"-c", writer.write()});

  SCOPED_TRACE(
      "// make good and bad connections to check blocked client gets reset");
  for (auto route : routes) {
    // we loop just for good measure, to additionally test that this behaviour
    // is repeatable
    for (int i = 0; i < 5; i++) {
      // good connection, followed by 2 bad ones. Good one should reset the
      // error counter
      MysqlClient cli;
      cli.username("username");
      cli.password("password");

      auto connect_res = cli.connect("127.0.0.1", route.bind_port);
      ASSERT_NO_ERROR(connect_res);

      EXPECT_NO_FATAL_FAILURE(make_bad_connection(route.bind_port));
      EXPECT_NO_FATAL_FAILURE(make_bad_connection(route.bind_port));
    }

    SCOPED_TRACE("// make bad connection to trigger blocked client");
    // make a 3rd consecutive bad connection - it should cause Router to start
    // blocking us
    EXPECT_NO_FATAL_FAILURE(make_bad_connection(route.bind_port));

    // we loop just for good measure, to additionally test that this behaviour
    // is repeatable
    for (int i = 0; i < 5; i++) {
      // now trying to make a good connection should fail due to blockage
      //
      MysqlClient cli;
      cli.username("username");
      cli.password("password");

      SCOPED_TRACE("// make connection to check if we are really blocked");

      auto connect_res = cli.connect("127.0.0.1", route.bind_port);
      ASSERT_ERROR(connect_res);
      EXPECT_EQ(connect_res.error().value(), 1129) << connect_res.error();

      EXPECT_THAT(connect_res.error().message(),
                  ::testing::HasSubstr("Too many connection errors"));
    }
  }
}

int main(int argc, char *argv[]) {
  net::impl::socket::init();

  ProcessManager::set_origin(Path(argv[0]).dirname());
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}