forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dns_transaction_unittest.cc
4132 lines (3557 loc) · 173 KB
/
dns_transaction_unittest.cc
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/dns_transaction.h"
#include <stdint.h>
#include <limits>
#include <memory>
#include <utility>
#include <vector>
#include "base/base64url.h"
#include "base/bind.h"
#include "base/containers/circular_deque.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_math.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/sys_byteorder.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/base/idempotency.h"
#include "net/base/ip_address.h"
#include "net/base/port_util.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/url_util.h"
#include "net/cookies/cookie_access_result.h"
#include "net/cookies/cookie_util.h"
#include "net/dns/dns_config.h"
#include "net/dns/dns_query.h"
#include "net/dns/dns_response.h"
#include "net/dns/dns_server_iterator.h"
#include "net/dns/dns_session.h"
#include "net/dns/dns_test_util.h"
#include "net/dns/dns_util.h"
#include "net/dns/public/dns_over_https_config.h"
#include "net/dns/public/dns_over_https_server_config.h"
#include "net/dns/public/dns_protocol.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/dns/resolve_context.h"
#include "net/http/http_util.h"
#include "net/log/net_log.h"
#include "net/log/net_log_capture_mode.h"
#include "net/log/net_log_with_source.h"
#include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/socket/socket_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_with_task_environment.h"
#include "net/test/url_request/url_request_failed_job.h"
#include "net/third_party/uri_template/uri_template.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_interceptor.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
using net::test::IsOk;
namespace net {
namespace {
base::TimeDelta kFallbackPeriod = base::Seconds(1);
const char kMockHostname[] = "mock.http";
// Like `net::DNSDomainFromDot()` except allows converting more names than
// accepted by that utility.
std::string DomainFromDot(base::StringPiece dotted_name) {
std::string dns_name;
while (true) {
size_t next_dot = dotted_name.find('.');
if (next_dot == base::StringPiece::npos) {
dns_name.append(1, base::checked_cast<base::StringPiece::value_type>(
dotted_name.size()));
dns_name.append(static_cast<std::string>(dotted_name));
dns_name.append(1, 0);
return dns_name;
} else {
dns_name.append(
1, base::checked_cast<base::StringPiece::value_type>(next_dot));
dns_name.append(
static_cast<std::string>(dotted_name.substr(0, next_dot)));
dotted_name = dotted_name.substr(next_dot + 1);
}
}
}
enum class Transport { UDP, TCP, HTTPS };
class NetLogCountingObserver : public net::NetLog::ThreadSafeObserver {
public:
NetLogCountingObserver() = default;
~NetLogCountingObserver() override {
if (net_log())
net_log()->RemoveObserver(this);
}
void OnAddEntry(const NetLogEntry& entry) override {
++count_;
if (!entry.params.is_none() && entry.params.is_dict())
dict_count_++;
}
int count() const { return count_; }
int dict_count() const { return dict_count_; }
private:
int count_ = 0;
int dict_count_ = 0;
};
// A SocketDataProvider builder.
class DnsSocketData {
public:
// The ctor takes parameters for the DnsQuery.
DnsSocketData(uint16_t id,
const char* dotted_name,
uint16_t qtype,
IoMode mode,
Transport transport,
const OptRecordRdata* opt_rdata = nullptr,
DnsQuery::PaddingStrategy padding_strategy =
DnsQuery::PaddingStrategy::NONE)
: query_(std::make_unique<DnsQuery>(id,
DomainFromDot(dotted_name),
qtype,
opt_rdata,
padding_strategy)),
transport_(transport) {
if (Transport::TCP == transport_) {
auto length = std::make_unique<uint16_t>();
*length = base::HostToNet16(query_->io_buffer()->size());
writes_.emplace_back(mode, reinterpret_cast<const char*>(length.get()),
sizeof(uint16_t), num_reads_and_writes());
lengths_.push_back(std::move(length));
}
writes_.emplace_back(mode, query_->io_buffer()->data(),
query_->io_buffer()->size(), num_reads_and_writes());
}
DnsSocketData(const DnsSocketData&) = delete;
DnsSocketData& operator=(const DnsSocketData&) = delete;
~DnsSocketData() = default;
// All responses must be added before GetProvider.
// Adds pre-built DnsResponse. |tcp_length| will be used in TCP mode only.
void AddResponseWithLength(std::unique_ptr<DnsResponse> response,
IoMode mode,
uint16_t tcp_length) {
CHECK(!provider_.get());
if (Transport::TCP == transport_) {
auto length = std::make_unique<uint16_t>();
*length = base::HostToNet16(tcp_length);
reads_.emplace_back(mode, reinterpret_cast<const char*>(length.get()),
sizeof(uint16_t), num_reads_and_writes());
lengths_.push_back(std::move(length));
}
reads_.emplace_back(mode, response->io_buffer()->data(),
response->io_buffer_size(), num_reads_and_writes());
responses_.push_back(std::move(response));
}
// Adds pre-built DnsResponse.
void AddResponse(std::unique_ptr<DnsResponse> response, IoMode mode) {
uint16_t tcp_length = response->io_buffer_size();
AddResponseWithLength(std::move(response), mode, tcp_length);
}
// Adds pre-built response from |data| buffer.
void AddResponseData(const uint8_t* data, size_t length, IoMode mode) {
CHECK(!provider_.get());
AddResponse(std::make_unique<DnsResponse>(
reinterpret_cast<const char*>(data), length, 0),
mode);
}
// Adds pre-built response from |data| buffer.
void AddResponseData(const uint8_t* data,
size_t length,
int offset,
IoMode mode) {
CHECK(!provider_.get());
AddResponse(
std::make_unique<DnsResponse>(reinterpret_cast<const char*>(data),
length - offset, offset),
mode);
}
// Add no-answer (RCODE only) response matching the query.
void AddRcode(int rcode, IoMode mode) {
auto response = std::make_unique<DnsResponse>(
query_->io_buffer()->data(), query_->io_buffer()->size(), 0);
dns_protocol::Header* header =
reinterpret_cast<dns_protocol::Header*>(response->io_buffer()->data());
header->flags |= base::HostToNet16(dns_protocol::kFlagResponse | rcode);
AddResponse(std::move(response), mode);
}
// Add error response.
void AddReadError(int error, IoMode mode) {
reads_.emplace_back(mode, error, num_reads_and_writes());
}
// Build, if needed, and return the SocketDataProvider. No new responses
// should be added afterwards.
SequencedSocketData* GetProvider() {
if (provider_.get())
return provider_.get();
// Terminate the reads with ERR_IO_PENDING to prevent overrun and default to
// timeout.
if (transport_ != Transport::HTTPS) {
reads_.emplace_back(SYNCHRONOUS, ERR_IO_PENDING,
writes_.size() + reads_.size());
}
provider_ = std::make_unique<SequencedSocketData>(reads_, writes_);
if (Transport::TCP == transport_ || Transport::HTTPS == transport_) {
provider_->set_connect_data(MockConnect(reads_[0].mode, OK));
}
return provider_.get();
}
uint16_t query_id() const { return query_->id(); }
IOBufferWithSize* query_buffer() { return query_->io_buffer(); }
private:
size_t num_reads_and_writes() const { return reads_.size() + writes_.size(); }
std::unique_ptr<DnsQuery> query_;
Transport transport_;
std::vector<std::unique_ptr<uint16_t>> lengths_;
std::vector<std::unique_ptr<DnsResponse>> responses_;
std::vector<MockWrite> writes_;
std::vector<MockRead> reads_;
std::unique_ptr<SequencedSocketData> provider_;
};
class TestSocketFactory;
// A variant of MockUDPClientSocket which always fails to Connect.
class FailingUDPClientSocket : public MockUDPClientSocket {
public:
FailingUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log)
: MockUDPClientSocket(data, net_log) {}
FailingUDPClientSocket(const FailingUDPClientSocket&) = delete;
FailingUDPClientSocket& operator=(const FailingUDPClientSocket&) = delete;
~FailingUDPClientSocket() override = default;
int Connect(const IPEndPoint& endpoint) override {
return ERR_CONNECTION_REFUSED;
}
};
// A variant of MockUDPClientSocket which notifies the factory OnConnect.
class TestUDPClientSocket : public MockUDPClientSocket {
public:
TestUDPClientSocket(TestSocketFactory* factory,
SocketDataProvider* data,
net::NetLog* net_log)
: MockUDPClientSocket(data, net_log), factory_(factory) {}
TestUDPClientSocket(const TestUDPClientSocket&) = delete;
TestUDPClientSocket& operator=(const TestUDPClientSocket&) = delete;
~TestUDPClientSocket() override = default;
int Connect(const IPEndPoint& endpoint) override;
private:
raw_ptr<TestSocketFactory> factory_;
};
// Creates TestUDPClientSockets and keeps endpoints reported via OnConnect.
class TestSocketFactory : public MockClientSocketFactory {
public:
TestSocketFactory() = default;
~TestSocketFactory() override = default;
std::unique_ptr<DatagramClientSocket> CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
NetLog* net_log,
const NetLogSource& source) override {
if (fail_next_socket_) {
fail_next_socket_ = false;
return std::make_unique<FailingUDPClientSocket>(&empty_data_, net_log);
}
SocketDataProvider* data_provider = mock_data().GetNext();
auto socket =
std::make_unique<TestUDPClientSocket>(this, data_provider, net_log);
// Even using DEFAULT_BIND, actual sockets have been measured to very rarely
// repeat the same source port multiple times in a row. Need to mimic that
// functionality here, so DnsUdpTracker doesn't misdiagnose repeated port
// as low entropy.
if (diverse_source_ports_)
socket->set_source_port(next_source_port_++);
return socket;
}
void OnConnect(const IPEndPoint& endpoint) {
remote_endpoints_.emplace_back(endpoint);
}
struct RemoteNameserver {
explicit RemoteNameserver(IPEndPoint insecure_nameserver)
: insecure_nameserver(insecure_nameserver) {}
explicit RemoteNameserver(DnsOverHttpsServerConfig secure_nameserver)
: secure_nameserver(secure_nameserver) {}
absl::optional<IPEndPoint> insecure_nameserver;
absl::optional<DnsOverHttpsServerConfig> secure_nameserver;
};
std::vector<RemoteNameserver> remote_endpoints_;
bool fail_next_socket_ = false;
bool diverse_source_ports_ = true;
private:
StaticSocketDataProvider empty_data_;
uint16_t next_source_port_ = 123;
};
int TestUDPClientSocket::Connect(const IPEndPoint& endpoint) {
factory_->OnConnect(endpoint);
return MockUDPClientSocket::Connect(endpoint);
}
// Helper class that holds a DnsTransaction and handles OnTransactionComplete.
class TransactionHelper {
public:
// If |expected_answer_count| < 0 then it is the expected net error.
explicit TransactionHelper(int expected_answer_count)
: expected_answer_count_(expected_answer_count) {}
// Mark that the transaction shall be destroyed immediately upon callback.
void set_cancel_in_callback() { cancel_in_callback_ = true; }
void StartTransaction(DnsTransactionFactory* factory,
const char* hostname,
uint16_t qtype,
bool secure,
ResolveContext* context) {
std::unique_ptr<DnsTransaction> transaction = factory->CreateTransaction(
hostname, qtype,
NetLogWithSource::Make(net::NetLog::Get(), net::NetLogSourceType::NONE),
secure, factory->GetSecureDnsModeForTest(), context,
true /* fast_timeout */);
transaction->SetRequestPriority(DEFAULT_PRIORITY);
EXPECT_EQ(qtype, transaction->GetType());
StartTransaction(std::move(transaction));
}
void StartTransaction(std::unique_ptr<DnsTransaction> transaction) {
EXPECT_FALSE(transaction_);
transaction_ = std::move(transaction);
qtype_ = transaction_->GetType();
transaction_->Start(base::BindOnce(
&TransactionHelper::OnTransactionComplete, base::Unretained(this)));
}
void Cancel() {
ASSERT_TRUE(transaction_.get() != nullptr);
transaction_.reset(nullptr);
}
void OnTransactionComplete(int rv, const DnsResponse* response) {
EXPECT_FALSE(completed_);
completed_ = true;
response_ = response;
transaction_complete_run_loop_.Quit();
if (cancel_in_callback_) {
Cancel();
return;
}
if (response)
EXPECT_TRUE(response->IsValid());
if (expected_answer_count_ >= 0) {
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(response != nullptr);
EXPECT_EQ(static_cast<unsigned>(expected_answer_count_),
response->answer_count());
EXPECT_EQ(qtype_, response->GetSingleQType());
DnsRecordParser parser = response->Parser();
DnsResourceRecord record;
for (int i = 0; i < expected_answer_count_; ++i) {
EXPECT_TRUE(parser.ReadRecord(&record));
}
} else {
EXPECT_EQ(expected_answer_count_, rv);
}
}
bool has_completed() const { return completed_; }
const DnsResponse* response() const { return response_; }
// Runs until the completion callback is called. Transaction must have already
// been started or this will never complete.
void RunUntilComplete() {
DCHECK(transaction_);
DCHECK(!transaction_complete_run_loop_.running());
transaction_complete_run_loop_.Run();
DCHECK(has_completed());
}
private:
uint16_t qtype_ = 0;
std::unique_ptr<DnsTransaction> transaction_;
raw_ptr<const DnsResponse> response_ = nullptr;
int expected_answer_count_;
bool cancel_in_callback_ = false;
base::RunLoop transaction_complete_run_loop_;
bool completed_ = false;
};
// Callback that allows a test to modify HttpResponseinfo
// before the response is sent to the requester. This allows
// response headers to be changed.
using ResponseModifierCallback =
base::RepeatingCallback<void(URLRequest* request, HttpResponseInfo* info)>;
// Callback that allows the test to substitute its own implementation
// of URLRequestJob to handle the request.
using DohJobMakerCallback = base::RepeatingCallback<std::unique_ptr<
URLRequestJob>(URLRequest* request, SocketDataProvider* data_provider)>;
// Callback to notify that URLRequestJob::Start has been called.
using UrlRequestStartedCallback = base::RepeatingCallback<void()>;
// Subclass of URLRequestJob which takes a SocketDataProvider with data
// representing both a DNS over HTTPS query and response.
class URLRequestMockDohJob : public URLRequestJob, public AsyncSocket {
public:
URLRequestMockDohJob(
URLRequest* request,
SocketDataProvider* data_provider,
ResponseModifierCallback response_modifier = ResponseModifierCallback(),
UrlRequestStartedCallback on_start = UrlRequestStartedCallback())
: URLRequestJob(request),
data_provider_(data_provider),
response_modifier_(response_modifier),
on_start_(on_start) {
data_provider_->Initialize(this);
MatchQueryData(request, data_provider);
}
// Compare the query contained in either the POST body or the body
// parameter of the GET query to the write data of the SocketDataProvider.
static void MatchQueryData(URLRequest* request,
SocketDataProvider* data_provider) {
std::string decoded_query;
if (request->method() == "GET") {
std::string encoded_query;
EXPECT_TRUE(GetValueForKeyInQuery(request->url(), "dns", &encoded_query));
EXPECT_GT(encoded_query.size(), 0ul);
EXPECT_TRUE(base::Base64UrlDecode(
encoded_query, base::Base64UrlDecodePolicy::IGNORE_PADDING,
&decoded_query));
} else if (request->method() == "POST") {
EXPECT_EQ(IDEMPOTENT, request->GetIdempotency());
const UploadDataStream* stream = request->get_upload_for_testing();
auto* readers = stream->GetElementReaders();
EXPECT_TRUE(readers);
EXPECT_FALSE(readers->empty());
for (auto& reader : *readers) {
const UploadBytesElementReader* byte_reader = reader->AsBytesReader();
decoded_query +=
std::string(byte_reader->bytes(), byte_reader->length());
}
}
std::string query(decoded_query);
MockWriteResult result(SYNCHRONOUS, 1);
while (result.result > 0 && query.length() > 0) {
result = data_provider->OnWrite(query);
if (result.result > 0)
query = query.substr(result.result);
}
}
static std::string GetMockHttpsUrl(const std::string& path) {
return "https://" + (kMockHostname + ("/" + path));
}
// URLRequestJob implementation:
void Start() override {
if (on_start_)
on_start_.Run();
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&URLRequestMockDohJob::StartAsync,
weak_factory_.GetWeakPtr()));
}
URLRequestMockDohJob(const URLRequestMockDohJob&) = delete;
URLRequestMockDohJob& operator=(const URLRequestMockDohJob&) = delete;
~URLRequestMockDohJob() override {
if (data_provider_)
data_provider_->DetachSocket();
}
int ReadRawData(IOBuffer* buf, int buf_size) override {
if (!data_provider_)
return ERR_FAILED;
if (leftover_data_len_ > 0) {
int rv = DoBufferCopy(leftover_data_, leftover_data_len_, buf, buf_size);
return rv;
}
if (data_provider_->AllReadDataConsumed())
return 0;
MockRead read = data_provider_->OnRead();
if (read.result < ERR_IO_PENDING)
return read.result;
if (read.result == ERR_IO_PENDING) {
pending_buf_ = buf;
pending_buf_size_ = buf_size;
return ERR_IO_PENDING;
}
return DoBufferCopy(read.data, read.data_len, buf, buf_size);
}
void GetResponseInfo(HttpResponseInfo* info) override {
// Send back mock headers.
std::string raw_headers;
raw_headers.append(
"HTTP/1.1 200 OK\n"
"Content-type: application/dns-message\n");
if (content_length_ > 0) {
raw_headers.append(base::StringPrintf("Content-Length: %1d\n",
static_cast<int>(content_length_)));
}
info->headers = base::MakeRefCounted<HttpResponseHeaders>(
HttpUtil::AssembleRawHeaders(raw_headers));
if (response_modifier_)
response_modifier_.Run(request(), info);
}
// AsyncSocket implementation:
void OnReadComplete(const MockRead& data) override {
EXPECT_NE(data.result, ERR_IO_PENDING);
if (data.result < 0)
return ReadRawDataComplete(data.result);
ReadRawDataComplete(DoBufferCopy(data.data, data.data_len, pending_buf_,
pending_buf_size_));
}
void OnWriteComplete(int rv) override {}
void OnConnectComplete(const MockConnect& data) override {}
void OnDataProviderDestroyed() override { data_provider_ = nullptr; }
private:
void StartAsync() {
if (!request_)
return;
if (content_length_)
set_expected_content_size(content_length_);
NotifyHeadersComplete();
}
int DoBufferCopy(const char* data,
int data_len,
IOBuffer* buf,
int buf_size) {
if (data_len > buf_size) {
memcpy(buf->data(), data, buf_size);
leftover_data_ = data + buf_size;
leftover_data_len_ = data_len - buf_size;
return buf_size;
}
memcpy(buf->data(), data, data_len);
return data_len;
}
const int content_length_ = 0;
const char* leftover_data_;
int leftover_data_len_ = 0;
raw_ptr<SocketDataProvider> data_provider_;
const ResponseModifierCallback response_modifier_;
const UrlRequestStartedCallback on_start_;
raw_ptr<IOBuffer> pending_buf_;
int pending_buf_size_;
base::WeakPtrFactory<URLRequestMockDohJob> weak_factory_{this};
};
class DnsTransactionTestBase : public testing::Test {
public:
DnsTransactionTestBase() = default;
~DnsTransactionTestBase() override {
// All queued transaction IDs should be used by a transaction calling
// GetNextId().
CHECK(transaction_ids_.empty());
}
// Generates |nameservers| for DnsConfig.
void ConfigureNumServers(size_t num_servers) {
CHECK_LE(num_servers, 255u);
config_.nameservers.clear();
for (size_t i = 0; i < num_servers; ++i) {
config_.nameservers.emplace_back(IPAddress(192, 168, 1, i),
dns_protocol::kDefaultPort);
}
}
// Configures the DnsConfig DNS-over-HTTPS server(s), which either
// accept GET or POST requests based on use_post. If a
// ResponseModifierCallback is provided it will be called to construct the
// HTTPResponse.
void ConfigureDohServers(bool use_post,
size_t num_doh_servers = 1,
bool make_available = true) {
GURL url(URLRequestMockDohJob::GetMockHttpsUrl("doh_test"));
URLRequestFilter* filter = URLRequestFilter::GetInstance();
filter->AddHostnameInterceptor(url.scheme(), url.host(),
std::make_unique<DohJobInterceptor>(this));
CHECK_LE(num_doh_servers, 255u);
std::vector<string> templates;
templates.reserve(num_doh_servers);
for (size_t i = 0; i < num_doh_servers; ++i) {
templates.push_back(URLRequestMockDohJob::GetMockHttpsUrl(
base::StringPrintf("doh_test_%zu", i)) +
(use_post ? "" : "{?dns}"));
}
config_.doh_config =
*DnsOverHttpsConfig::FromTemplatesForTesting(std::move(templates));
ConfigureFactory();
if (make_available) {
for (size_t server_index = 0; server_index < num_doh_servers;
++server_index) {
resolve_context_->RecordServerSuccess(
server_index, true /* is_doh_server */, session_.get());
}
}
}
// Called after fully configuring |config|.
void ConfigureFactory() {
session_ = base::MakeRefCounted<DnsSession>(
config_,
base::BindRepeating(&DnsTransactionTestBase::GetNextId,
base::Unretained(this)),
nullptr /* NetLog */);
resolve_context_->InvalidateCachesAndPerSessionData(
session_.get(), false /* network_change */);
transaction_factory_ = DnsTransactionFactory::CreateFactory(session_.get());
}
void AddSocketData(std::unique_ptr<DnsSocketData> data,
bool enqueue_transaction_id = true) {
CHECK(socket_factory_.get());
if (enqueue_transaction_id)
transaction_ids_.push_back(data->query_id());
socket_factory_->AddSocketDataProvider(data->GetProvider());
socket_data_.push_back(std::move(data));
}
// Add expected query for |dotted_name| and |qtype| with |id| and response
// taken verbatim from |data| of |data_length| bytes. The transaction id in
// |data| should equal |id|, unless testing mismatched response.
void AddQueryAndResponse(uint16_t id,
const char* dotted_name,
uint16_t qtype,
const uint8_t* response_data,
size_t response_length,
IoMode mode,
Transport transport,
const OptRecordRdata* opt_rdata = nullptr,
DnsQuery::PaddingStrategy padding_strategy =
DnsQuery::PaddingStrategy::NONE,
bool enqueue_transaction_id = true) {
CHECK(socket_factory_.get());
auto data = std::make_unique<DnsSocketData>(
id, dotted_name, qtype, mode, transport, opt_rdata, padding_strategy);
data->AddResponseData(response_data, response_length, mode);
AddSocketData(std::move(data), enqueue_transaction_id);
}
void AddQueryAndErrorResponse(uint16_t id,
const char* dotted_name,
uint16_t qtype,
int error,
IoMode mode,
Transport transport,
const OptRecordRdata* opt_rdata = nullptr,
DnsQuery::PaddingStrategy padding_strategy =
DnsQuery::PaddingStrategy::NONE,
bool enqueue_transaction_id = true) {
CHECK(socket_factory_.get());
auto data = std::make_unique<DnsSocketData>(
id, dotted_name, qtype, mode, transport, opt_rdata, padding_strategy);
data->AddReadError(error, mode);
AddSocketData(std::move(data), enqueue_transaction_id);
}
void AddAsyncQueryAndResponse(uint16_t id,
const char* dotted_name,
uint16_t qtype,
const uint8_t* data,
size_t data_length,
const OptRecordRdata* opt_rdata = nullptr) {
AddQueryAndResponse(id, dotted_name, qtype, data, data_length, ASYNC,
Transport::UDP, opt_rdata);
}
void AddSyncQueryAndResponse(uint16_t id,
const char* dotted_name,
uint16_t qtype,
const uint8_t* data,
size_t data_length,
const OptRecordRdata* opt_rdata = nullptr) {
AddQueryAndResponse(id, dotted_name, qtype, data, data_length, SYNCHRONOUS,
Transport::UDP, opt_rdata);
}
// Add expected query of |dotted_name| and |qtype| and no response.
void AddHangingQuery(
const char* dotted_name,
uint16_t qtype,
DnsQuery::PaddingStrategy padding_strategy =
DnsQuery::PaddingStrategy::NONE,
uint16_t id = base::RandInt(0, std::numeric_limits<uint16_t>::max()),
bool enqueue_transaction_id = true) {
auto data = std::make_unique<DnsSocketData>(
id, dotted_name, qtype, ASYNC, Transport::UDP, nullptr /* opt_rdata */,
padding_strategy);
AddSocketData(std::move(data), enqueue_transaction_id);
}
// Add expected query of |dotted_name| and |qtype| and matching response with
// no answer and RCODE set to |rcode|. The id will be generated randomly.
void AddQueryAndRcode(
const char* dotted_name,
uint16_t qtype,
int rcode,
IoMode mode,
Transport trans,
DnsQuery::PaddingStrategy padding_strategy =
DnsQuery::PaddingStrategy::NONE,
uint16_t id = base::RandInt(0, std::numeric_limits<uint16_t>::max()),
bool enqueue_transaction_id = true) {
CHECK_NE(dns_protocol::kRcodeNOERROR, rcode);
auto data = std::make_unique<DnsSocketData>(id, dotted_name, qtype, mode,
trans, nullptr /* opt_rdata */,
padding_strategy);
data->AddRcode(rcode, mode);
AddSocketData(std::move(data), enqueue_transaction_id);
}
void AddAsyncQueryAndRcode(const char* dotted_name,
uint16_t qtype,
int rcode) {
AddQueryAndRcode(dotted_name, qtype, rcode, ASYNC, Transport::UDP);
}
void AddSyncQueryAndRcode(const char* dotted_name,
uint16_t qtype,
int rcode) {
AddQueryAndRcode(dotted_name, qtype, rcode, SYNCHRONOUS, Transport::UDP);
}
// Checks if the sockets were connected in the order matching the indices in
// |servers|.
void CheckServerOrder(const size_t* servers, size_t num_attempts) {
ASSERT_EQ(num_attempts, socket_factory_->remote_endpoints_.size());
auto num_insecure_nameservers = session_->config().nameservers.size();
for (size_t i = 0; i < num_attempts; ++i) {
if (servers[i] < num_insecure_nameservers) {
// Check insecure server match.
EXPECT_EQ(
socket_factory_->remote_endpoints_[i].insecure_nameserver.value(),
session_->config().nameservers[servers[i]]);
} else {
// Check secure server match.
EXPECT_EQ(
socket_factory_->remote_endpoints_[i].secure_nameserver.value(),
session_->config()
.doh_config.servers()[servers[i] - num_insecure_nameservers]);
}
}
}
std::unique_ptr<URLRequestJob> MaybeInterceptRequest(URLRequest* request) {
// If the path indicates a redirect, skip checking the list of
// configured servers, because it won't be there and we still want
// to handle it.
bool server_found = request->url().path() == "/redirect-destination";
for (auto server : config_.doh_config.servers()) {
if (server_found)
break;
std::string url_base =
GetURLFromTemplateWithoutParameters(server.server_template());
if (server.use_post() && request->method() == "POST") {
if (url_base == request->url().spec()) {
server_found = true;
socket_factory_->remote_endpoints_.emplace_back(server);
}
} else if (!server.use_post() && request->method() == "GET") {
std::string prefix = url_base + "?dns=";
auto mispair = std::mismatch(prefix.begin(), prefix.end(),
request->url().spec().begin());
if (mispair.first == prefix.end()) {
server_found = true;
socket_factory_->remote_endpoints_.emplace_back(server);
}
}
}
EXPECT_TRUE(server_found);
EXPECT_TRUE(
request->isolation_info().network_isolation_key().IsTransient());
// All DoH requests for the same ResolveContext should use the same
// IsolationInfo, so network objects like sockets can be reused between
// requests.
if (!expect_multiple_isolation_infos_) {
if (!isolation_info_) {
isolation_info_ =
std::make_unique<IsolationInfo>(request->isolation_info());
} else {
EXPECT_TRUE(
isolation_info_->IsEqualForTesting(request->isolation_info()));
}
}
EXPECT_FALSE(request->allow_credentials());
EXPECT_EQ(SecureDnsPolicy::kBootstrap, request->secure_dns_policy());
std::string accept;
EXPECT_TRUE(request->extra_request_headers().GetHeader("Accept", &accept));
EXPECT_EQ(accept, "application/dns-message");
std::string language;
EXPECT_TRUE(request->extra_request_headers().GetHeader("Accept-Language",
&language));
EXPECT_EQ(language, "*");
std::string user_agent;
EXPECT_TRUE(
request->extra_request_headers().GetHeader("User-Agent", &user_agent));
EXPECT_EQ(user_agent, "Chrome");
SocketDataProvider* provider = socket_factory_->mock_data().GetNext();
if (doh_job_maker_)
return doh_job_maker_.Run(request, provider);
return std::make_unique<URLRequestMockDohJob>(
request, provider, response_modifier_, on_start_);
}
class DohJobInterceptor : public URLRequestInterceptor {
public:
explicit DohJobInterceptor(DnsTransactionTestBase* test) : test_(test) {}
DohJobInterceptor(const DohJobInterceptor&) = delete;
DohJobInterceptor& operator=(const DohJobInterceptor&) = delete;
~DohJobInterceptor() override = default;
// URLRequestInterceptor implementation:
std::unique_ptr<URLRequestJob> MaybeInterceptRequest(
URLRequest* request) const override {
return test_->MaybeInterceptRequest(request);
}
private:
raw_ptr<DnsTransactionTestBase> test_;
};
void SetResponseModifierCallback(ResponseModifierCallback response_modifier) {
response_modifier_ = response_modifier;
}
void SetDohJobMakerCallback(DohJobMakerCallback doh_job_maker) {
doh_job_maker_ = doh_job_maker;
}
void SetUrlRequestStartedCallback(UrlRequestStartedCallback on_start) {
on_start_ = on_start;
}
void SetUp() override {
// By default set one server,
ConfigureNumServers(1);
// and no retransmissions,
config_.attempts = 1;
// and an arbitrary fallback period.
config_.fallback_period = kFallbackPeriod;
auto context_builder = CreateTestURLRequestContextBuilder();
socket_factory_ = std::make_unique<TestSocketFactory>();
context_builder->set_client_socket_factory_for_testing(
socket_factory_.get());
request_context_ = context_builder->Build();
resolve_context_ = std::make_unique<ResolveContext>(
request_context_.get(), false /* enable_caching */);
ConfigureFactory();
}
void TearDown() override {
// Check that all socket data was at least written to.
for (size_t i = 0; i < socket_data_.size(); ++i) {
EXPECT_TRUE(socket_data_[i]->GetProvider()->AllWriteDataConsumed()) << i;
}
URLRequestFilter* filter = URLRequestFilter::GetInstance();
filter->ClearHandlers();
}
void set_expect_multiple_isolation_infos(
bool expect_multiple_isolation_infos) {
expect_multiple_isolation_infos_ = expect_multiple_isolation_infos;
}
protected:
int GetNextId(int min, int max) {
EXPECT_FALSE(transaction_ids_.empty());
int id = transaction_ids_.front();
transaction_ids_.pop_front();
EXPECT_GE(id, min);
EXPECT_LE(id, max);
return id;
}
DnsConfig config_;
std::vector<std::unique_ptr<DnsSocketData>> socket_data_;
base::circular_deque<int> transaction_ids_;
std::unique_ptr<TestSocketFactory> socket_factory_;
std::unique_ptr<URLRequestContext> request_context_;
std::unique_ptr<ResolveContext> resolve_context_;
scoped_refptr<DnsSession> session_;
std::unique_ptr<DnsTransactionFactory> transaction_factory_;
ResponseModifierCallback response_modifier_;
UrlRequestStartedCallback on_start_;
DohJobMakerCallback doh_job_maker_;
// Whether multiple IsolationInfos should be expected (due to there being
// multiple RequestContexts in use).
bool expect_multiple_isolation_infos_ = false;
// IsolationInfo used by DoH requests. Populated on first DoH request, and
// compared to IsolationInfo used by all subsequent requests, unless
// |expect_multiple_isolation_infos_| is true.
std::unique_ptr<IsolationInfo> isolation_info_;
};
class DnsTransactionTest : public DnsTransactionTestBase,
public WithTaskEnvironment {
public:
DnsTransactionTest() = default;
~DnsTransactionTest() override = default;
};
class DnsTransactionTestWithMockTime : public DnsTransactionTestBase,
public WithTaskEnvironment {
protected:
DnsTransactionTestWithMockTime()
: WithTaskEnvironment(
base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
~DnsTransactionTestWithMockTime() override = default;
};
TEST_F(DnsTransactionTest, Lookup) {
AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype,
kT0ResponseDatagram, std::size(kT0ResponseDatagram));
TransactionHelper helper0(kT0RecordCount);