forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflight_test.cc
More file actions
1733 lines (1486 loc) · 61.7 KB
/
Copy pathflight_test.cc
File metadata and controls
1733 lines (1486 loc) · 61.7 KB
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
#include "arrow/flight/api.h"
#include "arrow/flight/client_tracing_middleware.h"
#include "arrow/flight/server_tracing_middleware.h"
#include "arrow/ipc/test_common.h"
#include "arrow/status.h"
#include "arrow/testing/generator.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/util.h"
#include "arrow/util/base64.h"
#include "arrow/util/logging.h"
#ifdef GRPCPP_GRPCPP_H
#error "gRPC headers should not be in public API"
#endif
#ifdef GRPCPP_PP_INCLUDE
#include <grpcpp/grpcpp.h>
#else
#include <grpc++/grpc++.h>
#endif
// Include before test_util.h (boost), contains Windows fixes
#include "arrow/flight/platform.h"
#include "arrow/flight/serialization_internal.h"
#include "arrow/flight/test_definitions.h"
#include "arrow/flight/test_util.h"
// OTel includes must come after any gRPC includes, and
// client_header_internal.h includes gRPC. See:
// https://github.com/open-telemetry/opentelemetry-cpp/blob/main/examples/otlp/README.md
//
// > gRPC internally uses a different version of Abseil than
// > OpenTelemetry C++ SDK.
// > ...
// > ...in case if you run into conflict between Abseil library and
// > OpenTelemetry C++ absl::variant implementation, please include
// > either grpcpp/grpcpp.h or
// > opentelemetry/exporters/otlp/otlp_grpc_exporter.h BEFORE any
// > other API headers. This approach efficiently avoids the conflict
// > between the two different versions of Abseil.
#include "arrow/util/tracing_internal.h"
#ifdef ARROW_WITH_OPENTELEMETRY
#include <opentelemetry/context/propagation/global_propagator.h>
#include <opentelemetry/context/propagation/text_map_propagator.h>
#include <opentelemetry/sdk/trace/tracer_provider.h>
#include <opentelemetry/trace/propagation/http_trace_context.h>
#endif
namespace arrow {
namespace flight {
namespace pb = arrow::flight::protocol;
const char kValidUsername[] = "flight_username";
const char kValidPassword[] = "flight_password";
const char kInvalidUsername[] = "invalid_flight_username";
const char kInvalidPassword[] = "invalid_flight_password";
const char kBearerToken[] = "bearertoken";
const char kBasicPrefix[] = "Basic ";
const char kBearerPrefix[] = "Bearer ";
const char kAuthHeader[] = "authorization";
//------------------------------------------------------------
// Common transport tests
class GrpcConnectivityTest : public ConnectivityTest, public ::testing::Test {
protected:
std::string transport() const override { return "grpc"; }
void SetUp() override { SetUpTest(); }
void TearDown() override { TearDownTest(); }
};
ARROW_FLIGHT_TEST_CONNECTIVITY(GrpcConnectivityTest);
class GrpcDataTest : public DataTest, public ::testing::Test {
protected:
std::string transport() const override { return "grpc"; }
void SetUp() override { SetUpTest(); }
void TearDown() override { TearDownTest(); }
};
ARROW_FLIGHT_TEST_DATA(GrpcDataTest);
class GrpcDoPutTest : public DoPutTest, public ::testing::Test {
protected:
std::string transport() const override { return "grpc"; }
void SetUp() override { SetUpTest(); }
void TearDown() override { TearDownTest(); }
};
ARROW_FLIGHT_TEST_DO_PUT(GrpcDoPutTest);
class GrpcAppMetadataTest : public AppMetadataTest, public ::testing::Test {
protected:
std::string transport() const override { return "grpc"; }
void SetUp() override { SetUpTest(); }
void TearDown() override { TearDownTest(); }
};
ARROW_FLIGHT_TEST_APP_METADATA(GrpcAppMetadataTest);
class GrpcIpcOptionsTest : public IpcOptionsTest, public ::testing::Test {
protected:
std::string transport() const override { return "grpc"; }
void SetUp() override { SetUpTest(); }
void TearDown() override { TearDownTest(); }
};
ARROW_FLIGHT_TEST_IPC_OPTIONS(GrpcIpcOptionsTest);
class GrpcCudaDataTest : public CudaDataTest, public ::testing::Test {
protected:
std::string transport() const override { return "grpc"; }
void SetUp() override { SetUpTest(); }
void TearDown() override { TearDownTest(); }
};
ARROW_FLIGHT_TEST_CUDA_DATA(GrpcCudaDataTest);
class GrpcErrorHandlingTest : public ErrorHandlingTest, public ::testing::Test {
protected:
std::string transport() const override { return "grpc"; }
void SetUp() override { SetUpTest(); }
void TearDown() override { TearDownTest(); }
};
ARROW_FLIGHT_TEST_ERROR_HANDLING(GrpcErrorHandlingTest);
//------------------------------------------------------------
// Ad-hoc gRPC-specific tests
TEST(TestFlight, ConnectUri) {
TestServer server("flight-test-server");
server.Start();
ASSERT_TRUE(server.IsRunning());
std::stringstream ss;
ss << "grpc://localhost:" << server.port();
std::string uri = ss.str();
std::unique_ptr<FlightClient> client;
ASSERT_OK_AND_ASSIGN(auto location1, Location::Parse(uri));
ASSERT_OK_AND_ASSIGN(auto location2, Location::Parse(uri));
ASSERT_OK_AND_ASSIGN(client, FlightClient::Connect(location1));
ASSERT_OK(client->Close());
ASSERT_OK_AND_ASSIGN(client, FlightClient::Connect(location2));
ASSERT_OK(client->Close());
}
TEST(TestFlight, InvalidUriScheme) {
ASSERT_OK_AND_ASSIGN(auto location, Location::Parse("invalid://localhost:1234"));
EXPECT_RAISES_WITH_MESSAGE_THAT(
KeyError, ::testing::HasSubstr("No client transport implementation for invalid"),
FlightClient::Connect(location));
}
#ifndef _WIN32
TEST(TestFlight, ConnectUriUnix) {
TestServer server("flight-test-server", "/tmp/flight-test.sock");
server.Start();
ASSERT_TRUE(server.IsRunning());
std::stringstream ss;
ss << "grpc+unix://" << server.unix_sock();
std::string uri = ss.str();
std::unique_ptr<FlightClient> client;
ASSERT_OK_AND_ASSIGN(auto location1, Location::Parse(uri));
ASSERT_OK_AND_ASSIGN(auto location2, Location::Parse(uri));
ASSERT_OK_AND_ASSIGN(client, FlightClient::Connect(location1));
ASSERT_OK(client->Close());
ASSERT_OK_AND_ASSIGN(client, FlightClient::Connect(location2));
ASSERT_OK(client->Close());
}
#endif
// CI environments don't have an IPv6 interface configured
TEST(TestFlight, DISABLED_IpV6Port) {
std::unique_ptr<FlightServerBase> server = ExampleTestServer();
ASSERT_OK_AND_ASSIGN(auto location, Location::ForGrpcTcp("[::1]", 0));
FlightServerOptions options(location);
ASSERT_OK(server->Init(options));
ASSERT_GT(server->port(), 0);
ASSERT_OK_AND_ASSIGN(auto location2, Location::ForGrpcTcp("[::1]", server->port()));
std::unique_ptr<FlightClient> client;
ASSERT_OK_AND_ASSIGN(client, FlightClient::Connect(location2));
ASSERT_OK(client->ListFlights());
}
// ----------------------------------------------------------------------
// Client tests
class TestFlightClient : public ::testing::Test {
public:
void SetUp() {
server_ = ExampleTestServer();
ASSERT_OK_AND_ASSIGN(auto location, Location::ForGrpcTcp("localhost", 0));
FlightServerOptions options(location);
ASSERT_OK(server_->Init(options));
ASSERT_OK(ConnectClient());
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
}
Status ConnectClient() {
ARROW_ASSIGN_OR_RAISE(auto location,
Location::ForGrpcTcp("localhost", server_->port()));
return FlightClient::Connect(location).Value(&client_);
}
template <typename EndpointCheckFunc>
void CheckDoGet(const FlightDescriptor& descr,
const RecordBatchVector& expected_batches,
EndpointCheckFunc&& check_endpoints) {
auto expected_schema = expected_batches[0]->schema();
ASSERT_OK_AND_ASSIGN(auto info, client_->GetFlightInfo(descr));
check_endpoints(info->endpoints());
ipc::DictionaryMemo dict_memo;
ASSERT_OK_AND_ASSIGN(auto schema, info->GetSchema(&dict_memo));
AssertSchemaEqual(*expected_schema, *schema);
// By convention, fetch the first endpoint
Ticket ticket = info->endpoints()[0].ticket;
CheckDoGet(ticket, expected_batches);
}
void CheckDoGet(const Ticket& ticket, const RecordBatchVector& expected_batches) {
auto num_batches = static_cast<int>(expected_batches.size());
ASSERT_GE(num_batches, 2);
ASSERT_OK_AND_ASSIGN(auto stream, client_->DoGet(ticket));
ASSERT_OK_AND_ASSIGN(auto stream2, client_->DoGet(ticket));
ASSERT_OK_AND_ASSIGN(auto reader, MakeRecordBatchReader(std::move(stream2)));
FlightStreamChunk chunk;
std::shared_ptr<RecordBatch> batch;
for (int i = 0; i < num_batches; ++i) {
ASSERT_OK_AND_ASSIGN(chunk, stream->Next());
ASSERT_OK(reader->ReadNext(&batch));
ASSERT_NE(nullptr, chunk.data);
ASSERT_NE(nullptr, batch);
#if !defined(__MINGW32__)
ASSERT_BATCHES_EQUAL(*expected_batches[i], *chunk.data);
ASSERT_BATCHES_EQUAL(*expected_batches[i], *batch);
#else
// In MINGW32, the following code does not have the reproducibility at the LSB
// even when this is called twice with the same seed.
// As a workaround, use approxEqual
// /* from GenerateTypedData in random.cc */
// std::default_random_engine rng(seed); // seed = 282475250
// std::uniform_real_distribution<double> dist;
// std::generate(data, data + n, // n = 10
// [&dist, &rng] { return static_cast<ValueType>(dist(rng)); });
// /* data[1] = 0x40852cdfe23d3976 or 0x40852cdfe23d3975 */
ASSERT_BATCHES_APPROX_EQUAL(*expected_batches[i], *chunk.data);
ASSERT_BATCHES_APPROX_EQUAL(*expected_batches[i], *batch);
#endif
}
// Stream exhausted
ASSERT_OK_AND_ASSIGN(chunk, stream->Next());
ASSERT_OK(reader->ReadNext(&batch));
ASSERT_EQ(nullptr, chunk.data);
ASSERT_EQ(nullptr, batch);
}
protected:
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
};
class AuthTestServer : public FlightServerBase {
Status DoAction(const ServerCallContext& context, const Action& action,
std::unique_ptr<ResultStream>* result) override {
auto buf = Buffer::FromString(context.peer_identity());
auto peer = Buffer::FromString(context.peer());
*result = std::make_unique<SimpleResultStream>(
std::vector<Result>{Result{buf}, Result{peer}});
return Status::OK();
}
};
class TlsTestServer : public FlightServerBase {
Status DoAction(const ServerCallContext& context, const Action& action,
std::unique_ptr<ResultStream>* result) override {
auto buf = Buffer::FromString("Hello, world!");
*result = std::make_unique<SimpleResultStream>(std::vector<Result>{Result{buf}});
return Status::OK();
}
};
class HeaderAuthTestServer : public FlightServerBase {
public:
Status ListFlights(const ServerCallContext& context, const Criteria* criteria,
std::unique_ptr<FlightListing>* listings) override {
return Status::OK();
}
};
class TestAuthHandler : public ::testing::Test {
public:
void SetUp() {
ASSERT_OK(MakeServer<AuthTestServer>(
&server_, &client_,
[](FlightServerOptions* options) {
options->auth_handler =
std::make_unique<TestServerAuthHandler>("user", "p4ssw0rd");
return Status::OK();
},
[](FlightClientOptions* options) { return Status::OK(); }));
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
}
protected:
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
};
class TestBasicAuthHandler : public ::testing::Test {
public:
void SetUp() {
ASSERT_OK(MakeServer<AuthTestServer>(
&server_, &client_,
[](FlightServerOptions* options) {
options->auth_handler =
std::make_unique<TestServerBasicAuthHandler>("user", "p4ssw0rd");
return Status::OK();
},
[](FlightClientOptions* options) { return Status::OK(); }));
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
}
protected:
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
};
class TestTls : public ::testing::Test {
public:
void SetUp() {
// Manually initialize gRPC to try to ensure some thread-locals
// get initialized.
// https://github.com/grpc/grpc/issues/13856
// https://github.com/grpc/grpc/issues/20311
// In general, gRPC on MacOS struggles with TLS (both in the sense
// of thread-locals and encryption)
grpc_init();
server_.reset(new TlsTestServer);
ASSERT_OK_AND_ASSIGN(auto location, Location::ForGrpcTls("localhost", 0));
FlightServerOptions options(location);
ASSERT_RAISES(UnknownError, server_->Init(options));
ASSERT_OK(ExampleTlsCertificates(&options.tls_certificates));
ASSERT_OK(server_->Init(options));
ASSERT_OK_AND_ASSIGN(location_, Location::ForGrpcTls("localhost", server_->port()));
ASSERT_OK(ConnectClient());
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
grpc_shutdown();
}
Status ConnectClient() {
auto options = FlightClientOptions::Defaults();
CertKeyPair root_cert;
RETURN_NOT_OK(ExampleTlsCertificateRoot(&root_cert));
options.tls_root_certs = root_cert.pem_cert;
return FlightClient::Connect(location_, options).Value(&client_);
}
protected:
Location location_;
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
};
// A server middleware that rejects all calls.
class RejectServerMiddlewareFactory : public ServerMiddlewareFactory {
Status StartCall(const CallInfo& info, const CallHeaders& incoming_headers,
std::shared_ptr<ServerMiddleware>* middleware) override {
return MakeFlightError(FlightStatusCode::Unauthenticated, "All calls are rejected");
}
};
// A server middleware that counts the number of successful and failed
// calls.
class CountingServerMiddleware : public ServerMiddleware {
public:
CountingServerMiddleware(std::atomic<int>* successful, std::atomic<int>* failed)
: successful_(successful), failed_(failed) {}
void SendingHeaders(AddCallHeaders* outgoing_headers) override {}
void CallCompleted(const Status& status) override {
if (status.ok()) {
ARROW_IGNORE_EXPR((*successful_)++);
} else {
ARROW_IGNORE_EXPR((*failed_)++);
}
}
std::string name() const override { return "CountingServerMiddleware"; }
private:
std::atomic<int>* successful_;
std::atomic<int>* failed_;
};
class CountingServerMiddlewareFactory : public ServerMiddlewareFactory {
public:
CountingServerMiddlewareFactory() : successful_(0), failed_(0) {}
Status StartCall(const CallInfo& info, const CallHeaders& incoming_headers,
std::shared_ptr<ServerMiddleware>* middleware) override {
*middleware = std::make_shared<CountingServerMiddleware>(&successful_, &failed_);
return Status::OK();
}
std::atomic<int> successful_;
std::atomic<int> failed_;
};
// The current span ID, used to emulate OpenTracing style distributed
// tracing. Only used for communication between application code and
// client middleware.
static thread_local std::string current_span_id = "";
// A server middleware that stores the current span ID, in an
// emulation of OpenTracing style distributed tracing.
class TracingTestServerMiddleware : public ServerMiddleware {
public:
explicit TracingTestServerMiddleware(const std::string& current_span_id)
: span_id(current_span_id) {}
void SendingHeaders(AddCallHeaders* outgoing_headers) override {}
void CallCompleted(const Status& status) override {}
std::string name() const override { return "TracingTestServerMiddleware"; }
std::string span_id;
};
class TracingTestServerMiddlewareFactory : public ServerMiddlewareFactory {
public:
TracingTestServerMiddlewareFactory() {}
Status StartCall(const CallInfo& info, const CallHeaders& incoming_headers,
std::shared_ptr<ServerMiddleware>* middleware) override {
const std::pair<CallHeaders::const_iterator, CallHeaders::const_iterator>& iter_pair =
incoming_headers.equal_range("x-tracing-span-id");
if (iter_pair.first != iter_pair.second) {
const std::string_view& value = (*iter_pair.first).second;
*middleware = std::make_shared<TracingTestServerMiddleware>(std::string(value));
}
return Status::OK();
}
};
// Function to look in CallHeaders for a key that has a value starting with prefix and
// return the rest of the value after the prefix.
std::string FindKeyValPrefixInCallHeaders(const CallHeaders& incoming_headers,
const std::string& key,
const std::string& prefix) {
// Lambda function to compare characters without case sensitivity.
auto char_compare = [](const char& char1, const char& char2) {
return (::toupper(char1) == ::toupper(char2));
};
auto iter = incoming_headers.find(key);
if (iter == incoming_headers.end()) {
return "";
}
const std::string val(iter->second);
if (val.size() > prefix.length()) {
if (std::equal(val.begin(), val.begin() + prefix.length(), prefix.begin(),
char_compare)) {
return val.substr(prefix.length());
}
}
return "";
}
class HeaderAuthServerMiddleware : public ServerMiddleware {
public:
void SendingHeaders(AddCallHeaders* outgoing_headers) override {
outgoing_headers->AddHeader(kAuthHeader, std::string(kBearerPrefix) + kBearerToken);
}
void CallCompleted(const Status& status) override {}
std::string name() const override { return "HeaderAuthServerMiddleware"; }
};
void ParseBasicHeader(const CallHeaders& incoming_headers, std::string& username,
std::string& password) {
std::string encoded_credentials =
FindKeyValPrefixInCallHeaders(incoming_headers, kAuthHeader, kBasicPrefix);
std::stringstream decoded_stream(arrow::util::base64_decode(encoded_credentials));
std::getline(decoded_stream, username, ':');
std::getline(decoded_stream, password, ':');
}
// Factory for base64 header authentication testing.
class HeaderAuthServerMiddlewareFactory : public ServerMiddlewareFactory {
public:
HeaderAuthServerMiddlewareFactory() {}
Status StartCall(const CallInfo& info, const CallHeaders& incoming_headers,
std::shared_ptr<ServerMiddleware>* middleware) override {
std::string username, password;
ParseBasicHeader(incoming_headers, username, password);
if ((username == kValidUsername) && (password == kValidPassword)) {
*middleware = std::make_shared<HeaderAuthServerMiddleware>();
} else if ((username == kInvalidUsername) && (password == kInvalidPassword)) {
return MakeFlightError(FlightStatusCode::Unauthenticated, "Invalid credentials");
}
return Status::OK();
}
};
// A server middleware for validating incoming bearer header authentication.
class BearerAuthServerMiddleware : public ServerMiddleware {
public:
explicit BearerAuthServerMiddleware(const CallHeaders& incoming_headers, bool* isValid)
: isValid_(isValid) {
incoming_headers_ = incoming_headers;
}
void SendingHeaders(AddCallHeaders* outgoing_headers) override {
std::string bearer_token =
FindKeyValPrefixInCallHeaders(incoming_headers_, kAuthHeader, kBearerPrefix);
*isValid_ = (bearer_token == std::string(kBearerToken));
}
void CallCompleted(const Status& status) override {}
std::string name() const override { return "BearerAuthServerMiddleware"; }
private:
CallHeaders incoming_headers_;
bool* isValid_;
};
// Factory for base64 header authentication testing.
class BearerAuthServerMiddlewareFactory : public ServerMiddlewareFactory {
public:
BearerAuthServerMiddlewareFactory() : isValid_(false) {}
Status StartCall(const CallInfo& info, const CallHeaders& incoming_headers,
std::shared_ptr<ServerMiddleware>* middleware) override {
const std::pair<CallHeaders::const_iterator, CallHeaders::const_iterator>& iter_pair =
incoming_headers.equal_range(kAuthHeader);
if (iter_pair.first != iter_pair.second) {
*middleware =
std::make_shared<BearerAuthServerMiddleware>(incoming_headers, &isValid_);
}
return Status::OK();
}
bool GetIsValid() { return isValid_; }
private:
bool isValid_;
};
// A client middleware that adds a thread-local "request ID" to
// outgoing calls as a header, and keeps track of the status of
// completed calls. NOT thread-safe.
class PropagatingClientMiddleware : public ClientMiddleware {
public:
explicit PropagatingClientMiddleware(std::atomic<int>* received_headers,
std::vector<Status>* recorded_status)
: received_headers_(received_headers), recorded_status_(recorded_status) {}
void SendingHeaders(AddCallHeaders* outgoing_headers) {
// Pick up the span ID from thread locals. We have to use a
// thread-local for communication, since we aren't even
// instantiated until after the application code has already
// started the call (and so there's no chance for application code
// to pass us parameters directly).
outgoing_headers->AddHeader("x-tracing-span-id", current_span_id);
}
void ReceivedHeaders(const CallHeaders& incoming_headers) { (*received_headers_)++; }
void CallCompleted(const Status& status) { recorded_status_->push_back(status); }
private:
std::atomic<int>* received_headers_;
std::vector<Status>* recorded_status_;
};
class PropagatingClientMiddlewareFactory : public ClientMiddlewareFactory {
public:
void StartCall(const CallInfo& info, std::unique_ptr<ClientMiddleware>* middleware) {
recorded_calls_.push_back(info.method);
*middleware = std::make_unique<PropagatingClientMiddleware>(&received_headers_,
&recorded_status_);
}
void Reset() {
recorded_calls_.clear();
recorded_status_.clear();
received_headers_.fetch_and(0);
}
std::vector<FlightMethod> recorded_calls_;
std::vector<Status> recorded_status_;
std::atomic<int> received_headers_;
};
class ReportContextTestServer : public FlightServerBase {
Status DoAction(const ServerCallContext& context, const Action& action,
std::unique_ptr<ResultStream>* result) override {
std::shared_ptr<Buffer> buf;
const ServerMiddleware* middleware = context.GetMiddleware("tracing");
if (middleware == nullptr || middleware->name() != "TracingTestServerMiddleware") {
buf = Buffer::FromString("");
} else {
buf = Buffer::FromString(((const TracingTestServerMiddleware*)middleware)->span_id);
}
*result = std::make_unique<SimpleResultStream>(std::vector<Result>{Result{buf}});
return Status::OK();
}
};
class ErrorMiddlewareServer : public FlightServerBase {
Status DoAction(const ServerCallContext& context, const Action& action,
std::unique_ptr<ResultStream>* result) override {
std::string msg = "error_message";
auto buf = Buffer::FromString("");
std::shared_ptr<FlightStatusDetail> flightStatusDetail(
new FlightStatusDetail(FlightStatusCode::Failed, msg));
*result = std::make_unique<SimpleResultStream>(std::vector<Result>{Result{buf}});
return Status(StatusCode::ExecutionError, "test failed", flightStatusDetail);
}
};
class PropagatingTestServer : public FlightServerBase {
public:
explicit PropagatingTestServer(std::unique_ptr<FlightClient> client)
: client_(std::move(client)) {}
Status DoAction(const ServerCallContext& context, const Action& action,
std::unique_ptr<ResultStream>* result) override {
const ServerMiddleware* middleware = context.GetMiddleware("tracing");
if (middleware == nullptr || middleware->name() != "TracingTestServerMiddleware") {
current_span_id = "";
} else {
current_span_id = ((const TracingTestServerMiddleware*)middleware)->span_id;
}
return client_->DoAction(action).Value(result);
}
private:
std::unique_ptr<FlightClient> client_;
};
class TestRejectServerMiddleware : public ::testing::Test {
public:
void SetUp() {
ASSERT_OK(MakeServer<AppMetadataTestServer>(
&server_, &client_,
[](FlightServerOptions* options) {
options->middleware.push_back(
{"reject", std::make_shared<RejectServerMiddlewareFactory>()});
return Status::OK();
},
[](FlightClientOptions* options) { return Status::OK(); }));
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
}
protected:
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
};
class TestCountingServerMiddleware : public ::testing::Test {
public:
void SetUp() {
request_counter_ = std::make_shared<CountingServerMiddlewareFactory>();
ASSERT_OK(MakeServer<AppMetadataTestServer>(
&server_, &client_,
[&](FlightServerOptions* options) {
options->middleware.push_back({"request_counter", request_counter_});
return Status::OK();
},
[](FlightClientOptions* options) { return Status::OK(); }));
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
}
protected:
std::shared_ptr<CountingServerMiddlewareFactory> request_counter_;
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
};
// Setup for this test is 2 servers
// 1. Client makes request to server A with a request ID set
// 2. server A extracts the request ID and makes a request to server B
// with the same request ID set
// 3. server B extracts the request ID and sends it back
// 4. server A returns the response of server B
// 5. Client validates the response
class TestPropagatingMiddleware : public ::testing::Test {
public:
void SetUp() {
server_middleware_ = std::make_shared<TracingTestServerMiddlewareFactory>();
second_client_middleware_ = std::make_shared<PropagatingClientMiddlewareFactory>();
client_middleware_ = std::make_shared<PropagatingClientMiddlewareFactory>();
std::unique_ptr<FlightClient> server_client;
ASSERT_OK(MakeServer<ReportContextTestServer>(
&second_server_, &server_client,
[&](FlightServerOptions* options) {
options->middleware.push_back({"tracing", server_middleware_});
return Status::OK();
},
[&](FlightClientOptions* options) {
options->middleware.push_back(second_client_middleware_);
return Status::OK();
}));
ASSERT_OK(MakeServer<PropagatingTestServer>(
&first_server_, &client_,
[&](FlightServerOptions* options) {
options->middleware.push_back({"tracing", server_middleware_});
return Status::OK();
},
[&](FlightClientOptions* options) {
options->middleware.push_back(client_middleware_);
return Status::OK();
},
std::move(server_client)));
}
void ValidateStatus(const Status& status, const FlightMethod& method) {
ASSERT_EQ(1, client_middleware_->received_headers_);
ASSERT_EQ(method, client_middleware_->recorded_calls_.at(0));
ASSERT_EQ(status.code(), client_middleware_->recorded_status_.at(0).code());
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(first_server_->Shutdown());
ASSERT_OK(second_server_->Shutdown());
}
void CheckHeader(const std::string& header, const std::string& value,
const CallHeaders::const_iterator& it) {
// Construct a string_view before comparison to satisfy MSVC
std::string_view header_view(header.data(), header.length());
std::string_view value_view(value.data(), value.length());
ASSERT_EQ(header_view, (*it).first);
ASSERT_EQ(value_view, (*it).second);
}
protected:
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> first_server_;
std::unique_ptr<FlightServerBase> second_server_;
std::shared_ptr<TracingTestServerMiddlewareFactory> server_middleware_;
std::shared_ptr<PropagatingClientMiddlewareFactory> second_client_middleware_;
std::shared_ptr<PropagatingClientMiddlewareFactory> client_middleware_;
};
class TestErrorMiddleware : public ::testing::Test {
public:
void SetUp() {
ASSERT_OK(MakeServer<ErrorMiddlewareServer>(
&server_, &client_, [](FlightServerOptions* options) { return Status::OK(); },
[](FlightClientOptions* options) { return Status::OK(); }));
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
}
protected:
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
};
class TestBasicHeaderAuthMiddleware : public ::testing::Test {
public:
void SetUp() {
header_middleware_ = std::make_shared<HeaderAuthServerMiddlewareFactory>();
bearer_middleware_ = std::make_shared<BearerAuthServerMiddlewareFactory>();
std::pair<std::string, std::string> bearer = make_pair(
kAuthHeader, std::string(kBearerPrefix) + " " + std::string(kBearerToken));
ASSERT_OK(MakeServer<HeaderAuthTestServer>(
&server_, &client_,
[&](FlightServerOptions* options) {
options->auth_handler = std::make_unique<NoOpAuthHandler>();
options->middleware.push_back({"header-auth-server", header_middleware_});
options->middleware.push_back({"bearer-auth-server", bearer_middleware_});
return Status::OK();
},
[&](FlightClientOptions* options) { return Status::OK(); }));
}
void RunValidClientAuth() {
arrow::Result<std::pair<std::string, std::string>> bearer_result =
client_->AuthenticateBasicToken({}, kValidUsername, kValidPassword);
ASSERT_OK(bearer_result.status());
ASSERT_EQ(bearer_result.ValueOrDie().first, kAuthHeader);
ASSERT_EQ(bearer_result.ValueOrDie().second,
(std::string(kBearerPrefix) + kBearerToken));
std::unique_ptr<FlightListing> listing;
FlightCallOptions call_options;
call_options.headers.push_back(bearer_result.ValueOrDie());
ASSERT_OK_AND_ASSIGN(listing, client_->ListFlights(call_options, {}));
ASSERT_TRUE(bearer_middleware_->GetIsValid());
}
void RunInvalidClientAuth() {
arrow::Result<std::pair<std::string, std::string>> bearer_result =
client_->AuthenticateBasicToken({}, kInvalidUsername, kInvalidPassword);
ASSERT_RAISES(IOError, bearer_result.status());
ASSERT_THAT(bearer_result.status().message(),
::testing::HasSubstr("Invalid credentials"));
}
void TearDown() {
ASSERT_OK(client_->Close());
ASSERT_OK(server_->Shutdown());
}
protected:
std::unique_ptr<FlightClient> client_;
std::unique_ptr<FlightServerBase> server_;
std::shared_ptr<HeaderAuthServerMiddlewareFactory> header_middleware_;
std::shared_ptr<BearerAuthServerMiddlewareFactory> bearer_middleware_;
};
TEST_F(TestErrorMiddleware, TestMetadata) {
Action action;
// Run action1
action.type = "action1";
action.body = Buffer::FromString("action1-content");
ASSERT_OK_AND_ASSIGN(auto stream, client_->DoAction(action));
Status s = stream->Next().status();
ASSERT_FALSE(s.ok());
std::shared_ptr<FlightStatusDetail> flightStatusDetail =
FlightStatusDetail::UnwrapStatus(s);
ASSERT_TRUE(flightStatusDetail);
ASSERT_EQ(flightStatusDetail->extra_info(), "error_message");
}
TEST_F(TestFlightClient, ListFlights) {
ASSERT_OK_AND_ASSIGN(auto listing, client_->ListFlights());
ASSERT_TRUE(listing != nullptr);
std::vector<FlightInfo> flights = ExampleFlightInfo();
std::unique_ptr<FlightInfo> info;
for (const FlightInfo& flight : flights) {
ASSERT_OK_AND_ASSIGN(info, listing->Next());
AssertEqual(flight, *info);
}
ASSERT_OK_AND_ASSIGN(info, listing->Next());
ASSERT_TRUE(info == nullptr);
ASSERT_OK_AND_ASSIGN(info, listing->Next());
ASSERT_TRUE(info == nullptr);
}
TEST_F(TestFlightClient, ListFlightsWithCriteria) {
ASSERT_OK_AND_ASSIGN(auto listing, client_->ListFlights(FlightCallOptions(), {"foo"}));
std::unique_ptr<FlightInfo> info;
ASSERT_OK_AND_ASSIGN(info, listing->Next());
ASSERT_TRUE(info == nullptr);
}
TEST_F(TestFlightClient, GetFlightInfo) {
auto descr = FlightDescriptor::Path({"examples", "ints"});
ASSERT_OK_AND_ASSIGN(auto info, client_->GetFlightInfo(descr));
ASSERT_NE(info, nullptr);
std::vector<FlightInfo> flights = ExampleFlightInfo();
AssertEqual(flights[0], *info);
}
TEST_F(TestFlightClient, GetSchema) {
auto descr = FlightDescriptor::Path({"examples", "ints"});
ipc::DictionaryMemo dict_memo;
ASSERT_OK_AND_ASSIGN(auto schema_result, client_->GetSchema(descr));
ASSERT_NE(schema_result, nullptr);
ASSERT_OK(schema_result->GetSchema(&dict_memo));
}
TEST_F(TestFlightClient, GetFlightInfoNotFound) {
auto descr = FlightDescriptor::Path({"examples", "things"});
// XXX Ideally should be Invalid (or KeyError), but gRPC doesn't support
// multiple error codes.
auto st = client_->GetFlightInfo(descr).status();
ASSERT_RAISES(Invalid, st);
ASSERT_NE(st.message().find("Flight not found"), std::string::npos);
}
TEST_F(TestFlightClient, ListActions) {
ASSERT_OK_AND_ASSIGN(std::vector<ActionType> actions, client_->ListActions());
std::vector<ActionType> expected = ExampleActionTypes();
EXPECT_THAT(actions, ::testing::ContainerEq(expected));
}
TEST_F(TestFlightClient, DoAction) {
Action action;
std::unique_ptr<Result> result;
// Run action1
action.type = "action1";
const std::string action1_value = "action1-content";
action.body = Buffer::FromString(action1_value);
ASSERT_OK_AND_ASSIGN(auto stream, client_->DoAction(action));
for (int i = 0; i < 3; ++i) {
ASSERT_OK_AND_ASSIGN(result, stream->Next());
std::string expected = action1_value + "-part" + std::to_string(i);
ASSERT_EQ(expected, result->body->ToString());
}
// stream consumed
ASSERT_OK_AND_ASSIGN(result, stream->Next());
ASSERT_EQ(nullptr, result);
// Run action2, no results
action.type = "action2";
ASSERT_OK_AND_ASSIGN(stream, client_->DoAction(action));
ASSERT_OK_AND_ASSIGN(result, stream->Next());
ASSERT_EQ(nullptr, result);
}
TEST_F(TestFlightClient, RoundTripStatus) {
const auto descr = FlightDescriptor::Command("status-outofmemory");
const auto status = client_->GetFlightInfo(descr).status();
ASSERT_RAISES(OutOfMemory, status);
}
// Test setting generic transport options by configuring gRPC to fail