summaryrefslogtreecommitdiff
path: root/chromium/net/dns/dns_config_service_unittest.cc
blob: 759395939ddf12792c969578a492ee920c9c606e (plain)
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
// 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_config_service.h"

#include <memory>
#include <string>
#include <utility>

#include "base/bind.h"
#include "base/cancelable_callback.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_task_runner_handle.h"
#include "net/base/address_family.h"
#include "net/base/ip_address.h"
#include "net/dns/dns_hosts.h"
#include "net/dns/public/dns_protocol.h"
#include "net/dns/test_dns_config_service.h"
#include "net/test/test_with_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

using testing::_;
using testing::DoAll;
using testing::Return;
using testing::SetArgPointee;

class DnsConfigServiceTest : public TestWithTaskEnvironment {
 public:
  DnsConfigServiceTest()
      : TestWithTaskEnvironment(
            base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}

  void OnConfigChanged(const DnsConfig& config) {
    last_config_ = config;
    if (quit_on_config_)
      std::move(quit_on_config_).Run();
  }

 protected:
  void WaitForConfig() {
    base::RunLoop run_loop;
    quit_on_config_ = run_loop.QuitClosure();

    // Some work may be performed on `ThreadPool` and is not accounted for in a
    // `RunLoop::RunUntilIdle()` call.
    run_loop.RunUntilIdle();
    base::ThreadPoolInstance::Get()->FlushForTesting();
    if (!run_loop.AnyQuitCalled())
      run_loop.RunUntilIdle();

    // Validate a config notification was received.
    ASSERT_TRUE(run_loop.AnyQuitCalled());
  }

  void WaitForInvalidationTimeout() {
    base::RunLoop run_loop;
    quit_on_config_ = run_loop.QuitClosure();
    FastForwardBy(DnsConfigService::kInvalidationTimeout);

    // Validate a config notification was received, and that it was an empty
    // config (empty config always expected for invalidation).
    ASSERT_TRUE(run_loop.AnyQuitCalled());
    ASSERT_EQ(last_config_, DnsConfig());
  }

  void ValidateNoNotification() {
    base::RunLoop run_loop;
    quit_on_config_ = run_loop.QuitClosure();

    // Flush any potential work and wait for any potential invalidation timeout.
    run_loop.RunUntilIdle();
    base::ThreadPoolInstance::Get()->FlushForTesting();
    if (!run_loop.AnyQuitCalled())
      run_loop.RunUntilIdle();
    FastForwardBy(DnsConfigService::kInvalidationTimeout);

    // Validate no config notification was received.
    ASSERT_FALSE(run_loop.AnyQuitCalled());
    quit_on_config_.Reset();
  }

  // Generate a config using the given seed..
  DnsConfig MakeConfig(unsigned seed) {
    DnsConfig config;
    config.nameservers.emplace_back(IPAddress(1, 2, 3, 4), seed & 0xFFFF);
    EXPECT_TRUE(config.IsValid());
    return config;
  }

  // Generate hosts using the given seed.
  DnsHosts MakeHosts(unsigned seed) {
    DnsHosts hosts;
    std::string hosts_content = "127.0.0.1 localhost";
    hosts_content.append(seed, '1');
    ParseHosts(hosts_content, &hosts);
    EXPECT_FALSE(hosts.empty());
    return hosts;
  }

  void SetUpService(TestDnsConfigService& service) {
    service.WatchConfig(base::BindRepeating(
        &DnsConfigServiceTest::OnConfigChanged, base::Unretained(this)));

    // Run through any initial config notifications triggered by starting the
    // watch.
    base::RunLoop run_loop;
    quit_on_config_ = run_loop.QuitClosure();
    run_loop.RunUntilIdle();
    base::ThreadPoolInstance::Get()->FlushForTesting();
    run_loop.RunUntilIdle();
    FastForwardBy(DnsConfigService::kInvalidationTimeout);
    quit_on_config_.Reset();
  }

  void SetUp() override {
    service_ = std::make_unique<TestDnsConfigService>();
    SetUpService(*service_);
    EXPECT_FALSE(last_config_.IsValid());
  }

  void TearDown() override {
    // After test, expect no more config notifications.
    ValidateNoNotification();
  }

  DnsConfig last_config_;
  base::OnceClosure quit_on_config_;

  // Service under test.
  std::unique_ptr<TestDnsConfigService> service_;
};

class MockHostsParserFactory : public DnsHostsParser {
 public:
  HostsReadingTestDnsConfigService::HostsParserFactory GetFactory();

  MOCK_METHOD(bool, ParseHosts, (DnsHosts*), (const, override));

 private:
  class Delegator : public DnsHostsParser {
   public:
    explicit Delegator(MockHostsParserFactory* factory) : factory_(factory) {}

    bool ParseHosts(DnsHosts* hosts) const override {
      return factory_->ParseHosts(hosts);
    }

   private:
    raw_ptr<MockHostsParserFactory> factory_;
  };
};

HostsReadingTestDnsConfigService::HostsParserFactory
MockHostsParserFactory::GetFactory() {
  return base::BindLambdaForTesting(
      [this]() -> std::unique_ptr<DnsHostsParser> {
        return std::make_unique<Delegator>(this);
      });
}

DnsHosts::value_type CreateHostsEntry(base::StringPiece name,
                                      AddressFamily family,
                                      IPAddress address) {
  DnsHostsKey key = std::make_pair(std::string(name), family);
  return std::make_pair(std::move(key), address);
}

}  // namespace

TEST_F(DnsConfigServiceTest, FirstConfig) {
  DnsConfig config = MakeConfig(1);

  service_->OnConfigRead(config);
  // No hosts yet, so no config.
  EXPECT_TRUE(last_config_.Equals(DnsConfig()));

  service_->OnHostsRead(config.hosts);
  EXPECT_TRUE(last_config_.Equals(config));
}

TEST_F(DnsConfigServiceTest, Timeout) {
  DnsConfig config = MakeConfig(1);
  config.hosts = MakeHosts(1);
  ASSERT_TRUE(config.IsValid());

  service_->OnConfigRead(config);
  service_->OnHostsRead(config.hosts);
  EXPECT_FALSE(last_config_.Equals(DnsConfig()));
  EXPECT_TRUE(last_config_.Equals(config));

  service_->InvalidateConfig();
  WaitForInvalidationTimeout();
  EXPECT_FALSE(last_config_.Equals(config));
  EXPECT_TRUE(last_config_.Equals(DnsConfig()));

  service_->OnConfigRead(config);
  EXPECT_FALSE(last_config_.Equals(DnsConfig()));
  EXPECT_TRUE(last_config_.Equals(config));

  service_->InvalidateHosts();
  WaitForInvalidationTimeout();
  EXPECT_FALSE(last_config_.Equals(config));
  EXPECT_TRUE(last_config_.Equals(DnsConfig()));

  DnsConfig bad_config = last_config_ = MakeConfig(0xBAD);
  service_->InvalidateConfig();
  ValidateNoNotification();
  EXPECT_TRUE(last_config_.Equals(bad_config)) << "Unexpected change";

  last_config_ = DnsConfig();
  service_->OnConfigRead(config);
  service_->OnHostsRead(config.hosts);
  EXPECT_FALSE(last_config_.Equals(DnsConfig()));
  EXPECT_TRUE(last_config_.Equals(config));
}

TEST_F(DnsConfigServiceTest, SameConfig) {
  DnsConfig config = MakeConfig(1);
  config.hosts = MakeHosts(1);

  service_->OnConfigRead(config);
  service_->OnHostsRead(config.hosts);
  EXPECT_FALSE(last_config_.Equals(DnsConfig()));
  EXPECT_TRUE(last_config_.Equals(config));

  last_config_ = DnsConfig();
  service_->OnConfigRead(config);
  EXPECT_TRUE(last_config_.Equals(DnsConfig())) << "Unexpected change";

  service_->OnHostsRead(config.hosts);
  EXPECT_TRUE(last_config_.Equals(DnsConfig())) << "Unexpected change";
}

TEST_F(DnsConfigServiceTest, DifferentConfig) {
  DnsConfig config1 = MakeConfig(1);
  DnsConfig config2 = MakeConfig(2);
  DnsConfig config3 = MakeConfig(1);
  config1.hosts = MakeHosts(1);
  config2.hosts = MakeHosts(1);
  config3.hosts = MakeHosts(2);
  ASSERT_TRUE(config1.EqualsIgnoreHosts(config3));
  ASSERT_FALSE(config1.Equals(config2));
  ASSERT_FALSE(config1.Equals(config3));
  ASSERT_FALSE(config2.Equals(config3));

  service_->OnConfigRead(config1);
  service_->OnHostsRead(config1.hosts);
  EXPECT_FALSE(last_config_.Equals(DnsConfig()));
  EXPECT_TRUE(last_config_.Equals(config1));

  // It doesn't matter for this tests, but increases coverage.
  service_->InvalidateConfig();
  service_->InvalidateHosts();

  service_->OnConfigRead(config2);
  EXPECT_TRUE(last_config_.Equals(config1)) << "Unexpected change";
  service_->OnHostsRead(config2.hosts);  // Not an actual change.
  EXPECT_FALSE(last_config_.Equals(config1));
  EXPECT_TRUE(last_config_.Equals(config2));

  service_->OnConfigRead(config3);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config3));
  service_->OnHostsRead(config3.hosts);
  EXPECT_FALSE(last_config_.Equals(config2));
  EXPECT_TRUE(last_config_.Equals(config3));
}

TEST_F(DnsConfigServiceTest, WatchFailure) {
  DnsConfig config1 = MakeConfig(1);
  DnsConfig config2 = MakeConfig(2);
  config1.hosts = MakeHosts(1);
  config2.hosts = MakeHosts(2);

  service_->OnConfigRead(config1);
  service_->OnHostsRead(config1.hosts);
  EXPECT_FALSE(last_config_.Equals(DnsConfig()));
  EXPECT_TRUE(last_config_.Equals(config1));

  // Simulate watch failure.
  service_->set_watch_failed_for_testing(true);
  service_->InvalidateConfig();
  WaitForInvalidationTimeout();
  EXPECT_FALSE(last_config_.Equals(config1));
  EXPECT_TRUE(last_config_.Equals(DnsConfig()));

  DnsConfig bad_config = last_config_ = MakeConfig(0xBAD);
  // Actual change in config, so expect an update, but it should be empty.
  service_->OnConfigRead(config1);
  EXPECT_FALSE(last_config_.Equals(bad_config));
  EXPECT_TRUE(last_config_.Equals(DnsConfig()));

  last_config_ = bad_config;
  // Actual change in config, so expect an update, but it should be empty.
  service_->InvalidateConfig();
  service_->OnConfigRead(config2);
  EXPECT_FALSE(last_config_.Equals(bad_config));
  EXPECT_TRUE(last_config_.Equals(DnsConfig()));

  last_config_ = bad_config;
  // No change, so no update.
  service_->InvalidateConfig();
  service_->OnConfigRead(config2);
  EXPECT_TRUE(last_config_.Equals(bad_config));
}

TEST_F(DnsConfigServiceTest, HostsReadFailure) {
  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillRepeatedly(DoAll(SetArgPointee<0>(DnsHosts()), Return(false)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  service->OnConfigRead(MakeConfig(1));
  // No successfully read hosts, so no config result.
  EXPECT_EQ(last_config_, DnsConfig());

  // No change from retriggering read.
  service->TriggerHostsChangeNotification(/*success=*/true);
  ValidateNoNotification();
  EXPECT_EQ(last_config_, DnsConfig());
}

TEST_F(DnsConfigServiceTest, ReadEmptyHosts) {
  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillRepeatedly(DoAll(SetArgPointee<0>(DnsHosts()), Return(true)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  // Expect immediate result on reading config because HOSTS should already have
  // been read on initting watch in `SetUpService()`.
  DnsConfig config = MakeConfig(1);
  service->OnConfigRead(config);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, DnsHosts());

  // No change from retriggering read.
  service->TriggerHostsChangeNotification(/*success=*/true);
  ValidateNoNotification();
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, DnsHosts());
}

TEST_F(DnsConfigServiceTest, ReadSingleHosts) {
  DnsHosts hosts = {
      CreateHostsEntry("name", ADDRESS_FAMILY_IPV4, {IPAddress(1, 2, 3, 4)})};

  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillRepeatedly(DoAll(SetArgPointee<0>(hosts), Return(true)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  // Expect immediate result on reading config because HOSTS should already have
  // been read on initting watch in `SetUpService()`.
  DnsConfig config = MakeConfig(1);
  service->OnConfigRead(config);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, hosts);

  // No change from retriggering read.
  service->TriggerHostsChangeNotification(/*success=*/true);
  ValidateNoNotification();
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, hosts);
}

TEST_F(DnsConfigServiceTest, ReadMultipleHosts) {
  DnsHosts hosts = {
      CreateHostsEntry("name1", ADDRESS_FAMILY_IPV4, {IPAddress(1, 2, 3, 4)}),
      CreateHostsEntry("name2", ADDRESS_FAMILY_IPV4, {IPAddress(1, 2, 3, 5)}),
      CreateHostsEntry(
          "name1", ADDRESS_FAMILY_IPV6,
          {IPAddress(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15)})};

  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillRepeatedly(DoAll(SetArgPointee<0>(hosts), Return(true)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  // Expect immediate result on reading config because HOSTS should already have
  // been read on initting watch in `SetUpService()`.
  DnsConfig config = MakeConfig(1);
  service->OnConfigRead(config);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, hosts);

  // No change from retriggering read.
  service->TriggerHostsChangeNotification(/*success=*/true);
  ValidateNoNotification();
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, hosts);
}

TEST_F(DnsConfigServiceTest, HostsReadSubsequentFailure) {
  DnsHosts hosts = {
      CreateHostsEntry("name", ADDRESS_FAMILY_IPV4, {IPAddress(1, 2, 3, 4)})};

  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillOnce(DoAll(SetArgPointee<0>(hosts), Return(true)))
      .WillOnce(DoAll(SetArgPointee<0>(DnsHosts()), Return(false)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  // Expect immediate result on reading config because HOSTS should already have
  // been read on initting watch in `SetUpService()`.
  DnsConfig config = MakeConfig(1);
  service->OnConfigRead(config);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, hosts);

  // Config cleared after subsequent read.
  service->TriggerHostsChangeNotification(/*success=*/true);
  WaitForInvalidationTimeout();
  EXPECT_EQ(last_config_, DnsConfig());
}

TEST_F(DnsConfigServiceTest, HostsReadSubsequentSuccess) {
  DnsHosts hosts = {
      CreateHostsEntry("name", ADDRESS_FAMILY_IPV4, {IPAddress(1, 2, 3, 4)})};

  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillOnce(DoAll(SetArgPointee<0>(DnsHosts()), Return(false)))
      .WillOnce(DoAll(SetArgPointee<0>(hosts), Return(true)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  DnsConfig config = MakeConfig(1);
  service->OnConfigRead(config);
  // No successfully read hosts, so no config result.
  EXPECT_EQ(last_config_, DnsConfig());

  // Expect success after subsequent read.
  service->TriggerHostsChangeNotification(/*success=*/true);
  WaitForConfig();
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, hosts);
}

TEST_F(DnsConfigServiceTest, ConfigReadDuringHostsReRead) {
  DnsHosts hosts = {
      CreateHostsEntry("name", ADDRESS_FAMILY_IPV4, {IPAddress(1, 2, 3, 4)})};

  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillRepeatedly(DoAll(SetArgPointee<0>(hosts), Return(true)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  // Expect immediate result on reading config because HOSTS should already have
  // been read on initting watch in `SetUpService()`.
  DnsConfig config1 = MakeConfig(1);
  service->OnConfigRead(config1);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config1));
  EXPECT_EQ(last_config_.hosts, hosts);

  // Trigger HOSTS read, and expect no new-config notification yet.
  service->TriggerHostsChangeNotification(/*success=*/true);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config1));
  EXPECT_EQ(last_config_.hosts, hosts);

  // Simulate completion of a Config read. Expect no new-config notification
  // while HOSTS read still in progress.
  DnsConfig config2 = MakeConfig(2);
  service->OnConfigRead(config2);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config1));
  EXPECT_EQ(last_config_.hosts, hosts);

  // Expect new config on completion of HOSTS read.
  WaitForConfig();
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config2));
  EXPECT_EQ(last_config_.hosts, hosts);
}

TEST_F(DnsConfigServiceTest, HostsWatcherFailure) {
  DnsHosts hosts = {
      CreateHostsEntry("name", ADDRESS_FAMILY_IPV4, {IPAddress(1, 2, 3, 4)})};

  MockHostsParserFactory parser;
  EXPECT_CALL(parser, ParseHosts(_))
      .WillOnce(DoAll(SetArgPointee<0>(hosts), Return(true)));

  auto service =
      std::make_unique<HostsReadingTestDnsConfigService>(parser.GetFactory());
  SetUpService(*service);

  // Expect immediate result on reading config because HOSTS should already have
  // been read on initting watch in `SetUpService()`.
  DnsConfig config = MakeConfig(1);
  service->OnConfigRead(config);
  EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config));
  EXPECT_EQ(last_config_.hosts, hosts);

  // Simulate watcher failure.
  service->TriggerHostsChangeNotification(/*success=*/false);
  WaitForInvalidationTimeout();
  EXPECT_EQ(last_config_, DnsConfig());
}

}  // namespace net