• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/dns/host_resolver_manager.h"
6 
7 #include <iterator>
8 #include <limits>
9 #include <string>
10 #include <tuple>
11 #include <utility>
12 #include <vector>
13 
14 #include "base/auto_reset.h"
15 #include "base/containers/contains.h"
16 #include "base/functional/bind.h"
17 #include "base/functional/callback_helpers.h"
18 #include "base/location.h"
19 #include "base/memory/raw_ptr.h"
20 #include "base/memory/ref_counted.h"
21 #include "base/numerics/safe_conversions.h"
22 #include "base/rand_util.h"
23 #include "base/ranges/algorithm.h"
24 #include "base/run_loop.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/synchronization/condition_variable.h"
29 #include "base/synchronization/lock.h"
30 #include "base/task/sequenced_task_runner.h"
31 #include "base/task/single_thread_task_runner.h"
32 #include "base/task/thread_pool/thread_pool_instance.h"
33 #include "base/test/bind.h"
34 #include "base/test/metrics/histogram_tester.h"
35 #include "base/test/mock_callback.h"
36 #include "base/test/scoped_feature_list.h"
37 #include "base/test/simple_test_clock.h"
38 #include "base/test/test_mock_time_task_runner.h"
39 #include "base/test/test_timeouts.h"
40 #include "base/threading/thread_restrictions.h"
41 #include "base/time/time.h"
42 #include "base/timer/mock_timer.h"
43 #include "base/values.h"
44 #include "build/build_config.h"
45 #include "net/base/address_family.h"
46 #include "net/base/address_list.h"
47 #include "net/base/connection_endpoint_metadata_test_util.h"
48 #include "net/base/features.h"
49 #include "net/base/host_port_pair.h"
50 #include "net/base/ip_address.h"
51 #include "net/base/ip_endpoint.h"
52 #include "net/base/mock_network_change_notifier.h"
53 #include "net/base/net_errors.h"
54 #include "net/base/network_anonymization_key.h"
55 #include "net/base/schemeful_site.h"
56 #include "net/dns/dns_client.h"
57 #include "net/dns/dns_config.h"
58 #include "net/dns/dns_test_util.h"
59 #include "net/dns/dns_util.h"
60 #include "net/dns/host_resolver.h"
61 #include "net/dns/host_resolver_results_test_util.h"
62 #include "net/dns/host_resolver_system_task.h"
63 #include "net/dns/mock_host_resolver.h"
64 #include "net/dns/mock_mdns_client.h"
65 #include "net/dns/mock_mdns_socket_factory.h"
66 #include "net/dns/public/dns_config_overrides.h"
67 #include "net/dns/public/dns_over_https_config.h"
68 #include "net/dns/public/dns_protocol.h"
69 #include "net/dns/public/dns_query_type.h"
70 #include "net/dns/public/doh_provider_entry.h"
71 #include "net/dns/public/mdns_listener_update_type.h"
72 #include "net/dns/public/resolve_error_info.h"
73 #include "net/dns/public/secure_dns_mode.h"
74 #include "net/dns/public/secure_dns_policy.h"
75 #include "net/dns/resolve_context.h"
76 #include "net/dns/test_dns_config_service.h"
77 #include "net/log/net_log_event_type.h"
78 #include "net/log/net_log_source_type.h"
79 #include "net/log/net_log_with_source.h"
80 #include "net/log/test_net_log.h"
81 #include "net/log/test_net_log_util.h"
82 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
83 #include "net/socket/next_proto.h"
84 #include "net/socket/socket_test_util.h"
85 #include "net/test/gtest_util.h"
86 #include "net/test/test_with_task_environment.h"
87 #include "net/url_request/url_request_context.h"
88 #include "net/url_request/url_request_context_builder.h"
89 #include "net/url_request/url_request_test_util.h"
90 #include "testing/gmock/include/gmock/gmock.h"
91 #include "testing/gtest/include/gtest/gtest.h"
92 #include "url/gurl.h"
93 #include "url/scheme_host_port.h"
94 #include "url/url_constants.h"
95 
96 #if BUILDFLAG(ENABLE_MDNS)
97 #include "net/dns/mdns_client_impl.h"
98 #endif  // BUILDFLAG(ENABLE_MDNS)
99 
100 using net::test::IsError;
101 using net::test::IsOk;
102 using ::testing::_;
103 using ::testing::AllOf;
104 using ::testing::Between;
105 using ::testing::ByMove;
106 using ::testing::Eq;
107 using ::testing::IsEmpty;
108 using ::testing::Optional;
109 using ::testing::Pair;
110 using ::testing::Property;
111 using ::testing::Return;
112 using ::testing::UnorderedElementsAre;
113 
114 namespace net {
115 
116 namespace {
117 
118 const size_t kMaxJobs = 10u;
119 const size_t kMaxRetryAttempts = 4u;
120 
DefaultParams(scoped_refptr<HostResolverProc> resolver_proc)121 HostResolverSystemTask::Params DefaultParams(
122     scoped_refptr<HostResolverProc> resolver_proc) {
123   return HostResolverSystemTask::Params(std::move(resolver_proc),
124                                         kMaxRetryAttempts);
125 }
126 
127 // A HostResolverProc that pushes each host mapped into a list and allows
128 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
129 // it never calls SystemHostResolverCall. By default resolves all hostnames to
130 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
131 class MockHostResolverProc : public HostResolverProc {
132  public:
133   struct ResolveKey {
ResolveKeynet::__anonba1a09560111::MockHostResolverProc::ResolveKey134     ResolveKey(const std::string& hostname,
135                AddressFamily address_family,
136                HostResolverFlags flags)
137         : hostname(hostname), address_family(address_family), flags(flags) {}
operator <net::__anonba1a09560111::MockHostResolverProc::ResolveKey138     bool operator<(const ResolveKey& other) const {
139       return std::tie(address_family, hostname, flags) <
140              std::tie(other.address_family, other.hostname, other.flags);
141     }
142     std::string hostname;
143     AddressFamily address_family;
144     HostResolverFlags flags;
145   };
146 
147   typedef std::vector<ResolveKey> CaptureList;
148 
MockHostResolverProc()149   MockHostResolverProc()
150       : HostResolverProc(nullptr),
151         requests_waiting_(&lock_),
152         slots_available_(&lock_) {}
153 
154   MockHostResolverProc(const MockHostResolverProc&) = delete;
155   MockHostResolverProc& operator=(const MockHostResolverProc&) = delete;
156 
157   // Waits until |count| calls to |Resolve| are blocked. Returns false when
158   // timed out.
WaitFor(unsigned count)159   bool WaitFor(unsigned count) {
160     base::AutoLock lock(lock_);
161     base::Time start_time = base::Time::Now();
162     while (num_requests_waiting_ < count) {
163       requests_waiting_.TimedWait(TestTimeouts::action_timeout());
164       if (base::Time::Now() > start_time + TestTimeouts::action_timeout())
165         return false;
166     }
167     return true;
168   }
169 
170   // Signals |count| waiting calls to |Resolve|. First come first served.
SignalMultiple(unsigned count)171   void SignalMultiple(unsigned count) {
172     base::AutoLock lock(lock_);
173     num_slots_available_ += count;
174     slots_available_.Broadcast();
175   }
176 
177   // Signals all waiting calls to |Resolve|. Beware of races.
SignalAll()178   void SignalAll() {
179     base::AutoLock lock(lock_);
180     num_slots_available_ = num_requests_waiting_;
181     slots_available_.Broadcast();
182   }
183 
AddRule(const std::string & hostname,AddressFamily family,const AddressList & result,HostResolverFlags flags=0)184   void AddRule(const std::string& hostname,
185                AddressFamily family,
186                const AddressList& result,
187                HostResolverFlags flags = 0) {
188     base::AutoLock lock(lock_);
189     rules_[ResolveKey(hostname, family, flags)] = result;
190   }
191 
AddRule(const std::string & hostname,AddressFamily family,const std::string & ip_list,HostResolverFlags flags=0,const std::string & canonical_name="")192   void AddRule(const std::string& hostname,
193                AddressFamily family,
194                const std::string& ip_list,
195                HostResolverFlags flags = 0,
196                const std::string& canonical_name = "") {
197     AddressList result;
198     std::vector<std::string> dns_aliases;
199     if (canonical_name != "")
200       dns_aliases = {canonical_name};
201     int rv = ParseAddressList(ip_list, &result.endpoints());
202     result.SetDnsAliases(dns_aliases);
203     DCHECK_EQ(OK, rv);
204     AddRule(hostname, family, result, flags);
205   }
206 
AddRuleForAllFamilies(const std::string & hostname,const std::string & ip_list,HostResolverFlags flags=0,const std::string & canonical_name="")207   void AddRuleForAllFamilies(const std::string& hostname,
208                              const std::string& ip_list,
209                              HostResolverFlags flags = 0,
210                              const std::string& canonical_name = "") {
211     AddressList result;
212     std::vector<std::string> dns_aliases;
213     if (canonical_name != "")
214       dns_aliases = {canonical_name};
215     int rv = ParseAddressList(ip_list, &result.endpoints());
216     result.SetDnsAliases(dns_aliases);
217     DCHECK_EQ(OK, rv);
218     AddRule(hostname, ADDRESS_FAMILY_UNSPECIFIED, result, flags);
219     AddRule(hostname, ADDRESS_FAMILY_IPV4, result, flags);
220     AddRule(hostname, ADDRESS_FAMILY_IPV6, result, flags);
221   }
222 
Resolve(const std::string & hostname,AddressFamily address_family,HostResolverFlags host_resolver_flags,AddressList * addrlist,int * os_error)223   int Resolve(const std::string& hostname,
224               AddressFamily address_family,
225               HostResolverFlags host_resolver_flags,
226               AddressList* addrlist,
227               int* os_error) override {
228     base::AutoLock lock(lock_);
229     capture_list_.emplace_back(hostname, address_family, host_resolver_flags);
230     ++num_requests_waiting_;
231     requests_waiting_.Broadcast();
232     {
233       base::ScopedAllowBaseSyncPrimitivesForTesting
234           scoped_allow_base_sync_primitives;
235       while (!num_slots_available_)
236         slots_available_.Wait();
237     }
238     DCHECK_GT(num_requests_waiting_, 0u);
239     --num_slots_available_;
240     --num_requests_waiting_;
241     if (rules_.empty()) {
242       int rv = ParseAddressList("127.0.0.1", &addrlist->endpoints());
243       DCHECK_EQ(OK, rv);
244       return OK;
245     }
246     ResolveKey key(hostname, address_family, host_resolver_flags);
247     if (rules_.count(key) == 0)
248       return ERR_NAME_NOT_RESOLVED;
249     *addrlist = rules_[key];
250     return OK;
251   }
252 
GetCaptureList() const253   CaptureList GetCaptureList() const {
254     CaptureList copy;
255     {
256       base::AutoLock lock(lock_);
257       copy = capture_list_;
258     }
259     return copy;
260   }
261 
ClearCaptureList()262   void ClearCaptureList() {
263     base::AutoLock lock(lock_);
264     capture_list_.clear();
265   }
266 
HasBlockedRequests() const267   bool HasBlockedRequests() const {
268     base::AutoLock lock(lock_);
269     return num_requests_waiting_ > num_slots_available_;
270   }
271 
272  protected:
273   ~MockHostResolverProc() override = default;
274 
275  private:
276   mutable base::Lock lock_;
277   std::map<ResolveKey, AddressList> rules_;
278   CaptureList capture_list_;
279   unsigned num_requests_waiting_ = 0;
280   unsigned num_slots_available_ = 0;
281   base::ConditionVariable requests_waiting_;
282   base::ConditionVariable slots_available_;
283 };
284 
285 class ResolveHostResponseHelper {
286  public:
287   using Callback =
288       base::OnceCallback<void(CompletionOnceCallback completion_callback,
289                               int error)>;
290 
291   ResolveHostResponseHelper() = default;
ResolveHostResponseHelper(std::unique_ptr<HostResolver::ResolveHostRequest> request)292   explicit ResolveHostResponseHelper(
293       std::unique_ptr<HostResolver::ResolveHostRequest> request)
294       : request_(std::move(request)) {
295     top_level_result_error_ = request_->Start(base::BindOnce(
296         &ResolveHostResponseHelper::OnComplete, base::Unretained(this)));
297   }
ResolveHostResponseHelper(std::unique_ptr<HostResolver::ResolveHostRequest> request,Callback custom_callback)298   ResolveHostResponseHelper(
299       std::unique_ptr<HostResolver::ResolveHostRequest> request,
300       Callback custom_callback)
301       : request_(std::move(request)) {
302     top_level_result_error_ = request_->Start(
303         base::BindOnce(std::move(custom_callback),
304                        base::BindOnce(&ResolveHostResponseHelper::OnComplete,
305                                       base::Unretained(this))));
306   }
307 
308   ResolveHostResponseHelper(const ResolveHostResponseHelper&) = delete;
309   ResolveHostResponseHelper& operator=(const ResolveHostResponseHelper&) =
310       delete;
311 
complete() const312   bool complete() const { return top_level_result_error_ != ERR_IO_PENDING; }
313 
top_level_result_error()314   int top_level_result_error() {
315     WaitForCompletion();
316     return top_level_result_error_;
317   }
318 
result_error()319   int result_error() {
320     WaitForCompletion();
321     return request_->GetResolveErrorInfo().error;
322   }
323 
request()324   HostResolver::ResolveHostRequest* request() { return request_.get(); }
325 
CancelRequest()326   void CancelRequest() {
327     DCHECK(request_);
328     DCHECK(!complete());
329 
330     request_ = nullptr;
331   }
332 
OnComplete(int error)333   void OnComplete(int error) {
334     DCHECK(!complete());
335     top_level_result_error_ = error;
336 
337     run_loop_.Quit();
338   }
339 
340  private:
WaitForCompletion()341   void WaitForCompletion() {
342     DCHECK(request_);
343     if (complete()) {
344       return;
345     }
346     run_loop_.Run();
347     DCHECK(complete());
348   }
349 
350   std::unique_ptr<HostResolver::ResolveHostRequest> request_;
351   int top_level_result_error_ = ERR_IO_PENDING;
352   base::RunLoop run_loop_;
353 };
354 
355 // Using LookupAttemptHostResolverProc simulate very long lookups, and control
356 // which attempt resolves the host.
357 class LookupAttemptHostResolverProc : public HostResolverProc {
358  public:
LookupAttemptHostResolverProc(HostResolverProc * previous,int attempt_number_to_resolve,int total_attempts)359   LookupAttemptHostResolverProc(HostResolverProc* previous,
360                                 int attempt_number_to_resolve,
361                                 int total_attempts)
362       : HostResolverProc(previous),
363         attempt_number_to_resolve_(attempt_number_to_resolve),
364         total_attempts_(total_attempts),
365         all_done_(&lock_),
366         blocked_attempt_signal_(&lock_) {}
367 
368   // Test harness will wait for all attempts to finish before checking the
369   // results.
WaitForAllAttemptsToFinish()370   void WaitForAllAttemptsToFinish() {
371     base::AutoLock auto_lock(lock_);
372     while (total_attempts_resolved_ != total_attempts_) {
373       all_done_.Wait();
374     }
375   }
376 
WaitForNAttemptsToBeBlocked(int n)377   void WaitForNAttemptsToBeBlocked(int n) {
378     base::AutoLock auto_lock(lock_);
379     while (num_attempts_waiting_ < n) {
380       blocked_attempt_signal_.Wait();
381     }
382   }
383 
384   // All attempts will wait for an attempt to resolve the host.
WaitForAnAttemptToComplete()385   void WaitForAnAttemptToComplete() {
386     {
387       base::AutoLock auto_lock(lock_);
388       base::ScopedAllowBaseSyncPrimitivesForTesting
389           scoped_allow_base_sync_primitives;
390       while (resolved_attempt_number_ == 0)
391         all_done_.Wait();
392     }
393     all_done_.Broadcast();  // Tell all waiting attempts to proceed.
394   }
395 
396   // Returns the number of attempts that have finished the Resolve() method.
GetTotalAttemptsResolved()397   int GetTotalAttemptsResolved() {
398     base::AutoLock auto_lock(lock_);
399     return total_attempts_resolved_;
400   }
401 
402   // Sets the resolved attempt number and unblocks waiting
403   // attempts.
SetResolvedAttemptNumber(int n)404   void SetResolvedAttemptNumber(int n) {
405     base::AutoLock auto_lock(lock_);
406     EXPECT_EQ(0, resolved_attempt_number_);
407     resolved_attempt_number_ = n;
408     all_done_.Broadcast();
409   }
410 
411   // HostResolverProc methods.
Resolve(const std::string & host,AddressFamily address_family,HostResolverFlags host_resolver_flags,AddressList * addrlist,int * os_error)412   int Resolve(const std::string& host,
413               AddressFamily address_family,
414               HostResolverFlags host_resolver_flags,
415               AddressList* addrlist,
416               int* os_error) override {
417     bool wait_for_right_attempt_to_complete = true;
418     {
419       base::AutoLock auto_lock(lock_);
420       ++current_attempt_number_;
421       ++num_attempts_waiting_;
422       if (current_attempt_number_ == attempt_number_to_resolve_) {
423         resolved_attempt_number_ = current_attempt_number_;
424         wait_for_right_attempt_to_complete = false;
425       }
426     }
427 
428     blocked_attempt_signal_.Broadcast();
429 
430     if (wait_for_right_attempt_to_complete)
431       // Wait for the attempt_number_to_resolve_ attempt to resolve.
432       WaitForAnAttemptToComplete();
433 
434     int result = ResolveUsingPrevious(host, address_family, host_resolver_flags,
435                                       addrlist, os_error);
436 
437     {
438       base::AutoLock auto_lock(lock_);
439       ++total_attempts_resolved_;
440       --num_attempts_waiting_;
441     }
442 
443     all_done_.Broadcast();  // Tell all attempts to proceed.
444 
445     // Since any negative number is considered a network error, with -1 having
446     // special meaning (ERR_IO_PENDING). We could return the attempt that has
447     // resolved the host as a negative number. For example, if attempt number 3
448     // resolves the host, then this method returns -4.
449     if (result == OK)
450       return -1 - resolved_attempt_number_;
451     else
452       return result;
453   }
454 
455  protected:
456   ~LookupAttemptHostResolverProc() override = default;
457 
458  private:
459   int attempt_number_to_resolve_;
460   int current_attempt_number_ = 0;  // Incremented whenever Resolve is called.
461   int total_attempts_;
462   int total_attempts_resolved_ = 0;
463   int resolved_attempt_number_ = 0;
464   int num_attempts_waiting_ = 0;
465 
466   // All attempts wait for right attempt to be resolve.
467   base::Lock lock_;
468   base::ConditionVariable all_done_;
469   base::ConditionVariable blocked_attempt_signal_;
470 };
471 
472 // TestHostResolverManager's sole purpose is to mock the IPv6 reachability test.
473 // By default, this pretends that IPv6 is globally reachable.
474 // This class is necessary so unit tests run the same on dual-stack machines as
475 // well as IPv4 only machines.
476 class TestHostResolverManager : public HostResolverManager {
477  public:
TestHostResolverManager(const HostResolver::ManagerOptions & options,SystemDnsConfigChangeNotifier * notifier,NetLog * net_log,bool ipv6_reachable=true,bool ipv4_reachable=true,bool is_async=false)478   TestHostResolverManager(const HostResolver::ManagerOptions& options,
479                           SystemDnsConfigChangeNotifier* notifier,
480                           NetLog* net_log,
481                           bool ipv6_reachable = true,
482                           bool ipv4_reachable = true,
483                           bool is_async = false)
484       : HostResolverManager(options, notifier, net_log),
485         ipv6_reachable_(ipv6_reachable),
486         ipv4_reachable_(ipv4_reachable),
487         is_async_(is_async) {}
488 
489   ~TestHostResolverManager() override = default;
490 
491  private:
492   const bool ipv6_reachable_;
493   const bool ipv4_reachable_;
494   const bool is_async_;
495 
StartGloballyReachableCheck(const IPAddress & dest,const NetLogWithSource & net_log,CompletionOnceCallback callback)496   int StartGloballyReachableCheck(const IPAddress& dest,
497                                   const NetLogWithSource& net_log,
498                                   CompletionOnceCallback callback) override {
499     int rv = OK;
500     if (dest.IsIPv6()) {
501       rv = ipv6_reachable_ ? OK : ERR_FAILED;
502     } else {
503       rv = ipv4_reachable_ ? OK : ERR_FAILED;
504     }
505     if (is_async_) {
506       base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
507           FROM_HERE, base::BindOnce(std::move(callback), rv));
508       return ERR_IO_PENDING;
509     }
510     return rv;
511   }
512 };
513 
HasAddress(const IPAddress & search_address,const std::vector<IPEndPoint> & addresses)514 bool HasAddress(const IPAddress& search_address,
515                 const std::vector<IPEndPoint>& addresses) {
516   for (const auto& address : addresses) {
517     if (search_address == address.address())
518       return true;
519   }
520   return false;
521 }
522 
TestBothLoopbackIPs(const std::string & host)523 void TestBothLoopbackIPs(const std::string& host) {
524   std::vector<IPEndPoint> addresses;
525   EXPECT_TRUE(ResolveLocalHostname(host, &addresses));
526   EXPECT_EQ(2u, addresses.size());
527   EXPECT_TRUE(HasAddress(IPAddress::IPv4Localhost(), addresses));
528   EXPECT_TRUE(HasAddress(IPAddress::IPv6Localhost(), addresses));
529 }
530 
531 // Returns the DoH provider entry in `DohProviderEntry::GetList()` that matches
532 // `provider`. Crashes if there is no matching entry.
GetDohProviderEntryForTesting(base::StringPiece provider)533 const DohProviderEntry& GetDohProviderEntryForTesting(
534     base::StringPiece provider) {
535   auto provider_list = DohProviderEntry::GetList();
536   auto it =
537       base::ranges::find(provider_list, provider, &DohProviderEntry::provider);
538   CHECK(it != provider_list.end());
539   return **it;
540 }
541 
542 }  // namespace
543 
544 class HostResolverManagerTest : public TestWithTaskEnvironment {
545  public:
546   static const int kDefaultPort = 80;
547 
HostResolverManagerTest(base::test::TaskEnvironment::TimeSource time_source=base::test::TaskEnvironment::TimeSource::SYSTEM_TIME)548   explicit HostResolverManagerTest(
549       base::test::TaskEnvironment::TimeSource time_source =
550           base::test::TaskEnvironment::TimeSource::SYSTEM_TIME)
551       : TestWithTaskEnvironment(time_source),
552         proc_(base::MakeRefCounted<MockHostResolverProc>()) {}
553 
CreateResolver(bool check_ipv6_on_wifi=true)554   void CreateResolver(bool check_ipv6_on_wifi = true) {
555     CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
556                                       true /* ipv6_reachable */,
557                                       check_ipv6_on_wifi);
558   }
559 
DestroyResolver()560   void DestroyResolver() {
561     if (!resolver_)
562       return;
563 
564     resolver_->DeregisterResolveContext(resolve_context_.get());
565     resolver_ = nullptr;
566   }
567 
568   // This HostResolverManager will only allow 1 outstanding resolve at a time
569   // and perform no retries.
CreateSerialResolver(bool check_ipv6_on_wifi=true,bool ipv6_reachable=true,bool is_async=false)570   void CreateSerialResolver(bool check_ipv6_on_wifi = true,
571                             bool ipv6_reachable = true,
572                             bool is_async = false) {
573     HostResolverSystemTask::Params params = DefaultParams(proc_);
574     params.max_retry_attempts = 0u;
575     CreateResolverWithLimitsAndParams(1u, params, ipv6_reachable,
576                                       check_ipv6_on_wifi, is_async);
577   }
578 
579   void StaleAllowedFromIpTest(bool is_async);
580   void LocalOnlyFromIpTest(bool is_async);
581   void ChangePriorityTest(bool is_async);
582   void AbortOnlyExistingRequestsOnIPAddressChangeTest(bool is_async);
583   void FlushCacheOnIPAddressChangeTest(bool is_async);
584   void AbortOnIPAddressChangedTest(bool is_async);
585   void NumericIPv6AddressTest(bool is_async);
586   void NumericIPv6AddressWithSchemeTest(bool is_async);
587   void LocalhostIPV4IPV6LookupTest(bool is_async);
588   void IPv4AddressLiteralInIPv6OnlyNetworkTest(bool is_async);
589   void IPv4AddressLiteralInIPv6OnlyNetworkPort443Test(bool is_async);
590   void IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Test(bool is_async);
591   void IPv4AddressLiteralInIPv6OnlyNetworkBadAddressTest(bool is_async);
592 
593  protected:
594   // testing::Test implementation:
SetUp()595   void SetUp() override {
596     request_context_ = CreateTestURLRequestContextBuilder()->Build();
597     resolve_context_ = std::make_unique<ResolveContext>(
598         request_context_.get(), true /* enable_caching */);
599     CreateResolver();
600   }
601 
TearDown()602   void TearDown() override {
603     if (resolver_) {
604       EXPECT_EQ(0u, resolver_->num_running_dispatcher_jobs_for_tests());
605     }
606     DestroyResolver();
607     EXPECT_FALSE(proc_->HasBlockedRequests());
608   }
609 
CreateResolverWithLimitsAndParams(size_t max_concurrent_resolves,const HostResolverSystemTask::Params & params,bool ipv6_reachable,bool check_ipv6_on_wifi,bool is_async=false)610   void CreateResolverWithLimitsAndParams(
611       size_t max_concurrent_resolves,
612       const HostResolverSystemTask::Params& params,
613       bool ipv6_reachable,
614       bool check_ipv6_on_wifi,
615       bool is_async = false) {
616     HostResolver::ManagerOptions options = DefaultOptions();
617     options.max_concurrent_resolves = max_concurrent_resolves;
618     options.check_ipv6_on_wifi = check_ipv6_on_wifi;
619 
620     CreateResolverWithOptionsAndParams(std::move(options), params,
621                                        ipv6_reachable, is_async);
622   }
623 
DefaultOptions()624   virtual HostResolver::ManagerOptions DefaultOptions() {
625     HostResolver::ManagerOptions options;
626     options.max_concurrent_resolves = kMaxJobs;
627     options.max_system_retry_attempts = kMaxRetryAttempts;
628     return options;
629   }
630 
CreateResolverWithOptionsAndParams(HostResolver::ManagerOptions options,const HostResolverSystemTask::Params & params,bool ipv6_reachable,bool is_async=false,bool ipv4_reachable=true)631   virtual void CreateResolverWithOptionsAndParams(
632       HostResolver::ManagerOptions options,
633       const HostResolverSystemTask::Params& params,
634       bool ipv6_reachable,
635       bool is_async = false,
636       bool ipv4_reachable = true) {
637     // Use HostResolverManagerDnsTest if enabling DNS client.
638     DCHECK(!options.insecure_dns_client_enabled);
639 
640     DestroyResolver();
641 
642     resolver_ = std::make_unique<TestHostResolverManager>(
643         options, nullptr /* notifier */, nullptr /* net_log */, ipv6_reachable,
644         ipv4_reachable, is_async);
645     resolver_->set_host_resolver_system_params_for_test(params);
646     resolver_->RegisterResolveContext(resolve_context_.get());
647   }
648 
649   // Friendship is not inherited, so use proxies to access those.
num_running_dispatcher_jobs() const650   size_t num_running_dispatcher_jobs() const {
651     DCHECK(resolver_.get());
652     return resolver_->num_running_dispatcher_jobs_for_tests();
653   }
654 
set_allow_fallback_to_systemtask(bool allow_fallback_to_systemtask)655   void set_allow_fallback_to_systemtask(bool allow_fallback_to_systemtask) {
656     DCHECK(resolver_.get());
657     resolver_->allow_fallback_to_systemtask_ = allow_fallback_to_systemtask;
658   }
659 
maximum_insecure_dns_task_failures()660   static unsigned maximum_insecure_dns_task_failures() {
661     return DnsClient::kMaxInsecureFallbackFailures;
662   }
663 
StartIPv6ReachabilityCheck(const NetLogWithSource & net_log,CompletionOnceCallback callback)664   int StartIPv6ReachabilityCheck(const NetLogWithSource& net_log,
665                                  CompletionOnceCallback callback) {
666     return resolver_->StartIPv6ReachabilityCheck(net_log, std::move(callback));
667   }
668 
GetLastIpv6ProbeResult()669   bool GetLastIpv6ProbeResult() { return resolver_->last_ipv6_probe_result_; }
670 
PopulateCache(const HostCache::Key & key,IPEndPoint endpoint)671   void PopulateCache(const HostCache::Key& key, IPEndPoint endpoint) {
672     resolver_->CacheResult(resolve_context_->host_cache(), key,
673                            HostCache::Entry(OK, {endpoint}, /*aliases=*/{},
674                                             HostCache::Entry::SOURCE_UNKNOWN),
675                            base::Seconds(1));
676   }
677 
GetCacheHit(const HostCache::Key & key)678   const std::pair<const HostCache::Key, HostCache::Entry>* GetCacheHit(
679       const HostCache::Key& key) {
680     DCHECK(resolve_context_->host_cache());
681     return resolve_context_->host_cache()->LookupStale(
682         key, base::TimeTicks(), nullptr, false /* ignore_secure */);
683   }
684 
MakeCacheStale()685   void MakeCacheStale() {
686     DCHECK(resolve_context_->host_cache());
687     resolve_context_->host_cache()->Invalidate();
688   }
689 
CreateExpected(const std::string & ip_literal,uint16_t port)690   IPEndPoint CreateExpected(const std::string& ip_literal, uint16_t port) {
691     IPAddress ip;
692     bool result = ip.AssignFromIPLiteral(ip_literal);
693     DCHECK(result);
694     return IPEndPoint(ip, port);
695   }
696 
697   scoped_refptr<MockHostResolverProc> proc_;
698   std::unique_ptr<HostResolverManager> resolver_;
699   std::unique_ptr<URLRequestContext> request_context_;
700   std::unique_ptr<ResolveContext> resolve_context_;
701 };
702 
TEST_F(HostResolverManagerTest,AsynchronousLookup)703 TEST_F(HostResolverManagerTest, AsynchronousLookup) {
704   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
705   proc_->SignalMultiple(1u);
706 
707   ResolveHostResponseHelper response(resolver_->CreateRequest(
708       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
709       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
710       resolve_context_->host_cache()));
711 
712   EXPECT_THAT(response.result_error(), IsOk());
713   EXPECT_THAT(response.top_level_result_error(), IsOk());
714   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
715               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
716   EXPECT_THAT(response.request()->GetEndpointResults(),
717               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
718                   testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
719   EXPECT_FALSE(response.request()->GetStaleInfo());
720 
721   EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
722 
723   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
724       GetCacheHit(HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
725                                  0 /* host_resolver_flags */,
726                                  HostResolverSource::ANY,
727                                  NetworkAnonymizationKey()));
728   EXPECT_TRUE(cache_result);
729 }
730 
731 // TODO(crbug.com/1206799): Confirm scheme behavior once it affects behavior.
TEST_F(HostResolverManagerTest,AsynchronousLookupWithScheme)732 TEST_F(HostResolverManagerTest, AsynchronousLookupWithScheme) {
733   proc_->AddRuleForAllFamilies("host.test", "192.168.1.42");
734   proc_->SignalMultiple(1u);
735 
736   ResolveHostResponseHelper response(resolver_->CreateRequest(
737       url::SchemeHostPort(url::kHttpScheme, "host.test", 80),
738       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
739       resolve_context_.get(), resolve_context_->host_cache()));
740 
741   EXPECT_THAT(response.result_error(), IsOk());
742   EXPECT_THAT(response.top_level_result_error(), IsOk());
743   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
744               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
745   EXPECT_THAT(response.request()->GetEndpointResults(),
746               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
747                   testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
748   EXPECT_FALSE(response.request()->GetStaleInfo());
749 
750   EXPECT_EQ("host.test", proc_->GetCaptureList()[0].hostname);
751 
752   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
753       GetCacheHit(
754           HostCache::Key(url::SchemeHostPort(url::kHttpScheme, "host.test", 80),
755                          DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
756                          HostResolverSource::ANY, NetworkAnonymizationKey()));
757   EXPECT_TRUE(cache_result);
758 }
759 
TEST_F(HostResolverManagerTest,JobsClearedOnCompletion)760 TEST_F(HostResolverManagerTest, JobsClearedOnCompletion) {
761   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
762   proc_->SignalMultiple(1u);
763 
764   ResolveHostResponseHelper response(resolver_->CreateRequest(
765       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
766       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
767       resolve_context_->host_cache()));
768   EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
769 
770   EXPECT_THAT(response.result_error(), IsOk());
771   EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
772 }
773 
TEST_F(HostResolverManagerTest,JobsClearedOnCompletion_MultipleRequests)774 TEST_F(HostResolverManagerTest, JobsClearedOnCompletion_MultipleRequests) {
775   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
776   proc_->SignalMultiple(1u);
777 
778   ResolveHostResponseHelper response1(resolver_->CreateRequest(
779       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
780       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
781       resolve_context_->host_cache()));
782   ResolveHostResponseHelper response2(resolver_->CreateRequest(
783       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
784       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
785       resolve_context_->host_cache()));
786   EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
787 
788   EXPECT_THAT(response1.result_error(), IsOk());
789   EXPECT_THAT(response2.result_error(), IsOk());
790   EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
791 }
792 
TEST_F(HostResolverManagerTest,JobsClearedOnCompletion_Failure)793 TEST_F(HostResolverManagerTest, JobsClearedOnCompletion_Failure) {
794   proc_->AddRuleForAllFamilies(std::string(),
795                                "0.0.0.1");  // Default to failures.
796   proc_->SignalMultiple(1u);
797 
798   ResolveHostResponseHelper response(resolver_->CreateRequest(
799       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
800       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
801       resolve_context_->host_cache()));
802   EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
803 
804   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
805   EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
806 }
807 
TEST_F(HostResolverManagerTest,JobsClearedOnCompletion_Abort)808 TEST_F(HostResolverManagerTest, JobsClearedOnCompletion_Abort) {
809   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
810 
811   ResolveHostResponseHelper response(resolver_->CreateRequest(
812       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
813       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
814       resolve_context_->host_cache()));
815   EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
816 
817   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
818   proc_->SignalMultiple(1u);
819 
820   EXPECT_THAT(response.result_error(), IsError(ERR_NETWORK_CHANGED));
821   EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
822 }
823 
TEST_F(HostResolverManagerTest,DnsQueryType)824 TEST_F(HostResolverManagerTest, DnsQueryType) {
825   proc_->AddRule("host", ADDRESS_FAMILY_IPV4, "192.168.1.20");
826   proc_->AddRule("host", ADDRESS_FAMILY_IPV6, "::5");
827 
828   HostResolver::ResolveHostParameters parameters;
829 
830   parameters.dns_query_type = DnsQueryType::A;
831   ResolveHostResponseHelper v4_response(resolver_->CreateRequest(
832       HostPortPair("host", 80), NetworkAnonymizationKey(), NetLogWithSource(),
833       parameters, resolve_context_.get(), resolve_context_->host_cache()));
834 
835   parameters.dns_query_type = DnsQueryType::AAAA;
836   ResolveHostResponseHelper v6_response(resolver_->CreateRequest(
837       HostPortPair("host", 80), NetworkAnonymizationKey(), NetLogWithSource(),
838       parameters, resolve_context_.get(), resolve_context_->host_cache()));
839 
840   proc_->SignalMultiple(2u);
841 
842   EXPECT_THAT(v4_response.result_error(), IsOk());
843   EXPECT_THAT(v4_response.request()->GetAddressResults()->endpoints(),
844               testing::ElementsAre(CreateExpected("192.168.1.20", 80)));
845   EXPECT_THAT(v4_response.request()->GetEndpointResults(),
846               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
847                   testing::ElementsAre(CreateExpected("192.168.1.20", 80))))));
848 
849   EXPECT_THAT(v6_response.result_error(), IsOk());
850   EXPECT_THAT(v6_response.request()->GetAddressResults()->endpoints(),
851               testing::ElementsAre(CreateExpected("::5", 80)));
852   EXPECT_THAT(v6_response.request()->GetEndpointResults(),
853               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
854                   testing::ElementsAre(CreateExpected("::5", 80))))));
855 }
856 
TEST_F(HostResolverManagerTest,DnsQueryWithoutAliases)857 TEST_F(HostResolverManagerTest, DnsQueryWithoutAliases) {
858   proc_->AddRule("host", ADDRESS_FAMILY_IPV4, "192.168.1.20");
859 
860   HostResolver::ResolveHostParameters parameters;
861 
862   parameters.dns_query_type = DnsQueryType::A;
863   ResolveHostResponseHelper response(resolver_->CreateRequest(
864       HostPortPair("host", 80), NetworkAnonymizationKey(), NetLogWithSource(),
865       parameters, resolve_context_.get(), resolve_context_->host_cache()));
866 
867   proc_->SignalMultiple(1u);
868 
869   EXPECT_THAT(response.result_error(), IsOk());
870   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
871               testing::ElementsAre(CreateExpected("192.168.1.20", 80)));
872   EXPECT_THAT(response.request()->GetEndpointResults(),
873               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
874                   testing::ElementsAre(CreateExpected("192.168.1.20", 80))))));
875   EXPECT_THAT(response.request()->GetDnsAliasResults(),
876               testing::Pointee(testing::IsEmpty()));
877 }
878 
LocalhostIPV4IPV6LookupTest(bool is_async)879 void HostResolverManagerTest::LocalhostIPV4IPV6LookupTest(bool is_async) {
880   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
881                                     true /* ipv6_reachable */,
882                                     true /* check_ipv6_on_wifi */, is_async);
883   HostResolver::ResolveHostParameters parameters;
884 
885   parameters.dns_query_type = DnsQueryType::A;
886   ResolveHostResponseHelper v4_v4_response(resolver_->CreateRequest(
887       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
888       NetLogWithSource(), parameters, resolve_context_.get(),
889       resolve_context_->host_cache()));
890   EXPECT_THAT(v4_v4_response.result_error(), IsOk());
891   EXPECT_THAT(v4_v4_response.request()->GetAddressResults()->endpoints(),
892               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
893   EXPECT_THAT(v4_v4_response.request()->GetEndpointResults(),
894               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
895                   testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
896 
897   parameters.dns_query_type = DnsQueryType::AAAA;
898   ResolveHostResponseHelper v4_v6_response(resolver_->CreateRequest(
899       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
900       NetLogWithSource(), parameters, resolve_context_.get(),
901       resolve_context_->host_cache()));
902   EXPECT_THAT(v4_v6_response.result_error(), IsOk());
903   EXPECT_THAT(v4_v6_response.request()->GetAddressResults()->endpoints(),
904               testing::ElementsAre(CreateExpected("::1", 80)));
905   EXPECT_THAT(v4_v6_response.request()->GetEndpointResults(),
906               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
907                   testing::ElementsAre(CreateExpected("::1", 80))))));
908 
909   ResolveHostResponseHelper v4_unsp_response(resolver_->CreateRequest(
910       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
911       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
912       resolve_context_->host_cache()));
913   EXPECT_THAT(v4_unsp_response.result_error(), IsOk());
914   EXPECT_THAT(v4_unsp_response.request()->GetAddressResults()->endpoints(),
915               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
916                                             CreateExpected("::1", 80)));
917   EXPECT_THAT(
918       v4_unsp_response.request()->GetEndpointResults(),
919       testing::Pointee(testing::ElementsAre(
920           ExpectEndpointResult(testing::UnorderedElementsAre(
921               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
922 }
923 
TEST_F(HostResolverManagerTest,LocalhostIPV4IPV6LookupAsync)924 TEST_F(HostResolverManagerTest, LocalhostIPV4IPV6LookupAsync) {
925   LocalhostIPV4IPV6LookupTest(true);
926 }
927 
TEST_F(HostResolverManagerTest,LocalhostIPV4IPV6LookupSync)928 TEST_F(HostResolverManagerTest, LocalhostIPV4IPV6LookupSync) {
929   LocalhostIPV4IPV6LookupTest(false);
930 }
931 
TEST_F(HostResolverManagerTest,ResolveIPLiteralWithHostResolverSystemOnly)932 TEST_F(HostResolverManagerTest, ResolveIPLiteralWithHostResolverSystemOnly) {
933   const char kIpLiteral[] = "178.78.32.1";
934   // Add a mapping to tell if the resolver proc was called (if it was called,
935   // then the result will be the remapped value. Otherwise it will be the IP
936   // literal).
937   proc_->AddRuleForAllFamilies(kIpLiteral, "183.45.32.1");
938 
939   HostResolver::ResolveHostParameters parameters;
940   parameters.source = HostResolverSource::SYSTEM;
941   ResolveHostResponseHelper response(resolver_->CreateRequest(
942       HostPortPair(kIpLiteral, 80), NetworkAnonymizationKey(),
943       NetLogWithSource(), parameters, resolve_context_.get(),
944       resolve_context_->host_cache()));
945 
946   // IP literal resolution is expected to take precedence over source, so the
947   // result is expected to be the input IP, not the result IP from the proc rule
948   EXPECT_THAT(response.result_error(), IsOk());
949   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
950               testing::ElementsAre(CreateExpected(kIpLiteral, 80)));
951   EXPECT_THAT(response.request()->GetEndpointResults(),
952               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
953                   testing::ElementsAre(CreateExpected(kIpLiteral, 80))))));
954   EXPECT_FALSE(response.request()->GetStaleInfo());
955 }
956 
TEST_F(HostResolverManagerTest,EmptyListMeansNameNotResolved)957 TEST_F(HostResolverManagerTest, EmptyListMeansNameNotResolved) {
958   proc_->AddRuleForAllFamilies("just.testing", "");
959   proc_->SignalMultiple(1u);
960 
961   ResolveHostResponseHelper response(resolver_->CreateRequest(
962       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
963       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
964       resolve_context_->host_cache()));
965 
966   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
967   EXPECT_FALSE(response.request()->GetAddressResults());
968   EXPECT_FALSE(response.request()->GetEndpointResults());
969   EXPECT_FALSE(response.request()->GetStaleInfo());
970 
971   EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
972 }
973 
TEST_F(HostResolverManagerTest,FailedAsynchronousLookup)974 TEST_F(HostResolverManagerTest, FailedAsynchronousLookup) {
975   proc_->AddRuleForAllFamilies(std::string(),
976                                "0.0.0.1");  // Default to failures.
977   proc_->SignalMultiple(1u);
978 
979   ResolveHostResponseHelper response(resolver_->CreateRequest(
980       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
981       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
982       resolve_context_->host_cache()));
983   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
984   EXPECT_THAT(response.top_level_result_error(),
985               IsError(ERR_NAME_NOT_RESOLVED));
986   EXPECT_FALSE(response.request()->GetAddressResults());
987   EXPECT_FALSE(response.request()->GetEndpointResults());
988   EXPECT_FALSE(response.request()->GetStaleInfo());
989 
990   EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
991 
992   // Also test that the error is not cached.
993   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
994       GetCacheHit(HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
995                                  0 /* host_resolver_flags */,
996                                  HostResolverSource::ANY,
997                                  NetworkAnonymizationKey()));
998   EXPECT_FALSE(cache_result);
999 }
1000 
TEST_F(HostResolverManagerTest,AbortedAsynchronousLookup)1001 TEST_F(HostResolverManagerTest, AbortedAsynchronousLookup) {
1002   ResolveHostResponseHelper response0(resolver_->CreateRequest(
1003       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
1004       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1005       resolve_context_->host_cache()));
1006   ASSERT_FALSE(response0.complete());
1007   ASSERT_TRUE(proc_->WaitFor(1u));
1008 
1009   // Resolver is destroyed while job is running on WorkerPool.
1010   DestroyResolver();
1011 
1012   proc_->SignalAll();
1013 
1014   // To ensure there was no spurious callback, complete with a new resolver.
1015   CreateResolver();
1016   ResolveHostResponseHelper response1(resolver_->CreateRequest(
1017       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
1018       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1019       resolve_context_->host_cache()));
1020 
1021   proc_->SignalMultiple(2u);
1022 
1023   EXPECT_THAT(response1.result_error(), IsOk());
1024 
1025   // This request was canceled.
1026   EXPECT_FALSE(response0.complete());
1027 }
1028 
TEST_F(HostResolverManagerTest,NumericIPv4Address)1029 TEST_F(HostResolverManagerTest, NumericIPv4Address) {
1030   ResolveHostResponseHelper response(resolver_->CreateRequest(
1031       HostPortPair("127.1.2.3", 5555), NetworkAnonymizationKey(),
1032       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1033       resolve_context_->host_cache()));
1034 
1035   EXPECT_THAT(response.result_error(), IsOk());
1036   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
1037               testing::ElementsAre(CreateExpected("127.1.2.3", 5555)));
1038   EXPECT_THAT(
1039       response.request()->GetEndpointResults(),
1040       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
1041           testing::UnorderedElementsAre(CreateExpected("127.1.2.3", 5555))))));
1042 }
1043 
TEST_F(HostResolverManagerTest,NumericIPv4AddressWithScheme)1044 TEST_F(HostResolverManagerTest, NumericIPv4AddressWithScheme) {
1045   ResolveHostResponseHelper response(resolver_->CreateRequest(
1046       url::SchemeHostPort(url::kHttpsScheme, "127.1.2.3", 5555),
1047       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
1048       resolve_context_.get(), resolve_context_->host_cache()));
1049 
1050   EXPECT_THAT(response.result_error(), IsOk());
1051   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
1052               testing::ElementsAre(CreateExpected("127.1.2.3", 5555)));
1053   EXPECT_THAT(
1054       response.request()->GetEndpointResults(),
1055       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
1056           testing::UnorderedElementsAre(CreateExpected("127.1.2.3", 5555))))));
1057 }
1058 
NumericIPv6AddressTest(bool is_async)1059 void HostResolverManagerTest::NumericIPv6AddressTest(bool is_async) {
1060   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
1061                                     true /* ipv6_reachable */,
1062                                     true /* check_ipv6_on_wifi */, is_async);
1063   // Resolve a plain IPv6 address.  Don't worry about [brackets], because
1064   // the caller should have removed them.
1065   ResolveHostResponseHelper response(resolver_->CreateRequest(
1066       HostPortPair("2001:db8::1", 5555), NetworkAnonymizationKey(),
1067       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1068       resolve_context_->host_cache()));
1069 
1070   EXPECT_THAT(response.result_error(), IsOk());
1071   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
1072               testing::ElementsAre(CreateExpected("2001:db8::1", 5555)));
1073   EXPECT_THAT(response.request()->GetEndpointResults(),
1074               testing::Pointee(testing::UnorderedElementsAre(
1075                   ExpectEndpointResult(testing::UnorderedElementsAre(
1076                       CreateExpected("2001:db8::1", 5555))))));
1077 }
1078 
TEST_F(HostResolverManagerTest,NumericIPv6AddressAsync)1079 TEST_F(HostResolverManagerTest, NumericIPv6AddressAsync) {
1080   NumericIPv6AddressTest(true);
1081 }
1082 
TEST_F(HostResolverManagerTest,NumericIPv6AddressSync)1083 TEST_F(HostResolverManagerTest, NumericIPv6AddressSync) {
1084   NumericIPv6AddressTest(false);
1085 }
1086 
NumericIPv6AddressWithSchemeTest(bool is_async)1087 void HostResolverManagerTest::NumericIPv6AddressWithSchemeTest(bool is_async) {
1088   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
1089                                     true /* ipv6_reachable */,
1090                                     true /* check_ipv6_on_wifi */, is_async);
1091   ResolveHostResponseHelper response(resolver_->CreateRequest(
1092       url::SchemeHostPort(url::kFtpScheme, "[2001:db8::1]", 5555),
1093       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
1094       resolve_context_.get(), resolve_context_->host_cache()));
1095 
1096   EXPECT_THAT(response.result_error(), IsOk());
1097   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
1098               testing::ElementsAre(CreateExpected("2001:db8::1", 5555)));
1099   EXPECT_THAT(response.request()->GetEndpointResults(),
1100               testing::Pointee(testing::UnorderedElementsAre(
1101                   ExpectEndpointResult(testing::UnorderedElementsAre(
1102                       CreateExpected("2001:db8::1", 5555))))));
1103 }
1104 
TEST_F(HostResolverManagerTest,NumericIPv6AddressWithSchemeAsync)1105 TEST_F(HostResolverManagerTest, NumericIPv6AddressWithSchemeAsync) {
1106   NumericIPv6AddressWithSchemeTest(true);
1107 }
1108 
TEST_F(HostResolverManagerTest,NumericIPv6AddressWithSchemeSync)1109 TEST_F(HostResolverManagerTest, NumericIPv6AddressWithSchemeSync) {
1110   NumericIPv6AddressWithSchemeTest(false);
1111 }
1112 
1113 // Regression test for https://crbug.com/1432508.
1114 //
1115 // Tests that if a new request is made while the loop within
1116 // FinishIPv6ReachabilityCheck is still running, and the new request needs to
1117 // wait on a new IPv6 probe to complete, the new request does not try to modify
1118 // the same vector that FinishIPv6ReachabilityCheck is iterating over.
TEST_F(HostResolverManagerTest,AddRequestDuringFinishIPv6ReachabilityCheck)1119 TEST_F(HostResolverManagerTest, AddRequestDuringFinishIPv6ReachabilityCheck) {
1120   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
1121                                     true /* ipv6_reachable */,
1122                                     true /* check_ipv6_on_wifi */, true);
1123 
1124   // Reset `last_ipv6_probe_time_` if `reset_ipv6_probe_time` true so a new
1125   // request kicks off a new reachability probe.
1126   auto custom_callback_template = base::BindLambdaForTesting(
1127       [&](bool reset_ipv6_probe_time, const HostPortPair& next_host,
1128           std::unique_ptr<ResolveHostResponseHelper>* next_response,
1129           CompletionOnceCallback completion_callback, int error) {
1130         if (reset_ipv6_probe_time) {
1131           resolver_->ResetIPv6ProbeTimeForTesting();
1132         }
1133         *next_response = std::make_unique<ResolveHostResponseHelper>(
1134             resolver_->CreateRequest(next_host, NetworkAnonymizationKey(),
1135                                      NetLogWithSource(), absl::nullopt,
1136                                      resolve_context_.get(),
1137                                      resolve_context_->host_cache()));
1138         std::move(completion_callback).Run(error);
1139       });
1140 
1141   std::vector<std::unique_ptr<ResolveHostResponseHelper>> next_responses(3);
1142 
1143   ResolveHostResponseHelper response0(
1144       resolver_->CreateRequest(HostPortPair("2001:db8::1", 5555),
1145                                NetworkAnonymizationKey(), NetLogWithSource(),
1146                                absl::nullopt, resolve_context_.get(),
1147                                resolve_context_->host_cache()),
1148       base::BindOnce(custom_callback_template, true, HostPortPair("zzz", 80),
1149                      &next_responses[0]));
1150 
1151   // New requests made by response1 and response2 will wait for a new
1152   // reachability probe to complete.
1153   ResolveHostResponseHelper response1(
1154       resolver_->CreateRequest(HostPortPair("2001:db8::1", 5555),
1155                                NetworkAnonymizationKey(), NetLogWithSource(),
1156                                absl::nullopt, resolve_context_.get(),
1157                                resolve_context_->host_cache()),
1158       base::BindOnce(custom_callback_template, false, HostPortPair("aaa", 80),
1159                      &next_responses[1]));
1160 
1161   ResolveHostResponseHelper response2(
1162       resolver_->CreateRequest(HostPortPair("2001:db8::1", 5555),
1163                                NetworkAnonymizationKey(), NetLogWithSource(),
1164                                absl::nullopt, resolve_context_.get(),
1165                                resolve_context_->host_cache()),
1166       base::BindOnce(custom_callback_template, false, HostPortPair("eee", 80),
1167                      &next_responses[2]));
1168 
1169   // Unblock all calls to proc.
1170   proc_->SignalMultiple(6u);
1171 
1172   // All requests should return OK.
1173   EXPECT_THAT(response0.result_error(), IsOk());
1174   EXPECT_THAT(response1.result_error(), IsOk());
1175   EXPECT_THAT(response2.result_error(), IsOk());
1176   EXPECT_THAT(next_responses[0]->result_error(), IsOk());
1177   EXPECT_THAT(next_responses[1]->result_error(), IsOk());
1178   EXPECT_THAT(next_responses[2]->result_error(), IsOk());
1179 }
1180 
TEST_F(HostResolverManagerTest,EmptyHost)1181 TEST_F(HostResolverManagerTest, EmptyHost) {
1182   ResolveHostResponseHelper response(resolver_->CreateRequest(
1183       HostPortPair(std::string(), 5555), NetworkAnonymizationKey(),
1184       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1185       resolve_context_->host_cache()));
1186 
1187   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
1188   EXPECT_FALSE(response.request()->GetAddressResults());
1189   EXPECT_FALSE(response.request()->GetEndpointResults());
1190 }
1191 
TEST_F(HostResolverManagerTest,EmptyDotsHost)1192 TEST_F(HostResolverManagerTest, EmptyDotsHost) {
1193   for (int i = 0; i < 16; ++i) {
1194     ResolveHostResponseHelper response(resolver_->CreateRequest(
1195         HostPortPair(std::string(i, '.'), 5555), NetworkAnonymizationKey(),
1196         NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1197         resolve_context_->host_cache()));
1198 
1199     EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
1200     EXPECT_FALSE(response.request()->GetAddressResults());
1201     EXPECT_FALSE(response.request()->GetEndpointResults());
1202   }
1203 }
1204 
TEST_F(HostResolverManagerTest,LongHost)1205 TEST_F(HostResolverManagerTest, LongHost) {
1206   ResolveHostResponseHelper response(resolver_->CreateRequest(
1207       HostPortPair(std::string(4097, 'a'), 5555), NetworkAnonymizationKey(),
1208       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1209       resolve_context_->host_cache()));
1210 
1211   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
1212   EXPECT_FALSE(response.request()->GetAddressResults());
1213   EXPECT_FALSE(response.request()->GetEndpointResults());
1214 }
1215 
TEST_F(HostResolverManagerTest,DeDupeRequests)1216 TEST_F(HostResolverManagerTest, DeDupeRequests) {
1217   // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
1218   // blocked, these should all pile up until we signal it.
1219   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1220   responses.emplace_back(
1221       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1222           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1223           absl::nullopt, resolve_context_.get(),
1224           resolve_context_->host_cache())));
1225   responses.emplace_back(
1226       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1227           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1228           absl::nullopt, resolve_context_.get(),
1229           resolve_context_->host_cache())));
1230   responses.emplace_back(
1231       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1232           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1233           absl::nullopt, resolve_context_.get(),
1234           resolve_context_->host_cache())));
1235   responses.emplace_back(
1236       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1237           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1238           absl::nullopt, resolve_context_.get(),
1239           resolve_context_->host_cache())));
1240   responses.emplace_back(
1241       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1242           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1243           absl::nullopt, resolve_context_.get(),
1244           resolve_context_->host_cache())));
1245 
1246   for (auto& response : responses) {
1247     ASSERT_FALSE(response->complete());
1248   }
1249 
1250   proc_->SignalMultiple(2u);  // One for "a:80", one for "b:80".
1251 
1252   for (auto& response : responses) {
1253     EXPECT_THAT(response->result_error(), IsOk());
1254   }
1255 }
1256 
1257 // TODO(crbug.com/1206799): Delete/adapt once requests with different ports are
1258 // not deduped.
TEST_F(HostResolverManagerTest,DeDupeRequestsWithDifferentPorts)1259 TEST_F(HostResolverManagerTest, DeDupeRequestsWithDifferentPorts) {
1260   // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
1261   // blocked, these should all pile up until we signal it.
1262   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1263   responses.emplace_back(
1264       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1265           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1266           absl::nullopt, resolve_context_.get(),
1267           resolve_context_->host_cache())));
1268   responses.emplace_back(
1269       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1270           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1271           absl::nullopt, resolve_context_.get(),
1272           resolve_context_->host_cache())));
1273   responses.emplace_back(
1274       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1275           HostPortPair("b", 81), NetworkAnonymizationKey(), NetLogWithSource(),
1276           absl::nullopt, resolve_context_.get(),
1277           resolve_context_->host_cache())));
1278   responses.emplace_back(
1279       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1280           HostPortPair("a", 82), NetworkAnonymizationKey(), NetLogWithSource(),
1281           absl::nullopt, resolve_context_.get(),
1282           resolve_context_->host_cache())));
1283   responses.emplace_back(
1284       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1285           HostPortPair("b", 83), NetworkAnonymizationKey(), NetLogWithSource(),
1286           absl::nullopt, resolve_context_.get(),
1287           resolve_context_->host_cache())));
1288 
1289   for (auto& response : responses) {
1290     ASSERT_FALSE(response->complete());
1291   }
1292 
1293   proc_->SignalMultiple(2u);  // One for "a", one for "b".
1294 
1295   for (auto& response : responses) {
1296     EXPECT_THAT(response->result_error(), IsOk());
1297   }
1298 }
1299 
TEST_F(HostResolverManagerTest,CancelMultipleRequests)1300 TEST_F(HostResolverManagerTest, CancelMultipleRequests) {
1301   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1302   responses.emplace_back(
1303       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1304           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1305           absl::nullopt, resolve_context_.get(),
1306           resolve_context_->host_cache())));
1307   responses.emplace_back(
1308       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1309           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1310           absl::nullopt, resolve_context_.get(),
1311           resolve_context_->host_cache())));
1312   responses.emplace_back(
1313       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1314           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1315           absl::nullopt, resolve_context_.get(),
1316           resolve_context_->host_cache())));
1317   responses.emplace_back(
1318       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1319           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1320           absl::nullopt, resolve_context_.get(),
1321           resolve_context_->host_cache())));
1322   responses.emplace_back(
1323       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1324           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1325           absl::nullopt, resolve_context_.get(),
1326           resolve_context_->host_cache())));
1327 
1328   for (auto& response : responses) {
1329     ASSERT_FALSE(response->complete());
1330   }
1331 
1332   // Cancel everything except request for requests[3] ("a", 80).
1333   responses[0]->CancelRequest();
1334   responses[1]->CancelRequest();
1335   responses[2]->CancelRequest();
1336   responses[4]->CancelRequest();
1337 
1338   proc_->SignalMultiple(2u);  // One for "a", one for "b".
1339 
1340   EXPECT_THAT(responses[3]->result_error(), IsOk());
1341 
1342   EXPECT_FALSE(responses[0]->complete());
1343   EXPECT_FALSE(responses[1]->complete());
1344   EXPECT_FALSE(responses[2]->complete());
1345   EXPECT_FALSE(responses[4]->complete());
1346 }
1347 
TEST_F(HostResolverManagerTest,CanceledRequestsReleaseJobSlots)1348 TEST_F(HostResolverManagerTest, CanceledRequestsReleaseJobSlots) {
1349   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1350 
1351   // Fill up the dispatcher and queue.
1352   for (unsigned i = 0; i < kMaxJobs + 1; ++i) {
1353     std::string hostname = "a_";
1354     hostname[1] = 'a' + i;
1355 
1356     responses.emplace_back(
1357         std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1358             HostPortPair(hostname, 80), NetworkAnonymizationKey(),
1359             NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1360             resolve_context_->host_cache())));
1361     ASSERT_FALSE(responses.back()->complete());
1362 
1363     responses.emplace_back(
1364         std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1365             HostPortPair(hostname, 80), NetworkAnonymizationKey(),
1366             NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1367             resolve_context_->host_cache())));
1368     ASSERT_FALSE(responses.back()->complete());
1369   }
1370 
1371   ASSERT_TRUE(proc_->WaitFor(kMaxJobs));
1372 
1373   // Cancel all but last two.
1374   for (unsigned i = 0; i < responses.size() - 2; ++i) {
1375     responses[i]->CancelRequest();
1376   }
1377 
1378   ASSERT_TRUE(proc_->WaitFor(kMaxJobs + 1));
1379 
1380   proc_->SignalAll();
1381 
1382   size_t num_requests = responses.size();
1383   EXPECT_THAT(responses[num_requests - 1]->result_error(), IsOk());
1384   EXPECT_THAT(responses[num_requests - 2]->result_error(), IsOk());
1385   for (unsigned i = 0; i < num_requests - 2; ++i) {
1386     EXPECT_FALSE(responses[i]->complete());
1387   }
1388 }
1389 
TEST_F(HostResolverManagerTest,CancelWithinCallback)1390 TEST_F(HostResolverManagerTest, CancelWithinCallback) {
1391   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1392   auto custom_callback = base::BindLambdaForTesting(
1393       [&](CompletionOnceCallback completion_callback, int error) {
1394         for (auto& response : responses) {
1395           // Cancelling request is required to complete first, so that it can
1396           // attempt to cancel the others.  This test assumes all jobs are
1397           // completed in order.
1398           DCHECK(!response->complete());
1399 
1400           response->CancelRequest();
1401         }
1402         std::move(completion_callback).Run(error);
1403       });
1404 
1405   ResolveHostResponseHelper cancelling_response(
1406       resolver_->CreateRequest(HostPortPair("a", 80), NetworkAnonymizationKey(),
1407                                NetLogWithSource(), absl::nullopt,
1408                                resolve_context_.get(),
1409                                resolve_context_->host_cache()),
1410       std::move(custom_callback));
1411 
1412   responses.emplace_back(
1413       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1414           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1415           absl::nullopt, resolve_context_.get(),
1416           resolve_context_->host_cache())));
1417   responses.emplace_back(
1418       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1419           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1420           absl::nullopt, resolve_context_.get(),
1421           resolve_context_->host_cache())));
1422 
1423   proc_->SignalMultiple(2u);  // One for "a". One for "finalrequest".
1424 
1425   EXPECT_THAT(cancelling_response.result_error(), IsOk());
1426 
1427   ResolveHostResponseHelper final_response(resolver_->CreateRequest(
1428       HostPortPair("finalrequest", 70), NetworkAnonymizationKey(),
1429       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1430       resolve_context_->host_cache()));
1431   EXPECT_THAT(final_response.result_error(), IsOk());
1432 
1433   for (auto& response : responses) {
1434     EXPECT_FALSE(response->complete());
1435   }
1436 }
1437 
TEST_F(HostResolverManagerTest,DeleteWithinCallback)1438 TEST_F(HostResolverManagerTest, DeleteWithinCallback) {
1439   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1440   auto custom_callback = base::BindLambdaForTesting(
1441       [&](CompletionOnceCallback completion_callback, int error) {
1442         for (auto& response : responses) {
1443           // Deleting request is required to be first, so the other requests
1444           // will still be running to be deleted. This test assumes that the
1445           // Jobs will be Aborted in order and the requests in order within the
1446           // jobs.
1447           DCHECK(!response->complete());
1448         }
1449 
1450         DestroyResolver();
1451         std::move(completion_callback).Run(error);
1452       });
1453 
1454   ResolveHostResponseHelper deleting_response(
1455       resolver_->CreateRequest(HostPortPair("a", 80), NetworkAnonymizationKey(),
1456                                NetLogWithSource(), absl::nullopt,
1457                                resolve_context_.get(),
1458                                resolve_context_->host_cache()),
1459       std::move(custom_callback));
1460 
1461   // Start additional requests to be cancelled as part of the first's deletion.
1462   // Assumes all requests for a job are handled in order so that the deleting
1463   // request will run first and cancel the rest.
1464   responses.emplace_back(
1465       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1466           HostPortPair("a", 81), NetworkAnonymizationKey(), NetLogWithSource(),
1467           absl::nullopt, resolve_context_.get(),
1468           resolve_context_->host_cache())));
1469   responses.emplace_back(
1470       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1471           HostPortPair("a", 82), NetworkAnonymizationKey(), NetLogWithSource(),
1472           absl::nullopt, resolve_context_.get(),
1473           resolve_context_->host_cache())));
1474 
1475   proc_->SignalMultiple(3u);
1476 
1477   EXPECT_THAT(deleting_response.result_error(), IsOk());
1478 
1479   base::RunLoop().RunUntilIdle();
1480   for (auto& response : responses) {
1481     EXPECT_FALSE(response->complete());
1482   }
1483 }
1484 
TEST_F(HostResolverManagerTest,DeleteWithinAbortedCallback)1485 TEST_F(HostResolverManagerTest, DeleteWithinAbortedCallback) {
1486   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1487   ResolveHostResponseHelper::Callback custom_callback =
1488       base::BindLambdaForTesting(
1489           [&](CompletionOnceCallback completion_callback, int error) {
1490             for (auto& response : responses) {
1491               // Deleting request is required to be first, so the other requests
1492               // will still be running to be deleted. This test assumes that the
1493               // Jobs will be Aborted in order and the requests in order within
1494               // the jobs.
1495               DCHECK(!response->complete());
1496             }
1497             DestroyResolver();
1498             std::move(completion_callback).Run(error);
1499           });
1500 
1501   ResolveHostResponseHelper deleting_response(
1502       resolver_->CreateRequest(HostPortPair("a", 80), NetworkAnonymizationKey(),
1503                                NetLogWithSource(), absl::nullopt,
1504                                resolve_context_.get(),
1505                                resolve_context_->host_cache()),
1506       std::move(custom_callback));
1507 
1508   responses.emplace_back(
1509       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1510           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1511           absl::nullopt, resolve_context_.get(),
1512           resolve_context_->host_cache())));
1513   responses.emplace_back(
1514       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1515           HostPortPair("b", 82), NetworkAnonymizationKey(), NetLogWithSource(),
1516           absl::nullopt, resolve_context_.get(),
1517           resolve_context_->host_cache())));
1518   responses.emplace_back(
1519       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1520           HostPortPair("b", 82), NetworkAnonymizationKey(), NetLogWithSource(),
1521           absl::nullopt, resolve_context_.get(),
1522           resolve_context_->host_cache())));
1523 
1524   // Wait for all calls to queue up, trigger abort via IP address change, then
1525   // signal all the queued requests to let them all try to finish.
1526   EXPECT_TRUE(proc_->WaitFor(2u));
1527   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1528   proc_->SignalAll();
1529 
1530   EXPECT_THAT(deleting_response.result_error(), IsError(ERR_NETWORK_CHANGED));
1531   base::RunLoop().RunUntilIdle();
1532   for (auto& response : responses) {
1533     EXPECT_FALSE(response->complete());
1534   }
1535 }
1536 
TEST_F(HostResolverManagerTest,StartWithinCallback)1537 TEST_F(HostResolverManagerTest, StartWithinCallback) {
1538   std::unique_ptr<ResolveHostResponseHelper> new_response;
1539   auto custom_callback = base::BindLambdaForTesting(
1540       [&](CompletionOnceCallback completion_callback, int error) {
1541         new_response = std::make_unique<ResolveHostResponseHelper>(
1542             resolver_->CreateRequest(
1543                 HostPortPair("new", 70), NetworkAnonymizationKey(),
1544                 NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1545                 resolve_context_->host_cache()));
1546         std::move(completion_callback).Run(error);
1547       });
1548 
1549   ResolveHostResponseHelper starting_response(
1550       resolver_->CreateRequest(HostPortPair("a", 80), NetworkAnonymizationKey(),
1551                                NetLogWithSource(), absl::nullopt,
1552                                resolve_context_.get(),
1553                                resolve_context_->host_cache()),
1554       std::move(custom_callback));
1555 
1556   proc_->SignalMultiple(2u);  // One for "a". One for "new".
1557 
1558   EXPECT_THAT(starting_response.result_error(), IsOk());
1559   EXPECT_THAT(new_response->result_error(), IsOk());
1560 }
1561 
TEST_F(HostResolverManagerTest,StartWithinEvictionCallback)1562 TEST_F(HostResolverManagerTest, StartWithinEvictionCallback) {
1563   CreateSerialResolver();
1564   resolver_->SetMaxQueuedJobsForTesting(2);
1565 
1566   std::unique_ptr<ResolveHostResponseHelper> new_response;
1567   auto custom_callback = base::BindLambdaForTesting(
1568       [&](CompletionOnceCallback completion_callback, int error) {
1569         new_response = std::make_unique<ResolveHostResponseHelper>(
1570             resolver_->CreateRequest(
1571                 HostPortPair("new", 70), NetworkAnonymizationKey(),
1572                 NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1573                 resolve_context_->host_cache()));
1574         std::move(completion_callback).Run(error);
1575       });
1576 
1577   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
1578       HostPortPair("initial", 80), NetworkAnonymizationKey(),
1579       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1580       resolve_context_->host_cache()));
1581   ResolveHostResponseHelper evictee1_response(
1582       resolver_->CreateRequest(HostPortPair("evictee1", 80),
1583                                NetworkAnonymizationKey(), NetLogWithSource(),
1584                                absl::nullopt, resolve_context_.get(),
1585                                resolve_context_->host_cache()),
1586       std::move(custom_callback));
1587   ResolveHostResponseHelper evictee2_response(resolver_->CreateRequest(
1588       HostPortPair("evictee2", 80), NetworkAnonymizationKey(),
1589       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1590       resolve_context_->host_cache()));
1591 
1592   // Now one running request ("initial") and two queued requests ("evictee1" and
1593   // "evictee2"). Any further requests will cause evictions.
1594   ResolveHostResponseHelper evictor_response(resolver_->CreateRequest(
1595       HostPortPair("evictor", 80), NetworkAnonymizationKey(),
1596       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1597       resolve_context_->host_cache()));
1598   EXPECT_THAT(evictee1_response.result_error(),
1599               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
1600 
1601   // "new" should evict "evictee2"
1602   EXPECT_THAT(evictee2_response.result_error(),
1603               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
1604 
1605   proc_->SignalMultiple(3u);
1606 
1607   EXPECT_THAT(initial_response.result_error(), IsOk());
1608   EXPECT_THAT(evictor_response.result_error(), IsOk());
1609   EXPECT_THAT(new_response->result_error(), IsOk());
1610 }
1611 
1612 // Test where we start a new request within an eviction callback that itself
1613 // evicts the first evictor.
TEST_F(HostResolverManagerTest,StartWithinEvictionCallback_DoubleEviction)1614 TEST_F(HostResolverManagerTest, StartWithinEvictionCallback_DoubleEviction) {
1615   CreateSerialResolver();
1616   resolver_->SetMaxQueuedJobsForTesting(1);
1617 
1618   std::unique_ptr<ResolveHostResponseHelper> new_response;
1619   auto custom_callback = base::BindLambdaForTesting(
1620       [&](CompletionOnceCallback completion_callback, int error) {
1621         new_response = std::make_unique<ResolveHostResponseHelper>(
1622             resolver_->CreateRequest(
1623                 HostPortPair("new", 70), NetworkAnonymizationKey(),
1624                 NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1625                 resolve_context_->host_cache()));
1626         std::move(completion_callback).Run(error);
1627       });
1628 
1629   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
1630       HostPortPair("initial", 80), NetworkAnonymizationKey(),
1631       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1632       resolve_context_->host_cache()));
1633   ResolveHostResponseHelper evictee_response(
1634       resolver_->CreateRequest(HostPortPair("evictee", 80),
1635                                NetworkAnonymizationKey(), NetLogWithSource(),
1636                                absl::nullopt, resolve_context_.get(),
1637                                resolve_context_->host_cache()),
1638       std::move(custom_callback));
1639 
1640   // Now one running request ("initial") and one queued requests ("evictee").
1641   // Any further requests will cause evictions.
1642   ResolveHostResponseHelper evictor_response(resolver_->CreateRequest(
1643       HostPortPair("evictor", 80), NetworkAnonymizationKey(),
1644       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1645       resolve_context_->host_cache()));
1646   EXPECT_THAT(evictee_response.result_error(),
1647               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
1648 
1649   // "new" should evict "evictor"
1650   EXPECT_THAT(evictor_response.result_error(),
1651               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
1652 
1653   proc_->SignalMultiple(2u);
1654 
1655   EXPECT_THAT(initial_response.result_error(), IsOk());
1656   EXPECT_THAT(new_response->result_error(), IsOk());
1657 }
1658 
TEST_F(HostResolverManagerTest,StartWithinEvictionCallback_SameRequest)1659 TEST_F(HostResolverManagerTest, StartWithinEvictionCallback_SameRequest) {
1660   CreateSerialResolver();
1661   resolver_->SetMaxQueuedJobsForTesting(2);
1662 
1663   std::unique_ptr<ResolveHostResponseHelper> new_response;
1664   auto custom_callback = base::BindLambdaForTesting(
1665       [&](CompletionOnceCallback completion_callback, int error) {
1666         new_response = std::make_unique<ResolveHostResponseHelper>(
1667             resolver_->CreateRequest(
1668                 HostPortPair("evictor", 80), NetworkAnonymizationKey(),
1669                 NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1670                 resolve_context_->host_cache()));
1671         std::move(completion_callback).Run(error);
1672       });
1673 
1674   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
1675       HostPortPair("initial", 80), NetworkAnonymizationKey(),
1676       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1677       resolve_context_->host_cache()));
1678   ResolveHostResponseHelper evictee_response(
1679       resolver_->CreateRequest(HostPortPair("evictee", 80),
1680                                NetworkAnonymizationKey(), NetLogWithSource(),
1681                                absl::nullopt, resolve_context_.get(),
1682                                resolve_context_->host_cache()),
1683       std::move(custom_callback));
1684   ResolveHostResponseHelper additional_response(resolver_->CreateRequest(
1685       HostPortPair("additional", 80), NetworkAnonymizationKey(),
1686       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1687       resolve_context_->host_cache()));
1688 
1689   // Now one running request ("initial") and two queued requests ("evictee" and
1690   // "additional"). Any further requests will cause evictions.
1691   ResolveHostResponseHelper evictor_response(resolver_->CreateRequest(
1692       HostPortPair("evictor", 80), NetworkAnonymizationKey(),
1693       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
1694       resolve_context_->host_cache()));
1695   EXPECT_THAT(evictee_response.result_error(),
1696               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
1697 
1698   // Second "evictor" should be joined with the first and not evict "additional"
1699 
1700   // Only 3 proc requests because both "evictor" requests are combined.
1701   proc_->SignalMultiple(3u);
1702 
1703   EXPECT_THAT(initial_response.result_error(), IsOk());
1704   EXPECT_THAT(additional_response.result_error(), IsOk());
1705   EXPECT_THAT(evictor_response.result_error(), IsOk());
1706   EXPECT_THAT(new_response->result_error(), IsOk());
1707 }
1708 
TEST_F(HostResolverManagerTest,BypassCache)1709 TEST_F(HostResolverManagerTest, BypassCache) {
1710   proc_->SignalMultiple(2u);
1711 
1712   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
1713       HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1714       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
1715   EXPECT_THAT(initial_response.result_error(), IsOk());
1716   EXPECT_EQ(1u, proc_->GetCaptureList().size());
1717 
1718   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
1719       HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1720       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
1721   EXPECT_THAT(cached_response.result_error(), IsOk());
1722   // Expect no increase to calls to |proc_| because result was cached.
1723   EXPECT_EQ(1u, proc_->GetCaptureList().size());
1724 
1725   HostResolver::ResolveHostParameters parameters;
1726   parameters.cache_usage =
1727       HostResolver::ResolveHostParameters::CacheUsage::DISALLOWED;
1728   ResolveHostResponseHelper cache_bypassed_response(resolver_->CreateRequest(
1729       HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1730       parameters, resolve_context_.get(), resolve_context_->host_cache()));
1731   EXPECT_THAT(cache_bypassed_response.result_error(), IsOk());
1732   // Expect call to |proc_| because cache was bypassed.
1733   EXPECT_EQ(2u, proc_->GetCaptureList().size());
1734 }
1735 
FlushCacheOnIPAddressChangeTest(bool is_async)1736 void HostResolverManagerTest::FlushCacheOnIPAddressChangeTest(bool is_async) {
1737   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
1738                                     true /* ipv6_reachable */,
1739                                     true /* check_ipv6_on_wifi */, is_async);
1740   proc_->SignalMultiple(2u);  // One before the flush, one after.
1741 
1742   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
1743       HostPortPair("host1", 70), NetworkAnonymizationKey(), NetLogWithSource(),
1744       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
1745   EXPECT_THAT(initial_response.result_error(), IsOk());
1746   EXPECT_EQ(1u, proc_->GetCaptureList().size());
1747 
1748   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
1749       HostPortPair("host1", 75), NetworkAnonymizationKey(), NetLogWithSource(),
1750       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
1751   EXPECT_THAT(cached_response.result_error(), IsOk());
1752   EXPECT_EQ(1u, proc_->GetCaptureList().size());  // No expected increase.
1753 
1754   // Flush cache by triggering an IP address change.
1755   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1756   base::RunLoop().RunUntilIdle();  // Notification happens async.
1757 
1758   // Resolve "host1" again -- this time it won't be served from cache, so it
1759   // will complete asynchronously.
1760   ResolveHostResponseHelper flushed_response(resolver_->CreateRequest(
1761       HostPortPair("host1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1762       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
1763   EXPECT_THAT(flushed_response.result_error(), IsOk());
1764   EXPECT_EQ(2u, proc_->GetCaptureList().size());  // Expected increase.
1765 }
1766 
1767 // Test that IP address changes flush the cache but initial DNS config reads
1768 // do not.
TEST_F(HostResolverManagerTest,FlushCacheOnIPAddressChangeAsync)1769 TEST_F(HostResolverManagerTest, FlushCacheOnIPAddressChangeAsync) {
1770   FlushCacheOnIPAddressChangeTest(true);
1771 }
TEST_F(HostResolverManagerTest,FlushCacheOnIPAddressChangeSync)1772 TEST_F(HostResolverManagerTest, FlushCacheOnIPAddressChangeSync) {
1773   FlushCacheOnIPAddressChangeTest(false);
1774 }
1775 
AbortOnIPAddressChangedTest(bool is_async)1776 void HostResolverManagerTest::AbortOnIPAddressChangedTest(bool is_async) {
1777   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
1778                                     true /* ipv6_reachable */,
1779                                     true /* check_ipv6_on_wifi */, is_async);
1780   ResolveHostResponseHelper response(resolver_->CreateRequest(
1781       HostPortPair("host1", 70), NetworkAnonymizationKey(), NetLogWithSource(),
1782       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
1783 
1784   ASSERT_FALSE(response.complete());
1785   if (is_async) {
1786     base::RunLoop().RunUntilIdle();
1787   }
1788   ASSERT_TRUE(proc_->WaitFor(1u));
1789 
1790   // Triggering an IP address change.
1791   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1792   base::RunLoop().RunUntilIdle();  // Notification happens async.
1793   proc_->SignalAll();
1794 
1795   EXPECT_THAT(response.result_error(), IsError(ERR_NETWORK_CHANGED));
1796   EXPECT_FALSE(response.request()->GetAddressResults());
1797   EXPECT_FALSE(response.request()->GetEndpointResults());
1798   EXPECT_EQ(0u, resolve_context_->host_cache()->size());
1799 }
1800 
1801 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests.
TEST_F(HostResolverManagerTest,AbortOnIPAddressChangedAsync)1802 TEST_F(HostResolverManagerTest, AbortOnIPAddressChangedAsync) {
1803   AbortOnIPAddressChangedTest(true);
1804 }
TEST_F(HostResolverManagerTest,AbortOnIPAddressChangedSync)1805 TEST_F(HostResolverManagerTest, AbortOnIPAddressChangedSync) {
1806   AbortOnIPAddressChangedTest(false);
1807 }
1808 
1809 // Obey pool constraints after IP address has changed.
TEST_F(HostResolverManagerTest,ObeyPoolConstraintsAfterIPAddressChange)1810 TEST_F(HostResolverManagerTest, ObeyPoolConstraintsAfterIPAddressChange) {
1811   // Runs at most one job at a time.
1812   CreateSerialResolver();
1813 
1814   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1815   responses.emplace_back(
1816       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1817           HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1818           absl::nullopt, resolve_context_.get(),
1819           resolve_context_->host_cache())));
1820   responses.emplace_back(
1821       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1822           HostPortPair("b", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1823           absl::nullopt, resolve_context_.get(),
1824           resolve_context_->host_cache())));
1825   responses.emplace_back(
1826       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1827           HostPortPair("c", 80), NetworkAnonymizationKey(), NetLogWithSource(),
1828           absl::nullopt, resolve_context_.get(),
1829           resolve_context_->host_cache())));
1830 
1831   for (auto& response : responses) {
1832     ASSERT_FALSE(response->complete());
1833   }
1834   ASSERT_TRUE(proc_->WaitFor(1u));
1835 
1836   // Triggering an IP address change.
1837   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1838   base::RunLoop().RunUntilIdle();  // Notification happens async.
1839   proc_->SignalMultiple(3u);  // Let the false-start go so that we can catch it.
1840 
1841   // Requests should complete one at a time, with the first failing.
1842   EXPECT_THAT(responses[0]->result_error(), IsError(ERR_NETWORK_CHANGED));
1843   EXPECT_EQ(1u, num_running_dispatcher_jobs());
1844   EXPECT_FALSE(responses[1]->complete());
1845   EXPECT_FALSE(responses[2]->complete());
1846 
1847   EXPECT_THAT(responses[1]->result_error(), IsOk());
1848   EXPECT_EQ(1u, num_running_dispatcher_jobs());
1849   EXPECT_FALSE(responses[2]->complete());
1850 
1851   EXPECT_THAT(responses[2]->result_error(), IsOk());
1852 }
1853 
AbortOnlyExistingRequestsOnIPAddressChangeTest(bool is_async)1854 void HostResolverManagerTest::AbortOnlyExistingRequestsOnIPAddressChangeTest(
1855     bool is_async) {
1856   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
1857                                     true /* ipv6_reachable */,
1858                                     true /* check_ipv6_on_wifi */, is_async);
1859   auto custom_callback_template = base::BindLambdaForTesting(
1860       [&](const HostPortPair& next_host,
1861           std::unique_ptr<ResolveHostResponseHelper>* next_response,
1862           CompletionOnceCallback completion_callback, int error) {
1863         *next_response = std::make_unique<ResolveHostResponseHelper>(
1864             resolver_->CreateRequest(next_host, NetworkAnonymizationKey(),
1865                                      NetLogWithSource(), absl::nullopt,
1866                                      resolve_context_.get(),
1867                                      resolve_context_->host_cache()));
1868         std::move(completion_callback).Run(error);
1869       });
1870 
1871   std::vector<std::unique_ptr<ResolveHostResponseHelper>> next_responses(3);
1872 
1873   ResolveHostResponseHelper response0(
1874       resolver_->CreateRequest(HostPortPair("bbb", 80),
1875                                NetworkAnonymizationKey(), NetLogWithSource(),
1876                                absl::nullopt, resolve_context_.get(),
1877                                resolve_context_->host_cache()),
1878       base::BindOnce(custom_callback_template, HostPortPair("zzz", 80),
1879                      &next_responses[0]));
1880 
1881   ResolveHostResponseHelper response1(
1882       resolver_->CreateRequest(HostPortPair("eee", 80),
1883                                NetworkAnonymizationKey(), NetLogWithSource(),
1884                                absl::nullopt, resolve_context_.get(),
1885                                resolve_context_->host_cache()),
1886       base::BindOnce(custom_callback_template, HostPortPair("aaa", 80),
1887                      &next_responses[1]));
1888 
1889   ResolveHostResponseHelper response2(
1890       resolver_->CreateRequest(HostPortPair("ccc", 80),
1891                                NetworkAnonymizationKey(), NetLogWithSource(),
1892                                absl::nullopt, resolve_context_.get(),
1893                                resolve_context_->host_cache()),
1894       base::BindOnce(custom_callback_template, HostPortPair("eee", 80),
1895                      &next_responses[2]));
1896 
1897   if (is_async) {
1898     base::RunLoop().RunUntilIdle();
1899   }
1900   // Wait until all are blocked;
1901   ASSERT_TRUE(proc_->WaitFor(3u));
1902 
1903   // Trigger an IP address change.
1904   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1905   // This should abort all running jobs.
1906   base::RunLoop().RunUntilIdle();
1907 
1908   EXPECT_THAT(response0.result_error(), IsError(ERR_NETWORK_CHANGED));
1909   EXPECT_THAT(response1.result_error(), IsError(ERR_NETWORK_CHANGED));
1910   EXPECT_THAT(response2.result_error(), IsError(ERR_NETWORK_CHANGED));
1911 
1912   EXPECT_FALSE(next_responses[0]->complete());
1913   EXPECT_FALSE(next_responses[1]->complete());
1914   EXPECT_FALSE(next_responses[2]->complete());
1915 
1916   // Unblock all calls to proc.
1917   proc_->SignalMultiple(6u);
1918 
1919   // Run until the re-started requests finish.
1920   EXPECT_THAT(next_responses[0]->result_error(), IsOk());
1921   EXPECT_THAT(next_responses[1]->result_error(), IsOk());
1922   EXPECT_THAT(next_responses[2]->result_error(), IsOk());
1923 
1924   // Verify that results of aborted Jobs were not cached.
1925   EXPECT_EQ(6u, proc_->GetCaptureList().size());
1926   EXPECT_EQ(3u, resolve_context_->host_cache()->size());
1927 }
1928 // Tests that a new Request made from the callback of a previously aborted one
1929 // will not be aborted.
TEST_F(HostResolverManagerTest,AbortOnlyExistingRequestsOnIPAddressChangeAsync)1930 TEST_F(HostResolverManagerTest,
1931        AbortOnlyExistingRequestsOnIPAddressChangeAsync) {
1932   AbortOnlyExistingRequestsOnIPAddressChangeTest(true);
1933 }
TEST_F(HostResolverManagerTest,AbortOnlyExistingRequestsOnIPAddressChangeSync)1934 TEST_F(HostResolverManagerTest,
1935        AbortOnlyExistingRequestsOnIPAddressChangeSync) {
1936   AbortOnlyExistingRequestsOnIPAddressChangeTest(false);
1937 }
1938 
1939 // Tests that when the maximum threads is set to 1, requests are dequeued
1940 // in order of priority.
TEST_F(HostResolverManagerTest,HigherPriorityRequestsStartedFirst)1941 TEST_F(HostResolverManagerTest, HigherPriorityRequestsStartedFirst) {
1942   CreateSerialResolver();
1943 
1944   HostResolver::ResolveHostParameters low_priority;
1945   low_priority.initial_priority = LOW;
1946   HostResolver::ResolveHostParameters medium_priority;
1947   medium_priority.initial_priority = MEDIUM;
1948   HostResolver::ResolveHostParameters highest_priority;
1949   highest_priority.initial_priority = HIGHEST;
1950 
1951   // Note that at this point the MockHostResolverProc is blocked, so any
1952   // requests we make will not complete.
1953 
1954   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
1955   responses.emplace_back(
1956       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1957           HostPortPair("req0", 80), NetworkAnonymizationKey(),
1958           NetLogWithSource(), low_priority, resolve_context_.get(),
1959           resolve_context_->host_cache())));
1960   responses.emplace_back(
1961       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1962           HostPortPair("req1", 80), NetworkAnonymizationKey(),
1963           NetLogWithSource(), medium_priority, resolve_context_.get(),
1964           resolve_context_->host_cache())));
1965   responses.emplace_back(
1966       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1967           HostPortPair("req2", 80), NetworkAnonymizationKey(),
1968           NetLogWithSource(), medium_priority, resolve_context_.get(),
1969           resolve_context_->host_cache())));
1970   responses.emplace_back(
1971       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1972           HostPortPair("req3", 80), NetworkAnonymizationKey(),
1973           NetLogWithSource(), low_priority, resolve_context_.get(),
1974           resolve_context_->host_cache())));
1975   responses.emplace_back(
1976       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1977           HostPortPair("req4", 80), NetworkAnonymizationKey(),
1978           NetLogWithSource(), highest_priority, resolve_context_.get(),
1979           resolve_context_->host_cache())));
1980   responses.emplace_back(
1981       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1982           HostPortPair("req5", 80), NetworkAnonymizationKey(),
1983           NetLogWithSource(), low_priority, resolve_context_.get(),
1984           resolve_context_->host_cache())));
1985   responses.emplace_back(
1986       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1987           HostPortPair("req6", 80), NetworkAnonymizationKey(),
1988           NetLogWithSource(), low_priority, resolve_context_.get(),
1989           resolve_context_->host_cache())));
1990   responses.emplace_back(
1991       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
1992           HostPortPair("req5", 80), NetworkAnonymizationKey(),
1993           NetLogWithSource(), highest_priority, resolve_context_.get(),
1994           resolve_context_->host_cache())));
1995 
1996   for (const auto& response : responses) {
1997     ASSERT_FALSE(response->complete());
1998   }
1999 
2000   // Unblock the resolver thread so the requests can run.
2001   proc_->SignalMultiple(responses.size());  // More than needed.
2002 
2003   // Wait for all the requests to complete successfully.
2004   for (auto& response : responses) {
2005     EXPECT_THAT(response->result_error(), IsOk());
2006   }
2007 
2008   // Since we have restricted to a single concurrent thread in the jobpool,
2009   // the requests should complete in order of priority (with the exception
2010   // of the first request, which gets started right away, since there is
2011   // nothing outstanding).
2012   MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
2013   ASSERT_EQ(7u, capture_list.size());
2014 
2015   EXPECT_EQ("req0", capture_list[0].hostname);
2016   EXPECT_EQ("req4", capture_list[1].hostname);
2017   EXPECT_EQ("req5", capture_list[2].hostname);
2018   EXPECT_EQ("req1", capture_list[3].hostname);
2019   EXPECT_EQ("req2", capture_list[4].hostname);
2020   EXPECT_EQ("req3", capture_list[5].hostname);
2021   EXPECT_EQ("req6", capture_list[6].hostname);
2022 }
2023 
ChangePriorityTest(bool is_async)2024 void HostResolverManagerTest::ChangePriorityTest(bool is_async) {
2025   CreateSerialResolver(true /* check_ipv6_on_wifi */, true /* ipv6_reachable */,
2026                        is_async);
2027 
2028   HostResolver::ResolveHostParameters lowest_priority;
2029   lowest_priority.initial_priority = LOWEST;
2030   HostResolver::ResolveHostParameters low_priority;
2031   low_priority.initial_priority = LOW;
2032   HostResolver::ResolveHostParameters medium_priority;
2033   medium_priority.initial_priority = MEDIUM;
2034 
2035   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
2036   responses.emplace_back(
2037       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2038           HostPortPair("req0", 80), NetworkAnonymizationKey(),
2039           NetLogWithSource(), medium_priority, resolve_context_.get(),
2040           resolve_context_->host_cache())));
2041   responses.emplace_back(
2042       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2043           HostPortPair("req1", 80), NetworkAnonymizationKey(),
2044           NetLogWithSource(), low_priority, resolve_context_.get(),
2045           resolve_context_->host_cache())));
2046   responses.emplace_back(
2047       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2048           HostPortPair("req2", 80), NetworkAnonymizationKey(),
2049           NetLogWithSource(), lowest_priority, resolve_context_.get(),
2050           resolve_context_->host_cache())));
2051 
2052   // req0 starts immediately; without ChangePriority, req1 and then req2 should
2053   // run.
2054   for (const auto& response : responses) {
2055     ASSERT_FALSE(response->complete());
2056   }
2057 
2058   // Changing req2 to HIGHEST should make it run before req1.
2059   // (It can't run before req0, since req0 started immediately.)
2060   responses[2]->request()->ChangeRequestPriority(HIGHEST);
2061 
2062   // Let all 3 requests finish.
2063   proc_->SignalMultiple(3u);
2064 
2065   for (auto& response : responses) {
2066     EXPECT_THAT(response->result_error(), IsOk());
2067   }
2068 
2069   MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
2070   ASSERT_EQ(3u, capture_list.size());
2071 
2072   EXPECT_EQ("req0", capture_list[0].hostname);
2073   EXPECT_EQ("req2", capture_list[1].hostname);
2074   EXPECT_EQ("req1", capture_list[2].hostname);
2075 }
2076 
2077 // Test that changing a job's priority affects the dequeueing order.
TEST_F(HostResolverManagerTest,ChangePriorityAsync)2078 TEST_F(HostResolverManagerTest, ChangePriorityAsync) {
2079   ChangePriorityTest(true);
2080 }
2081 
TEST_F(HostResolverManagerTest,ChangePrioritySync)2082 TEST_F(HostResolverManagerTest, ChangePrioritySync) {
2083   ChangePriorityTest(false);
2084 }
2085 
2086 // Try cancelling a job which has not started yet.
TEST_F(HostResolverManagerTest,CancelPendingRequest)2087 TEST_F(HostResolverManagerTest, CancelPendingRequest) {
2088   CreateSerialResolver();
2089 
2090   HostResolver::ResolveHostParameters lowest_priority;
2091   lowest_priority.initial_priority = LOWEST;
2092   HostResolver::ResolveHostParameters low_priority;
2093   low_priority.initial_priority = LOW;
2094   HostResolver::ResolveHostParameters medium_priority;
2095   medium_priority.initial_priority = MEDIUM;
2096   HostResolver::ResolveHostParameters highest_priority;
2097   highest_priority.initial_priority = HIGHEST;
2098 
2099   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
2100   responses.emplace_back(
2101       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2102           HostPortPair("req0", 80), NetworkAnonymizationKey(),
2103           NetLogWithSource(), lowest_priority, resolve_context_.get(),
2104           resolve_context_->host_cache())));
2105   responses.emplace_back(
2106       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2107           HostPortPair("req1", 80), NetworkAnonymizationKey(),
2108           NetLogWithSource(), highest_priority, resolve_context_.get(),
2109           resolve_context_->host_cache())));
2110   responses.emplace_back(
2111       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2112           HostPortPair("req2", 80), NetworkAnonymizationKey(),
2113           NetLogWithSource(), medium_priority, resolve_context_.get(),
2114           resolve_context_->host_cache())));
2115   responses.emplace_back(
2116       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2117           HostPortPair("req3", 80), NetworkAnonymizationKey(),
2118           NetLogWithSource(), low_priority, resolve_context_.get(),
2119           resolve_context_->host_cache())));
2120   responses.emplace_back(
2121       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2122           HostPortPair("req4", 80), NetworkAnonymizationKey(),
2123           NetLogWithSource(), highest_priority, resolve_context_.get(),
2124           resolve_context_->host_cache())));
2125   responses.emplace_back(
2126       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2127           HostPortPair("req5", 80), NetworkAnonymizationKey(),
2128           NetLogWithSource(), lowest_priority, resolve_context_.get(),
2129           resolve_context_->host_cache())));
2130   responses.emplace_back(
2131       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2132           HostPortPair("req6", 80), NetworkAnonymizationKey(),
2133           NetLogWithSource(), medium_priority, resolve_context_.get(),
2134           resolve_context_->host_cache())));
2135 
2136   // Cancel some requests
2137   responses[1]->CancelRequest();
2138   responses[4]->CancelRequest();
2139   responses[5]->CancelRequest();
2140 
2141   // Unblock the resolver thread so the requests can run.
2142   proc_->SignalMultiple(responses.size());  // More than needed.
2143 
2144   // Let everything try to finish.
2145   base::RunLoop().RunUntilIdle();
2146 
2147   // Wait for all the requests to complete succesfully.
2148   EXPECT_THAT(responses[0]->result_error(), IsOk());
2149   EXPECT_THAT(responses[2]->result_error(), IsOk());
2150   EXPECT_THAT(responses[3]->result_error(), IsOk());
2151   EXPECT_THAT(responses[6]->result_error(), IsOk());
2152 
2153   // Cancelled requests shouldn't complete.
2154   EXPECT_FALSE(responses[1]->complete());
2155   EXPECT_FALSE(responses[4]->complete());
2156   EXPECT_FALSE(responses[5]->complete());
2157 
2158   // Verify that they called out to the resolver proc (which runs on the
2159   // resolver thread) in the expected order.
2160   MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
2161   ASSERT_EQ(4u, capture_list.size());
2162 
2163   EXPECT_EQ("req0", capture_list[0].hostname);
2164   EXPECT_EQ("req2", capture_list[1].hostname);
2165   EXPECT_EQ("req6", capture_list[2].hostname);
2166   EXPECT_EQ("req3", capture_list[3].hostname);
2167 }
2168 
2169 // Test that when too many requests are enqueued, old ones start to be aborted.
TEST_F(HostResolverManagerTest,QueueOverflow)2170 TEST_F(HostResolverManagerTest, QueueOverflow) {
2171   CreateSerialResolver();
2172 
2173   // Allow only 3 queued jobs.
2174   const size_t kMaxPendingJobs = 3u;
2175   resolver_->SetMaxQueuedJobsForTesting(kMaxPendingJobs);
2176 
2177   HostResolver::ResolveHostParameters lowest_priority;
2178   lowest_priority.initial_priority = LOWEST;
2179   HostResolver::ResolveHostParameters low_priority;
2180   low_priority.initial_priority = LOW;
2181   HostResolver::ResolveHostParameters medium_priority;
2182   medium_priority.initial_priority = MEDIUM;
2183   HostResolver::ResolveHostParameters highest_priority;
2184   highest_priority.initial_priority = HIGHEST;
2185 
2186   // Note that at this point the MockHostResolverProc is blocked, so any
2187   // requests we make will not complete.
2188 
2189   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
2190   responses.emplace_back(
2191       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2192           HostPortPair("req0", 80), NetworkAnonymizationKey(),
2193           NetLogWithSource(), lowest_priority, resolve_context_.get(),
2194           resolve_context_->host_cache())));
2195   responses.emplace_back(
2196       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2197           HostPortPair("req1", 80), NetworkAnonymizationKey(),
2198           NetLogWithSource(), highest_priority, resolve_context_.get(),
2199           resolve_context_->host_cache())));
2200   responses.emplace_back(
2201       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2202           HostPortPair("req2", 80), NetworkAnonymizationKey(),
2203           NetLogWithSource(), medium_priority, resolve_context_.get(),
2204           resolve_context_->host_cache())));
2205   responses.emplace_back(
2206       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2207           HostPortPair("req3", 80), NetworkAnonymizationKey(),
2208           NetLogWithSource(), medium_priority, resolve_context_.get(),
2209           resolve_context_->host_cache())));
2210 
2211   // At this point, there are 3 enqueued jobs (and one "running" job).
2212   // Insertion of subsequent requests will cause evictions.
2213 
2214   responses.emplace_back(
2215       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2216           HostPortPair("req4", 80), NetworkAnonymizationKey(),
2217           NetLogWithSource(), low_priority, resolve_context_.get(),
2218           resolve_context_->host_cache())));
2219   EXPECT_THAT(responses[4]->result_error(),
2220               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));  // Evicts self.
2221   EXPECT_FALSE(responses[4]->request()->GetAddressResults());
2222   EXPECT_FALSE(responses[4]->request()->GetEndpointResults());
2223 
2224   responses.emplace_back(
2225       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2226           HostPortPair("req5", 80), NetworkAnonymizationKey(),
2227           NetLogWithSource(), medium_priority, resolve_context_.get(),
2228           resolve_context_->host_cache())));
2229   EXPECT_THAT(responses[2]->result_error(),
2230               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
2231   EXPECT_FALSE(responses[2]->request()->GetAddressResults());
2232   EXPECT_FALSE(responses[2]->request()->GetEndpointResults());
2233 
2234   responses.emplace_back(
2235       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2236           HostPortPair("req6", 80), NetworkAnonymizationKey(),
2237           NetLogWithSource(), highest_priority, resolve_context_.get(),
2238           resolve_context_->host_cache())));
2239   EXPECT_THAT(responses[3]->result_error(),
2240               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
2241   EXPECT_FALSE(responses[3]->request()->GetAddressResults());
2242   EXPECT_FALSE(responses[3]->request()->GetEndpointResults());
2243 
2244   responses.emplace_back(
2245       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
2246           HostPortPair("req7", 80), NetworkAnonymizationKey(),
2247           NetLogWithSource(), medium_priority, resolve_context_.get(),
2248           resolve_context_->host_cache())));
2249   EXPECT_THAT(responses[5]->result_error(),
2250               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
2251   EXPECT_FALSE(responses[5]->request()->GetAddressResults());
2252   EXPECT_FALSE(responses[5]->request()->GetEndpointResults());
2253 
2254   // Unblock the resolver thread so the requests can run.
2255   proc_->SignalMultiple(4u);
2256 
2257   // The rest should succeed.
2258   EXPECT_THAT(responses[0]->result_error(), IsOk());
2259   EXPECT_TRUE(responses[0]->request()->GetAddressResults());
2260   EXPECT_TRUE(responses[0]->request()->GetEndpointResults());
2261   EXPECT_THAT(responses[1]->result_error(), IsOk());
2262   EXPECT_TRUE(responses[1]->request()->GetAddressResults());
2263   EXPECT_TRUE(responses[1]->request()->GetEndpointResults());
2264   EXPECT_THAT(responses[6]->result_error(), IsOk());
2265   EXPECT_TRUE(responses[6]->request()->GetAddressResults());
2266   EXPECT_TRUE(responses[6]->request()->GetEndpointResults());
2267   EXPECT_THAT(responses[7]->result_error(), IsOk());
2268   EXPECT_TRUE(responses[7]->request()->GetAddressResults());
2269   EXPECT_TRUE(responses[7]->request()->GetEndpointResults());
2270 
2271   // Verify that they called out the the resolver proc (which runs on the
2272   // resolver thread) in the expected order.
2273   MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
2274   ASSERT_EQ(4u, capture_list.size());
2275 
2276   EXPECT_EQ("req0", capture_list[0].hostname);
2277   EXPECT_EQ("req1", capture_list[1].hostname);
2278   EXPECT_EQ("req6", capture_list[2].hostname);
2279   EXPECT_EQ("req7", capture_list[3].hostname);
2280 
2281   // Verify that the evicted (incomplete) requests were not cached.
2282   EXPECT_EQ(4u, resolve_context_->host_cache()->size());
2283 
2284   for (size_t i = 0; i < responses.size(); ++i) {
2285     EXPECT_TRUE(responses[i]->complete()) << i;
2286   }
2287 }
2288 
2289 // Tests that jobs can self-evict by setting the max queue to 0.
TEST_F(HostResolverManagerTest,QueueOverflow_SelfEvict)2290 TEST_F(HostResolverManagerTest, QueueOverflow_SelfEvict) {
2291   CreateSerialResolver();
2292   resolver_->SetMaxQueuedJobsForTesting(0);
2293 
2294   // Note that at this point the MockHostResolverProc is blocked, so any
2295   // requests we make will not complete.
2296 
2297   ResolveHostResponseHelper run_response(resolver_->CreateRequest(
2298       HostPortPair("run", 80), NetworkAnonymizationKey(), NetLogWithSource(),
2299       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
2300 
2301   ResolveHostResponseHelper evict_response(resolver_->CreateRequest(
2302       HostPortPair("req1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
2303       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
2304   EXPECT_THAT(evict_response.result_error(),
2305               IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE));
2306   EXPECT_FALSE(evict_response.request()->GetAddressResults());
2307   EXPECT_FALSE(evict_response.request()->GetEndpointResults());
2308 
2309   proc_->SignalMultiple(1u);
2310 
2311   EXPECT_THAT(run_response.result_error(), IsOk());
2312   EXPECT_TRUE(run_response.request()->GetAddressResults());
2313   EXPECT_TRUE(run_response.request()->GetEndpointResults());
2314 }
2315 
2316 // Make sure that the dns query type parameter is respected when raw IPs are
2317 // passed in.
TEST_F(HostResolverManagerTest,AddressFamilyWithRawIPs)2318 TEST_F(HostResolverManagerTest, AddressFamilyWithRawIPs) {
2319   HostResolver::ResolveHostParameters v4_parameters;
2320   v4_parameters.dns_query_type = DnsQueryType::A;
2321 
2322   HostResolver::ResolveHostParameters v6_parameters;
2323   v6_parameters.dns_query_type = DnsQueryType::AAAA;
2324 
2325   ResolveHostResponseHelper v4_v4_request(resolver_->CreateRequest(
2326       HostPortPair("127.0.0.1", 80), NetworkAnonymizationKey(),
2327       NetLogWithSource(), v4_parameters, resolve_context_.get(),
2328       resolve_context_->host_cache()));
2329   EXPECT_THAT(v4_v4_request.result_error(), IsOk());
2330   EXPECT_THAT(v4_v4_request.request()->GetAddressResults()->endpoints(),
2331               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
2332   EXPECT_THAT(
2333       v4_v4_request.request()->GetEndpointResults(),
2334       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2335           testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
2336 
2337   ResolveHostResponseHelper v4_v6_request(resolver_->CreateRequest(
2338       HostPortPair("127.0.0.1", 80), NetworkAnonymizationKey(),
2339       NetLogWithSource(), v6_parameters, resolve_context_.get(),
2340       resolve_context_->host_cache()));
2341   EXPECT_THAT(v4_v6_request.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
2342 
2343   ResolveHostResponseHelper v4_unsp_request(resolver_->CreateRequest(
2344       HostPortPair("127.0.0.1", 80), NetworkAnonymizationKey(),
2345       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2346       resolve_context_->host_cache()));
2347   EXPECT_THAT(v4_unsp_request.result_error(), IsOk());
2348   EXPECT_THAT(v4_unsp_request.request()->GetAddressResults()->endpoints(),
2349               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
2350   EXPECT_THAT(
2351       v4_unsp_request.request()->GetEndpointResults(),
2352       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2353           testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
2354 
2355   ResolveHostResponseHelper v6_v4_request(resolver_->CreateRequest(
2356       HostPortPair("::1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
2357       v4_parameters, resolve_context_.get(), resolve_context_->host_cache()));
2358   EXPECT_THAT(v6_v4_request.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
2359 
2360   ResolveHostResponseHelper v6_v6_request(resolver_->CreateRequest(
2361       HostPortPair("::1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
2362       v6_parameters, resolve_context_.get(), resolve_context_->host_cache()));
2363   EXPECT_THAT(v6_v6_request.result_error(), IsOk());
2364   EXPECT_THAT(v6_v6_request.request()->GetAddressResults()->endpoints(),
2365               testing::ElementsAre(CreateExpected("::1", 80)));
2366   EXPECT_THAT(
2367       v6_v6_request.request()->GetEndpointResults(),
2368       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2369           testing::ElementsAre(CreateExpected("::1", 80))))));
2370 
2371   ResolveHostResponseHelper v6_unsp_request(resolver_->CreateRequest(
2372       HostPortPair("::1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
2373       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
2374   EXPECT_THAT(v6_unsp_request.result_error(), IsOk());
2375   EXPECT_THAT(v6_unsp_request.request()->GetAddressResults()->endpoints(),
2376               testing::ElementsAre(CreateExpected("::1", 80)));
2377   EXPECT_THAT(
2378       v6_unsp_request.request()->GetEndpointResults(),
2379       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2380           testing::ElementsAre(CreateExpected("::1", 80))))));
2381 }
2382 
TEST_F(HostResolverManagerTest,LocalOnly_FromCache)2383 TEST_F(HostResolverManagerTest, LocalOnly_FromCache) {
2384   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
2385   proc_->SignalMultiple(1u);  // Need only one.
2386 
2387   HostResolver::ResolveHostParameters source_none_parameters;
2388   source_none_parameters.source = HostResolverSource::LOCAL_ONLY;
2389 
2390   // First NONE query expected to complete synchronously with a cache miss.
2391   ResolveHostResponseHelper cache_miss_request(resolver_->CreateRequest(
2392       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2393       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2394       resolve_context_->host_cache()));
2395   EXPECT_TRUE(cache_miss_request.complete());
2396   EXPECT_THAT(cache_miss_request.result_error(), IsError(ERR_DNS_CACHE_MISS));
2397   EXPECT_FALSE(cache_miss_request.request()->GetAddressResults());
2398   EXPECT_FALSE(cache_miss_request.request()->GetEndpointResults());
2399   EXPECT_FALSE(cache_miss_request.request()->GetStaleInfo());
2400 
2401   // Normal query to populate the cache.
2402   ResolveHostResponseHelper normal_request(resolver_->CreateRequest(
2403       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2404       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2405       resolve_context_->host_cache()));
2406   EXPECT_THAT(normal_request.result_error(), IsOk());
2407   EXPECT_FALSE(normal_request.request()->GetStaleInfo());
2408 
2409   // Second NONE query expected to complete synchronously with cache hit.
2410   ResolveHostResponseHelper cache_hit_request(resolver_->CreateRequest(
2411       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2412       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2413       resolve_context_->host_cache()));
2414   EXPECT_TRUE(cache_hit_request.complete());
2415   EXPECT_THAT(cache_hit_request.result_error(), IsOk());
2416   EXPECT_THAT(cache_hit_request.request()->GetAddressResults()->endpoints(),
2417               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
2418   EXPECT_THAT(
2419       cache_hit_request.request()->GetEndpointResults(),
2420       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2421           testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
2422   EXPECT_FALSE(cache_hit_request.request()->GetStaleInfo().value().is_stale());
2423 }
2424 
TEST_F(HostResolverManagerTest,LocalOnly_StaleEntry)2425 TEST_F(HostResolverManagerTest, LocalOnly_StaleEntry) {
2426   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
2427   proc_->SignalMultiple(1u);  // Need only one.
2428 
2429   HostResolver::ResolveHostParameters source_none_parameters;
2430   source_none_parameters.source = HostResolverSource::LOCAL_ONLY;
2431 
2432   // First NONE query expected to complete synchronously with a cache miss.
2433   ResolveHostResponseHelper cache_miss_request(resolver_->CreateRequest(
2434       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2435       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2436       resolve_context_->host_cache()));
2437   EXPECT_TRUE(cache_miss_request.complete());
2438   EXPECT_THAT(cache_miss_request.result_error(), IsError(ERR_DNS_CACHE_MISS));
2439   EXPECT_FALSE(cache_miss_request.request()->GetAddressResults());
2440   EXPECT_FALSE(cache_miss_request.request()->GetEndpointResults());
2441   EXPECT_FALSE(cache_miss_request.request()->GetStaleInfo());
2442 
2443   // Normal query to populate the cache.
2444   ResolveHostResponseHelper normal_request(resolver_->CreateRequest(
2445       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2446       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2447       resolve_context_->host_cache()));
2448   EXPECT_THAT(normal_request.result_error(), IsOk());
2449   EXPECT_FALSE(normal_request.request()->GetStaleInfo());
2450 
2451   MakeCacheStale();
2452 
2453   // Second NONE query still expected to complete synchronously with cache miss.
2454   ResolveHostResponseHelper stale_request(resolver_->CreateRequest(
2455       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2456       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2457       resolve_context_->host_cache()));
2458   EXPECT_TRUE(stale_request.complete());
2459   EXPECT_THAT(stale_request.result_error(), IsError(ERR_DNS_CACHE_MISS));
2460   EXPECT_FALSE(stale_request.request()->GetAddressResults());
2461   EXPECT_FALSE(stale_request.request()->GetEndpointResults());
2462   EXPECT_FALSE(stale_request.request()->GetStaleInfo());
2463 }
2464 
LocalOnlyFromIpTest(bool is_async)2465 void HostResolverManagerTest::LocalOnlyFromIpTest(bool is_async) {
2466   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
2467                                     true /* ipv6_reachable */,
2468                                     true /* check_ipv6_on_wifi */, is_async);
2469   HostResolver::ResolveHostParameters source_none_parameters;
2470   source_none_parameters.source = HostResolverSource::LOCAL_ONLY;
2471 
2472   ResolveHostResponseHelper response(resolver_->CreateRequest(
2473       HostPortPair("1.2.3.4", 56), NetworkAnonymizationKey(),
2474       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2475       resolve_context_->host_cache()));
2476 
2477   // If IPv6 reachability is asynchronous, the first request will return
2478   // NAME_NOT_RESOLVED. Do a second request to confirm that it returns OK once
2479   // reachability check completes.
2480   if (is_async) {
2481     // Expected to resolve synchronously.
2482     EXPECT_TRUE(response.complete());
2483     EXPECT_EQ(response.result_error(), ERR_NAME_NOT_RESOLVED);
2484     EXPECT_FALSE(response.request()->GetAddressResults());
2485     EXPECT_FALSE(response.request()->GetEndpointResults());
2486     EXPECT_FALSE(response.request()->GetStaleInfo());
2487     base::RunLoop().RunUntilIdle();
2488 
2489     ResolveHostResponseHelper response2(resolver_->CreateRequest(
2490         HostPortPair("1.2.3.4", 56), NetworkAnonymizationKey(),
2491         NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2492         resolve_context_->host_cache()));
2493     EXPECT_TRUE(response2.complete());
2494     EXPECT_THAT(response2.result_error(), IsOk());
2495     EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
2496                 testing::ElementsAre(CreateExpected("1.2.3.4", 56)));
2497     EXPECT_THAT(response2.request()->GetEndpointResults(),
2498                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
2499                     testing::ElementsAre(CreateExpected("1.2.3.4", 56))))));
2500     EXPECT_FALSE(response2.request()->GetStaleInfo());
2501   } else {
2502     // Expected to resolve synchronously.
2503     EXPECT_TRUE(response.complete());
2504     EXPECT_THAT(response.result_error(), IsOk());
2505     EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
2506                 testing::ElementsAre(CreateExpected("1.2.3.4", 56)));
2507     EXPECT_THAT(response.request()->GetEndpointResults(),
2508                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
2509                     testing::ElementsAre(CreateExpected("1.2.3.4", 56))))));
2510     EXPECT_FALSE(response.request()->GetStaleInfo());
2511   }
2512 }
2513 
TEST_F(HostResolverManagerTest,LocalOnly_FromIpAsync)2514 TEST_F(HostResolverManagerTest, LocalOnly_FromIpAsync) {
2515   LocalOnlyFromIpTest(true);
2516 }
2517 
TEST_F(HostResolverManagerTest,LocalOnly_FromIpSync)2518 TEST_F(HostResolverManagerTest, LocalOnly_FromIpSync) {
2519   LocalOnlyFromIpTest(false);
2520 }
2521 
TEST_F(HostResolverManagerTest,LocalOnly_InvalidName)2522 TEST_F(HostResolverManagerTest, LocalOnly_InvalidName) {
2523   proc_->AddRuleForAllFamilies("foo,bar.com", "192.168.1.42");
2524 
2525   HostResolver::ResolveHostParameters source_none_parameters;
2526   source_none_parameters.source = HostResolverSource::LOCAL_ONLY;
2527 
2528   ResolveHostResponseHelper response(resolver_->CreateRequest(
2529       HostPortPair("foo,bar.com", 57), NetworkAnonymizationKey(),
2530       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2531       resolve_context_->host_cache()));
2532 
2533   // Expected to fail synchronously.
2534   EXPECT_TRUE(response.complete());
2535   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
2536   EXPECT_FALSE(response.request()->GetAddressResults());
2537   EXPECT_FALSE(response.request()->GetEndpointResults());
2538   EXPECT_FALSE(response.request()->GetStaleInfo());
2539 }
2540 
TEST_F(HostResolverManagerTest,LocalOnly_InvalidLocalhost)2541 TEST_F(HostResolverManagerTest, LocalOnly_InvalidLocalhost) {
2542   HostResolver::ResolveHostParameters source_none_parameters;
2543   source_none_parameters.source = HostResolverSource::LOCAL_ONLY;
2544 
2545   ResolveHostResponseHelper response(resolver_->CreateRequest(
2546       HostPortPair("foo,bar.localhost", 58), NetworkAnonymizationKey(),
2547       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
2548       resolve_context_->host_cache()));
2549 
2550   // Expected to fail synchronously.
2551   EXPECT_TRUE(response.complete());
2552   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
2553   EXPECT_FALSE(response.request()->GetAddressResults());
2554   EXPECT_FALSE(response.request()->GetEndpointResults());
2555   EXPECT_FALSE(response.request()->GetStaleInfo());
2556 }
2557 
TEST_F(HostResolverManagerTest,StaleAllowed)2558 TEST_F(HostResolverManagerTest, StaleAllowed) {
2559   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
2560   proc_->SignalMultiple(1u);  // Need only one.
2561 
2562   HostResolver::ResolveHostParameters stale_allowed_parameters;
2563   stale_allowed_parameters.source = HostResolverSource::LOCAL_ONLY;
2564   stale_allowed_parameters.cache_usage =
2565       HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
2566 
2567   // First query expected to complete synchronously as a cache miss.
2568   ResolveHostResponseHelper cache_miss_request(resolver_->CreateRequest(
2569       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2570       NetLogWithSource(), stale_allowed_parameters, resolve_context_.get(),
2571       resolve_context_->host_cache()));
2572   EXPECT_TRUE(cache_miss_request.complete());
2573   EXPECT_THAT(cache_miss_request.result_error(), IsError(ERR_DNS_CACHE_MISS));
2574   EXPECT_FALSE(cache_miss_request.request()->GetAddressResults());
2575   EXPECT_FALSE(cache_miss_request.request()->GetEndpointResults());
2576   EXPECT_FALSE(cache_miss_request.request()->GetStaleInfo());
2577 
2578   // Normal query to populate cache
2579   ResolveHostResponseHelper normal_request(resolver_->CreateRequest(
2580       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2581       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2582       resolve_context_->host_cache()));
2583   EXPECT_THAT(normal_request.result_error(), IsOk());
2584   EXPECT_FALSE(normal_request.request()->GetStaleInfo());
2585 
2586   MakeCacheStale();
2587 
2588   // Second NONE query expected to get a stale cache hit.
2589   ResolveHostResponseHelper stale_request(resolver_->CreateRequest(
2590       HostPortPair("just.testing", 84), NetworkAnonymizationKey(),
2591       NetLogWithSource(), stale_allowed_parameters, resolve_context_.get(),
2592       resolve_context_->host_cache()));
2593   EXPECT_TRUE(stale_request.complete());
2594   EXPECT_THAT(stale_request.result_error(), IsOk());
2595   EXPECT_THAT(stale_request.request()->GetAddressResults()->endpoints(),
2596               testing::ElementsAre(CreateExpected("192.168.1.42", 84)));
2597   EXPECT_THAT(
2598       stale_request.request()->GetEndpointResults(),
2599       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2600           testing::ElementsAre(CreateExpected("192.168.1.42", 84))))));
2601   EXPECT_TRUE(stale_request.request()->GetStaleInfo().value().is_stale());
2602 }
2603 
TEST_F(HostResolverManagerTest,StaleAllowed_NonLocal)2604 TEST_F(HostResolverManagerTest, StaleAllowed_NonLocal) {
2605   proc_->AddRuleForAllFamilies("just.testing", "192.168.2.42");
2606   proc_->SignalMultiple(1u);  // Need only one.
2607 
2608   HostResolver::ResolveHostParameters stale_allowed_parameters;
2609   stale_allowed_parameters.cache_usage =
2610       HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
2611 
2612   // Normal non-local resolves should still work normally with the STALE_ALLOWED
2613   // parameter, and there should be no stale info.
2614   ResolveHostResponseHelper response(resolver_->CreateRequest(
2615       HostPortPair("just.testing", 85), NetworkAnonymizationKey(),
2616       NetLogWithSource(), stale_allowed_parameters, resolve_context_.get(),
2617       resolve_context_->host_cache()));
2618   EXPECT_THAT(response.result_error(), IsOk());
2619   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
2620               testing::ElementsAre(CreateExpected("192.168.2.42", 85)));
2621   EXPECT_THAT(
2622       response.request()->GetEndpointResults(),
2623       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2624           testing::ElementsAre(CreateExpected("192.168.2.42", 85))))));
2625   EXPECT_FALSE(response.request()->GetStaleInfo());
2626 }
2627 
StaleAllowedFromIpTest(bool is_async)2628 void HostResolverManagerTest::StaleAllowedFromIpTest(bool is_async) {
2629   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
2630                                     true /* ipv6_reachable */,
2631                                     true /* check_ipv6_on_wifi */, is_async);
2632   HostResolver::ResolveHostParameters stale_allowed_parameters;
2633   stale_allowed_parameters.cache_usage =
2634       HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
2635 
2636   ResolveHostResponseHelper response(resolver_->CreateRequest(
2637       HostPortPair("1.2.3.4", 57), NetworkAnonymizationKey(),
2638       NetLogWithSource(), stale_allowed_parameters, resolve_context_.get(),
2639       resolve_context_->host_cache()));
2640 
2641   if (!is_async) {
2642     // Expected to resolve synchronously without stale info.
2643     EXPECT_TRUE(response.complete());
2644   }
2645   EXPECT_THAT(response.result_error(), IsOk());
2646   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
2647               testing::ElementsAre(CreateExpected("1.2.3.4", 57)));
2648   EXPECT_THAT(
2649       response.request()->GetEndpointResults(),
2650       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2651           testing::ElementsAre(CreateExpected("1.2.3.4", 57))))));
2652   EXPECT_FALSE(response.request()->GetStaleInfo());
2653 }
2654 
TEST_F(HostResolverManagerTest,StaleAllowed_FromIpAsync)2655 TEST_F(HostResolverManagerTest, StaleAllowed_FromIpAsync) {
2656   StaleAllowedFromIpTest(true);
2657 }
2658 
TEST_F(HostResolverManagerTest,StaleAllowed_FromIpSync)2659 TEST_F(HostResolverManagerTest, StaleAllowed_FromIpSync) {
2660   StaleAllowedFromIpTest(false);
2661 }
2662 
2663 // TODO(mgersh): add a test case for errors with positive TTL after
2664 // https://crbug.com/115051 is fixed.
2665 
2666 // Test the retry attempts simulating host resolver proc that takes too long.
TEST_F(HostResolverManagerTest,MultipleAttempts)2667 TEST_F(HostResolverManagerTest, MultipleAttempts) {
2668   // Total number of attempts would be 3 and we want the 3rd attempt to resolve
2669   // the host. First and second attempt will be forced to wait until they get
2670   // word that a resolution has completed. The 3rd resolution attempt will try
2671   // to get done ASAP, and won't wait.
2672   int kAttemptNumberToResolve = 3;
2673   int kTotalAttempts = 3;
2674 
2675   // Add a little bit of extra fudge to the delay to allow reasonable
2676   // flexibility for time > vs >= etc.  We don't need to fail the test if we
2677   // retry at t=6001 instead of t=6000.
2678   base::TimeDelta kSleepFudgeFactor = base::Milliseconds(1);
2679 
2680   auto resolver_proc = base::MakeRefCounted<LookupAttemptHostResolverProc>(
2681       nullptr, kAttemptNumberToResolve, kTotalAttempts);
2682 
2683   HostResolverSystemTask::Params params = DefaultParams(resolver_proc);
2684   base::TimeDelta unresponsive_delay = params.unresponsive_delay;
2685   int retry_factor = params.retry_factor;
2686 
2687   CreateResolverWithLimitsAndParams(kMaxJobs, params, true /* ipv6_reachable */,
2688                                     true /* check_ipv6_on_wifi */);
2689 
2690   // Override the current thread task runner, so we can simulate the passage of
2691   // time and avoid any actual sleeps.
2692   auto test_task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
2693   base::SingleThreadTaskRunner::CurrentHandleOverrideForTesting
2694       task_runner_current_default_handle_override(test_task_runner);
2695 
2696   // Resolve "host1".
2697   ResolveHostResponseHelper response(resolver_->CreateRequest(
2698       HostPortPair("host1", 70), NetworkAnonymizationKey(), NetLogWithSource(),
2699       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
2700   EXPECT_FALSE(response.complete());
2701 
2702   resolver_proc->WaitForNAttemptsToBeBlocked(1);
2703   EXPECT_FALSE(response.complete());
2704 
2705   test_task_runner->FastForwardBy(unresponsive_delay + kSleepFudgeFactor);
2706   resolver_proc->WaitForNAttemptsToBeBlocked(2);
2707   EXPECT_FALSE(response.complete());
2708 
2709   test_task_runner->FastForwardBy(unresponsive_delay * retry_factor +
2710                                   kSleepFudgeFactor);
2711 
2712   resolver_proc->WaitForAllAttemptsToFinish();
2713   test_task_runner->RunUntilIdle();
2714 
2715   // Resolve returns -4 to indicate that 3rd attempt has resolved the host.
2716   // Since we're using a TestMockTimeTaskRunner, the RunLoop stuff in
2717   // result_error() will fail if it actually has to wait, but unless there's an
2718   // error, the result should be immediately ready by this point.
2719   EXPECT_EQ(-4, response.result_error());
2720 
2721   // We should be done with retries, but make sure none erroneously happen.
2722   test_task_runner->FastForwardUntilNoTasksRemain();
2723 
2724   EXPECT_EQ(resolver_proc->GetTotalAttemptsResolved(), kTotalAttempts);
2725 }
2726 
2727 // Regression test for https://crbug.com/976948.
2728 //
2729 // Tests that when the maximum number of retries is set to
2730 // |HostResolver::ManagerOptions::kDefaultRetryAttempts| the
2731 // number of retries used is 4 rather than something higher.
TEST_F(HostResolverManagerTest,DefaultMaxRetryAttempts)2732 TEST_F(HostResolverManagerTest, DefaultMaxRetryAttempts) {
2733   auto test_task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
2734   base::SingleThreadTaskRunner::CurrentHandleOverrideForTesting
2735       task_runner_current_default_handle_override(test_task_runner);
2736 
2737   // Instantiate a ResolverProc that will block all incoming requests.
2738   auto resolver_proc = base::MakeRefCounted<LookupAttemptHostResolverProc>(
2739       nullptr, std::numeric_limits<size_t>::max(),
2740       std::numeric_limits<size_t>::max());
2741 
2742   // This corresponds to kDefaultMaxRetryAttempts in
2743   // HostResolverSystemTask::Params::HostResolverSystemTask::Params(). The
2744   // correspondence is verified below, since that symbol is not exported.
2745   const size_t expected_max_retries = 4;
2746 
2747   // Use the special value |ManagerOptions::kDefaultRetryAttempts|, which is
2748   // expected to translate into |expected_num_retries|.
2749   ASSERT_NE(HostResolverSystemTask::Params::kDefaultRetryAttempts,
2750             expected_max_retries);
2751   HostResolverSystemTask::Params params(
2752       resolver_proc, HostResolverSystemTask::Params::kDefaultRetryAttempts);
2753   ASSERT_EQ(params.max_retry_attempts, expected_max_retries);
2754 
2755   CreateResolverWithLimitsAndParams(kMaxJobs, params,
2756                                     false /* ipv6_reachable */,
2757                                     false /* check_ipv6_on_wifi */);
2758   // Resolve "host1". The resolver proc will hang all requests so this
2759   // resolution should remain stalled until calling SetResolvedAttemptNumber().
2760   ResolveHostResponseHelper response(resolver_->CreateRequest(
2761       HostPortPair("host1", 70), NetworkAnonymizationKey(), NetLogWithSource(),
2762       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
2763   EXPECT_FALSE(response.complete());
2764 
2765   // Simulate running the main thread (network task runner) for a long
2766   // time. Because none of the attempts posted to worker pool can complete, this
2767   // should cause all of the retry attempts to get posted, according to the
2768   // exponential backoff schedule.
2769   test_task_runner->FastForwardBy(base::Minutes(20));
2770 
2771   // Unblock the resolver proc, then wait for all the worker pool and main
2772   // thread tasks to complete. Note that the call to SetResolvedAttemptNumber(1)
2773   // will cause all the blocked resolver procs tasks fail with -2.
2774   resolver_proc->SetResolvedAttemptNumber(1);
2775   const int kExpectedError = -2;
2776   base::ThreadPoolInstance::Get()->FlushForTesting();
2777   test_task_runner->RunUntilIdle();
2778 
2779   ASSERT_TRUE(response.complete());
2780   EXPECT_EQ(kExpectedError, response.result_error());
2781 
2782   // Ensure that the original attempt was executed on the worker pool, as well
2783   // as the maximum number of allowed retries, and no more.
2784   EXPECT_EQ(static_cast<int>(expected_max_retries + 1),
2785             resolver_proc->GetTotalAttemptsResolved());
2786 }
2787 
2788 // If a host resolves to a list that includes 127.0.53.53, this is treated as
2789 // an error. 127.0.53.53 is a localhost address, however it has been given a
2790 // special significance by ICANN to help surface name collision resulting from
2791 // the new gTLDs.
TEST_F(HostResolverManagerTest,NameCollisionIcann)2792 TEST_F(HostResolverManagerTest, NameCollisionIcann) {
2793   proc_->AddRuleForAllFamilies("single", "127.0.53.53");
2794   proc_->AddRuleForAllFamilies("multiple", "127.0.0.1,127.0.53.53");
2795   proc_->AddRuleForAllFamilies("ipv6", "::127.0.53.53");
2796   proc_->AddRuleForAllFamilies("not_reserved1", "53.53.0.127");
2797   proc_->AddRuleForAllFamilies("not_reserved2", "127.0.53.54");
2798   proc_->AddRuleForAllFamilies("not_reserved3", "10.0.53.53");
2799   proc_->SignalMultiple(6u);
2800 
2801   ResolveHostResponseHelper single_response(resolver_->CreateRequest(
2802       HostPortPair("single", 80), NetworkAnonymizationKey(), NetLogWithSource(),
2803       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
2804   EXPECT_THAT(single_response.result_error(),
2805               IsError(ERR_ICANN_NAME_COLLISION));
2806   EXPECT_FALSE(single_response.request()->GetAddressResults());
2807   EXPECT_FALSE(single_response.request()->GetEndpointResults());
2808 
2809   // ERR_ICANN_NAME_COLLISION is cached like any other error, using a fixed TTL
2810   // for failed entries from proc-based resolver. That said, the fixed TTL is 0,
2811   // so it should never be cached.
2812   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
2813       GetCacheHit(HostCache::Key(
2814           "single", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
2815           HostResolverSource::ANY, NetworkAnonymizationKey()));
2816   EXPECT_FALSE(cache_result);
2817 
2818   ResolveHostResponseHelper multiple_response(resolver_->CreateRequest(
2819       HostPortPair("multiple", 80), NetworkAnonymizationKey(),
2820       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2821       resolve_context_->host_cache()));
2822   EXPECT_THAT(multiple_response.result_error(),
2823               IsError(ERR_ICANN_NAME_COLLISION));
2824 
2825   // Resolving an IP literal of 127.0.53.53 however is allowed.
2826   ResolveHostResponseHelper literal_response(resolver_->CreateRequest(
2827       HostPortPair("127.0.53.53", 80), NetworkAnonymizationKey(),
2828       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2829       resolve_context_->host_cache()));
2830   EXPECT_THAT(literal_response.result_error(), IsOk());
2831 
2832   // Moreover the address should not be recognized when embedded in an IPv6
2833   // address.
2834   ResolveHostResponseHelper ipv6_response(resolver_->CreateRequest(
2835       HostPortPair("127.0.53.53", 80), NetworkAnonymizationKey(),
2836       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2837       resolve_context_->host_cache()));
2838   EXPECT_THAT(ipv6_response.result_error(), IsOk());
2839 
2840   // Try some other IPs which are similar, but NOT an exact match on
2841   // 127.0.53.53.
2842   ResolveHostResponseHelper similar_response1(resolver_->CreateRequest(
2843       HostPortPair("not_reserved1", 80), NetworkAnonymizationKey(),
2844       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2845       resolve_context_->host_cache()));
2846   EXPECT_THAT(similar_response1.result_error(), IsOk());
2847 
2848   ResolveHostResponseHelper similar_response2(resolver_->CreateRequest(
2849       HostPortPair("not_reserved2", 80), NetworkAnonymizationKey(),
2850       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2851       resolve_context_->host_cache()));
2852   EXPECT_THAT(similar_response2.result_error(), IsOk());
2853 
2854   ResolveHostResponseHelper similar_response3(resolver_->CreateRequest(
2855       HostPortPair("not_reserved3", 80), NetworkAnonymizationKey(),
2856       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2857       resolve_context_->host_cache()));
2858   EXPECT_THAT(similar_response3.result_error(), IsOk());
2859 }
2860 
TEST_F(HostResolverManagerTest,StartIPv6ReachabilityCheck)2861 TEST_F(HostResolverManagerTest, StartIPv6ReachabilityCheck) {
2862   // The real HostResolverManager is needed since TestHostResolverManager will
2863   // bypass the IPv6 reachability tests.
2864   DestroyResolver();
2865   resolver_ = std::make_unique<HostResolverManager>(
2866       DefaultOptions(), nullptr /* system_dns_config_notifier */,
2867       nullptr /* net_log */);
2868   // Verify that two consecutive calls return the same value.
2869   RecordingNetLogObserver net_log_observer;
2870   NetLogWithSource net_log =
2871       NetLogWithSource::Make(net::NetLog::Get(), NetLogSourceType::NONE);
2872 
2873   int attempt1 =
2874       StartIPv6ReachabilityCheck(net_log, base::DoNothingAs<void(int)>());
2875   EXPECT_EQ(attempt1, OK);
2876   int result1 = GetLastIpv6ProbeResult();
2877   int attempt2 =
2878       StartIPv6ReachabilityCheck(net_log, base::DoNothingAs<void(int)>());
2879   EXPECT_EQ(attempt2, OK);
2880   int result2 = GetLastIpv6ProbeResult();
2881   EXPECT_EQ(result1, result2);
2882   // Filter reachability check events and verify that there are two of them.
2883   auto probe_event_list = net_log_observer.GetEntriesWithType(
2884       NetLogEventType::HOST_RESOLVER_MANAGER_IPV6_REACHABILITY_CHECK);
2885   ASSERT_EQ(2U, probe_event_list.size());
2886 
2887   // Verify that the first request was not cached and the second one was.
2888   EXPECT_FALSE(GetBooleanValueFromParams(probe_event_list[0], "cached"));
2889   EXPECT_TRUE(GetBooleanValueFromParams(probe_event_list[1], "cached"));
2890 }
2891 
TEST_F(HostResolverManagerTest,IncludeCanonicalName)2892 TEST_F(HostResolverManagerTest, IncludeCanonicalName) {
2893   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42",
2894                                HOST_RESOLVER_CANONNAME, "canon.name");
2895   proc_->SignalMultiple(2u);
2896 
2897   HostResolver::ResolveHostParameters parameters;
2898   parameters.include_canonical_name = true;
2899   ResolveHostResponseHelper response(resolver_->CreateRequest(
2900       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2901       NetLogWithSource(), parameters, resolve_context_.get(),
2902       resolve_context_->host_cache()));
2903   ResolveHostResponseHelper response_no_flag(resolver_->CreateRequest(
2904       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2905       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2906       resolve_context_->host_cache()));
2907 
2908   EXPECT_THAT(response.result_error(), IsOk());
2909   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
2910               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
2911   EXPECT_THAT(
2912       response.request()->GetEndpointResults(),
2913       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2914           testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
2915   EXPECT_THAT(response.request()->GetDnsAliasResults(),
2916               testing::Pointee(testing::UnorderedElementsAre("canon.name")));
2917 
2918   EXPECT_THAT(response_no_flag.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
2919 }
2920 
TEST_F(HostResolverManagerTest,FixupCanonicalName)2921 TEST_F(HostResolverManagerTest, FixupCanonicalName) {
2922   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42", /*flags=*/0,
2923                                "CANON.name");
2924   proc_->SignalMultiple(1u);
2925 
2926   ResolveHostResponseHelper response(resolver_->CreateRequest(
2927       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2928       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2929       resolve_context_->host_cache()));
2930 
2931   EXPECT_THAT(response.result_error(), IsOk());
2932   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
2933               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
2934   EXPECT_THAT(
2935       response.request()->GetEndpointResults(),
2936       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2937           testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
2938   EXPECT_THAT(response.request()->GetDnsAliasResults(),
2939               testing::Pointee(testing::UnorderedElementsAre("canon.name")));
2940 }
2941 
TEST_F(HostResolverManagerTest,IncludeCanonicalNameButNotReceived)2942 TEST_F(HostResolverManagerTest, IncludeCanonicalNameButNotReceived) {
2943   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42",
2944                                HOST_RESOLVER_CANONNAME);
2945   proc_->SignalMultiple(2u);
2946 
2947   HostResolver::ResolveHostParameters parameters;
2948   parameters.include_canonical_name = true;
2949   ResolveHostResponseHelper response(resolver_->CreateRequest(
2950       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2951       NetLogWithSource(), parameters, resolve_context_.get(),
2952       resolve_context_->host_cache()));
2953   ResolveHostResponseHelper response_no_flag(resolver_->CreateRequest(
2954       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2955       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2956       resolve_context_->host_cache()));
2957 
2958   EXPECT_THAT(response.result_error(), IsOk());
2959   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
2960               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
2961   EXPECT_THAT(
2962       response.request()->GetEndpointResults(),
2963       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2964           testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
2965   EXPECT_THAT(response.request()->GetDnsAliasResults(),
2966               testing::Pointee(testing::IsEmpty()));
2967 
2968   EXPECT_THAT(response_no_flag.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
2969 }
2970 
2971 // If `ResolveHostParameters::include_canonical_name` is set, canonical name
2972 // should be returned exactly as received from the system resolver, without any
2973 // attempt to do URL hostname canonicalization on it.
TEST_F(HostResolverManagerTest,IncludeCanonicalNameSkipsUrlCanonicalization)2974 TEST_F(HostResolverManagerTest, IncludeCanonicalNameSkipsUrlCanonicalization) {
2975   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42",
2976                                HOST_RESOLVER_CANONNAME, "CANON.name");
2977   proc_->SignalMultiple(2u);
2978 
2979   HostResolver::ResolveHostParameters parameters;
2980   parameters.include_canonical_name = true;
2981   ResolveHostResponseHelper response(resolver_->CreateRequest(
2982       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2983       NetLogWithSource(), parameters, resolve_context_.get(),
2984       resolve_context_->host_cache()));
2985   ResolveHostResponseHelper response_no_flag(resolver_->CreateRequest(
2986       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
2987       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
2988       resolve_context_->host_cache()));
2989 
2990   EXPECT_THAT(response.result_error(), IsOk());
2991   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
2992               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
2993   EXPECT_THAT(
2994       response.request()->GetEndpointResults(),
2995       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
2996           testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
2997   EXPECT_THAT(response.request()->GetDnsAliasResults(),
2998               testing::Pointee(testing::UnorderedElementsAre("CANON.name")));
2999 
3000   EXPECT_THAT(response_no_flag.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
3001 }
3002 
TEST_F(HostResolverManagerTest,LoopbackOnly)3003 TEST_F(HostResolverManagerTest, LoopbackOnly) {
3004   proc_->AddRuleForAllFamilies("otherlocal", "127.0.0.1",
3005                                HOST_RESOLVER_LOOPBACK_ONLY);
3006   proc_->SignalMultiple(2u);
3007 
3008   HostResolver::ResolveHostParameters parameters;
3009   parameters.loopback_only = true;
3010   ResolveHostResponseHelper response(resolver_->CreateRequest(
3011       HostPortPair("otherlocal", 80), NetworkAnonymizationKey(),
3012       NetLogWithSource(), parameters, resolve_context_.get(),
3013       resolve_context_->host_cache()));
3014   ResolveHostResponseHelper response_no_flag(resolver_->CreateRequest(
3015       HostPortPair("otherlocal", 80), NetworkAnonymizationKey(),
3016       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
3017       resolve_context_->host_cache()));
3018 
3019   EXPECT_THAT(response.result_error(), IsOk());
3020   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
3021               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
3022   EXPECT_THAT(
3023       response.request()->GetEndpointResults(),
3024       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
3025           testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
3026 
3027   EXPECT_THAT(response_no_flag.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
3028 }
3029 
TEST_F(HostResolverManagerTest,IsSpeculative)3030 TEST_F(HostResolverManagerTest, IsSpeculative) {
3031   proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
3032   proc_->SignalMultiple(1u);
3033 
3034   HostResolver::ResolveHostParameters parameters;
3035   parameters.is_speculative = true;
3036 
3037   ResolveHostResponseHelper response(resolver_->CreateRequest(
3038       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
3039       NetLogWithSource(), parameters, resolve_context_.get(),
3040       resolve_context_->host_cache()));
3041 
3042   EXPECT_THAT(response.result_error(), IsOk());
3043   EXPECT_FALSE(response.request()->GetAddressResults());
3044   EXPECT_FALSE(response.request()->GetEndpointResults());
3045 
3046   ASSERT_EQ(1u, proc_->GetCaptureList().size());
3047   EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
3048 
3049   // Reresolve without the |is_speculative| flag should immediately return from
3050   // cache.
3051   ResolveHostResponseHelper response2(resolver_->CreateRequest(
3052       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
3053       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
3054       resolve_context_->host_cache()));
3055 
3056   EXPECT_THAT(response2.result_error(), IsOk());
3057   EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
3058               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
3059   EXPECT_THAT(
3060       response2.request()->GetEndpointResults(),
3061       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
3062           testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
3063 
3064   EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
3065   EXPECT_EQ(1u, proc_->GetCaptureList().size());  // No increase.
3066 }
3067 
TEST_F(HostResolverManagerTest,AvoidMulticastResolutionParameter)3068 TEST_F(HostResolverManagerTest, AvoidMulticastResolutionParameter) {
3069   proc_->AddRuleForAllFamilies("avoid.multicast.test", "123.123.123.123",
3070                                HOST_RESOLVER_AVOID_MULTICAST);
3071   proc_->SignalMultiple(2u);
3072 
3073   HostResolver::ResolveHostParameters parameters;
3074   parameters.avoid_multicast_resolution = true;
3075   ResolveHostResponseHelper response(resolver_->CreateRequest(
3076       HostPortPair("avoid.multicast.test", 80), NetworkAnonymizationKey(),
3077       NetLogWithSource(), parameters, resolve_context_.get(),
3078       resolve_context_->host_cache()));
3079   ResolveHostResponseHelper response_no_flag(resolver_->CreateRequest(
3080       HostPortPair("avoid.multicast.test", 80), NetworkAnonymizationKey(),
3081       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
3082       resolve_context_->host_cache()));
3083 
3084   EXPECT_THAT(response.result_error(), IsOk());
3085   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
3086               testing::ElementsAre(CreateExpected("123.123.123.123", 80)));
3087   EXPECT_THAT(
3088       response.request()->GetEndpointResults(),
3089       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
3090           testing::ElementsAre(CreateExpected("123.123.123.123", 80))))));
3091 
3092   EXPECT_THAT(response_no_flag.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
3093 }
3094 
3095 #if BUILDFLAG(ENABLE_MDNS)
3096 const uint8_t kMdnsResponseA[] = {
3097     // Header
3098     0x00, 0x00,  // ID is zeroed out
3099     0x81, 0x80,  // Standard query response, RA, no error
3100     0x00, 0x00,  // No questions (for simplicity)
3101     0x00, 0x01,  // 1 RR (answers)
3102     0x00, 0x00,  // 0 authority RRs
3103     0x00, 0x00,  // 0 additional RRs
3104 
3105     // "myhello.local."
3106     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3107     0x00,
3108 
3109     0x00, 0x01,              // TYPE is A.
3110     0x00, 0x01,              // CLASS is IN.
3111     0x00, 0x00, 0x00, 0x10,  // TTL is 16 (seconds)
3112     0x00, 0x04,              // RDLENGTH is 4 bytes.
3113     0x01, 0x02, 0x03, 0x04,  // 1.2.3.4
3114 };
3115 
3116 const uint8_t kMdnsResponseA2[] = {
3117     // Header
3118     0x00, 0x00,  // ID is zeroed out
3119     0x81, 0x80,  // Standard query response, RA, no error
3120     0x00, 0x00,  // No questions (for simplicity)
3121     0x00, 0x01,  // 1 RR (answers)
3122     0x00, 0x00,  // 0 authority RRs
3123     0x00, 0x00,  // 0 additional RRs
3124 
3125     // "myhello.local."
3126     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3127     0x00,
3128 
3129     0x00, 0x01,              // TYPE is A.
3130     0x00, 0x01,              // CLASS is IN.
3131     0x00, 0x00, 0x00, 0x10,  // TTL is 16 (seconds)
3132     0x00, 0x04,              // RDLENGTH is 4 bytes.
3133     0x05, 0x06, 0x07, 0x08,  // 5.6.7.8
3134 };
3135 
3136 const uint8_t kMdnsResponseA2Goodbye[] = {
3137     // Header
3138     0x00, 0x00,  // ID is zeroed out
3139     0x81, 0x80,  // Standard query response, RA, no error
3140     0x00, 0x00,  // No questions (for simplicity)
3141     0x00, 0x01,  // 1 RR (answers)
3142     0x00, 0x00,  // 0 authority RRs
3143     0x00, 0x00,  // 0 additional RRs
3144 
3145     // "myhello.local."
3146     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3147     0x00,
3148 
3149     0x00, 0x01,              // TYPE is A.
3150     0x00, 0x01,              // CLASS is IN.
3151     0x00, 0x00, 0x00, 0x00,  // TTL is 0 (signaling "goodbye" removal of result)
3152     0x00, 0x04,              // RDLENGTH is 4 bytes.
3153     0x05, 0x06, 0x07, 0x08,  // 5.6.7.8
3154 };
3155 
3156 const uint8_t kMdnsResponseAAAA[] = {
3157     // Header
3158     0x00, 0x00,  // ID is zeroed out
3159     0x81, 0x80,  // Standard query response, RA, no error
3160     0x00, 0x00,  // No questions (for simplicity)
3161     0x00, 0x01,  // 1 RR (answers)
3162     0x00, 0x00,  // 0 authority RRs
3163     0x00, 0x00,  // 0 additional RRs
3164 
3165     // "myhello.local."
3166     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3167     0x00,
3168 
3169     0x00, 0x1C,              // TYPE is AAAA.
3170     0x00, 0x01,              // CLASS is IN.
3171     0x00, 0x00, 0x00, 0x10,  // TTL is 16 (seconds)
3172     0x00, 0x10,              // RDLENGTH is 16 bytes.
3173 
3174     // 000a:0000:0000:0000:0001:0002:0003:0004
3175     0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
3176     0x00, 0x03, 0x00, 0x04};
3177 
3178 // An MDNS response indicating that the responder owns the hostname, but the
3179 // specific requested type (AAAA) does not exist because the responder only has
3180 // A addresses.
3181 const uint8_t kMdnsResponseNsec[] = {
3182     // Header
3183     0x00, 0x00,  // ID is zeroed out
3184     0x81, 0x80,  // Standard query response, RA, no error
3185     0x00, 0x00,  // No questions (for simplicity)
3186     0x00, 0x01,  // 1 RR (answers)
3187     0x00, 0x00,  // 0 authority RRs
3188     0x00, 0x00,  // 0 additional RRs
3189 
3190     // "myhello.local."
3191     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3192     0x00,
3193 
3194     0x00, 0x2f,              // TYPE is NSEC.
3195     0x00, 0x01,              // CLASS is IN.
3196     0x00, 0x00, 0x00, 0x10,  // TTL is 16 (seconds)
3197     0x00, 0x06,              // RDLENGTH is 6 bytes.
3198     0xc0, 0x0c,  // Next Domain Name (always pointer back to name in MDNS)
3199     0x00,        // Bitmap block number (always 0 in MDNS)
3200     0x02,        // Bitmap length is 2
3201     0x00, 0x08   // A type only
3202 };
3203 
3204 const uint8_t kMdnsResponseTxt[] = {
3205     // Header
3206     0x00, 0x00,  // ID is zeroed out
3207     0x81, 0x80,  // Standard query response, RA, no error
3208     0x00, 0x00,  // No questions (for simplicity)
3209     0x00, 0x01,  // 1 RR (answers)
3210     0x00, 0x00,  // 0 authority RRs
3211     0x00, 0x00,  // 0 additional RRs
3212 
3213     // "myhello.local."
3214     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3215     0x00,
3216 
3217     0x00, 0x10,              // TYPE is TXT.
3218     0x00, 0x01,              // CLASS is IN.
3219     0x00, 0x00, 0x00, 0x11,  // TTL is 17 (seconds)
3220     0x00, 0x08,              // RDLENGTH is 8 bytes.
3221 
3222     // "foo"
3223     0x03, 0x66, 0x6f, 0x6f,
3224     // "bar"
3225     0x03, 0x62, 0x61, 0x72};
3226 
3227 const uint8_t kMdnsResponsePtr[] = {
3228     // Header
3229     0x00, 0x00,  // ID is zeroed out
3230     0x81, 0x80,  // Standard query response, RA, no error
3231     0x00, 0x00,  // No questions (for simplicity)
3232     0x00, 0x01,  // 1 RR (answers)
3233     0x00, 0x00,  // 0 authority RRs
3234     0x00, 0x00,  // 0 additional RRs
3235 
3236     // "myhello.local."
3237     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3238     0x00,
3239 
3240     0x00, 0x0c,              // TYPE is PTR.
3241     0x00, 0x01,              // CLASS is IN.
3242     0x00, 0x00, 0x00, 0x12,  // TTL is 18 (seconds)
3243     0x00, 0x09,              // RDLENGTH is 9 bytes.
3244 
3245     // "foo.com."
3246     0x03, 'f', 'o', 'o', 0x03, 'c', 'o', 'm', 0x00};
3247 
3248 const uint8_t kMdnsResponsePtrRoot[] = {
3249     // Header
3250     0x00, 0x00,  // ID is zeroed out
3251     0x81, 0x80,  // Standard query response, RA, no error
3252     0x00, 0x00,  // No questions (for simplicity)
3253     0x00, 0x01,  // 1 RR (answers)
3254     0x00, 0x00,  // 0 authority RRs
3255     0x00, 0x00,  // 0 additional RRs
3256 
3257     // "myhello.local."
3258     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3259     0x00,
3260 
3261     0x00, 0x0c,              // TYPE is PTR.
3262     0x00, 0x01,              // CLASS is IN.
3263     0x00, 0x00, 0x00, 0x13,  // TTL is 19 (seconds)
3264     0x00, 0x01,              // RDLENGTH is 1 byte.
3265 
3266     // "." (the root domain)
3267     0x00};
3268 
3269 const uint8_t kMdnsResponseSrv[] = {
3270     // Header
3271     0x00, 0x00,  // ID is zeroed out
3272     0x81, 0x80,  // Standard query response, RA, no error
3273     0x00, 0x00,  // No questions (for simplicity)
3274     0x00, 0x01,  // 1 RR (answers)
3275     0x00, 0x00,  // 0 authority RRs
3276     0x00, 0x00,  // 0 additional RRs
3277 
3278     // "myhello.local."
3279     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3280     0x00,
3281 
3282     0x00, 0x21,              // TYPE is SRV.
3283     0x00, 0x01,              // CLASS is IN.
3284     0x00, 0x00, 0x00, 0x13,  // TTL is 19 (seconds)
3285     0x00, 0x0f,              // RDLENGTH is 15 bytes.
3286 
3287     0x00, 0x05,  // Priority 5
3288     0x00, 0x01,  // Weight 1
3289     0x20, 0x49,  // Port 8265
3290 
3291     // "foo.com."
3292     0x03, 'f', 'o', 'o', 0x03, 'c', 'o', 'm', 0x00};
3293 
3294 const uint8_t kMdnsResponseSrvUnrestricted[] = {
3295     // Header
3296     0x00, 0x00,  // ID is zeroed out
3297     0x81, 0x80,  // Standard query response, RA, no error
3298     0x00, 0x00,  // No questions (for simplicity)
3299     0x00, 0x01,  // 1 RR (answers)
3300     0x00, 0x00,  // 0 authority RRs
3301     0x00, 0x00,  // 0 additional RRs
3302 
3303     // "foo bar(A1B2)._ipps._tcp.local"
3304     0x0d, 'f', 'o', 'o', ' ', 'b', 'a', 'r', '(', 'A', '1', 'B', '2', ')', 0x05,
3305     '_', 'i', 'p', 'p', 's', 0x04, '_', 't', 'c', 'p', 0x05, 'l', 'o', 'c', 'a',
3306     'l', 0x00,
3307 
3308     0x00, 0x21,              // TYPE is SRV.
3309     0x00, 0x01,              // CLASS is IN.
3310     0x00, 0x00, 0x00, 0x13,  // TTL is 19 (seconds)
3311     0x00, 0x0f,              // RDLENGTH is 15 bytes.
3312 
3313     0x00, 0x05,  // Priority 5
3314     0x00, 0x01,  // Weight 1
3315     0x20, 0x49,  // Port 8265
3316 
3317     // "foo.com."
3318     0x03, 'f', 'o', 'o', 0x03, 'c', 'o', 'm', 0x00};
3319 
3320 const uint8_t kMdnsResponseSrvUnrestrictedResult[] = {
3321     // Header
3322     0x00, 0x00,  // ID is zeroed out
3323     0x81, 0x80,  // Standard query response, RA, no error
3324     0x00, 0x00,  // No questions (for simplicity)
3325     0x00, 0x01,  // 1 RR (answers)
3326     0x00, 0x00,  // 0 authority RRs
3327     0x00, 0x00,  // 0 additional RRs
3328 
3329     // "myhello.local."
3330     0x07, 'm', 'y', 'h', 'e', 'l', 'l', 'o', 0x05, 'l', 'o', 'c', 'a', 'l',
3331     0x00,
3332 
3333     0x00, 0x21,              // TYPE is SRV.
3334     0x00, 0x01,              // CLASS is IN.
3335     0x00, 0x00, 0x00, 0x13,  // TTL is 19 (seconds)
3336     0x00, 0x15,              // RDLENGTH is 21 bytes.
3337 
3338     0x00, 0x05,  // Priority 5
3339     0x00, 0x01,  // Weight 1
3340     0x20, 0x49,  // Port 8265
3341 
3342     // "foo bar.local"
3343     0x07, 'f', 'o', 'o', ' ', 'b', 'a', 'r', 0x05, 'l', 'o', 'c', 'a', 'l',
3344     0x00};
3345 
TEST_F(HostResolverManagerTest,Mdns)3346 TEST_F(HostResolverManagerTest, Mdns) {
3347   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3348   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3349   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3350   // 2 socket creations for every transaction.
3351   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(4);
3352 
3353   HostResolver::ResolveHostParameters parameters;
3354   parameters.source = HostResolverSource::MULTICAST_DNS;
3355 
3356   ResolveHostResponseHelper response(resolver_->CreateRequest(
3357       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3358       NetLogWithSource(), parameters, resolve_context_.get(),
3359       resolve_context_->host_cache()));
3360 
3361   socket_factory_ptr->SimulateReceive(kMdnsResponseA, sizeof(kMdnsResponseA));
3362   socket_factory_ptr->SimulateReceive(kMdnsResponseAAAA,
3363                                       sizeof(kMdnsResponseAAAA));
3364 
3365   EXPECT_THAT(response.result_error(), IsOk());
3366   EXPECT_THAT(
3367       response.request()->GetAddressResults()->endpoints(),
3368       testing::UnorderedElementsAre(
3369           CreateExpected("1.2.3.4", 80),
3370           CreateExpected("000a:0000:0000:0000:0001:0002:0003:0004", 80)));
3371   EXPECT_THAT(
3372       response.request()->GetEndpointResults(),
3373       testing::Pointee(testing::UnorderedElementsAre(
3374           ExpectEndpointResult(testing::UnorderedElementsAre(
3375               CreateExpected("000a:0000:0000:0000:0001:0002:0003:0004", 80),
3376               CreateExpected("1.2.3.4", 80))))));
3377   EXPECT_FALSE(response.request()->GetTextResults());
3378   EXPECT_FALSE(response.request()->GetHostnameResults());
3379   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3380 }
3381 
TEST_F(HostResolverManagerTest,Mdns_AaaaOnly)3382 TEST_F(HostResolverManagerTest, Mdns_AaaaOnly) {
3383   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3384   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3385   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3386   // 2 socket creations for every transaction.
3387   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(2);
3388 
3389   HostResolver::ResolveHostParameters parameters;
3390   parameters.dns_query_type = DnsQueryType::AAAA;
3391   parameters.source = HostResolverSource::MULTICAST_DNS;
3392 
3393   ResolveHostResponseHelper response(resolver_->CreateRequest(
3394       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3395       NetLogWithSource(), parameters, resolve_context_.get(),
3396       resolve_context_->host_cache()));
3397 
3398   socket_factory_ptr->SimulateReceive(kMdnsResponseAAAA,
3399                                       sizeof(kMdnsResponseAAAA));
3400 
3401   EXPECT_THAT(response.result_error(), IsOk());
3402   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
3403               testing::ElementsAre(CreateExpected(
3404                   "000a:0000:0000:0000:0001:0002:0003:0004", 80)));
3405   EXPECT_THAT(response.request()->GetEndpointResults(),
3406               testing::Pointee(testing::UnorderedElementsAre(
3407                   ExpectEndpointResult(testing::ElementsAre(CreateExpected(
3408                       "000a:0000:0000:0000:0001:0002:0003:0004", 80))))));
3409 }
3410 
TEST_F(HostResolverManagerTest,Mdns_Txt)3411 TEST_F(HostResolverManagerTest, Mdns_Txt) {
3412   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3413   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3414   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3415   // 2 socket creations for every transaction.
3416   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(2);
3417 
3418   HostResolver::ResolveHostParameters parameters;
3419   parameters.dns_query_type = DnsQueryType::TXT;
3420   parameters.source = HostResolverSource::MULTICAST_DNS;
3421 
3422   ResolveHostResponseHelper response(resolver_->CreateRequest(
3423       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3424       NetLogWithSource(), parameters, resolve_context_.get(),
3425       resolve_context_->host_cache()));
3426 
3427   socket_factory_ptr->SimulateReceive(kMdnsResponseTxt,
3428                                       sizeof(kMdnsResponseTxt));
3429 
3430   EXPECT_THAT(response.result_error(), IsOk());
3431   EXPECT_FALSE(response.request()->GetAddressResults());
3432   EXPECT_FALSE(response.request()->GetEndpointResults());
3433   EXPECT_THAT(response.request()->GetTextResults(),
3434               testing::Optional(testing::ElementsAre("foo", "bar")));
3435   EXPECT_FALSE(response.request()->GetHostnameResults());
3436   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3437 }
3438 
TEST_F(HostResolverManagerTest,Mdns_Ptr)3439 TEST_F(HostResolverManagerTest, Mdns_Ptr) {
3440   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3441   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3442   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3443   // 2 socket creations for every transaction.
3444   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(2);
3445 
3446   HostResolver::ResolveHostParameters parameters;
3447   parameters.dns_query_type = DnsQueryType::PTR;
3448   parameters.source = HostResolverSource::MULTICAST_DNS;
3449 
3450   ResolveHostResponseHelper response(resolver_->CreateRequest(
3451       HostPortPair("myhello.local", 83), NetworkAnonymizationKey(),
3452       NetLogWithSource(), parameters, resolve_context_.get(),
3453       resolve_context_->host_cache()));
3454 
3455   socket_factory_ptr->SimulateReceive(kMdnsResponsePtr,
3456                                       sizeof(kMdnsResponsePtr));
3457 
3458   EXPECT_THAT(response.result_error(), IsOk());
3459   EXPECT_FALSE(response.request()->GetAddressResults());
3460   EXPECT_FALSE(response.request()->GetEndpointResults());
3461   EXPECT_FALSE(response.request()->GetTextResults());
3462   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3463   EXPECT_THAT(
3464       response.request()->GetHostnameResults(),
3465       testing::Optional(testing::ElementsAre(HostPortPair("foo.com", 83))));
3466 }
3467 
TEST_F(HostResolverManagerTest,Mdns_Srv)3468 TEST_F(HostResolverManagerTest, Mdns_Srv) {
3469   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3470   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3471   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3472   // 2 socket creations for every transaction.
3473   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(2);
3474 
3475   HostResolver::ResolveHostParameters parameters;
3476   parameters.dns_query_type = DnsQueryType::SRV;
3477   parameters.source = HostResolverSource::MULTICAST_DNS;
3478 
3479   ResolveHostResponseHelper response(resolver_->CreateRequest(
3480       HostPortPair("myhello.local", 83), NetworkAnonymizationKey(),
3481       NetLogWithSource(), parameters, resolve_context_.get(),
3482       resolve_context_->host_cache()));
3483 
3484   socket_factory_ptr->SimulateReceive(kMdnsResponseSrv,
3485                                       sizeof(kMdnsResponseSrv));
3486 
3487   EXPECT_THAT(response.result_error(), IsOk());
3488   EXPECT_FALSE(response.request()->GetAddressResults());
3489   EXPECT_FALSE(response.request()->GetEndpointResults());
3490   EXPECT_FALSE(response.request()->GetTextResults());
3491   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3492   EXPECT_THAT(
3493       response.request()->GetHostnameResults(),
3494       testing::Optional(testing::ElementsAre(HostPortPair("foo.com", 8265))));
3495 }
3496 
3497 // Test that we are able to create multicast DNS requests that contain
3498 // characters not permitted in the DNS spec such as spaces and parenthesis.
TEST_F(HostResolverManagerTest,Mdns_Srv_Unrestricted)3499 TEST_F(HostResolverManagerTest, Mdns_Srv_Unrestricted) {
3500   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3501   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3502   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3503 
3504   HostResolver::ResolveHostParameters parameters;
3505   parameters.dns_query_type = DnsQueryType::SRV;
3506   parameters.source = HostResolverSource::MULTICAST_DNS;
3507 
3508   ResolveHostResponseHelper response(resolver_->CreateRequest(
3509       HostPortPair("foo bar(A1B2)._ipps._tcp.local", 83),
3510       NetworkAnonymizationKey(), NetLogWithSource(), parameters,
3511       resolve_context_.get(), resolve_context_->host_cache()));
3512 
3513   socket_factory_ptr->SimulateReceive(kMdnsResponseSrvUnrestricted,
3514                                       sizeof(kMdnsResponseSrvUnrestricted));
3515 
3516   EXPECT_THAT(response.result_error(), IsOk());
3517   EXPECT_FALSE(response.request()->GetAddressResults());
3518   EXPECT_FALSE(response.request()->GetEndpointResults());
3519   EXPECT_FALSE(response.request()->GetTextResults());
3520   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3521   EXPECT_THAT(
3522       response.request()->GetHostnameResults(),
3523       testing::Optional(testing::ElementsAre(HostPortPair("foo.com", 8265))));
3524 }
3525 
3526 // Test that we are able to create multicast DNS requests that contain
3527 // characters not permitted in the DNS spec such as spaces and parenthesis.
TEST_F(HostResolverManagerTest,Mdns_Srv_Result_Unrestricted)3528 TEST_F(HostResolverManagerTest, Mdns_Srv_Result_Unrestricted) {
3529   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3530   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3531   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3532 
3533   HostResolver::ResolveHostParameters parameters;
3534   parameters.dns_query_type = DnsQueryType::SRV;
3535   parameters.source = HostResolverSource::MULTICAST_DNS;
3536 
3537   ResolveHostResponseHelper response(resolver_->CreateRequest(
3538       HostPortPair("myhello.local", 83), NetworkAnonymizationKey(),
3539       NetLogWithSource(), parameters, resolve_context_.get(),
3540       resolve_context_->host_cache()));
3541 
3542   socket_factory_ptr->SimulateReceive(
3543       kMdnsResponseSrvUnrestrictedResult,
3544       sizeof(kMdnsResponseSrvUnrestrictedResult));
3545 
3546   EXPECT_THAT(response.result_error(), IsOk());
3547   EXPECT_FALSE(response.request()->GetAddressResults());
3548   EXPECT_FALSE(response.request()->GetEndpointResults());
3549   EXPECT_FALSE(response.request()->GetTextResults());
3550   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3551   EXPECT_THAT(response.request()->GetHostnameResults(),
3552               testing::Optional(
3553                   testing::ElementsAre(HostPortPair("foo bar.local", 8265))));
3554 }
3555 
3556 // Test multicast DNS handling of NSEC responses (used for explicit negative
3557 // response).
TEST_F(HostResolverManagerTest,Mdns_Nsec)3558 TEST_F(HostResolverManagerTest, Mdns_Nsec) {
3559   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3560   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3561   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3562   // 2 socket creations for every transaction.
3563   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(2);
3564 
3565   HostResolver::ResolveHostParameters parameters;
3566   parameters.dns_query_type = DnsQueryType::AAAA;
3567   parameters.source = HostResolverSource::MULTICAST_DNS;
3568 
3569   ResolveHostResponseHelper response(resolver_->CreateRequest(
3570       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3571       NetLogWithSource(), parameters, resolve_context_.get(),
3572       resolve_context_->host_cache()));
3573 
3574   socket_factory_ptr->SimulateReceive(kMdnsResponseNsec,
3575                                       sizeof(kMdnsResponseNsec));
3576 
3577   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
3578   EXPECT_FALSE(response.request()->GetAddressResults());
3579   EXPECT_FALSE(response.request()->GetEndpointResults());
3580 }
3581 
TEST_F(HostResolverManagerTest,Mdns_NoResponse)3582 TEST_F(HostResolverManagerTest, Mdns_NoResponse) {
3583   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3584   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3585   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3586   // 2 socket creations for every transaction.
3587   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(4);
3588 
3589   // Add a little bit of extra fudge to the delay to allow reasonable
3590   // flexibility for time > vs >= etc.  We don't need to fail the test if we
3591   // timeout at t=6001 instead of t=6000.
3592   base::TimeDelta kSleepFudgeFactor = base::Milliseconds(1);
3593 
3594   // Override the current thread task runner, so we can simulate the passage of
3595   // time to trigger the timeout.
3596   auto test_task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
3597   base::SingleThreadTaskRunner::CurrentHandleOverrideForTesting
3598       task_runner_current_default_handle_override(test_task_runner);
3599 
3600   HostResolver::ResolveHostParameters parameters;
3601   parameters.source = HostResolverSource::MULTICAST_DNS;
3602 
3603   ResolveHostResponseHelper response(resolver_->CreateRequest(
3604       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3605       NetLogWithSource(), parameters, resolve_context_.get(),
3606       resolve_context_->host_cache()));
3607 
3608   ASSERT_TRUE(test_task_runner->HasPendingTask());
3609   test_task_runner->FastForwardBy(MDnsTransaction::kTransactionTimeout +
3610                                   kSleepFudgeFactor);
3611 
3612   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
3613   EXPECT_FALSE(response.request()->GetAddressResults());
3614   EXPECT_FALSE(response.request()->GetEndpointResults());
3615   EXPECT_FALSE(response.request()->GetTextResults());
3616   EXPECT_FALSE(response.request()->GetHostnameResults());
3617   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3618 
3619   test_task_runner->FastForwardUntilNoTasksRemain();
3620 }
3621 
TEST_F(HostResolverManagerTest,Mdns_WrongType)3622 TEST_F(HostResolverManagerTest, Mdns_WrongType) {
3623   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3624   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3625   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3626   // 2 socket creations for every transaction.
3627   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(2);
3628 
3629   // Add a little bit of extra fudge to the delay to allow reasonable
3630   // flexibility for time > vs >= etc.  We don't need to fail the test if we
3631   // timeout at t=6001 instead of t=6000.
3632   base::TimeDelta kSleepFudgeFactor = base::Milliseconds(1);
3633 
3634   // Override the current thread task runner, so we can simulate the passage of
3635   // time to trigger the timeout.
3636   auto test_task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
3637   base::SingleThreadTaskRunner::CurrentHandleOverrideForTesting
3638       task_runner_current_default_handle_override(test_task_runner);
3639 
3640   HostResolver::ResolveHostParameters parameters;
3641   parameters.dns_query_type = DnsQueryType::A;
3642   parameters.source = HostResolverSource::MULTICAST_DNS;
3643 
3644   ResolveHostResponseHelper response(resolver_->CreateRequest(
3645       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3646       NetLogWithSource(), parameters, resolve_context_.get(),
3647       resolve_context_->host_cache()));
3648 
3649   // Not the requested type. Should be ignored.
3650   socket_factory_ptr->SimulateReceive(kMdnsResponseTxt,
3651                                       sizeof(kMdnsResponseTxt));
3652 
3653   ASSERT_TRUE(test_task_runner->HasPendingTask());
3654   test_task_runner->FastForwardBy(MDnsTransaction::kTransactionTimeout +
3655                                   kSleepFudgeFactor);
3656 
3657   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
3658   EXPECT_FALSE(response.request()->GetAddressResults());
3659   EXPECT_FALSE(response.request()->GetEndpointResults());
3660   EXPECT_FALSE(response.request()->GetTextResults());
3661   EXPECT_FALSE(response.request()->GetHostnameResults());
3662   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
3663 
3664   test_task_runner->FastForwardUntilNoTasksRemain();
3665 }
3666 
3667 // Test for a request for both A and AAAA results where results only exist for
3668 // one type.
TEST_F(HostResolverManagerTest,Mdns_PartialResults)3669 TEST_F(HostResolverManagerTest, Mdns_PartialResults) {
3670   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3671   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3672   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3673   // 2 socket creations for every transaction.
3674   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(4);
3675 
3676   // Add a little bit of extra fudge to the delay to allow reasonable
3677   // flexibility for time > vs >= etc.  We don't need to fail the test if we
3678   // timeout at t=6001 instead of t=6000.
3679   base::TimeDelta kSleepFudgeFactor = base::Milliseconds(1);
3680 
3681   // Override the current thread task runner, so we can simulate the passage of
3682   // time to trigger the timeout.
3683   auto test_task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
3684   base::SingleThreadTaskRunner::CurrentHandleOverrideForTesting
3685       task_runner_current_default_handle_override(test_task_runner);
3686 
3687   HostResolver::ResolveHostParameters parameters;
3688   parameters.source = HostResolverSource::MULTICAST_DNS;
3689 
3690   ResolveHostResponseHelper response(resolver_->CreateRequest(
3691       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3692       NetLogWithSource(), parameters, resolve_context_.get(),
3693       resolve_context_->host_cache()));
3694 
3695   ASSERT_TRUE(test_task_runner->HasPendingTask());
3696 
3697   socket_factory_ptr->SimulateReceive(kMdnsResponseA, sizeof(kMdnsResponseA));
3698   test_task_runner->FastForwardBy(MDnsTransaction::kTransactionTimeout +
3699                                   kSleepFudgeFactor);
3700 
3701   EXPECT_THAT(response.result_error(), IsOk());
3702   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
3703               testing::ElementsAre(CreateExpected("1.2.3.4", 80)));
3704   EXPECT_THAT(
3705       response.request()->GetEndpointResults(),
3706       testing::Pointee(testing::UnorderedElementsAre(ExpectEndpointResult(
3707           testing::ElementsAre(CreateExpected("1.2.3.4", 80))))));
3708 
3709   test_task_runner->FastForwardUntilNoTasksRemain();
3710 }
3711 
TEST_F(HostResolverManagerTest,Mdns_Cancel)3712 TEST_F(HostResolverManagerTest, Mdns_Cancel) {
3713   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3714   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3715   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3716   // 2 socket creations for every transaction.
3717   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(4);
3718 
3719   HostResolver::ResolveHostParameters parameters;
3720   parameters.source = HostResolverSource::MULTICAST_DNS;
3721 
3722   ResolveHostResponseHelper response(resolver_->CreateRequest(
3723       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3724       NetLogWithSource(), parameters, resolve_context_.get(),
3725       resolve_context_->host_cache()));
3726 
3727   response.CancelRequest();
3728 
3729   socket_factory_ptr->SimulateReceive(kMdnsResponseA, sizeof(kMdnsResponseA));
3730   socket_factory_ptr->SimulateReceive(kMdnsResponseAAAA,
3731                                       sizeof(kMdnsResponseAAAA));
3732 
3733   base::RunLoop().RunUntilIdle();
3734   EXPECT_FALSE(response.complete());
3735 }
3736 
3737 // Test for a two-transaction query where the first fails to start. The second
3738 // should be cancelled.
TEST_F(HostResolverManagerTest,Mdns_PartialFailure)3739 TEST_F(HostResolverManagerTest, Mdns_PartialFailure) {
3740   // Setup a mock MDnsClient where the first transaction will always return
3741   // |false| immediately on Start(). Second transaction may or may not be
3742   // created, but if it is, Start() not expected to be called because the
3743   // overall request should immediately fail.
3744   auto transaction1 = std::make_unique<MockMDnsTransaction>();
3745   EXPECT_CALL(*transaction1, Start()).WillOnce(Return(false));
3746   auto transaction2 = std::make_unique<MockMDnsTransaction>();
3747   EXPECT_CALL(*transaction2, Start()).Times(0);
3748 
3749   auto client = std::make_unique<MockMDnsClient>();
3750   EXPECT_CALL(*client, CreateTransaction(_, _, _, _))
3751       .Times(Between(1, 2))  // Second transaction optionally created.
3752       .WillOnce(Return(ByMove(std::move(transaction1))))
3753       .WillOnce(Return(ByMove(std::move(transaction2))));
3754   EXPECT_CALL(*client, IsListening()).WillRepeatedly(Return(true));
3755   resolver_->SetMdnsClientForTesting(std::move(client));
3756 
3757   HostResolver::ResolveHostParameters parameters;
3758   parameters.source = HostResolverSource::MULTICAST_DNS;
3759 
3760   ResolveHostResponseHelper response(resolver_->CreateRequest(
3761       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3762       NetLogWithSource(), parameters, resolve_context_.get(),
3763       resolve_context_->host_cache()));
3764 
3765   EXPECT_THAT(response.result_error(), IsError(ERR_FAILED));
3766   EXPECT_FALSE(response.request()->GetAddressResults());
3767   EXPECT_FALSE(response.request()->GetEndpointResults());
3768 }
3769 
TEST_F(HostResolverManagerTest,Mdns_ListenFailure)3770 TEST_F(HostResolverManagerTest, Mdns_ListenFailure) {
3771   // Inject an MdnsClient mock that will always fail to start listening.
3772   auto client = std::make_unique<MockMDnsClient>();
3773   EXPECT_CALL(*client, StartListening(_)).WillOnce(Return(ERR_FAILED));
3774   EXPECT_CALL(*client, IsListening()).WillRepeatedly(Return(false));
3775   resolver_->SetMdnsClientForTesting(std::move(client));
3776 
3777   HostResolver::ResolveHostParameters parameters;
3778   parameters.source = HostResolverSource::MULTICAST_DNS;
3779 
3780   ResolveHostResponseHelper response(resolver_->CreateRequest(
3781       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
3782       NetLogWithSource(), parameters, resolve_context_.get(),
3783       resolve_context_->host_cache()));
3784 
3785   EXPECT_THAT(response.result_error(), IsError(ERR_FAILED));
3786   EXPECT_FALSE(response.request()->GetAddressResults());
3787   EXPECT_FALSE(response.request()->GetEndpointResults());
3788 }
3789 
3790 // Implementation of HostResolver::MdnsListenerDelegate that records all
3791 // received results in maps.
3792 class TestMdnsListenerDelegate : public HostResolver::MdnsListener::Delegate {
3793  public:
3794   using UpdateKey = std::pair<MdnsListenerUpdateType, DnsQueryType>;
3795 
OnAddressResult(MdnsListenerUpdateType update_type,DnsQueryType result_type,IPEndPoint address)3796   void OnAddressResult(MdnsListenerUpdateType update_type,
3797                        DnsQueryType result_type,
3798                        IPEndPoint address) override {
3799     address_results_.insert({{update_type, result_type}, address});
3800   }
3801 
OnTextResult(MdnsListenerUpdateType update_type,DnsQueryType result_type,std::vector<std::string> text_records)3802   void OnTextResult(MdnsListenerUpdateType update_type,
3803                     DnsQueryType result_type,
3804                     std::vector<std::string> text_records) override {
3805     for (auto& text_record : text_records) {
3806       text_results_.insert(
3807           {{update_type, result_type}, std::move(text_record)});
3808     }
3809   }
3810 
OnHostnameResult(MdnsListenerUpdateType update_type,DnsQueryType result_type,HostPortPair host)3811   void OnHostnameResult(MdnsListenerUpdateType update_type,
3812                         DnsQueryType result_type,
3813                         HostPortPair host) override {
3814     hostname_results_.insert({{update_type, result_type}, std::move(host)});
3815   }
3816 
OnUnhandledResult(MdnsListenerUpdateType update_type,DnsQueryType result_type)3817   void OnUnhandledResult(MdnsListenerUpdateType update_type,
3818                          DnsQueryType result_type) override {
3819     unhandled_results_.insert({update_type, result_type});
3820   }
3821 
address_results()3822   const std::multimap<UpdateKey, IPEndPoint>& address_results() {
3823     return address_results_;
3824   }
3825 
text_results()3826   const std::multimap<UpdateKey, std::string>& text_results() {
3827     return text_results_;
3828   }
3829 
hostname_results()3830   const std::multimap<UpdateKey, HostPortPair>& hostname_results() {
3831     return hostname_results_;
3832   }
3833 
unhandled_results()3834   const std::multiset<UpdateKey>& unhandled_results() {
3835     return unhandled_results_;
3836   }
3837 
3838   template <typename T>
CreateExpectedResult(MdnsListenerUpdateType update_type,DnsQueryType query_type,T result)3839   static std::pair<UpdateKey, T> CreateExpectedResult(
3840       MdnsListenerUpdateType update_type,
3841       DnsQueryType query_type,
3842       T result) {
3843     return std::make_pair(std::make_pair(update_type, query_type), result);
3844   }
3845 
3846  private:
3847   std::multimap<UpdateKey, IPEndPoint> address_results_;
3848   std::multimap<UpdateKey, std::string> text_results_;
3849   std::multimap<UpdateKey, HostPortPair> hostname_results_;
3850   std::multiset<UpdateKey> unhandled_results_;
3851 };
3852 
TEST_F(HostResolverManagerTest,MdnsListener)3853 TEST_F(HostResolverManagerTest, MdnsListener) {
3854   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3855   base::SimpleTestClock clock;
3856   clock.SetNow(base::Time::Now());
3857   auto cache_cleanup_timer = std::make_unique<base::MockOneShotTimer>();
3858   auto* cache_cleanup_timer_ptr = cache_cleanup_timer.get();
3859   auto mdns_client =
3860       std::make_unique<MDnsClientImpl>(&clock, std::move(cache_cleanup_timer));
3861   ASSERT_THAT(mdns_client->StartListening(socket_factory.get()), IsOk());
3862   resolver_->SetMdnsClientForTesting(std::move(mdns_client));
3863 
3864   TestMdnsListenerDelegate delegate;
3865   std::unique_ptr<HostResolver::MdnsListener> listener =
3866       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 80),
3867                                     DnsQueryType::A);
3868 
3869   ASSERT_THAT(listener->Start(&delegate), IsOk());
3870   ASSERT_THAT(delegate.address_results(), testing::IsEmpty());
3871 
3872   socket_factory->SimulateReceive(kMdnsResponseA, sizeof(kMdnsResponseA));
3873   socket_factory->SimulateReceive(kMdnsResponseA2, sizeof(kMdnsResponseA2));
3874   socket_factory->SimulateReceive(kMdnsResponseA2Goodbye,
3875                                   sizeof(kMdnsResponseA2Goodbye));
3876 
3877   // Per RFC6762 section 10.1, removals take effect 1 second after receiving the
3878   // goodbye message.
3879   clock.Advance(base::Seconds(1));
3880   cache_cleanup_timer_ptr->Fire();
3881 
3882   // Expect 1 record adding "1.2.3.4", another changing to "5.6.7.8", and a
3883   // final removing "5.6.7.8".
3884   EXPECT_THAT(delegate.address_results(),
3885               testing::ElementsAre(
3886                   TestMdnsListenerDelegate::CreateExpectedResult(
3887                       MdnsListenerUpdateType::kAdded, DnsQueryType::A,
3888                       CreateExpected("1.2.3.4", 80)),
3889                   TestMdnsListenerDelegate::CreateExpectedResult(
3890                       MdnsListenerUpdateType::kChanged, DnsQueryType::A,
3891                       CreateExpected("5.6.7.8", 80)),
3892                   TestMdnsListenerDelegate::CreateExpectedResult(
3893                       MdnsListenerUpdateType::kRemoved, DnsQueryType::A,
3894                       CreateExpected("5.6.7.8", 80))));
3895 
3896   EXPECT_THAT(delegate.text_results(), testing::IsEmpty());
3897   EXPECT_THAT(delegate.hostname_results(), testing::IsEmpty());
3898   EXPECT_THAT(delegate.unhandled_results(), testing::IsEmpty());
3899 }
3900 
TEST_F(HostResolverManagerTest,MdnsListener_StartListenFailure)3901 TEST_F(HostResolverManagerTest, MdnsListener_StartListenFailure) {
3902   // Inject an MdnsClient mock that will always fail to start listening.
3903   auto client = std::make_unique<MockMDnsClient>();
3904   EXPECT_CALL(*client, StartListening(_)).WillOnce(Return(ERR_TIMED_OUT));
3905   EXPECT_CALL(*client, IsListening()).WillRepeatedly(Return(false));
3906   resolver_->SetMdnsClientForTesting(std::move(client));
3907 
3908   TestMdnsListenerDelegate delegate;
3909   std::unique_ptr<HostResolver::MdnsListener> listener =
3910       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 80),
3911                                     DnsQueryType::A);
3912 
3913   EXPECT_THAT(listener->Start(&delegate), IsError(ERR_TIMED_OUT));
3914   EXPECT_THAT(delegate.address_results(), testing::IsEmpty());
3915 }
3916 
3917 // Test that removal notifications are sent on natural expiration of MDNS
3918 // records.
TEST_F(HostResolverManagerTest,MdnsListener_Expiration)3919 TEST_F(HostResolverManagerTest, MdnsListener_Expiration) {
3920   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3921   base::SimpleTestClock clock;
3922   clock.SetNow(base::Time::Now());
3923   auto cache_cleanup_timer = std::make_unique<base::MockOneShotTimer>();
3924   auto* cache_cleanup_timer_ptr = cache_cleanup_timer.get();
3925   auto mdns_client =
3926       std::make_unique<MDnsClientImpl>(&clock, std::move(cache_cleanup_timer));
3927   ASSERT_THAT(mdns_client->StartListening(socket_factory.get()), IsOk());
3928   resolver_->SetMdnsClientForTesting(std::move(mdns_client));
3929 
3930   TestMdnsListenerDelegate delegate;
3931   std::unique_ptr<HostResolver::MdnsListener> listener =
3932       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 100),
3933                                     DnsQueryType::A);
3934 
3935   ASSERT_THAT(listener->Start(&delegate), IsOk());
3936   ASSERT_THAT(delegate.address_results(), testing::IsEmpty());
3937 
3938   socket_factory->SimulateReceive(kMdnsResponseA, sizeof(kMdnsResponseA));
3939 
3940   EXPECT_THAT(
3941       delegate.address_results(),
3942       testing::ElementsAre(TestMdnsListenerDelegate::CreateExpectedResult(
3943           MdnsListenerUpdateType::kAdded, DnsQueryType::A,
3944           CreateExpected("1.2.3.4", 100))));
3945 
3946   clock.Advance(base::Seconds(16));
3947   cache_cleanup_timer_ptr->Fire();
3948 
3949   EXPECT_THAT(delegate.address_results(),
3950               testing::ElementsAre(
3951                   TestMdnsListenerDelegate::CreateExpectedResult(
3952                       MdnsListenerUpdateType::kAdded, DnsQueryType::A,
3953                       CreateExpected("1.2.3.4", 100)),
3954                   TestMdnsListenerDelegate::CreateExpectedResult(
3955                       MdnsListenerUpdateType::kRemoved, DnsQueryType::A,
3956                       CreateExpected("1.2.3.4", 100))));
3957 
3958   EXPECT_THAT(delegate.text_results(), testing::IsEmpty());
3959   EXPECT_THAT(delegate.hostname_results(), testing::IsEmpty());
3960   EXPECT_THAT(delegate.unhandled_results(), testing::IsEmpty());
3961 }
3962 
TEST_F(HostResolverManagerTest,MdnsListener_Txt)3963 TEST_F(HostResolverManagerTest, MdnsListener_Txt) {
3964   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3965   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3966   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3967 
3968   TestMdnsListenerDelegate delegate;
3969   std::unique_ptr<HostResolver::MdnsListener> listener =
3970       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 12),
3971                                     DnsQueryType::TXT);
3972 
3973   ASSERT_THAT(listener->Start(&delegate), IsOk());
3974   ASSERT_THAT(delegate.text_results(), testing::IsEmpty());
3975 
3976   socket_factory_ptr->SimulateReceive(kMdnsResponseTxt,
3977                                       sizeof(kMdnsResponseTxt));
3978 
3979   EXPECT_THAT(
3980       delegate.text_results(),
3981       testing::ElementsAre(
3982           TestMdnsListenerDelegate::CreateExpectedResult(
3983               MdnsListenerUpdateType::kAdded, DnsQueryType::TXT, "foo"),
3984           TestMdnsListenerDelegate::CreateExpectedResult(
3985               MdnsListenerUpdateType::kAdded, DnsQueryType::TXT, "bar")));
3986 
3987   EXPECT_THAT(delegate.address_results(), testing::IsEmpty());
3988   EXPECT_THAT(delegate.hostname_results(), testing::IsEmpty());
3989   EXPECT_THAT(delegate.unhandled_results(), testing::IsEmpty());
3990 }
3991 
TEST_F(HostResolverManagerTest,MdnsListener_Ptr)3992 TEST_F(HostResolverManagerTest, MdnsListener_Ptr) {
3993   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
3994   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
3995   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
3996 
3997   TestMdnsListenerDelegate delegate;
3998   std::unique_ptr<HostResolver::MdnsListener> listener =
3999       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 13),
4000                                     DnsQueryType::PTR);
4001 
4002   ASSERT_THAT(listener->Start(&delegate), IsOk());
4003   ASSERT_THAT(delegate.text_results(), testing::IsEmpty());
4004 
4005   socket_factory_ptr->SimulateReceive(kMdnsResponsePtr,
4006                                       sizeof(kMdnsResponsePtr));
4007 
4008   EXPECT_THAT(
4009       delegate.hostname_results(),
4010       testing::ElementsAre(TestMdnsListenerDelegate::CreateExpectedResult(
4011           MdnsListenerUpdateType::kAdded, DnsQueryType::PTR,
4012           HostPortPair("foo.com", 13))));
4013 
4014   EXPECT_THAT(delegate.address_results(), testing::IsEmpty());
4015   EXPECT_THAT(delegate.text_results(), testing::IsEmpty());
4016   EXPECT_THAT(delegate.unhandled_results(), testing::IsEmpty());
4017 }
4018 
TEST_F(HostResolverManagerTest,MdnsListener_Srv)4019 TEST_F(HostResolverManagerTest, MdnsListener_Srv) {
4020   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
4021   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
4022   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
4023 
4024   TestMdnsListenerDelegate delegate;
4025   std::unique_ptr<HostResolver::MdnsListener> listener =
4026       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 14),
4027                                     DnsQueryType::SRV);
4028 
4029   ASSERT_THAT(listener->Start(&delegate), IsOk());
4030   ASSERT_THAT(delegate.text_results(), testing::IsEmpty());
4031 
4032   socket_factory_ptr->SimulateReceive(kMdnsResponseSrv,
4033                                       sizeof(kMdnsResponseSrv));
4034 
4035   EXPECT_THAT(
4036       delegate.hostname_results(),
4037       testing::ElementsAre(TestMdnsListenerDelegate::CreateExpectedResult(
4038           MdnsListenerUpdateType::kAdded, DnsQueryType::SRV,
4039           HostPortPair("foo.com", 8265))));
4040 
4041   EXPECT_THAT(delegate.address_results(), testing::IsEmpty());
4042   EXPECT_THAT(delegate.text_results(), testing::IsEmpty());
4043   EXPECT_THAT(delegate.unhandled_results(), testing::IsEmpty());
4044 }
4045 
4046 // Ensure query types we are not listening for do not affect MdnsListener.
TEST_F(HostResolverManagerTest,MdnsListener_NonListeningTypes)4047 TEST_F(HostResolverManagerTest, MdnsListener_NonListeningTypes) {
4048   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
4049   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
4050   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
4051 
4052   TestMdnsListenerDelegate delegate;
4053   std::unique_ptr<HostResolver::MdnsListener> listener =
4054       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 41),
4055                                     DnsQueryType::A);
4056 
4057   ASSERT_THAT(listener->Start(&delegate), IsOk());
4058 
4059   socket_factory_ptr->SimulateReceive(kMdnsResponseAAAA,
4060                                       sizeof(kMdnsResponseAAAA));
4061 
4062   EXPECT_THAT(delegate.address_results(), testing::IsEmpty());
4063   EXPECT_THAT(delegate.text_results(), testing::IsEmpty());
4064   EXPECT_THAT(delegate.hostname_results(), testing::IsEmpty());
4065   EXPECT_THAT(delegate.unhandled_results(), testing::IsEmpty());
4066 }
4067 
TEST_F(HostResolverManagerTest,MdnsListener_RootDomain)4068 TEST_F(HostResolverManagerTest, MdnsListener_RootDomain) {
4069   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
4070   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
4071   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
4072 
4073   TestMdnsListenerDelegate delegate;
4074   std::unique_ptr<HostResolver::MdnsListener> listener =
4075       resolver_->CreateMdnsListener(HostPortPair("myhello.local", 5),
4076                                     DnsQueryType::PTR);
4077 
4078   ASSERT_THAT(listener->Start(&delegate), IsOk());
4079 
4080   socket_factory_ptr->SimulateReceive(kMdnsResponsePtrRoot,
4081                                       sizeof(kMdnsResponsePtrRoot));
4082 
4083   EXPECT_THAT(delegate.unhandled_results(),
4084               testing::ElementsAre(std::make_pair(
4085                   MdnsListenerUpdateType::kAdded, DnsQueryType::PTR)));
4086 
4087   EXPECT_THAT(delegate.address_results(), testing::IsEmpty());
4088   EXPECT_THAT(delegate.text_results(), testing::IsEmpty());
4089   EXPECT_THAT(delegate.hostname_results(), testing::IsEmpty());
4090 }
4091 #endif  // BUILDFLAG(ENABLE_MDNS)
4092 
CreateValidDnsConfig()4093 DnsConfig CreateValidDnsConfig() {
4094   IPAddress dns_ip(192, 168, 1, 0);
4095   DnsConfig config;
4096   config.nameservers.emplace_back(dns_ip, dns_protocol::kDefaultPort);
4097   config.doh_config =
4098       *DnsOverHttpsConfig::FromString("https://dns.example.com/");
4099   config.secure_dns_mode = SecureDnsMode::kOff;
4100   EXPECT_TRUE(config.IsValid());
4101   return config;
4102 }
4103 
CreateUpgradableDnsConfig()4104 DnsConfig CreateUpgradableDnsConfig() {
4105   DnsConfig config;
4106   config.secure_dns_mode = SecureDnsMode::kAutomatic;
4107   config.allow_dns_over_https_upgrade = true;
4108 
4109   auto ProviderHasAddr = [](base::StringPiece provider, const IPAddress& addr) {
4110     return base::Contains(GetDohProviderEntryForTesting(provider).ip_addresses,
4111                           addr);
4112   };
4113 
4114   // Cloudflare upgradeable IPs
4115   IPAddress dns_ip0(1, 0, 0, 1);
4116   IPAddress dns_ip1;
4117   EXPECT_TRUE(dns_ip1.AssignFromIPLiteral("2606:4700:4700::1111"));
4118   EXPECT_TRUE(ProviderHasAddr("Cloudflare", dns_ip0));
4119   EXPECT_TRUE(ProviderHasAddr("Cloudflare", dns_ip1));
4120   // CleanBrowsingFamily upgradeable IP
4121   IPAddress dns_ip2;
4122   EXPECT_TRUE(dns_ip2.AssignFromIPLiteral("2a0d:2a00:2::"));
4123   EXPECT_TRUE(ProviderHasAddr("CleanBrowsingFamily", dns_ip2));
4124   // CleanBrowsingSecure upgradeable IP
4125   IPAddress dns_ip3(185, 228, 169, 9);
4126   EXPECT_TRUE(ProviderHasAddr("CleanBrowsingSecure", dns_ip3));
4127   // Non-upgradeable IP
4128   IPAddress dns_ip4(1, 2, 3, 4);
4129 
4130   config.nameservers = {
4131       IPEndPoint(dns_ip0, dns_protocol::kDefaultPort),
4132       IPEndPoint(dns_ip1, dns_protocol::kDefaultPort),
4133       IPEndPoint(dns_ip2, 54),
4134       IPEndPoint(dns_ip3, dns_protocol::kDefaultPort),
4135       IPEndPoint(dns_ip4, dns_protocol::kDefaultPort),
4136   };
4137   EXPECT_TRUE(config.IsValid());
4138   return config;
4139 }
4140 
4141 // Check that entries are written to the cache with the right NIK.
TEST_F(HostResolverManagerTest,NetworkAnonymizationKeyWriteToHostCache)4142 TEST_F(HostResolverManagerTest, NetworkAnonymizationKeyWriteToHostCache) {
4143   const SchemefulSite kSite1(GURL("https://origin1.test/"));
4144   const SchemefulSite kSite2(GURL("https://origin2.test/"));
4145   auto kNetworkAnonymizationKey1 =
4146       net::NetworkAnonymizationKey::CreateSameSite(kSite1);
4147   auto kNetworkAnonymizationKey2 =
4148       net::NetworkAnonymizationKey::CreateSameSite(kSite2);
4149 
4150   const char kFirstDnsResult[] = "192.168.1.42";
4151   const char kSecondDnsResult[] = "192.168.1.43";
4152 
4153   for (bool split_cache_by_network_anonymization_key : {false, true}) {
4154     base::test::ScopedFeatureList feature_list;
4155     if (split_cache_by_network_anonymization_key) {
4156       feature_list.InitAndEnableFeature(
4157           features::kSplitHostCacheByNetworkIsolationKey);
4158     } else {
4159       feature_list.InitAndDisableFeature(
4160           features::kSplitHostCacheByNetworkIsolationKey);
4161     }
4162     proc_->AddRuleForAllFamilies("just.testing", kFirstDnsResult);
4163     proc_->SignalMultiple(1u);
4164 
4165     // Resolve a host using kNetworkAnonymizationKey1.
4166     ResolveHostResponseHelper response1(resolver_->CreateRequest(
4167         HostPortPair("just.testing", 80), kNetworkAnonymizationKey1,
4168         NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4169         resolve_context_->host_cache()));
4170     EXPECT_THAT(response1.result_error(), IsOk());
4171     EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
4172                 testing::ElementsAre(CreateExpected(kFirstDnsResult, 80)));
4173     EXPECT_THAT(
4174         response1.request()->GetEndpointResults(),
4175         testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4176             testing::ElementsAre(CreateExpected(kFirstDnsResult, 80))))));
4177     EXPECT_FALSE(response1.request()->GetStaleInfo());
4178     EXPECT_EQ(1u, proc_->GetCaptureList().size());
4179 
4180     // If the host cache is being split by NetworkAnonymizationKeys, there
4181     // should be an entry in the HostCache with kNetworkAnonymizationKey1.
4182     // Otherwise, there should be an entry with the empty NAK.
4183     if (split_cache_by_network_anonymization_key) {
4184       EXPECT_TRUE(GetCacheHit(
4185           HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
4186                          0 /* host_resolver_flags */, HostResolverSource::ANY,
4187                          kNetworkAnonymizationKey1)));
4188 
4189       EXPECT_FALSE(GetCacheHit(
4190           HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
4191                          0 /* host_resolver_flags */, HostResolverSource::ANY,
4192                          NetworkAnonymizationKey())));
4193     } else {
4194       EXPECT_FALSE(GetCacheHit(
4195           HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
4196                          0 /* host_resolver_flags */, HostResolverSource::ANY,
4197                          kNetworkAnonymizationKey1)));
4198 
4199       EXPECT_TRUE(GetCacheHit(
4200           HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
4201                          0 /* host_resolver_flags */, HostResolverSource::ANY,
4202                          NetworkAnonymizationKey())));
4203     }
4204 
4205     // There should be no entry using kNetworkAnonymizationKey2 in either case.
4206     EXPECT_FALSE(GetCacheHit(HostCache::Key(
4207         "just.testing", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
4208         HostResolverSource::ANY, kNetworkAnonymizationKey2)));
4209 
4210     // A request using kNetworkAnonymizationKey2 should only be served out of
4211     // the cache of the cache if |split_cache_by_network_anonymization_key| is
4212     // false. If it's not served over the network, it is provided a different
4213     // result.
4214     if (split_cache_by_network_anonymization_key) {
4215       proc_->AddRuleForAllFamilies("just.testing", kSecondDnsResult);
4216       proc_->SignalMultiple(1u);
4217     }
4218     ResolveHostResponseHelper response2(resolver_->CreateRequest(
4219         HostPortPair("just.testing", 80), kNetworkAnonymizationKey2,
4220         NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4221         resolve_context_->host_cache()));
4222     EXPECT_THAT(response2.result_error(), IsOk());
4223     if (split_cache_by_network_anonymization_key) {
4224       EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
4225                   testing::ElementsAre(CreateExpected(kSecondDnsResult, 80)));
4226       EXPECT_THAT(
4227           response2.request()->GetEndpointResults(),
4228           testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4229               testing::ElementsAre(CreateExpected(kSecondDnsResult, 80))))));
4230       EXPECT_FALSE(response2.request()->GetStaleInfo());
4231       EXPECT_EQ(2u, proc_->GetCaptureList().size());
4232       EXPECT_TRUE(GetCacheHit(
4233           HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
4234                          0 /* host_resolver_flags */, HostResolverSource::ANY,
4235                          kNetworkAnonymizationKey2)));
4236     } else {
4237       EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
4238                   testing::ElementsAre(CreateExpected(kFirstDnsResult, 80)));
4239       EXPECT_THAT(
4240           response2.request()->GetEndpointResults(),
4241           testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4242               testing::ElementsAre(CreateExpected(kFirstDnsResult, 80))))));
4243       EXPECT_TRUE(response2.request()->GetStaleInfo());
4244       EXPECT_EQ(1u, proc_->GetCaptureList().size());
4245       EXPECT_FALSE(GetCacheHit(
4246           HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
4247                          0 /* host_resolver_flags */, HostResolverSource::ANY,
4248                          kNetworkAnonymizationKey2)));
4249     }
4250 
4251     resolve_context_->host_cache()->clear();
4252     proc_->ClearCaptureList();
4253   }
4254 }
4255 
4256 // Check that entries are read to the cache with the right NIK.
TEST_F(HostResolverManagerTest,NetworkAnonymizationKeyReadFromHostCache)4257 TEST_F(HostResolverManagerTest, NetworkAnonymizationKeyReadFromHostCache) {
4258   const SchemefulSite kSite1(GURL("https://origin1.test/"));
4259   const SchemefulSite kSite2(GURL("https://origin2.test/"));
4260   auto kNetworkAnonymizationKey1 =
4261       net::NetworkAnonymizationKey::CreateSameSite(kSite1);
4262   auto kNetworkAnonymizationKey2 =
4263       net::NetworkAnonymizationKey::CreateSameSite(kSite2);
4264 
4265   struct CacheEntry {
4266     NetworkAnonymizationKey network_anonymization_key;
4267     const char* cached_ip_address;
4268   };
4269 
4270   const CacheEntry kCacheEntries[] = {
4271       {NetworkAnonymizationKey(), "192.168.1.42"},
4272       {kNetworkAnonymizationKey1, "192.168.1.43"},
4273       {kNetworkAnonymizationKey2, "192.168.1.44"},
4274   };
4275 
4276   // Add entries to cache for the empty NIK, NIK1, and NIK2. Only the
4277   // HostResolverManager obeys network state partitioning, so this is fine to do
4278   // regardless of the feature value.
4279   for (const auto& cache_entry : kCacheEntries) {
4280     HostCache::Key key("just.testing", DnsQueryType::UNSPECIFIED, 0,
4281                        HostResolverSource::ANY,
4282                        cache_entry.network_anonymization_key);
4283     IPAddress address;
4284     ASSERT_TRUE(address.AssignFromIPLiteral(cache_entry.cached_ip_address));
4285     HostCache::Entry entry = HostCache::Entry(
4286         OK, {{address, 80}}, /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);
4287     resolve_context_->host_cache()->Set(key, entry, base::TimeTicks::Now(),
4288                                         base::Days(1));
4289   }
4290 
4291   for (bool split_cache_by_network_anonymization_key : {false, true}) {
4292     base::test::ScopedFeatureList feature_list;
4293     if (split_cache_by_network_anonymization_key) {
4294       feature_list.InitAndEnableFeature(
4295           features::kSplitHostCacheByNetworkIsolationKey);
4296     } else {
4297       feature_list.InitAndDisableFeature(
4298           features::kSplitHostCacheByNetworkIsolationKey);
4299     }
4300 
4301     // A request that uses kNetworkAnonymizationKey1 will return cache entry 1
4302     // if the NetworkAnonymizationKeys are being used, and cache entry 0
4303     // otherwise.
4304     ResolveHostResponseHelper response1(resolver_->CreateRequest(
4305         HostPortPair("just.testing", 80), kNetworkAnonymizationKey1,
4306         NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4307         resolve_context_->host_cache()));
4308     EXPECT_THAT(response1.result_error(), IsOk());
4309     EXPECT_THAT(
4310         response1.request()->GetAddressResults()->endpoints(),
4311         testing::ElementsAre(CreateExpected(
4312             kCacheEntries[split_cache_by_network_anonymization_key ? 1 : 0]
4313                 .cached_ip_address,
4314             80)));
4315     EXPECT_THAT(
4316         response1.request()->GetEndpointResults(),
4317         testing::Pointee(testing::ElementsAre(
4318             ExpectEndpointResult(testing::ElementsAre(CreateExpected(
4319                 kCacheEntries[split_cache_by_network_anonymization_key ? 1 : 0]
4320                     .cached_ip_address,
4321                 80))))));
4322     EXPECT_TRUE(response1.request()->GetStaleInfo());
4323 
4324     // A request that uses kNetworkAnonymizationKey2 will return cache entry 2
4325     // if the NetworkAnonymizationKeys are being used, and cache entry 0
4326     // otherwise.
4327     ResolveHostResponseHelper response2(resolver_->CreateRequest(
4328         HostPortPair("just.testing", 80), kNetworkAnonymizationKey2,
4329         NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4330         resolve_context_->host_cache()));
4331     EXPECT_THAT(response2.result_error(), IsOk());
4332     EXPECT_THAT(
4333         response2.request()->GetAddressResults()->endpoints(),
4334         testing::ElementsAre(CreateExpected(
4335             kCacheEntries[split_cache_by_network_anonymization_key ? 2 : 0]
4336                 .cached_ip_address,
4337             80)));
4338     EXPECT_THAT(
4339         response2.request()->GetEndpointResults(),
4340         testing::Pointee(testing::ElementsAre(
4341             ExpectEndpointResult(testing::ElementsAre(CreateExpected(
4342                 kCacheEntries[split_cache_by_network_anonymization_key ? 2 : 0]
4343                     .cached_ip_address,
4344                 80))))));
4345     EXPECT_TRUE(response2.request()->GetStaleInfo());
4346   }
4347 }
4348 
4349 // Test that two requests made with different NetworkAnonymizationKeys are not
4350 // merged if network state partitioning is enabled.
TEST_F(HostResolverManagerTest,NetworkAnonymizationKeyTwoRequestsAtOnce)4351 TEST_F(HostResolverManagerTest, NetworkAnonymizationKeyTwoRequestsAtOnce) {
4352   const SchemefulSite kSite1(GURL("https://origin1.test/"));
4353   const SchemefulSite kSite2(GURL("https://origin2.test/"));
4354   auto kNetworkAnonymizationKey1 =
4355       net::NetworkAnonymizationKey::CreateSameSite(kSite1);
4356   auto kNetworkAnonymizationKey2 =
4357       net::NetworkAnonymizationKey::CreateSameSite(kSite2);
4358 
4359   const char kDnsResult[] = "192.168.1.42";
4360 
4361   for (bool split_cache_by_network_anonymization_key : {false, true}) {
4362     base::test::ScopedFeatureList feature_list;
4363     if (split_cache_by_network_anonymization_key) {
4364       feature_list.InitAndEnableFeature(
4365           features::kSplitHostCacheByNetworkIsolationKey);
4366     } else {
4367       feature_list.InitAndDisableFeature(
4368           features::kSplitHostCacheByNetworkIsolationKey);
4369     }
4370     proc_->AddRuleForAllFamilies("just.testing", kDnsResult);
4371 
4372     // Start resolving a host using kNetworkAnonymizationKey1.
4373     ResolveHostResponseHelper response1(resolver_->CreateRequest(
4374         HostPortPair("just.testing", 80), kNetworkAnonymizationKey1,
4375         NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4376         resolve_context_->host_cache()));
4377     EXPECT_FALSE(response1.complete());
4378 
4379     // Start resolving the same host using kNetworkAnonymizationKey2.
4380     ResolveHostResponseHelper response2(resolver_->CreateRequest(
4381         HostPortPair("just.testing", 80), kNetworkAnonymizationKey2,
4382         NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4383         resolve_context_->host_cache()));
4384     EXPECT_FALSE(response2.complete());
4385 
4386     // Wait for and complete the expected number of over-the-wire DNS
4387     // resolutions.
4388     if (split_cache_by_network_anonymization_key) {
4389       proc_->WaitFor(2);
4390       EXPECT_EQ(2u, proc_->GetCaptureList().size());
4391       proc_->SignalMultiple(2u);
4392     } else {
4393       proc_->WaitFor(1);
4394       EXPECT_EQ(1u, proc_->GetCaptureList().size());
4395       proc_->SignalMultiple(1u);
4396     }
4397 
4398     // Both requests should have completed successfully, with neither served out
4399     // of the cache.
4400 
4401     EXPECT_THAT(response1.result_error(), IsOk());
4402     EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
4403                 testing::ElementsAre(CreateExpected(kDnsResult, 80)));
4404     EXPECT_THAT(response1.request()->GetEndpointResults(),
4405                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4406                     testing::ElementsAre(CreateExpected(kDnsResult, 80))))));
4407     EXPECT_FALSE(response1.request()->GetStaleInfo());
4408 
4409     EXPECT_THAT(response2.result_error(), IsOk());
4410     EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
4411                 testing::ElementsAre(CreateExpected(kDnsResult, 80)));
4412     EXPECT_THAT(response2.request()->GetEndpointResults(),
4413                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4414                     testing::ElementsAre(CreateExpected(kDnsResult, 80))))));
4415     EXPECT_FALSE(response2.request()->GetStaleInfo());
4416 
4417     resolve_context_->host_cache()->clear();
4418     proc_->ClearCaptureList();
4419   }
4420 }
4421 
4422 // Test that two otherwise-identical requests with different ResolveContexts are
4423 // not merged.
TEST_F(HostResolverManagerTest,ContextsNotMerged)4424 TEST_F(HostResolverManagerTest, ContextsNotMerged) {
4425   const char kDnsResult[] = "192.168.1.42";
4426 
4427   proc_->AddRuleForAllFamilies("just.testing", kDnsResult);
4428 
4429   // Start resolving a host using |resolve_context_|.
4430   ResolveHostResponseHelper response1(resolver_->CreateRequest(
4431       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
4432       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4433       resolve_context_->host_cache()));
4434   EXPECT_FALSE(response1.complete());
4435 
4436   // Start resolving the same host using another ResolveContext and cache.
4437   ResolveContext resolve_context2(resolve_context_->url_request_context(),
4438                                   true /* enable_caching */);
4439   resolver_->RegisterResolveContext(&resolve_context2);
4440   ResolveHostResponseHelper response2(resolver_->CreateRequest(
4441       HostPortPair("just.testing", 80), NetworkAnonymizationKey(),
4442       NetLogWithSource(), absl::nullopt, &resolve_context2,
4443       resolve_context2.host_cache()));
4444   EXPECT_FALSE(response2.complete());
4445   EXPECT_EQ(2u, resolver_->num_jobs_for_testing());
4446 
4447   // Wait for and complete the 2 over-the-wire DNS resolutions.
4448   proc_->WaitFor(2);
4449   EXPECT_EQ(2u, proc_->GetCaptureList().size());
4450   proc_->SignalMultiple(2u);
4451 
4452   // Both requests should have completed successfully, with neither served out
4453   // of the cache.
4454 
4455   EXPECT_THAT(response1.result_error(), IsOk());
4456   EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
4457               testing::ElementsAre(CreateExpected(kDnsResult, 80)));
4458   EXPECT_THAT(response1.request()->GetEndpointResults(),
4459               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4460                   testing::ElementsAre(CreateExpected(kDnsResult, 80))))));
4461   EXPECT_FALSE(response1.request()->GetStaleInfo());
4462 
4463   EXPECT_THAT(response2.result_error(), IsOk());
4464   EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
4465               testing::ElementsAre(CreateExpected(kDnsResult, 80)));
4466   EXPECT_THAT(response2.request()->GetEndpointResults(),
4467               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4468                   testing::ElementsAre(CreateExpected(kDnsResult, 80))))));
4469   EXPECT_FALSE(response2.request()->GetStaleInfo());
4470 
4471   EXPECT_EQ(1u, resolve_context_->host_cache()->size());
4472   EXPECT_EQ(1u, resolve_context2.host_cache()->size());
4473 
4474   resolver_->DeregisterResolveContext(&resolve_context2);
4475 }
4476 
4477 // Specialized fixture for tests of DnsTask.
4478 class HostResolverManagerDnsTest : public HostResolverManagerTest {
4479  public:
HostResolverManagerDnsTest(base::test::TaskEnvironment::TimeSource time_source=base::test::TaskEnvironment::TimeSource::MOCK_TIME)4480   explicit HostResolverManagerDnsTest(
4481       base::test::TaskEnvironment::TimeSource time_source =
4482           base::test::TaskEnvironment::TimeSource::MOCK_TIME)
4483       : HostResolverManagerTest(time_source),
4484         notifier_task_runner_(
4485             base::MakeRefCounted<base::TestMockTimeTaskRunner>()) {
4486     auto config_service = std::make_unique<TestDnsConfigService>();
4487     config_service_ = config_service.get();
4488     notifier_ = std::make_unique<SystemDnsConfigChangeNotifier>(
4489         notifier_task_runner_, std::move(config_service));
4490   }
4491 
4492   void Ipv6UnreachableTest(bool is_async);
4493   void Ipv6UnreachableInvalidConfigTest(bool is_async);
4494 
4495  protected:
TearDown()4496   void TearDown() override {
4497     HostResolverManagerTest::TearDown();
4498     InvalidateDnsConfig();
4499 
4500     // Ensure |notifier_| is fully cleaned up before test shutdown.
4501     notifier_.reset();
4502     notifier_task_runner_->RunUntilIdle();
4503   }
4504 
4505   // HostResolverManagerTest implementation:
DefaultOptions()4506   HostResolver::ManagerOptions DefaultOptions() override {
4507     HostResolver::ManagerOptions options =
4508         HostResolverManagerTest::DefaultOptions();
4509     options.insecure_dns_client_enabled = true;
4510     options.additional_types_via_insecure_dns_enabled = true;
4511     return options;
4512   }
4513 
CreateResolverWithOptionsAndParams(HostResolver::ManagerOptions options,const HostResolverSystemTask::Params & params,bool ipv6_reachable,bool is_async=false,bool ipv4_reachable=true)4514   void CreateResolverWithOptionsAndParams(
4515       HostResolver::ManagerOptions options,
4516       const HostResolverSystemTask::Params& params,
4517       bool ipv6_reachable,
4518       bool is_async = false,
4519       bool ipv4_reachable = true) override {
4520     DestroyResolver();
4521 
4522     resolver_ = std::make_unique<TestHostResolverManager>(
4523         options, notifier_.get(), nullptr /* net_log */, ipv6_reachable,
4524         ipv4_reachable, is_async);
4525     auto dns_client =
4526         std::make_unique<MockDnsClient>(DnsConfig(), CreateDefaultDnsRules());
4527     dns_client_ = dns_client.get();
4528     resolver_->SetDnsClientForTesting(std::move(dns_client));
4529     resolver_->SetInsecureDnsClientEnabled(
4530         options.insecure_dns_client_enabled,
4531         options.additional_types_via_insecure_dns_enabled);
4532     resolver_->set_host_resolver_system_params_for_test(params);
4533     resolver_->RegisterResolveContext(resolve_context_.get());
4534   }
4535 
4536   // Call after CreateResolver() to update the resolver with a new MockDnsClient
4537   // using |config| and |rules|.
UseMockDnsClient(const DnsConfig & config,MockDnsClientRuleList rules)4538   void UseMockDnsClient(const DnsConfig& config, MockDnsClientRuleList rules) {
4539     // HostResolver expects DnsConfig to get set after setting DnsClient, so
4540     // create first with an empty config and then update the config.
4541     auto dns_client =
4542         std::make_unique<MockDnsClient>(DnsConfig(), std::move(rules));
4543     dns_client_ = dns_client.get();
4544     resolver_->SetDnsClientForTesting(std::move(dns_client));
4545     resolver_->SetInsecureDnsClientEnabled(
4546         /*enabled=*/true,
4547         /*additional_dns_types_enabled=*/true);
4548     if (!config.Equals(DnsConfig()))
4549       ChangeDnsConfig(config);
4550   }
4551 
CreateDefaultDnsRules()4552   static MockDnsClientRuleList CreateDefaultDnsRules() {
4553     MockDnsClientRuleList rules;
4554 
4555     AddDnsRule(&rules, "nodomain", dns_protocol::kTypeA,
4556                MockDnsClientRule::ResultType::kNoDomain, false /* delay */);
4557     AddDnsRule(&rules, "nodomain", dns_protocol::kTypeAAAA,
4558                MockDnsClientRule::ResultType::kNoDomain, false /* delay */);
4559     AddDnsRule(&rules, "nx", dns_protocol::kTypeA,
4560                MockDnsClientRule::ResultType::kFail, false /* delay */);
4561     AddDnsRule(&rules, "nx", dns_protocol::kTypeAAAA,
4562                MockDnsClientRule::ResultType::kFail, false /* delay */);
4563     AddDnsRule(&rules, "ok", dns_protocol::kTypeA,
4564                MockDnsClientRule::ResultType::kOk, false /* delay */);
4565     AddDnsRule(&rules, "ok", dns_protocol::kTypeAAAA,
4566                MockDnsClientRule::ResultType::kOk, false /* delay */);
4567     AddDnsRule(&rules, "4ok", dns_protocol::kTypeA,
4568                MockDnsClientRule::ResultType::kOk, false /* delay */);
4569     AddDnsRule(&rules, "4ok", dns_protocol::kTypeAAAA,
4570                MockDnsClientRule::ResultType::kEmpty, false /* delay */);
4571     AddDnsRule(&rules, "6ok", dns_protocol::kTypeA,
4572                MockDnsClientRule::ResultType::kEmpty, false /* delay */);
4573     AddDnsRule(&rules, "6ok", dns_protocol::kTypeAAAA,
4574                MockDnsClientRule::ResultType::kOk, false /* delay */);
4575     AddDnsRule(&rules, "4nx", dns_protocol::kTypeA,
4576                MockDnsClientRule::ResultType::kOk, false /* delay */);
4577     AddDnsRule(&rules, "4nx", dns_protocol::kTypeAAAA,
4578                MockDnsClientRule::ResultType::kFail, false /* delay */);
4579     AddDnsRule(&rules, "empty", dns_protocol::kTypeA,
4580                MockDnsClientRule::ResultType::kEmpty, false /* delay */);
4581     AddDnsRule(&rules, "empty", dns_protocol::kTypeAAAA,
4582                MockDnsClientRule::ResultType::kEmpty, false /* delay */);
4583 
4584     AddDnsRule(&rules, "slow_nx", dns_protocol::kTypeA,
4585                MockDnsClientRule::ResultType::kFail, true /* delay */);
4586     AddDnsRule(&rules, "slow_nx", dns_protocol::kTypeAAAA,
4587                MockDnsClientRule::ResultType::kFail, true /* delay */);
4588 
4589     AddDnsRule(&rules, "4slow_ok", dns_protocol::kTypeA,
4590                MockDnsClientRule::ResultType::kOk, true /* delay */);
4591     AddDnsRule(&rules, "4slow_ok", dns_protocol::kTypeAAAA,
4592                MockDnsClientRule::ResultType::kOk, false /* delay */);
4593     AddDnsRule(&rules, "6slow_ok", dns_protocol::kTypeA,
4594                MockDnsClientRule::ResultType::kOk, false /* delay */);
4595     AddDnsRule(&rules, "6slow_ok", dns_protocol::kTypeAAAA,
4596                MockDnsClientRule::ResultType::kOk, true /* delay */);
4597     AddDnsRule(&rules, "4slow_4ok", dns_protocol::kTypeA,
4598                MockDnsClientRule::ResultType::kOk, true /* delay */);
4599     AddDnsRule(&rules, "4slow_4ok", dns_protocol::kTypeAAAA,
4600                MockDnsClientRule::ResultType::kEmpty, false /* delay */);
4601     AddDnsRule(&rules, "4slow_4timeout", dns_protocol::kTypeA,
4602                MockDnsClientRule::ResultType::kTimeout, true /* delay */);
4603     AddDnsRule(&rules, "4slow_4timeout", dns_protocol::kTypeAAAA,
4604                MockDnsClientRule::ResultType::kOk, false /* delay */);
4605     AddDnsRule(&rules, "4slow_6timeout", dns_protocol::kTypeA,
4606                MockDnsClientRule::ResultType::kOk, true /* delay */);
4607     AddDnsRule(&rules, "4slow_6timeout", dns_protocol::kTypeAAAA,
4608                MockDnsClientRule::ResultType::kTimeout, false /* delay */);
4609 
4610     AddDnsRule(&rules, "4collision", dns_protocol::kTypeA,
4611                IPAddress(127, 0, 53, 53), false /* delay */);
4612     AddDnsRule(&rules, "4collision", dns_protocol::kTypeAAAA,
4613                MockDnsClientRule::ResultType::kEmpty, false /* delay */);
4614     AddDnsRule(&rules, "6collision", dns_protocol::kTypeA,
4615                MockDnsClientRule::ResultType::kEmpty, false /* delay */);
4616     // This isn't the expected IP for collisions (but looks close to it).
4617     AddDnsRule(&rules, "6collision", dns_protocol::kTypeAAAA,
4618                IPAddress(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 0, 53, 53),
4619                false /* delay */);
4620 
4621     AddSecureDnsRule(&rules, "automatic_nodomain", dns_protocol::kTypeA,
4622                      MockDnsClientRule::ResultType::kNoDomain,
4623                      false /* delay */);
4624     AddSecureDnsRule(&rules, "automatic_nodomain", dns_protocol::kTypeAAAA,
4625                      MockDnsClientRule::ResultType::kNoDomain,
4626                      false /* delay */);
4627     AddDnsRule(&rules, "automatic_nodomain", dns_protocol::kTypeA,
4628                MockDnsClientRule::ResultType::kNoDomain, false /* delay */);
4629     AddDnsRule(&rules, "automatic_nodomain", dns_protocol::kTypeAAAA,
4630                MockDnsClientRule::ResultType::kNoDomain, false /* delay */);
4631     AddSecureDnsRule(&rules, "automatic", dns_protocol::kTypeA,
4632                      MockDnsClientRule::ResultType::kOk, false /* delay */);
4633     AddSecureDnsRule(&rules, "automatic", dns_protocol::kTypeAAAA,
4634                      MockDnsClientRule::ResultType::kOk, false /* delay */);
4635     AddDnsRule(&rules, "automatic", dns_protocol::kTypeA,
4636                MockDnsClientRule::ResultType::kOk, false /* delay */);
4637     AddDnsRule(&rules, "automatic", dns_protocol::kTypeAAAA,
4638                MockDnsClientRule::ResultType::kOk, false /* delay */);
4639     AddDnsRule(&rules, "insecure_automatic", dns_protocol::kTypeA,
4640                MockDnsClientRule::ResultType::kOk, false /* delay */);
4641     AddDnsRule(&rules, "insecure_automatic", dns_protocol::kTypeAAAA,
4642                MockDnsClientRule::ResultType::kOk, false /* delay */);
4643 
4644     AddSecureDnsRule(&rules, "secure", dns_protocol::kTypeA,
4645                      MockDnsClientRule::ResultType::kOk, false /* delay */);
4646     AddSecureDnsRule(&rules, "secure", dns_protocol::kTypeAAAA,
4647                      MockDnsClientRule::ResultType::kOk, false /* delay */);
4648 
4649     return rules;
4650   }
4651 
4652   // Adds a rule to |rules|.
AddDnsRule(MockDnsClientRuleList * rules,const std::string & prefix,uint16_t qtype,MockDnsClientRule::ResultType result_type,bool delay)4653   static void AddDnsRule(MockDnsClientRuleList* rules,
4654                          const std::string& prefix,
4655                          uint16_t qtype,
4656                          MockDnsClientRule::ResultType result_type,
4657                          bool delay) {
4658     rules->emplace_back(prefix, qtype, false /* secure */,
4659                         MockDnsClientRule::Result(result_type), delay);
4660   }
4661 
AddDnsRule(MockDnsClientRuleList * rules,const std::string & prefix,uint16_t qtype,const IPAddress & result_ip,bool delay)4662   static void AddDnsRule(MockDnsClientRuleList* rules,
4663                          const std::string& prefix,
4664                          uint16_t qtype,
4665                          const IPAddress& result_ip,
4666                          bool delay) {
4667     rules->emplace_back(prefix, qtype, false /* secure */,
4668                         MockDnsClientRule::Result(
4669                             BuildTestDnsAddressResponse(prefix, result_ip)),
4670                         delay);
4671   }
4672 
AddDnsRule(MockDnsClientRuleList * rules,const std::string & prefix,uint16_t qtype,IPAddress result_ip,std::string cannonname,bool delay)4673   static void AddDnsRule(MockDnsClientRuleList* rules,
4674                          const std::string& prefix,
4675                          uint16_t qtype,
4676                          IPAddress result_ip,
4677                          std::string cannonname,
4678                          bool delay) {
4679     rules->emplace_back(
4680         prefix, qtype, false /* secure */,
4681         MockDnsClientRule::Result(BuildTestDnsAddressResponseWithCname(
4682             prefix, result_ip, std::move(cannonname))),
4683         delay);
4684   }
4685 
AddDnsRule(MockDnsClientRuleList * rules,const std::string & prefix,uint16_t qtype,DnsResponse dns_test_response,bool delay)4686   static void AddDnsRule(MockDnsClientRuleList* rules,
4687 
4688                          const std::string& prefix,
4689                          uint16_t qtype,
4690                          DnsResponse dns_test_response,
4691                          bool delay) {
4692     rules->emplace_back(prefix, qtype, false /* secure */,
4693                         MockDnsClientRule::Result(std::move(dns_test_response)),
4694                         delay);
4695   }
4696 
AddSecureDnsRule(MockDnsClientRuleList * rules,const std::string & prefix,uint16_t qtype,MockDnsClientRule::ResultType result_type,bool delay)4697   static void AddSecureDnsRule(MockDnsClientRuleList* rules,
4698                                const std::string& prefix,
4699                                uint16_t qtype,
4700                                MockDnsClientRule::ResultType result_type,
4701                                bool delay) {
4702     rules->emplace_back(prefix, qtype, true /* secure */,
4703                         MockDnsClientRule::Result(result_type), delay);
4704   }
4705 
ChangeDnsConfig(const DnsConfig & config)4706   void ChangeDnsConfig(const DnsConfig& config) {
4707     DCHECK(config.IsValid());
4708     notifier_task_runner_->PostTask(
4709         FROM_HERE,
4710         base::BindOnce(&TestDnsConfigService::OnHostsRead,
4711                        base::Unretained(config_service_), config.hosts));
4712     notifier_task_runner_->PostTask(
4713         FROM_HERE, base::BindOnce(&TestDnsConfigService::OnConfigRead,
4714                                   base::Unretained(config_service_), config));
4715 
4716     notifier_task_runner_->RunUntilIdle();
4717     base::RunLoop().RunUntilIdle();
4718   }
4719 
InvalidateDnsConfig()4720   void InvalidateDnsConfig() {
4721     notifier_task_runner_->PostTask(
4722         FROM_HERE,
4723         base::BindOnce(&TestDnsConfigService::OnHostsRead,
4724                        base::Unretained(config_service_), DnsHosts()));
4725     notifier_task_runner_->PostTask(
4726         FROM_HERE, base::BindOnce(&TestDnsConfigService::InvalidateConfig,
4727                                   base::Unretained(config_service_)));
4728 
4729     notifier_task_runner_->FastForwardBy(
4730         DnsConfigService::kInvalidationTimeout);
4731     base::RunLoop().RunUntilIdle();
4732   }
4733 
SetInitialDnsConfig(const DnsConfig & config)4734   void SetInitialDnsConfig(const DnsConfig& config) {
4735     InvalidateDnsConfig();
4736     ChangeDnsConfig(config);
4737   }
4738 
TriggerInsecureFailureCondition()4739   void TriggerInsecureFailureCondition() {
4740     proc_->AddRuleForAllFamilies(std::string(),
4741                                  std::string());  // Default to failures.
4742 
4743     // Disable Secure DNS for these requests.
4744     HostResolver::ResolveHostParameters parameters;
4745     parameters.secure_dns_policy = SecureDnsPolicy::kDisable;
4746 
4747     std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
4748     for (unsigned i = 0; i < maximum_insecure_dns_task_failures(); ++i) {
4749       // Use custom names to require separate Jobs.
4750       std::string hostname = base::StringPrintf("nx_%u", i);
4751       // Ensure fallback to HostResolverSystemTask succeeds.
4752       proc_->AddRuleForAllFamilies(hostname, "192.168.1.101");
4753       responses.emplace_back(
4754           std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
4755               HostPortPair(hostname, 80), NetworkAnonymizationKey(),
4756               NetLogWithSource(), parameters, resolve_context_.get(),
4757               resolve_context_->host_cache())));
4758     }
4759 
4760     proc_->SignalMultiple(responses.size());
4761 
4762     for (const auto& response : responses)
4763       EXPECT_THAT(response->result_error(), IsOk());
4764 
4765     ASSERT_FALSE(proc_->HasBlockedRequests());
4766   }
4767 
4768   scoped_refptr<base::TestMockTimeTaskRunner> notifier_task_runner_;
4769   raw_ptr<TestDnsConfigService> config_service_;
4770   std::unique_ptr<SystemDnsConfigChangeNotifier> notifier_;
4771 
4772   // Owned by |resolver_|.
4773   raw_ptr<MockDnsClient> dns_client_ = nullptr;
4774 };
4775 
TEST_F(HostResolverManagerDnsTest,FlushCacheOnDnsConfigChange)4776 TEST_F(HostResolverManagerDnsTest, FlushCacheOnDnsConfigChange) {
4777   proc_->SignalMultiple(2u);  // One before the flush, one after.
4778 
4779   // Resolve to populate the cache.
4780   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
4781       HostPortPair("host1", 70), NetworkAnonymizationKey(), NetLogWithSource(),
4782       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
4783   EXPECT_THAT(initial_response.result_error(), IsOk());
4784   EXPECT_EQ(1u, proc_->GetCaptureList().size());
4785 
4786   // Result expected to come from the cache.
4787   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
4788       HostPortPair("host1", 75), NetworkAnonymizationKey(), NetLogWithSource(),
4789       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
4790   EXPECT_THAT(cached_response.result_error(), IsOk());
4791   EXPECT_EQ(1u, proc_->GetCaptureList().size());  // No expected increase.
4792 
4793   // Flush cache by triggering a DNS config change.
4794   ChangeDnsConfig(CreateValidDnsConfig());
4795 
4796   // Expect flushed from cache and therefore served from |proc_|.
4797   ResolveHostResponseHelper flushed_response(resolver_->CreateRequest(
4798       HostPortPair("host1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
4799       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
4800   EXPECT_THAT(flushed_response.result_error(), IsOk());
4801   EXPECT_EQ(2u, proc_->GetCaptureList().size());  // Expected increase.
4802 }
4803 
TEST_F(HostResolverManagerDnsTest,DisableAndEnableInsecureDnsClient)4804 TEST_F(HostResolverManagerDnsTest, DisableAndEnableInsecureDnsClient) {
4805   // Disable fallback to allow testing how requests are initially handled.
4806   set_allow_fallback_to_systemtask(false);
4807 
4808   ChangeDnsConfig(CreateValidDnsConfig());
4809   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.2.47");
4810   proc_->SignalMultiple(1u);
4811 
4812   resolver_->SetInsecureDnsClientEnabled(
4813       /*enabled=*/false,
4814       /*additional_dns_types_enabled*/ false);
4815   ResolveHostResponseHelper response_system(resolver_->CreateRequest(
4816       HostPortPair("nx_succeed", 1212), NetworkAnonymizationKey(),
4817       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4818       resolve_context_->host_cache()));
4819   EXPECT_THAT(response_system.result_error(), IsOk());
4820   EXPECT_THAT(response_system.request()->GetAddressResults()->endpoints(),
4821               testing::ElementsAre(CreateExpected("192.168.2.47", 1212)));
4822   EXPECT_THAT(
4823       response_system.request()->GetEndpointResults(),
4824       testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4825           testing::ElementsAre(CreateExpected("192.168.2.47", 1212))))));
4826 
4827   resolver_->SetInsecureDnsClientEnabled(/*enabled*/ true,
4828                                          /*additional_dns_types_enabled=*/true);
4829   ResolveHostResponseHelper response_dns_client(resolver_->CreateRequest(
4830       HostPortPair("ok_fail", 1212), NetworkAnonymizationKey(),
4831       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4832       resolve_context_->host_cache()));
4833   EXPECT_THAT(response_dns_client.result_error(), IsOk());
4834   EXPECT_THAT(response_dns_client.request()->GetAddressResults()->endpoints(),
4835               testing::UnorderedElementsAre(CreateExpected("::1", 1212),
4836                                             CreateExpected("127.0.0.1", 1212)));
4837   EXPECT_THAT(
4838       response_dns_client.request()->GetEndpointResults(),
4839       testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4840           testing::UnorderedElementsAre(CreateExpected("::1", 1212),
4841                                         CreateExpected("127.0.0.1", 1212))))));
4842 }
4843 
TEST_F(HostResolverManagerDnsTest,UseHostResolverSystemTaskWhenPrivateDnsActive)4844 TEST_F(HostResolverManagerDnsTest,
4845        UseHostResolverSystemTaskWhenPrivateDnsActive) {
4846   // Disable fallback to allow testing how requests are initially handled.
4847   set_allow_fallback_to_systemtask(false);
4848   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.2.47");
4849   proc_->SignalMultiple(1u);
4850 
4851   DnsConfig config = CreateValidDnsConfig();
4852   config.dns_over_tls_active = true;
4853   ChangeDnsConfig(config);
4854   ResolveHostResponseHelper response_system(resolver_->CreateRequest(
4855       HostPortPair("nx_succeed", 1212), NetworkAnonymizationKey(),
4856       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4857       resolve_context_->host_cache()));
4858   EXPECT_THAT(response_system.result_error(), IsOk());
4859   EXPECT_THAT(response_system.request()->GetAddressResults()->endpoints(),
4860               testing::ElementsAre(CreateExpected("192.168.2.47", 1212)));
4861   EXPECT_THAT(
4862       response_system.request()->GetEndpointResults(),
4863       testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
4864           testing::ElementsAre(CreateExpected("192.168.2.47", 1212))))));
4865 }
4866 
4867 // RFC 6761 localhost names should always resolve to loopback.
TEST_F(HostResolverManagerDnsTest,LocalhostLookup)4868 TEST_F(HostResolverManagerDnsTest, LocalhostLookup) {
4869   // Add a rule resolving localhost names to a non-loopback IP and test
4870   // that they still resolves to loopback.
4871   proc_->AddRuleForAllFamilies("foo.localhost", "192.168.1.42");
4872   proc_->AddRuleForAllFamilies("localhost", "192.168.1.42");
4873   proc_->AddRuleForAllFamilies("localhost.", "192.168.1.42");
4874 
4875   ResolveHostResponseHelper response0(resolver_->CreateRequest(
4876       HostPortPair("foo.localhost", 80), NetworkAnonymizationKey(),
4877       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4878       resolve_context_->host_cache()));
4879   EXPECT_THAT(response0.result_error(), IsOk());
4880   EXPECT_THAT(response0.request()->GetAddressResults()->endpoints(),
4881               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
4882                                             CreateExpected("::1", 80)));
4883   EXPECT_THAT(
4884       response0.request()->GetEndpointResults(),
4885       testing::Pointee(testing::ElementsAre(
4886           ExpectEndpointResult(testing::UnorderedElementsAre(
4887               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
4888 
4889   ResolveHostResponseHelper response1(resolver_->CreateRequest(
4890       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
4891       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4892       resolve_context_->host_cache()));
4893   EXPECT_THAT(response1.result_error(), IsOk());
4894   EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
4895               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
4896                                             CreateExpected("::1", 80)));
4897   EXPECT_THAT(
4898       response1.request()->GetEndpointResults(),
4899       testing::Pointee(testing::ElementsAre(
4900           ExpectEndpointResult(testing::UnorderedElementsAre(
4901               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
4902 
4903   ResolveHostResponseHelper response2(resolver_->CreateRequest(
4904       HostPortPair("localhost.", 80), NetworkAnonymizationKey(),
4905       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4906       resolve_context_->host_cache()));
4907   EXPECT_THAT(response2.result_error(), IsOk());
4908   EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
4909               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
4910                                             CreateExpected("::1", 80)));
4911   EXPECT_THAT(
4912       response2.request()->GetEndpointResults(),
4913       testing::Pointee(testing::ElementsAre(
4914           ExpectEndpointResult(testing::UnorderedElementsAre(
4915               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
4916 }
4917 
4918 // RFC 6761 localhost names should always resolve to loopback, even if a HOSTS
4919 // file is active.
TEST_F(HostResolverManagerDnsTest,LocalhostLookupWithHosts)4920 TEST_F(HostResolverManagerDnsTest, LocalhostLookupWithHosts) {
4921   DnsHosts hosts;
4922   hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] =
4923       IPAddress({192, 168, 1, 1});
4924   hosts[DnsHostsKey("foo.localhost", ADDRESS_FAMILY_IPV4)] =
4925       IPAddress({192, 168, 1, 2});
4926 
4927   DnsConfig config = CreateValidDnsConfig();
4928   config.hosts = hosts;
4929   ChangeDnsConfig(config);
4930 
4931   ResolveHostResponseHelper response0(resolver_->CreateRequest(
4932       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
4933       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4934       resolve_context_->host_cache()));
4935   EXPECT_THAT(response0.result_error(), IsOk());
4936   EXPECT_THAT(response0.request()->GetAddressResults()->endpoints(),
4937               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
4938                                             CreateExpected("::1", 80)));
4939   EXPECT_THAT(
4940       response0.request()->GetEndpointResults(),
4941       testing::Pointee(testing::ElementsAre(
4942           ExpectEndpointResult(testing::UnorderedElementsAre(
4943               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
4944 
4945   ResolveHostResponseHelper response1(resolver_->CreateRequest(
4946       HostPortPair("foo.localhost", 80), NetworkAnonymizationKey(),
4947       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4948       resolve_context_->host_cache()));
4949   EXPECT_THAT(response1.result_error(), IsOk());
4950   EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
4951               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
4952                                             CreateExpected("::1", 80)));
4953   EXPECT_THAT(
4954       response1.request()->GetEndpointResults(),
4955       testing::Pointee(testing::ElementsAre(
4956           ExpectEndpointResult(testing::UnorderedElementsAre(
4957               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
4958 }
4959 
4960 // Test successful and fallback resolutions in HostResolverManager::DnsTask.
TEST_F(HostResolverManagerDnsTest,DnsTask)4961 TEST_F(HostResolverManagerDnsTest, DnsTask) {
4962   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
4963   // All other hostnames will fail in proc_.
4964 
4965   // Initially there is no config, so client should not be invoked.
4966   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
4967       HostPortPair("ok_fail", 80), NetworkAnonymizationKey(),
4968       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4969       resolve_context_->host_cache()));
4970   EXPECT_FALSE(initial_response.complete());
4971 
4972   proc_->SignalMultiple(1u);
4973 
4974   EXPECT_THAT(initial_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
4975 
4976   ChangeDnsConfig(CreateValidDnsConfig());
4977 
4978   ResolveHostResponseHelper response0(resolver_->CreateRequest(
4979       HostPortPair("ok_fail", 80), NetworkAnonymizationKey(),
4980       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4981       resolve_context_->host_cache()));
4982   ResolveHostResponseHelper response1(resolver_->CreateRequest(
4983       HostPortPair("nx_fail", 80), NetworkAnonymizationKey(),
4984       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4985       resolve_context_->host_cache()));
4986   ResolveHostResponseHelper response2(resolver_->CreateRequest(
4987       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
4988       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
4989       resolve_context_->host_cache()));
4990 
4991   proc_->SignalMultiple(4u);
4992 
4993   // Resolved by MockDnsClient.
4994   EXPECT_THAT(response0.result_error(), IsOk());
4995   EXPECT_THAT(response0.request()->GetAddressResults()->endpoints(),
4996               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
4997                                             CreateExpected("::1", 80)));
4998   EXPECT_THAT(
4999       response0.request()->GetEndpointResults(),
5000       testing::Pointee(testing::ElementsAre(
5001           ExpectEndpointResult(testing::UnorderedElementsAre(
5002               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5003 
5004   // Fallback to HostResolverSystemTask.
5005   EXPECT_THAT(response1.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5006   EXPECT_THAT(response2.result_error(), IsOk());
5007   EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
5008               testing::ElementsAre(CreateExpected("192.168.1.102", 80)));
5009   EXPECT_THAT(response2.request()->GetEndpointResults(),
5010               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5011                   testing::ElementsAre(CreateExpected("192.168.1.102", 80))))));
5012 }
5013 
TEST_F(HostResolverManagerDnsTest,DnsTaskWithScheme)5014 TEST_F(HostResolverManagerDnsTest, DnsTaskWithScheme) {
5015   ChangeDnsConfig(CreateValidDnsConfig());
5016 
5017   ResolveHostResponseHelper response(resolver_->CreateRequest(
5018       url::SchemeHostPort(url::kWsScheme, "ok_fail", 80),
5019       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
5020       resolve_context_.get(), resolve_context_->host_cache()));
5021 
5022   // Resolved by MockDnsClient.
5023   EXPECT_THAT(response.result_error(), IsOk());
5024   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
5025               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5026                                             CreateExpected("::1", 80)));
5027   EXPECT_THAT(
5028       response.request()->GetEndpointResults(),
5029       testing::Pointee(testing::ElementsAre(
5030           ExpectEndpointResult(testing::UnorderedElementsAre(
5031               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5032 }
5033 
5034 // Test successful and failing resolutions in HostResolverManager::DnsTask when
5035 // fallback to HostResolverSystemTask is disabled.
TEST_F(HostResolverManagerDnsTest,NoFallbackToHostResolverSystemTask)5036 TEST_F(HostResolverManagerDnsTest, NoFallbackToHostResolverSystemTask) {
5037   set_allow_fallback_to_systemtask(false);
5038 
5039   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
5040   // All other hostnames will fail in proc_.
5041 
5042   // Set empty DnsConfig.
5043   InvalidateDnsConfig();
5044   // Initially there is no config, so client should not be invoked.
5045   ResolveHostResponseHelper initial_response0(resolver_->CreateRequest(
5046       HostPortPair("ok_fail", 80), NetworkAnonymizationKey(),
5047       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5048       resolve_context_->host_cache()));
5049   ResolveHostResponseHelper initial_response1(resolver_->CreateRequest(
5050       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
5051       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5052       resolve_context_->host_cache()));
5053   proc_->SignalMultiple(2u);
5054 
5055   EXPECT_THAT(initial_response0.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5056   EXPECT_THAT(initial_response1.result_error(), IsOk());
5057   EXPECT_THAT(initial_response1.request()->GetAddressResults()->endpoints(),
5058               testing::ElementsAre(CreateExpected("192.168.1.102", 80)));
5059   EXPECT_THAT(initial_response1.request()->GetEndpointResults(),
5060               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5061                   testing::ElementsAre(CreateExpected("192.168.1.102", 80))))));
5062 
5063   // Switch to a valid config.
5064   ChangeDnsConfig(CreateValidDnsConfig());
5065   // First request is resolved by MockDnsClient, others should fail due to
5066   // disabled fallback to HostResolverSystemTask.
5067   ResolveHostResponseHelper response0(resolver_->CreateRequest(
5068       HostPortPair("ok_fail", 80), NetworkAnonymizationKey(),
5069       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5070       resolve_context_->host_cache()));
5071   ResolveHostResponseHelper response1(resolver_->CreateRequest(
5072       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
5073       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5074       resolve_context_->host_cache()));
5075   proc_->SignalMultiple(6u);
5076 
5077   // Resolved by MockDnsClient.
5078   EXPECT_THAT(response0.result_error(), IsOk());
5079   EXPECT_THAT(response0.request()->GetAddressResults()->endpoints(),
5080               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5081                                             CreateExpected("::1", 80)));
5082   EXPECT_THAT(
5083       response0.request()->GetEndpointResults(),
5084       testing::Pointee(testing::ElementsAre(
5085           ExpectEndpointResult(testing::UnorderedElementsAre(
5086               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5087   // Fallback to HostResolverSystemTask is disabled.
5088   EXPECT_THAT(response1.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5089 }
5090 
5091 // Test behavior of OnDnsTaskFailure when Job is aborted.
TEST_F(HostResolverManagerDnsTest,OnDnsTaskFailureAbortedJob)5092 TEST_F(HostResolverManagerDnsTest, OnDnsTaskFailureAbortedJob) {
5093   ChangeDnsConfig(CreateValidDnsConfig());
5094   ResolveHostResponseHelper response(resolver_->CreateRequest(
5095       HostPortPair("nx_abort", 80), NetworkAnonymizationKey(),
5096       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5097       resolve_context_->host_cache()));
5098   // Abort all jobs here.
5099   CreateResolver();
5100   proc_->SignalMultiple(1u);
5101   // Run to completion.
5102   base::RunLoop().RunUntilIdle();  // Notification happens async.
5103   // It shouldn't crash during OnDnsTaskFailure callbacks.
5104   EXPECT_FALSE(response.complete());
5105 
5106   // Repeat test with Fallback to HostResolverSystemTask disabled
5107   set_allow_fallback_to_systemtask(false);
5108   ChangeDnsConfig(CreateValidDnsConfig());
5109   ResolveHostResponseHelper no_fallback_response(resolver_->CreateRequest(
5110       HostPortPair("nx_abort", 80), NetworkAnonymizationKey(),
5111       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5112       resolve_context_->host_cache()));
5113   // Abort all jobs here.
5114   CreateResolver();
5115   proc_->SignalMultiple(2u);
5116   // Run to completion.
5117   base::RunLoop().RunUntilIdle();  // Notification happens async.
5118   // It shouldn't crash during OnDnsTaskFailure callbacks.
5119   EXPECT_FALSE(no_fallback_response.complete());
5120 }
5121 
5122 // Fallback to proc allowed with ANY source.
TEST_F(HostResolverManagerDnsTest,FallbackBySource_Any)5123 TEST_F(HostResolverManagerDnsTest, FallbackBySource_Any) {
5124   // Ensure fallback is otherwise allowed by resolver settings.
5125   set_allow_fallback_to_systemtask(true);
5126 
5127   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
5128   // All other hostnames will fail in proc_.
5129 
5130   ChangeDnsConfig(CreateValidDnsConfig());
5131 
5132   ResolveHostResponseHelper response0(resolver_->CreateRequest(
5133       HostPortPair("nx_fail", 80), NetworkAnonymizationKey(),
5134       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5135       resolve_context_->host_cache()));
5136   ResolveHostResponseHelper response1(resolver_->CreateRequest(
5137       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
5138       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5139       resolve_context_->host_cache()));
5140   proc_->SignalMultiple(2u);
5141 
5142   EXPECT_THAT(response0.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5143   EXPECT_THAT(response1.result_error(), IsOk());
5144   EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
5145               testing::ElementsAre(CreateExpected("192.168.1.102", 80)));
5146   EXPECT_THAT(response1.request()->GetEndpointResults(),
5147               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5148                   testing::ElementsAre(CreateExpected("192.168.1.102", 80))))));
5149 }
5150 
5151 // Fallback to proc not allowed with DNS source.
TEST_F(HostResolverManagerDnsTest,FallbackBySource_Dns)5152 TEST_F(HostResolverManagerDnsTest, FallbackBySource_Dns) {
5153   // Ensure fallback is otherwise allowed by resolver settings.
5154   set_allow_fallback_to_systemtask(true);
5155 
5156   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
5157   // All other hostnames will fail in proc_.
5158 
5159   ChangeDnsConfig(CreateValidDnsConfig());
5160 
5161   HostResolver::ResolveHostParameters parameters;
5162   parameters.source = HostResolverSource::DNS;
5163   ResolveHostResponseHelper response0(resolver_->CreateRequest(
5164       HostPortPair("nx_fail", 80), NetworkAnonymizationKey(),
5165       NetLogWithSource(), parameters, resolve_context_.get(),
5166       resolve_context_->host_cache()));
5167   ResolveHostResponseHelper response1(resolver_->CreateRequest(
5168       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
5169       NetLogWithSource(), parameters, resolve_context_.get(),
5170       resolve_context_->host_cache()));
5171   // Nothing should reach |proc_| on success, but let failures through to fail
5172   // instead of hanging.
5173   proc_->SignalMultiple(2u);
5174 
5175   EXPECT_THAT(response0.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5176   EXPECT_THAT(response1.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5177 }
5178 
5179 // Fallback to proc on DnsClient change allowed with ANY source.
TEST_F(HostResolverManagerDnsTest,FallbackOnAbortBySource_Any)5180 TEST_F(HostResolverManagerDnsTest, FallbackOnAbortBySource_Any) {
5181   // Ensure fallback is otherwise allowed by resolver settings.
5182   set_allow_fallback_to_systemtask(true);
5183 
5184   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
5185   // All other hostnames will fail in proc_.
5186 
5187   ChangeDnsConfig(CreateValidDnsConfig());
5188 
5189   ResolveHostResponseHelper response0(resolver_->CreateRequest(
5190       HostPortPair("ok_fail", 80), NetworkAnonymizationKey(),
5191       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5192       resolve_context_->host_cache()));
5193   ResolveHostResponseHelper response1(resolver_->CreateRequest(
5194       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
5195       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5196       resolve_context_->host_cache()));
5197   proc_->SignalMultiple(2u);
5198 
5199   // Simulate the case when the preference or policy has disabled the insecure
5200   // DNS client causing AbortInsecureDnsTasks.
5201   resolver_->SetInsecureDnsClientEnabled(
5202       /*enabled=*/false,
5203       /*additional_dns_types_enabled=*/false);
5204 
5205   // All requests should fallback to system resolver.
5206   EXPECT_THAT(response0.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5207   EXPECT_THAT(response1.result_error(), IsOk());
5208   EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
5209               testing::ElementsAre(CreateExpected("192.168.1.102", 80)));
5210   EXPECT_THAT(response1.request()->GetEndpointResults(),
5211               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5212                   testing::ElementsAre(CreateExpected("192.168.1.102", 80))))));
5213 }
5214 
5215 // Fallback to system on DnsClient change not allowed with DNS source.
TEST_F(HostResolverManagerDnsTest,FallbackOnAbortBySource_Dns)5216 TEST_F(HostResolverManagerDnsTest, FallbackOnAbortBySource_Dns) {
5217   // Ensure fallback is otherwise allowed by resolver settings.
5218   set_allow_fallback_to_systemtask(true);
5219 
5220   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
5221   // All other hostnames will fail in proc_.
5222 
5223   ChangeDnsConfig(CreateValidDnsConfig());
5224 
5225   HostResolver::ResolveHostParameters parameters;
5226   parameters.source = HostResolverSource::DNS;
5227   ResolveHostResponseHelper response0(resolver_->CreateRequest(
5228       HostPortPair("ok_fail", 80), NetworkAnonymizationKey(),
5229       NetLogWithSource(), parameters, resolve_context_.get(),
5230       resolve_context_->host_cache()));
5231   ResolveHostResponseHelper response1(resolver_->CreateRequest(
5232       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
5233       NetLogWithSource(), parameters, resolve_context_.get(),
5234       resolve_context_->host_cache()));
5235   // Nothing should reach |proc_| on success, but let failures through to fail
5236   // instead of hanging.
5237   proc_->SignalMultiple(2u);
5238 
5239   // Simulate the case when the preference or policy has disabled the insecure
5240   // DNS client causing AbortInsecureDnsTasks.
5241   resolver_->SetInsecureDnsClientEnabled(
5242       /*enabled=*/false,
5243       /*additional_dns_types_enabled=*/false);
5244 
5245   // No fallback expected.  All requests should fail.
5246   EXPECT_THAT(response0.result_error(), IsError(ERR_NETWORK_CHANGED));
5247   EXPECT_THAT(response1.result_error(), IsError(ERR_NETWORK_CHANGED));
5248 }
5249 
5250 // Insecure DnsClient change shouldn't affect secure DnsTasks.
TEST_F(HostResolverManagerDnsTest,DisableInsecureDnsClient_SecureDnsTasksUnaffected)5251 TEST_F(HostResolverManagerDnsTest,
5252        DisableInsecureDnsClient_SecureDnsTasksUnaffected) {
5253   // Ensure fallback is otherwise allowed by resolver settings.
5254   set_allow_fallback_to_systemtask(true);
5255 
5256   proc_->AddRuleForAllFamilies("automatic", "192.168.1.102");
5257   // All other hostnames will fail in proc_.
5258 
5259   ChangeDnsConfig(CreateValidDnsConfig());
5260   DnsConfigOverrides overrides;
5261   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
5262   resolver_->SetDnsConfigOverrides(overrides);
5263 
5264   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
5265       HostPortPair("automatic", 80), NetworkAnonymizationKey(),
5266       NetLogWithSource(),
5267       /* optional_parameters=*/absl::nullopt, resolve_context_.get(),
5268       resolve_context_->host_cache()));
5269   EXPECT_FALSE(response_secure.complete());
5270 
5271   // Simulate the case when the preference or policy has disabled the insecure
5272   // DNS client causing AbortInsecureDnsTasks.
5273   resolver_->SetInsecureDnsClientEnabled(
5274       /*enabled=*/false,
5275       /*additional_dns_types_enabled*/ false);
5276 
5277   EXPECT_THAT(response_secure.result_error(), IsOk());
5278   EXPECT_THAT(response_secure.request()->GetAddressResults()->endpoints(),
5279               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5280                                             CreateExpected("::1", 80)));
5281   EXPECT_THAT(
5282       response_secure.request()->GetEndpointResults(),
5283       testing::Pointee(testing::ElementsAre(
5284           ExpectEndpointResult(testing::UnorderedElementsAre(
5285               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5286 }
5287 
TEST_F(HostResolverManagerDnsTest,DnsTaskUnspec)5288 TEST_F(HostResolverManagerDnsTest, DnsTaskUnspec) {
5289   ChangeDnsConfig(CreateValidDnsConfig());
5290 
5291   proc_->AddRuleForAllFamilies("4nx", "192.168.1.101");
5292   // All other hostnames will fail in proc_.
5293 
5294   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
5295   responses.emplace_back(
5296       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5297           HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5298           absl::nullopt, resolve_context_.get(),
5299           resolve_context_->host_cache())));
5300   responses.emplace_back(
5301       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5302           HostPortPair("4ok", 80), NetworkAnonymizationKey(),
5303           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5304           resolve_context_->host_cache())));
5305   responses.emplace_back(
5306       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5307           HostPortPair("6ok", 80), NetworkAnonymizationKey(),
5308           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5309           resolve_context_->host_cache())));
5310   responses.emplace_back(
5311       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5312           HostPortPair("4nx", 80), NetworkAnonymizationKey(),
5313           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5314           resolve_context_->host_cache())));
5315 
5316   proc_->SignalMultiple(4u);
5317 
5318   for (auto& response : responses) {
5319     EXPECT_THAT(response->result_error(), IsOk());
5320   }
5321 
5322   EXPECT_THAT(responses[0]->request()->GetAddressResults()->endpoints(),
5323               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5324                                             CreateExpected("::1", 80)));
5325   EXPECT_THAT(
5326       responses[0]->request()->GetEndpointResults(),
5327       testing::Pointee(testing::ElementsAre(
5328           ExpectEndpointResult(testing::UnorderedElementsAre(
5329               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5330   EXPECT_THAT(responses[1]->request()->GetAddressResults()->endpoints(),
5331               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
5332   EXPECT_THAT(responses[1]->request()->GetEndpointResults(),
5333               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5334                   testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
5335   EXPECT_THAT(responses[2]->request()->GetAddressResults()->endpoints(),
5336               testing::ElementsAre(CreateExpected("::1", 80)));
5337   EXPECT_THAT(responses[2]->request()->GetEndpointResults(),
5338               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5339                   testing::ElementsAre(CreateExpected("::1", 80))))));
5340   EXPECT_THAT(responses[3]->request()->GetAddressResults()->endpoints(),
5341               testing::ElementsAre(CreateExpected("192.168.1.101", 80)));
5342   EXPECT_THAT(responses[3]->request()->GetEndpointResults(),
5343               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5344                   testing::ElementsAre(CreateExpected("192.168.1.101", 80))))));
5345 }
5346 
TEST_F(HostResolverManagerDnsTest,NameCollisionIcann)5347 TEST_F(HostResolverManagerDnsTest, NameCollisionIcann) {
5348   ChangeDnsConfig(CreateValidDnsConfig());
5349 
5350   // When the resolver returns an A record with 127.0.53.53 it should be
5351   // mapped to a special error.
5352   ResolveHostResponseHelper response_ipv4(resolver_->CreateRequest(
5353       HostPortPair("4collision", 80), NetworkAnonymizationKey(),
5354       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5355       resolve_context_->host_cache()));
5356   EXPECT_THAT(response_ipv4.result_error(), IsError(ERR_ICANN_NAME_COLLISION));
5357   EXPECT_FALSE(response_ipv4.request()->GetAddressResults());
5358   EXPECT_FALSE(response_ipv4.request()->GetEndpointResults());
5359 
5360   // When the resolver returns an AAAA record with ::127.0.53.53 it should
5361   // work just like any other IP. (Despite having the same suffix, it is not
5362   // considered special)
5363   ResolveHostResponseHelper response_ipv6(resolver_->CreateRequest(
5364       HostPortPair("6collision", 80), NetworkAnonymizationKey(),
5365       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5366       resolve_context_->host_cache()));
5367   EXPECT_THAT(response_ipv6.result_error(), IsOk());
5368   EXPECT_THAT(response_ipv6.request()->GetAddressResults()->endpoints(),
5369               testing::ElementsAre(CreateExpected("::127.0.53.53", 80)));
5370   EXPECT_THAT(response_ipv6.request()->GetEndpointResults(),
5371               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5372                   testing::ElementsAre(CreateExpected("::127.0.53.53", 80))))));
5373 }
5374 
TEST_F(HostResolverManagerDnsTest,ServeFromHosts)5375 TEST_F(HostResolverManagerDnsTest, ServeFromHosts) {
5376   // Initially, use empty HOSTS file.
5377   DnsConfig config = CreateValidDnsConfig();
5378   ChangeDnsConfig(config);
5379 
5380   proc_->AddRuleForAllFamilies(std::string(),
5381                                std::string());  // Default to failures.
5382   proc_->SignalMultiple(1u);  // For the first request which misses.
5383 
5384   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
5385       HostPortPair("nx_ipv4", 80), NetworkAnonymizationKey(),
5386       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5387       resolve_context_->host_cache()));
5388   EXPECT_THAT(initial_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5389 
5390   IPAddress local_ipv4 = IPAddress::IPv4Localhost();
5391   IPAddress local_ipv6 = IPAddress::IPv6Localhost();
5392 
5393   DnsHosts hosts;
5394   hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = local_ipv4;
5395   hosts[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6)] = local_ipv6;
5396   hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4)] = local_ipv4;
5397   hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6)] = local_ipv6;
5398 
5399   // Update HOSTS file.
5400   config.hosts = hosts;
5401   ChangeDnsConfig(config);
5402 
5403   ResolveHostResponseHelper response_ipv4(resolver_->CreateRequest(
5404       HostPortPair("nx_ipv4", 80), NetworkAnonymizationKey(),
5405       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5406       resolve_context_->host_cache()));
5407   EXPECT_THAT(response_ipv4.result_error(), IsOk());
5408   EXPECT_THAT(response_ipv4.request()->GetAddressResults()->endpoints(),
5409               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
5410   EXPECT_THAT(response_ipv4.request()->GetEndpointResults(),
5411               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5412                   testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
5413   EXPECT_THAT(response_ipv4.request()->GetDnsAliasResults(),
5414               testing::Pointee(testing::IsEmpty()));
5415 
5416   ResolveHostResponseHelper response_ipv6(resolver_->CreateRequest(
5417       HostPortPair("nx_ipv6", 80), NetworkAnonymizationKey(),
5418       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5419       resolve_context_->host_cache()));
5420   EXPECT_THAT(response_ipv6.result_error(), IsOk());
5421   EXPECT_THAT(response_ipv6.request()->GetAddressResults()->endpoints(),
5422               testing::ElementsAre(CreateExpected("::1", 80)));
5423   EXPECT_THAT(response_ipv6.request()->GetEndpointResults(),
5424               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5425                   testing::ElementsAre(CreateExpected("::1", 80))))));
5426   EXPECT_THAT(response_ipv6.request()->GetDnsAliasResults(),
5427               testing::Pointee(testing::IsEmpty()));
5428 
5429   ResolveHostResponseHelper response_both(resolver_->CreateRequest(
5430       HostPortPair("nx_both", 80), NetworkAnonymizationKey(),
5431       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5432       resolve_context_->host_cache()));
5433   EXPECT_THAT(response_both.result_error(), IsOk());
5434   EXPECT_THAT(response_both.request()->GetAddressResults()->endpoints(),
5435               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5436                                             CreateExpected("::1", 80)));
5437   EXPECT_THAT(
5438       response_both.request()->GetEndpointResults(),
5439       testing::Pointee(testing::ElementsAre(
5440           ExpectEndpointResult(testing::UnorderedElementsAre(
5441               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5442   EXPECT_THAT(response_both.request()->GetDnsAliasResults(),
5443               testing::Pointee(testing::IsEmpty()));
5444 
5445   // Requests with specified DNS query type.
5446   HostResolver::ResolveHostParameters parameters;
5447 
5448   parameters.dns_query_type = DnsQueryType::A;
5449   ResolveHostResponseHelper response_specified_ipv4(resolver_->CreateRequest(
5450       HostPortPair("nx_ipv4", 80), NetworkAnonymizationKey(),
5451       NetLogWithSource(), parameters, resolve_context_.get(),
5452       resolve_context_->host_cache()));
5453   EXPECT_THAT(response_specified_ipv4.result_error(), IsOk());
5454   EXPECT_THAT(
5455       response_specified_ipv4.request()->GetAddressResults()->endpoints(),
5456       testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
5457   EXPECT_THAT(response_specified_ipv4.request()->GetEndpointResults(),
5458               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5459                   testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
5460   EXPECT_THAT(response_specified_ipv4.request()->GetDnsAliasResults(),
5461               testing::Pointee(testing::IsEmpty()));
5462 
5463   parameters.dns_query_type = DnsQueryType::AAAA;
5464   ResolveHostResponseHelper response_specified_ipv6(resolver_->CreateRequest(
5465       HostPortPair("nx_ipv6", 80), NetworkAnonymizationKey(),
5466       NetLogWithSource(), parameters, resolve_context_.get(),
5467       resolve_context_->host_cache()));
5468   EXPECT_THAT(response_specified_ipv6.result_error(), IsOk());
5469   EXPECT_THAT(
5470       response_specified_ipv6.request()->GetAddressResults()->endpoints(),
5471       testing::ElementsAre(CreateExpected("::1", 80)));
5472   EXPECT_THAT(response_specified_ipv6.request()->GetEndpointResults(),
5473               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5474                   testing::ElementsAre(CreateExpected("::1", 80))))));
5475   EXPECT_THAT(response_specified_ipv6.request()->GetDnsAliasResults(),
5476               testing::Pointee(testing::IsEmpty()));
5477 }
5478 
TEST_F(HostResolverManagerDnsTest,SkipHostsWithUpcomingHostResolverSystemTask)5479 TEST_F(HostResolverManagerDnsTest,
5480        SkipHostsWithUpcomingHostResolverSystemTask) {
5481   // Disable the DnsClient.
5482   resolver_->SetInsecureDnsClientEnabled(
5483       /*enabled=*/false,
5484       /*additional_dns_types_enabled=*/false);
5485 
5486   proc_->AddRuleForAllFamilies(std::string(),
5487                                std::string());  // Default to failures.
5488   proc_->SignalMultiple(1u);  // For the first request which misses.
5489 
5490   DnsConfig config = CreateValidDnsConfig();
5491   DnsHosts hosts;
5492   hosts[DnsHostsKey("hosts", ADDRESS_FAMILY_IPV4)] = IPAddress::IPv4Localhost();
5493 
5494   // Update HOSTS file.
5495   config.hosts = hosts;
5496   ChangeDnsConfig(config);
5497 
5498   ResolveHostResponseHelper response(resolver_->CreateRequest(
5499       HostPortPair("hosts", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5500       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5501   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5502 }
5503 
5504 // Test that hosts ending in ".local" or ".local." are resolved using the system
5505 // resolver.
TEST_F(HostResolverManagerDnsTest,BypassDnsTask)5506 TEST_F(HostResolverManagerDnsTest, BypassDnsTask) {
5507   ChangeDnsConfig(CreateValidDnsConfig());
5508 
5509   proc_->AddRuleForAllFamilies(std::string(),
5510                                std::string());  // Default to failures.
5511 
5512   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
5513 
5514   responses.emplace_back(
5515       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5516           HostPortPair("ok.local", 80), NetworkAnonymizationKey(),
5517           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5518           resolve_context_->host_cache())));
5519   responses.emplace_back(
5520       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5521           HostPortPair("ok.local.", 80), NetworkAnonymizationKey(),
5522           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5523           resolve_context_->host_cache())));
5524   responses.emplace_back(
5525       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5526           HostPortPair("oklocal", 80), NetworkAnonymizationKey(),
5527           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5528           resolve_context_->host_cache())));
5529   responses.emplace_back(
5530       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5531           HostPortPair("oklocal.", 80), NetworkAnonymizationKey(),
5532           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5533           resolve_context_->host_cache())));
5534   responses.emplace_back(
5535       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5536           HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5537           absl::nullopt, resolve_context_.get(),
5538           resolve_context_->host_cache())));
5539 
5540   proc_->SignalMultiple(5u);
5541 
5542   for (size_t i = 0; i < 2; ++i)
5543     EXPECT_THAT(responses[i]->result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5544 
5545   for (size_t i = 2; i < responses.size(); ++i)
5546     EXPECT_THAT(responses[i]->result_error(), IsOk());
5547 }
5548 
5549 #if BUILDFLAG(ENABLE_MDNS)
5550 // Test that non-address queries for hosts ending in ".local" are resolved using
5551 // the MDNS resolver.
TEST_F(HostResolverManagerDnsTest,BypassDnsToMdnsWithNonAddress)5552 TEST_F(HostResolverManagerDnsTest, BypassDnsToMdnsWithNonAddress) {
5553   // Ensure DNS task and system requests will fail.
5554   MockDnsClientRuleList rules;
5555   rules.emplace_back(
5556       "myhello.local", dns_protocol::kTypeTXT, false /* secure */,
5557       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
5558       false /* delay */);
5559   CreateResolver();
5560   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
5561   proc_->AddRuleForAllFamilies(std::string(), std::string());
5562 
5563   auto socket_factory = std::make_unique<MockMDnsSocketFactory>();
5564   MockMDnsSocketFactory* socket_factory_ptr = socket_factory.get();
5565   resolver_->SetMdnsSocketFactoryForTesting(std::move(socket_factory));
5566   // 2 socket creations for every transaction.
5567   EXPECT_CALL(*socket_factory_ptr, OnSendTo(_)).Times(2);
5568 
5569   HostResolver::ResolveHostParameters dns_parameters;
5570   dns_parameters.dns_query_type = DnsQueryType::TXT;
5571 
5572   ResolveHostResponseHelper response(resolver_->CreateRequest(
5573       HostPortPair("myhello.local", 80), NetworkAnonymizationKey(),
5574       NetLogWithSource(), dns_parameters, resolve_context_.get(),
5575       resolve_context_->host_cache()));
5576 
5577   socket_factory_ptr->SimulateReceive(kMdnsResponseTxt,
5578                                       sizeof(kMdnsResponseTxt));
5579   proc_->SignalMultiple(1u);
5580 
5581   EXPECT_THAT(response.result_error(), IsOk());
5582   EXPECT_THAT(response.request()->GetTextResults(),
5583               testing::Optional(testing::ElementsAre("foo", "bar")));
5584 }
5585 #endif  // BUILDFLAG(ENABLE_MDNS)
5586 
5587 // Test that DNS task is always used when explicitly requested as the source,
5588 // even with a case that would normally bypass it eg hosts ending in ".local".
TEST_F(HostResolverManagerDnsTest,DnsNotBypassedWhenDnsSource)5589 TEST_F(HostResolverManagerDnsTest, DnsNotBypassedWhenDnsSource) {
5590   // Ensure DNS task requests will succeed and system requests will fail.
5591   ChangeDnsConfig(CreateValidDnsConfig());
5592   proc_->AddRuleForAllFamilies(std::string(), std::string());
5593 
5594   HostResolver::ResolveHostParameters dns_parameters;
5595   dns_parameters.source = HostResolverSource::DNS;
5596 
5597   ResolveHostResponseHelper dns_response(resolver_->CreateRequest(
5598       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5599       dns_parameters, resolve_context_.get(), resolve_context_->host_cache()));
5600   ResolveHostResponseHelper dns_local_response(resolver_->CreateRequest(
5601       HostPortPair("ok.local", 80), NetworkAnonymizationKey(),
5602       NetLogWithSource(), dns_parameters, resolve_context_.get(),
5603       resolve_context_->host_cache()));
5604   ResolveHostResponseHelper normal_local_response(resolver_->CreateRequest(
5605       HostPortPair("ok.local", 80), NetworkAnonymizationKey(),
5606       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5607       resolve_context_->host_cache()));
5608 
5609   proc_->SignalMultiple(3u);
5610 
5611   EXPECT_THAT(dns_response.result_error(), IsOk());
5612   EXPECT_THAT(dns_local_response.result_error(), IsOk());
5613   EXPECT_THAT(normal_local_response.result_error(),
5614               IsError(ERR_NAME_NOT_RESOLVED));
5615 }
5616 
TEST_F(HostResolverManagerDnsTest,SystemOnlyBypassesDnsTask)5617 TEST_F(HostResolverManagerDnsTest, SystemOnlyBypassesDnsTask) {
5618   // Ensure DNS task requests will succeed and system requests will fail.
5619   ChangeDnsConfig(CreateValidDnsConfig());
5620   proc_->AddRuleForAllFamilies(std::string(), std::string());
5621 
5622   ResolveHostResponseHelper dns_response(resolver_->CreateRequest(
5623       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5624       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5625 
5626   HostResolver::ResolveHostParameters parameters;
5627   parameters.source = HostResolverSource::SYSTEM;
5628   ResolveHostResponseHelper system_response(resolver_->CreateRequest(
5629       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5630       parameters, resolve_context_.get(), resolve_context_->host_cache()));
5631 
5632   proc_->SignalMultiple(2u);
5633 
5634   EXPECT_THAT(dns_response.result_error(), IsOk());
5635   EXPECT_THAT(system_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5636 }
5637 
TEST_F(HostResolverManagerDnsTest,DisableInsecureDnsClientOnPersistentFailure)5638 TEST_F(HostResolverManagerDnsTest,
5639        DisableInsecureDnsClientOnPersistentFailure) {
5640   ChangeDnsConfig(CreateValidDnsConfig());
5641 
5642   // Check that DnsTask works.
5643   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
5644       HostPortPair("ok_1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5645       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5646   EXPECT_THAT(initial_response.result_error(), IsOk());
5647 
5648   TriggerInsecureFailureCondition();
5649 
5650   // Insecure DnsTasks should be disabled by now unless explicitly requested via
5651   // |source|.
5652   ResolveHostResponseHelper fail_response(resolver_->CreateRequest(
5653       HostPortPair("ok_2", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5654       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5655   HostResolver::ResolveHostParameters parameters;
5656   parameters.source = HostResolverSource::DNS;
5657   ResolveHostResponseHelper dns_response(resolver_->CreateRequest(
5658       HostPortPair("ok_2", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5659       parameters, resolve_context_.get(), resolve_context_->host_cache()));
5660   proc_->SignalMultiple(2u);
5661   EXPECT_THAT(fail_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
5662   EXPECT_THAT(dns_response.result_error(), IsOk());
5663 
5664   // Check that it is re-enabled after DNS change.
5665   ChangeDnsConfig(CreateValidDnsConfig());
5666   ResolveHostResponseHelper reenabled_response(resolver_->CreateRequest(
5667       HostPortPair("ok_3", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5668       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5669   EXPECT_THAT(reenabled_response.result_error(), IsOk());
5670 }
5671 
TEST_F(HostResolverManagerDnsTest,SecureDnsWorksAfterInsecureFailure)5672 TEST_F(HostResolverManagerDnsTest, SecureDnsWorksAfterInsecureFailure) {
5673   DnsConfig config = CreateValidDnsConfig();
5674   config.secure_dns_mode = SecureDnsMode::kSecure;
5675   ChangeDnsConfig(config);
5676 
5677   TriggerInsecureFailureCondition();
5678 
5679   // Secure DnsTasks should not be affected.
5680   ResolveHostResponseHelper secure_response(resolver_->CreateRequest(
5681       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5682       /* optional_parameters=*/absl::nullopt, resolve_context_.get(),
5683       resolve_context_->host_cache()));
5684   EXPECT_THAT(secure_response.result_error(), IsOk());
5685 }
5686 
TEST_F(HostResolverManagerDnsTest,DontDisableDnsClientOnSporadicFailure)5687 TEST_F(HostResolverManagerDnsTest, DontDisableDnsClientOnSporadicFailure) {
5688   ChangeDnsConfig(CreateValidDnsConfig());
5689 
5690   // |proc_| defaults to successes.
5691 
5692   // 20 failures interleaved with 20 successes.
5693   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
5694   for (unsigned i = 0; i < 40; ++i) {
5695     // Use custom names to require separate Jobs.
5696     std::string hostname = (i % 2) == 0 ? base::StringPrintf("nx_%u", i)
5697                                         : base::StringPrintf("ok_%u", i);
5698     responses.emplace_back(
5699         std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
5700             HostPortPair(hostname, 80), NetworkAnonymizationKey(),
5701             NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5702             resolve_context_->host_cache())));
5703   }
5704 
5705   proc_->SignalMultiple(40u);
5706 
5707   for (const auto& response : responses)
5708     EXPECT_THAT(response->result_error(), IsOk());
5709 
5710   // Make |proc_| default to failures.
5711   proc_->AddRuleForAllFamilies(std::string(), std::string());
5712 
5713   // DnsTask should still be enabled.
5714   ResolveHostResponseHelper final_response(resolver_->CreateRequest(
5715       HostPortPair("ok_last", 80), NetworkAnonymizationKey(),
5716       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5717       resolve_context_->host_cache()));
5718   EXPECT_THAT(final_response.result_error(), IsOk());
5719 }
5720 
Ipv6UnreachableTest(bool is_async)5721 void HostResolverManagerDnsTest::Ipv6UnreachableTest(bool is_async) {
5722   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
5723                                     false /* ipv6_reachable */,
5724                                     true /* check_ipv6_on_wifi */, is_async);
5725   ChangeDnsConfig(CreateValidDnsConfig());
5726 
5727   ResolveHostResponseHelper response(resolver_->CreateRequest(
5728       HostPortPair("ok", 500), NetworkAnonymizationKey(), NetLogWithSource(),
5729       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5730   EXPECT_THAT(response.result_error(), IsOk());
5731 
5732   // Only expect IPv4 results.
5733   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
5734               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 500)));
5735   EXPECT_THAT(response.request()->GetEndpointResults(),
5736               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5737                   testing::ElementsAre(CreateExpected("127.0.0.1", 500))))));
5738 }
5739 
TEST_F(HostResolverManagerDnsTest,Ipv6UnreachableAsync)5740 TEST_F(HostResolverManagerDnsTest, Ipv6UnreachableAsync) {
5741   Ipv6UnreachableTest(true);
5742 }
5743 
TEST_F(HostResolverManagerDnsTest,Ipv6UnreachableSync)5744 TEST_F(HostResolverManagerDnsTest, Ipv6UnreachableSync) {
5745   Ipv6UnreachableTest(false);
5746 }
5747 
Ipv6UnreachableInvalidConfigTest(bool is_async)5748 void HostResolverManagerDnsTest::Ipv6UnreachableInvalidConfigTest(
5749     bool is_async) {
5750   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
5751                                     false /* ipv6_reachable */,
5752                                     true /* check_ipv6_on_wifi */, is_async);
5753 
5754   proc_->AddRule("example.com", ADDRESS_FAMILY_UNSPECIFIED, "1.2.3.4,::5");
5755   proc_->SignalMultiple(1u);
5756 
5757   ResolveHostResponseHelper response(resolver_->CreateRequest(
5758       HostPortPair("example.com", 500), NetworkAnonymizationKey(),
5759       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5760       resolve_context_->host_cache()));
5761   EXPECT_THAT(response.result_error(), IsOk());
5762   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
5763               testing::UnorderedElementsAre(CreateExpected("1.2.3.4", 500),
5764                                             CreateExpected("::5", 500)));
5765   EXPECT_THAT(
5766       response.request()->GetEndpointResults(),
5767       testing::Pointee(testing::ElementsAre(
5768           ExpectEndpointResult(testing::UnorderedElementsAre(
5769               CreateExpected("::5", 500), CreateExpected("1.2.3.4", 500))))));
5770 }
5771 // Without a valid DnsConfig, assume IPv6 is needed and ignore prober.
TEST_F(HostResolverManagerDnsTest,Ipv6Unreachable_InvalidConfigAsync)5772 TEST_F(HostResolverManagerDnsTest, Ipv6Unreachable_InvalidConfigAsync) {
5773   Ipv6UnreachableInvalidConfigTest(true);
5774 }
5775 
TEST_F(HostResolverManagerDnsTest,Ipv6Unreachable_InvalidConfigSync)5776 TEST_F(HostResolverManagerDnsTest, Ipv6Unreachable_InvalidConfigSync) {
5777   Ipv6UnreachableInvalidConfigTest(false);
5778 }
5779 
TEST_F(HostResolverManagerDnsTest,Ipv6Unreachable_UseLocalIpv6)5780 TEST_F(HostResolverManagerDnsTest, Ipv6Unreachable_UseLocalIpv6) {
5781   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
5782                                     false /* ipv6_reachable */,
5783                                     true /* check_ipv6_on_wifi */);
5784 
5785   DnsConfig config = CreateValidDnsConfig();
5786   config.use_local_ipv6 = true;
5787   ChangeDnsConfig(config);
5788 
5789   ResolveHostResponseHelper response1(resolver_->CreateRequest(
5790       HostPortPair("ok", 500), NetworkAnonymizationKey(), NetLogWithSource(),
5791       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5792   EXPECT_THAT(response1.result_error(), IsOk());
5793   EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
5794               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 500),
5795                                             CreateExpected("::1", 500)));
5796   EXPECT_THAT(
5797       response1.request()->GetEndpointResults(),
5798       testing::Pointee(testing::ElementsAre(
5799           ExpectEndpointResult(testing::UnorderedElementsAre(
5800               CreateExpected("::1", 500), CreateExpected("127.0.0.1", 500))))));
5801 
5802   // Set |use_local_ipv6| to false. Expect only IPv4 results.
5803   config.use_local_ipv6 = false;
5804   ChangeDnsConfig(config);
5805 
5806   ResolveHostResponseHelper response2(resolver_->CreateRequest(
5807       HostPortPair("ok", 500), NetworkAnonymizationKey(), NetLogWithSource(),
5808       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5809   EXPECT_THAT(response2.result_error(), IsOk());
5810   EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
5811               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 500)));
5812   EXPECT_THAT(response2.request()->GetEndpointResults(),
5813               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5814                   testing::ElementsAre(CreateExpected("127.0.0.1", 500))))));
5815 }
5816 
5817 // Confirm that resolving "localhost" is unrestricted even if there are no
5818 // global IPv6 address. See SystemHostResolverCall for rationale.
5819 // Test both the DnsClient and system host resolver paths.
TEST_F(HostResolverManagerDnsTest,Ipv6Unreachable_Localhost)5820 TEST_F(HostResolverManagerDnsTest, Ipv6Unreachable_Localhost) {
5821   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
5822                                     false /* ipv6_reachable */,
5823                                     true /* check_ipv6_on_wifi */);
5824 
5825   // Make request fail if we actually get to the system resolver.
5826   proc_->AddRuleForAllFamilies(std::string(), std::string());
5827 
5828   // Try without DnsClient.
5829   resolver_->SetInsecureDnsClientEnabled(
5830       /*enabled=*/false,
5831       /*additional_dns_types_enabled=*/false);
5832   ResolveHostResponseHelper system_response(resolver_->CreateRequest(
5833       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
5834       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5835       resolve_context_->host_cache()));
5836   EXPECT_THAT(system_response.result_error(), IsOk());
5837   EXPECT_THAT(system_response.request()->GetAddressResults()->endpoints(),
5838               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5839                                             CreateExpected("::1", 80)));
5840   EXPECT_THAT(
5841       system_response.request()->GetEndpointResults(),
5842       testing::Pointee(testing::ElementsAre(
5843           ExpectEndpointResult(testing::UnorderedElementsAre(
5844               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5845 
5846   // With DnsClient
5847   UseMockDnsClient(CreateValidDnsConfig(), CreateDefaultDnsRules());
5848   ResolveHostResponseHelper builtin_response(resolver_->CreateRequest(
5849       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
5850       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5851       resolve_context_->host_cache()));
5852   EXPECT_THAT(builtin_response.result_error(), IsOk());
5853   EXPECT_THAT(builtin_response.request()->GetAddressResults()->endpoints(),
5854               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5855                                             CreateExpected("::1", 80)));
5856   EXPECT_THAT(
5857       builtin_response.request()->GetEndpointResults(),
5858       testing::Pointee(testing::ElementsAre(
5859           ExpectEndpointResult(testing::UnorderedElementsAre(
5860               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5861 
5862   // DnsClient configured without ipv6 (but ipv6 should still work for
5863   // localhost).
5864   DnsConfig config = CreateValidDnsConfig();
5865   config.use_local_ipv6 = false;
5866   ChangeDnsConfig(config);
5867   ResolveHostResponseHelper ipv6_disabled_response(resolver_->CreateRequest(
5868       HostPortPair("localhost", 80), NetworkAnonymizationKey(),
5869       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
5870       resolve_context_->host_cache()));
5871   EXPECT_THAT(ipv6_disabled_response.result_error(), IsOk());
5872   EXPECT_THAT(
5873       ipv6_disabled_response.request()->GetAddressResults()->endpoints(),
5874       testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
5875                                     CreateExpected("::1", 80)));
5876   EXPECT_THAT(
5877       ipv6_disabled_response.request()->GetEndpointResults(),
5878       testing::Pointee(testing::ElementsAre(
5879           ExpectEndpointResult(testing::UnorderedElementsAre(
5880               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
5881 }
5882 
5883 // Test that IPv6 being unreachable only causes the AAAA query to be disabled,
5884 // rather than querying only for A. See https://crbug.com/1272055.
TEST_F(HostResolverManagerDnsTest,Ipv6UnreachableOnlyDisablesAAAAQuery)5885 TEST_F(HostResolverManagerDnsTest, Ipv6UnreachableOnlyDisablesAAAAQuery) {
5886   const std::string kName = "https.test";
5887 
5888   base::test::ScopedFeatureList features;
5889   features.InitAndEnableFeatureWithParameters(
5890       features::kUseDnsHttpsSvcb,
5891       {// Disable timeouts.
5892        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
5893        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
5894        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
5895        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
5896        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
5897        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
5898 
5899   MockDnsClientRuleList rules;
5900   std::vector<DnsResourceRecord> records = {
5901       BuildTestHttpsAliasRecord(kName, "alias.test")};
5902   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
5903                      MockDnsClientRule::Result(BuildTestDnsResponse(
5904                          kName, dns_protocol::kTypeHttps, records)),
5905                      /*delay=*/false);
5906   rules.emplace_back(
5907       kName, dns_protocol::kTypeA, /*secure=*/false,
5908       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
5909       /*delay=*/false);
5910   rules.emplace_back(
5911       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
5912       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kUnexpected),
5913       /*delay=*/false);
5914 
5915   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
5916                                     /*ipv6_reachable=*/false,
5917                                     /*check_ipv6_on_wifi=*/true);
5918   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
5919 
5920   ResolveHostResponseHelper response(resolver_->CreateRequest(
5921       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
5922       NetworkAnonymizationKey(), NetLogWithSource(),
5923       /*optional_parameters=*/absl::nullopt, resolve_context_.get(),
5924       resolve_context_->host_cache()));
5925   EXPECT_THAT(response.result_error(), IsOk());
5926   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
5927               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 443)));
5928   EXPECT_THAT(
5929       response.request()->GetEndpointResults(),
5930       testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
5931           testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 443))))));
5932   EXPECT_FALSE(response.request()->GetHostnameResults());
5933   EXPECT_FALSE(response.request()->GetTextResults());
5934   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
5935               testing::Pointee(testing::ElementsAre(true)));
5936 }
5937 
TEST_F(HostResolverManagerDnsTest,SeparateJobsBySecureDnsMode)5938 TEST_F(HostResolverManagerDnsTest, SeparateJobsBySecureDnsMode) {
5939   MockDnsClientRuleList rules;
5940   rules.emplace_back(
5941       "a", dns_protocol::kTypeA, true /* secure */,
5942       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
5943       false /* delay */);
5944   rules.emplace_back(
5945       "a", dns_protocol::kTypeAAAA, true /* secure */,
5946       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
5947       false /* delay */);
5948   rules.emplace_back(
5949       "a", dns_protocol::kTypeA, false /* secure */,
5950       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
5951       true /* delay */);
5952   rules.emplace_back(
5953       "a", dns_protocol::kTypeAAAA, false /* secure */,
5954       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
5955       true /* delay */);
5956   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
5957   DnsConfigOverrides overrides;
5958   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
5959   resolver_->SetDnsConfigOverrides(overrides);
5960 
5961   // Create three requests. One with a DISABLE policy parameter, one with no
5962   // resolution parameters at all, and one with an ALLOW policy parameter
5963   // (which is a no-op).
5964   HostResolver::ResolveHostParameters parameters_disable_secure;
5965   parameters_disable_secure.secure_dns_policy = SecureDnsPolicy::kDisable;
5966   ResolveHostResponseHelper insecure_response(resolver_->CreateRequest(
5967       HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5968       parameters_disable_secure, resolve_context_.get(),
5969       resolve_context_->host_cache()));
5970   EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
5971 
5972   ResolveHostResponseHelper automatic_response0(resolver_->CreateRequest(
5973       HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5974       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
5975   EXPECT_EQ(2u, resolver_->num_jobs_for_testing());
5976 
5977   HostResolver::ResolveHostParameters parameters_allow_secure;
5978   parameters_allow_secure.secure_dns_policy = SecureDnsPolicy::kAllow;
5979   ResolveHostResponseHelper automatic_response1(resolver_->CreateRequest(
5980       HostPortPair("a", 80), NetworkAnonymizationKey(), NetLogWithSource(),
5981       parameters_allow_secure, resolve_context_.get(),
5982       resolve_context_->host_cache()));
5983   // The AUTOMATIC mode requests should be joined into the same job.
5984   EXPECT_EQ(2u, resolver_->num_jobs_for_testing());
5985 
5986   // Automatic mode requests have completed.  Insecure request is still blocked.
5987   base::RunLoop().RunUntilIdle();
5988   EXPECT_FALSE(insecure_response.complete());
5989   EXPECT_TRUE(automatic_response0.complete());
5990   EXPECT_TRUE(automatic_response1.complete());
5991   EXPECT_THAT(automatic_response0.result_error(), IsOk());
5992   EXPECT_THAT(automatic_response1.result_error(), IsOk());
5993 
5994   // Complete insecure transaction.
5995   dns_client_->CompleteDelayedTransactions();
5996   EXPECT_TRUE(insecure_response.complete());
5997   EXPECT_THAT(insecure_response.result_error(), IsOk());
5998 }
5999 
6000 // Cancel a request with a single DNS transaction active.
TEST_F(HostResolverManagerDnsTest,CancelWithOneTransactionActive)6001 TEST_F(HostResolverManagerDnsTest, CancelWithOneTransactionActive) {
6002   // Disable ipv6 to ensure we'll only try a single transaction for the host.
6003   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
6004                                     false /* ipv6_reachable */,
6005                                     true /* check_ipv6_on_wifi */);
6006   DnsConfig config = CreateValidDnsConfig();
6007   config.use_local_ipv6 = false;
6008   ChangeDnsConfig(config);
6009 
6010   ResolveHostResponseHelper response(resolver_->CreateRequest(
6011       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6012       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6013   ASSERT_FALSE(response.complete());
6014   ASSERT_EQ(1u, num_running_dispatcher_jobs());
6015 
6016   response.CancelRequest();
6017   base::RunLoop().RunUntilIdle();
6018   EXPECT_FALSE(response.complete());
6019 
6020   // Dispatcher state checked in TearDown.
6021 }
6022 
6023 // Cancel a request with a single DNS transaction active and another pending.
TEST_F(HostResolverManagerDnsTest,CancelWithOneTransactionActiveOnePending)6024 TEST_F(HostResolverManagerDnsTest, CancelWithOneTransactionActiveOnePending) {
6025   CreateSerialResolver();
6026   ChangeDnsConfig(CreateValidDnsConfig());
6027 
6028   ResolveHostResponseHelper response(resolver_->CreateRequest(
6029       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6030       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6031   EXPECT_EQ(1u, num_running_dispatcher_jobs());
6032 
6033   response.CancelRequest();
6034   base::RunLoop().RunUntilIdle();
6035   EXPECT_FALSE(response.complete());
6036 
6037   // Dispatcher state checked in TearDown.
6038 }
6039 
6040 // Cancel a request with two DNS transactions active.
TEST_F(HostResolverManagerDnsTest,CancelWithTwoTransactionsActive)6041 TEST_F(HostResolverManagerDnsTest, CancelWithTwoTransactionsActive) {
6042   ChangeDnsConfig(CreateValidDnsConfig());
6043 
6044   ResolveHostResponseHelper response(resolver_->CreateRequest(
6045       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6046       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6047   EXPECT_EQ(2u, num_running_dispatcher_jobs());
6048 
6049   response.CancelRequest();
6050   base::RunLoop().RunUntilIdle();
6051   EXPECT_FALSE(response.complete());
6052 
6053   // Dispatcher state checked in TearDown.
6054 }
6055 
6056 // Delete a resolver with some active requests and some queued requests.
TEST_F(HostResolverManagerDnsTest,DeleteWithActiveTransactions)6057 TEST_F(HostResolverManagerDnsTest, DeleteWithActiveTransactions) {
6058   // At most 10 Jobs active at once.
6059   CreateResolverWithLimitsAndParams(10u, DefaultParams(proc_),
6060                                     true /* ipv6_reachable */,
6061                                     true /* check_ipv6_on_wifi */);
6062 
6063   ChangeDnsConfig(CreateValidDnsConfig());
6064 
6065   // Add 12 DNS lookups (creating well more than 10 transaction).
6066   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
6067   for (int i = 0; i < 12; ++i) {
6068     std::string hostname = base::StringPrintf("ok%i", i);
6069     responses.emplace_back(
6070         std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
6071             HostPortPair(hostname, 80), NetworkAnonymizationKey(),
6072             NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6073             resolve_context_->host_cache())));
6074   }
6075   EXPECT_EQ(10u, num_running_dispatcher_jobs());
6076 
6077   DestroyResolver();
6078 
6079   base::RunLoop().RunUntilIdle();
6080   for (auto& response : responses) {
6081     EXPECT_FALSE(response->complete());
6082   }
6083 }
6084 
TEST_F(HostResolverManagerDnsTest,DeleteWithSecureTransactions)6085 TEST_F(HostResolverManagerDnsTest, DeleteWithSecureTransactions) {
6086   ChangeDnsConfig(CreateValidDnsConfig());
6087   DnsConfigOverrides overrides;
6088   overrides.secure_dns_mode = SecureDnsMode::kSecure;
6089   resolver_->SetDnsConfigOverrides(overrides);
6090 
6091   ResolveHostResponseHelper response(resolver_->CreateRequest(
6092       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6093       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6094 
6095   DestroyResolver();
6096 
6097   base::RunLoop().RunUntilIdle();
6098   EXPECT_FALSE(response.complete());
6099 }
6100 
TEST_F(HostResolverManagerDnsTest,DeleteWithCompletedRequests)6101 TEST_F(HostResolverManagerDnsTest, DeleteWithCompletedRequests) {
6102   ChangeDnsConfig(CreateValidDnsConfig());
6103 
6104   ResolveHostResponseHelper response(resolver_->CreateRequest(
6105       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6106       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6107 
6108   EXPECT_THAT(response.result_error(), IsOk());
6109   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
6110               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6111                                             CreateExpected("::1", 80)));
6112   EXPECT_THAT(
6113       response.request()->GetEndpointResults(),
6114       testing::Pointee(testing::ElementsAre(
6115           ExpectEndpointResult(testing::UnorderedElementsAre(
6116               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6117 
6118   DestroyResolver();
6119 
6120   // Completed requests should be unaffected by manager destruction.
6121   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
6122               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6123                                             CreateExpected("::1", 80)));
6124   EXPECT_THAT(
6125       response.request()->GetEndpointResults(),
6126       testing::Pointee(testing::ElementsAre(
6127           ExpectEndpointResult(testing::UnorderedElementsAre(
6128               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6129 }
6130 
6131 // Cancel a request with only the IPv6 transaction active.
TEST_F(HostResolverManagerDnsTest,CancelWithIPv6TransactionActive)6132 TEST_F(HostResolverManagerDnsTest, CancelWithIPv6TransactionActive) {
6133   ChangeDnsConfig(CreateValidDnsConfig());
6134 
6135   ResolveHostResponseHelper response(resolver_->CreateRequest(
6136       HostPortPair("6slow_ok", 80), NetworkAnonymizationKey(),
6137       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6138       resolve_context_->host_cache()));
6139   EXPECT_EQ(2u, num_running_dispatcher_jobs());
6140 
6141   // The IPv4 request should complete, the IPv6 request is still pending.
6142   base::RunLoop().RunUntilIdle();
6143   EXPECT_EQ(1u, num_running_dispatcher_jobs());
6144 
6145   response.CancelRequest();
6146   base::RunLoop().RunUntilIdle();
6147   EXPECT_FALSE(response.complete());
6148 
6149   // Dispatcher state checked in TearDown.
6150 }
6151 
6152 // Cancel a request with only the IPv4 transaction pending.
TEST_F(HostResolverManagerDnsTest,CancelWithIPv4TransactionPending)6153 TEST_F(HostResolverManagerDnsTest, CancelWithIPv4TransactionPending) {
6154   set_allow_fallback_to_systemtask(false);
6155   ChangeDnsConfig(CreateValidDnsConfig());
6156 
6157   ResolveHostResponseHelper response(resolver_->CreateRequest(
6158       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
6159       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6160       resolve_context_->host_cache()));
6161   EXPECT_EQ(2u, num_running_dispatcher_jobs());
6162 
6163   // The IPv6 request should complete, the IPv4 request is still pending.
6164   base::RunLoop().RunUntilIdle();
6165   EXPECT_EQ(1u, num_running_dispatcher_jobs());
6166 
6167   response.CancelRequest();
6168   base::RunLoop().RunUntilIdle();
6169   EXPECT_FALSE(response.complete());
6170 }
6171 
TEST_F(HostResolverManagerDnsTest,CancelWithAutomaticModeTransactionPending)6172 TEST_F(HostResolverManagerDnsTest, CancelWithAutomaticModeTransactionPending) {
6173   MockDnsClientRuleList rules;
6174   rules.emplace_back(
6175       "secure_6slow_6nx_insecure_6slow_ok", dns_protocol::kTypeA,
6176       true /* secure */,
6177       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
6178       false /* delay */);
6179   rules.emplace_back(
6180       "secure_6slow_6nx_insecure_6slow_ok", dns_protocol::kTypeAAAA,
6181       true /* secure */,
6182       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
6183       true /* delay */);
6184   rules.emplace_back(
6185       "secure_6slow_6nx_insecure_6slow_ok", dns_protocol::kTypeA,
6186       false /* secure */,
6187       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
6188       false /* delay */);
6189   rules.emplace_back(
6190       "secure_6slow_6nx_insecure_6slow_ok", dns_protocol::kTypeAAAA,
6191       false /* secure */,
6192       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
6193       true /* delay */);
6194   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
6195 
6196   DnsConfigOverrides overrides;
6197   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6198   resolver_->SetDnsConfigOverrides(overrides);
6199 
6200   ResolveHostResponseHelper response0(resolver_->CreateRequest(
6201       HostPortPair("secure_6slow_6nx_insecure_6slow_ok", 80),
6202       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
6203       resolve_context_.get(), resolve_context_->host_cache()));
6204   EXPECT_EQ(0u, num_running_dispatcher_jobs());
6205 
6206   // The secure IPv4 request should complete, the secure IPv6 request is still
6207   // pending.
6208   base::RunLoop().RunUntilIdle();
6209   EXPECT_EQ(0u, num_running_dispatcher_jobs());
6210 
6211   response0.CancelRequest();
6212   base::RunLoop().RunUntilIdle();
6213   EXPECT_FALSE(response0.complete());
6214   EXPECT_EQ(0u, num_running_dispatcher_jobs());
6215 
6216   ResolveHostResponseHelper response1(resolver_->CreateRequest(
6217       HostPortPair("secure_6slow_6nx_insecure_6slow_ok", 80),
6218       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
6219       resolve_context_.get(), resolve_context_->host_cache()));
6220   EXPECT_EQ(0u, num_running_dispatcher_jobs());
6221 
6222   // The secure IPv4 request should complete, the secure IPv6 request is still
6223   // pending.
6224   base::RunLoop().RunUntilIdle();
6225   EXPECT_EQ(0u, num_running_dispatcher_jobs());
6226 
6227   // Let the secure IPv6 request complete and start the insecure requests.
6228   dns_client_->CompleteDelayedTransactions();
6229   EXPECT_EQ(2u, num_running_dispatcher_jobs());
6230 
6231   // The insecure IPv4 request should complete, the insecure IPv6 request is
6232   // still pending.
6233   base::RunLoop().RunUntilIdle();
6234   EXPECT_EQ(1u, num_running_dispatcher_jobs());
6235 
6236   response1.CancelRequest();
6237   base::RunLoop().RunUntilIdle();
6238   EXPECT_FALSE(response1.complete());
6239 
6240   // Dispatcher state checked in TearDown.
6241 }
6242 
6243 // Test cases where AAAA completes first.
TEST_F(HostResolverManagerDnsTest,AAAACompletesFirst)6244 TEST_F(HostResolverManagerDnsTest, AAAACompletesFirst) {
6245   set_allow_fallback_to_systemtask(false);
6246   ChangeDnsConfig(CreateValidDnsConfig());
6247 
6248   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
6249   responses.emplace_back(
6250       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
6251           HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
6252           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6253           resolve_context_->host_cache())));
6254   responses.emplace_back(
6255       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
6256           HostPortPair("4slow_4ok", 80), NetworkAnonymizationKey(),
6257           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6258           resolve_context_->host_cache())));
6259   responses.emplace_back(
6260       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
6261           HostPortPair("4slow_4timeout", 80), NetworkAnonymizationKey(),
6262           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6263           resolve_context_->host_cache())));
6264   responses.emplace_back(
6265       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
6266           HostPortPair("4slow_6timeout", 80), NetworkAnonymizationKey(),
6267           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6268           resolve_context_->host_cache())));
6269 
6270   base::RunLoop().RunUntilIdle();
6271   EXPECT_FALSE(responses[0]->complete());
6272   EXPECT_FALSE(responses[1]->complete());
6273   EXPECT_FALSE(responses[2]->complete());
6274   // The IPv6 of request 3 should have failed and resulted in cancelling the
6275   // IPv4 request.
6276   EXPECT_THAT(responses[3]->result_error(), IsError(ERR_DNS_TIMED_OUT));
6277   EXPECT_EQ(3u, num_running_dispatcher_jobs());
6278 
6279   dns_client_->CompleteDelayedTransactions();
6280   EXPECT_THAT(responses[0]->result_error(), IsOk());
6281   EXPECT_THAT(responses[0]->request()->GetAddressResults()->endpoints(),
6282               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6283                                             CreateExpected("::1", 80)));
6284   EXPECT_THAT(
6285       responses[0]->request()->GetEndpointResults(),
6286       testing::Pointee(testing::ElementsAre(
6287           ExpectEndpointResult(testing::UnorderedElementsAre(
6288               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6289 
6290   EXPECT_THAT(responses[1]->result_error(), IsOk());
6291   EXPECT_THAT(responses[1]->request()->GetAddressResults()->endpoints(),
6292               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
6293   EXPECT_THAT(responses[1]->request()->GetEndpointResults(),
6294               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6295                   testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
6296 
6297   EXPECT_THAT(responses[2]->result_error(), IsError(ERR_DNS_TIMED_OUT));
6298 }
6299 
TEST_F(HostResolverManagerDnsTest,AAAACompletesFirst_AutomaticMode)6300 TEST_F(HostResolverManagerDnsTest, AAAACompletesFirst_AutomaticMode) {
6301   MockDnsClientRuleList rules;
6302   rules.emplace_back(
6303       "secure_slow_nx_insecure_4slow_ok", dns_protocol::kTypeA,
6304       true /* secure */,
6305       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
6306       true /* delay */);
6307   rules.emplace_back(
6308       "secure_slow_nx_insecure_4slow_ok", dns_protocol::kTypeAAAA,
6309       true /* secure */,
6310       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
6311       true /* delay */);
6312   rules.emplace_back(
6313       "secure_slow_nx_insecure_4slow_ok", dns_protocol::kTypeA,
6314       false /* secure */,
6315       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
6316       true /* delay */);
6317   rules.emplace_back(
6318       "secure_slow_nx_insecure_4slow_ok", dns_protocol::kTypeAAAA,
6319       false /* secure */,
6320       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
6321       false /* delay */);
6322   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
6323   DnsConfigOverrides overrides;
6324   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6325   resolver_->SetDnsConfigOverrides(overrides);
6326 
6327   ResolveHostResponseHelper response(resolver_->CreateRequest(
6328       HostPortPair("secure_slow_nx_insecure_4slow_ok", 80),
6329       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
6330       resolve_context_.get(), resolve_context_->host_cache()));
6331   base::RunLoop().RunUntilIdle();
6332   EXPECT_FALSE(response.complete());
6333   // Complete the secure transactions.
6334   dns_client_->CompleteDelayedTransactions();
6335   base::RunLoop().RunUntilIdle();
6336   EXPECT_FALSE(response.complete());
6337   // Complete the insecure transactions.
6338   dns_client_->CompleteDelayedTransactions();
6339   ASSERT_THAT(response.result_error(), IsOk());
6340   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
6341               testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
6342   EXPECT_THAT(response.request()->GetEndpointResults(),
6343               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6344                   testing::ElementsAre(CreateExpected("127.0.0.1", 80))))));
6345   HostCache::Key insecure_key =
6346       HostCache::Key("secure_slow_nx_insecure_4slow_ok",
6347                      DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6348                      HostResolverSource::ANY, NetworkAnonymizationKey());
6349   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
6350       GetCacheHit(insecure_key);
6351   EXPECT_TRUE(!!cache_result);
6352 }
6353 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic)6354 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic) {
6355   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.100");
6356   set_allow_fallback_to_systemtask(true);
6357 
6358   ChangeDnsConfig(CreateValidDnsConfig());
6359   DnsConfigOverrides overrides;
6360   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6361   resolver_->SetDnsConfigOverrides(overrides);
6362   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
6363 
6364   // A successful DoH request should result in a secure cache entry.
6365   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
6366       HostPortPair("automatic", 80), NetworkAnonymizationKey(),
6367       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6368       resolve_context_->host_cache()));
6369   ASSERT_THAT(response_secure.result_error(), IsOk());
6370   EXPECT_FALSE(
6371       response_secure.request()->GetResolveErrorInfo().is_secure_network_error);
6372   EXPECT_THAT(response_secure.request()->GetAddressResults()->endpoints(),
6373               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6374                                             CreateExpected("::1", 80)));
6375   EXPECT_THAT(
6376       response_secure.request()->GetEndpointResults(),
6377       testing::Pointee(testing::ElementsAre(
6378           ExpectEndpointResult(testing::UnorderedElementsAre(
6379               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6380   HostCache::Key secure_key = HostCache::Key(
6381       "automatic", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6382       HostResolverSource::ANY, NetworkAnonymizationKey());
6383   secure_key.secure = true;
6384   cache_result = GetCacheHit(secure_key);
6385   EXPECT_TRUE(!!cache_result);
6386 
6387   // A successful plaintext DNS request should result in an insecure cache
6388   // entry.
6389   ResolveHostResponseHelper response_insecure(resolver_->CreateRequest(
6390       HostPortPair("insecure_automatic", 80), NetworkAnonymizationKey(),
6391       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6392       resolve_context_->host_cache()));
6393   ASSERT_THAT(response_insecure.result_error(), IsOk());
6394   EXPECT_FALSE(response_insecure.request()
6395                    ->GetResolveErrorInfo()
6396                    .is_secure_network_error);
6397   EXPECT_THAT(response_insecure.request()->GetAddressResults()->endpoints(),
6398               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6399                                             CreateExpected("::1", 80)));
6400   EXPECT_THAT(
6401       response_insecure.request()->GetEndpointResults(),
6402       testing::Pointee(testing::ElementsAre(
6403           ExpectEndpointResult(testing::UnorderedElementsAre(
6404               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6405   HostCache::Key insecure_key =
6406       HostCache::Key("insecure_automatic", DnsQueryType::UNSPECIFIED,
6407                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6408                      NetworkAnonymizationKey());
6409   cache_result = GetCacheHit(insecure_key);
6410   EXPECT_TRUE(!!cache_result);
6411 
6412   // Fallback to HostResolverSystemTask allowed in AUTOMATIC mode.
6413   ResolveHostResponseHelper response_system(resolver_->CreateRequest(
6414       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
6415       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6416       resolve_context_->host_cache()));
6417   proc_->SignalMultiple(1u);
6418   EXPECT_THAT(response_system.result_error(), IsOk());
6419   EXPECT_THAT(response_system.request()->GetAddressResults()->endpoints(),
6420               testing::ElementsAre(CreateExpected("192.168.1.100", 80)));
6421   EXPECT_THAT(response_system.request()->GetEndpointResults(),
6422               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6423                   testing::ElementsAre(CreateExpected("192.168.1.100", 80))))));
6424 }
6425 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_SecureCache)6426 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic_SecureCache) {
6427   ChangeDnsConfig(CreateValidDnsConfig());
6428   DnsConfigOverrides overrides;
6429   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6430   resolver_->SetDnsConfigOverrides(overrides);
6431 
6432   // Populate cache with a secure entry.
6433   HostCache::Key cached_secure_key =
6434       HostCache::Key("automatic_cached", DnsQueryType::UNSPECIFIED,
6435                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6436                      NetworkAnonymizationKey());
6437   cached_secure_key.secure = true;
6438   IPEndPoint kExpectedSecureIP = CreateExpected("192.168.1.102", 80);
6439   PopulateCache(cached_secure_key, kExpectedSecureIP);
6440 
6441   // The secure cache should be checked prior to any DoH request being sent.
6442   ResolveHostResponseHelper response_secure_cached(resolver_->CreateRequest(
6443       HostPortPair("automatic_cached", 80), NetworkAnonymizationKey(),
6444       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6445       resolve_context_->host_cache()));
6446   EXPECT_THAT(response_secure_cached.result_error(), IsOk());
6447   EXPECT_FALSE(response_secure_cached.request()
6448                    ->GetResolveErrorInfo()
6449                    .is_secure_network_error);
6450   EXPECT_THAT(
6451       response_secure_cached.request()->GetAddressResults()->endpoints(),
6452       testing::ElementsAre(kExpectedSecureIP));
6453   EXPECT_THAT(response_secure_cached.request()->GetEndpointResults(),
6454               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6455                   testing::ElementsAre(kExpectedSecureIP)))));
6456   EXPECT_FALSE(
6457       response_secure_cached.request()->GetStaleInfo().value().is_stale());
6458 }
6459 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_InsecureCache)6460 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic_InsecureCache) {
6461   ChangeDnsConfig(CreateValidDnsConfig());
6462   DnsConfigOverrides overrides;
6463   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6464   resolver_->SetDnsConfigOverrides(overrides);
6465 
6466   // Populate cache with an insecure entry.
6467   HostCache::Key cached_insecure_key =
6468       HostCache::Key("insecure_automatic_cached", DnsQueryType::UNSPECIFIED,
6469                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6470                      NetworkAnonymizationKey());
6471   IPEndPoint kExpectedInsecureIP = CreateExpected("192.168.1.103", 80);
6472   PopulateCache(cached_insecure_key, kExpectedInsecureIP);
6473 
6474   // The insecure cache should be checked after DoH requests fail.
6475   ResolveHostResponseHelper response_insecure_cached(resolver_->CreateRequest(
6476       HostPortPair("insecure_automatic_cached", 80), NetworkAnonymizationKey(),
6477       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6478       resolve_context_->host_cache()));
6479   EXPECT_THAT(response_insecure_cached.result_error(), IsOk());
6480   EXPECT_FALSE(response_insecure_cached.request()
6481                    ->GetResolveErrorInfo()
6482                    .is_secure_network_error);
6483   EXPECT_THAT(
6484       response_insecure_cached.request()->GetAddressResults()->endpoints(),
6485       testing::ElementsAre(kExpectedInsecureIP));
6486   EXPECT_THAT(response_insecure_cached.request()->GetEndpointResults(),
6487               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6488                   testing::ElementsAre(kExpectedInsecureIP)))));
6489   EXPECT_FALSE(
6490       response_insecure_cached.request()->GetStaleInfo().value().is_stale());
6491 }
6492 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_Downgrade)6493 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic_Downgrade) {
6494   ChangeDnsConfig(CreateValidDnsConfig());
6495   // There is no DoH server available.
6496   DnsConfigOverrides overrides;
6497   overrides.dns_over_https_config.emplace();
6498   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6499   resolver_->SetDnsConfigOverrides(overrides);
6500   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
6501 
6502   // Populate cache with both secure and insecure entries.
6503   HostCache::Key cached_secure_key =
6504       HostCache::Key("automatic_cached", DnsQueryType::UNSPECIFIED,
6505                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6506                      NetworkAnonymizationKey());
6507   cached_secure_key.secure = true;
6508   IPEndPoint kExpectedSecureIP = CreateExpected("192.168.1.102", 80);
6509   PopulateCache(cached_secure_key, kExpectedSecureIP);
6510   HostCache::Key cached_insecure_key =
6511       HostCache::Key("insecure_automatic_cached", DnsQueryType::UNSPECIFIED,
6512                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6513                      NetworkAnonymizationKey());
6514   IPEndPoint kExpectedInsecureIP = CreateExpected("192.168.1.103", 80);
6515   PopulateCache(cached_insecure_key, kExpectedInsecureIP);
6516 
6517   // The secure cache should still be checked first.
6518   ResolveHostResponseHelper response_cached(resolver_->CreateRequest(
6519       HostPortPair("automatic_cached", 80), NetworkAnonymizationKey(),
6520       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6521       resolve_context_->host_cache()));
6522   EXPECT_THAT(response_cached.result_error(), IsOk());
6523   EXPECT_THAT(response_cached.request()->GetAddressResults()->endpoints(),
6524               testing::ElementsAre(kExpectedSecureIP));
6525   EXPECT_THAT(response_cached.request()->GetEndpointResults(),
6526               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6527                   testing::ElementsAre(kExpectedSecureIP)))));
6528 
6529   // The insecure cache should be checked before any insecure requests are sent.
6530   ResolveHostResponseHelper insecure_response_cached(resolver_->CreateRequest(
6531       HostPortPair("insecure_automatic_cached", 80), NetworkAnonymizationKey(),
6532       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6533       resolve_context_->host_cache()));
6534   EXPECT_THAT(insecure_response_cached.result_error(), IsOk());
6535   EXPECT_THAT(
6536       insecure_response_cached.request()->GetAddressResults()->endpoints(),
6537       testing::ElementsAre(kExpectedInsecureIP));
6538   EXPECT_THAT(insecure_response_cached.request()->GetEndpointResults(),
6539               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6540                   testing::ElementsAre(kExpectedInsecureIP)))));
6541 
6542   // The DnsConfig doesn't contain DoH servers so AUTOMATIC mode will be
6543   // downgraded to OFF. A successful plaintext DNS request should result in an
6544   // insecure cache entry.
6545   ResolveHostResponseHelper response(resolver_->CreateRequest(
6546       HostPortPair("automatic", 80), NetworkAnonymizationKey(),
6547       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6548       resolve_context_->host_cache()));
6549   ASSERT_THAT(response.result_error(), IsOk());
6550   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
6551               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6552                                             CreateExpected("::1", 80)));
6553   EXPECT_THAT(
6554       response.request()->GetEndpointResults(),
6555       testing::Pointee(testing::ElementsAre(
6556           ExpectEndpointResult(testing::UnorderedElementsAre(
6557               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6558   HostCache::Key key = HostCache::Key(
6559       "automatic", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6560       HostResolverSource::ANY, NetworkAnonymizationKey());
6561   cache_result = GetCacheHit(key);
6562   EXPECT_TRUE(!!cache_result);
6563 }
6564 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_Unavailable)6565 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic_Unavailable) {
6566   ChangeDnsConfig(CreateValidDnsConfig());
6567   DnsConfigOverrides overrides;
6568   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6569   resolver_->SetDnsConfigOverrides(overrides);
6570   dns_client_->SetForceDohServerAvailable(false);
6571 
6572   // DoH requests should be skipped when there are no available DoH servers
6573   // in automatic mode. The cached result should be in the insecure cache.
6574   ResolveHostResponseHelper response_automatic(resolver_->CreateRequest(
6575       HostPortPair("automatic", 80), NetworkAnonymizationKey(),
6576       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6577       resolve_context_->host_cache()));
6578   ASSERT_THAT(response_automatic.result_error(), IsOk());
6579   EXPECT_FALSE(response_automatic.request()
6580                    ->GetResolveErrorInfo()
6581                    .is_secure_network_error);
6582   EXPECT_THAT(response_automatic.request()->GetAddressResults()->endpoints(),
6583               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6584                                             CreateExpected("::1", 80)));
6585   EXPECT_THAT(
6586       response_automatic.request()->GetEndpointResults(),
6587       testing::Pointee(testing::ElementsAre(
6588           ExpectEndpointResult(testing::UnorderedElementsAre(
6589               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6590   HostCache::Key secure_key = HostCache::Key(
6591       "automatic", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6592       HostResolverSource::ANY, NetworkAnonymizationKey());
6593   secure_key.secure = true;
6594   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
6595       GetCacheHit(secure_key);
6596   EXPECT_FALSE(!!cache_result);
6597 
6598   HostCache::Key insecure_key = HostCache::Key(
6599       "automatic", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6600       HostResolverSource::ANY, NetworkAnonymizationKey());
6601   cache_result = GetCacheHit(insecure_key);
6602   EXPECT_TRUE(!!cache_result);
6603 }
6604 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_Unavailable_Fail)6605 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic_Unavailable_Fail) {
6606   set_allow_fallback_to_systemtask(false);
6607   ChangeDnsConfig(CreateValidDnsConfig());
6608   DnsConfigOverrides overrides;
6609   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6610   resolver_->SetDnsConfigOverrides(overrides);
6611   dns_client_->SetForceDohServerAvailable(false);
6612 
6613   // Insecure requests that fail should not be cached.
6614   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
6615       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6616       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6617   ASSERT_THAT(response_secure.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
6618   EXPECT_FALSE(
6619       response_secure.request()->GetResolveErrorInfo().is_secure_network_error);
6620 
6621   HostCache::Key secure_key = HostCache::Key(
6622       "secure", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6623       HostResolverSource::ANY, NetworkAnonymizationKey());
6624   secure_key.secure = true;
6625   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
6626       GetCacheHit(secure_key);
6627   EXPECT_FALSE(!!cache_result);
6628 
6629   HostCache::Key insecure_key = HostCache::Key(
6630       "secure", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6631       HostResolverSource::ANY, NetworkAnonymizationKey());
6632   cache_result = GetCacheHit(insecure_key);
6633   EXPECT_FALSE(!!cache_result);
6634 }
6635 
6636 // Test that DoH server availability is respected per-context.
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_UnavailableByContext)6637 TEST_F(HostResolverManagerDnsTest,
6638        SecureDnsMode_Automatic_UnavailableByContext) {
6639   // Create and register two separate contexts.
6640   auto request_context1 = CreateTestURLRequestContextBuilder()->Build();
6641   auto request_context2 = CreateTestURLRequestContextBuilder()->Build();
6642   ResolveContext resolve_context1(request_context1.get(),
6643                                   false /* enable_caching */);
6644   ResolveContext resolve_context2(request_context2.get(),
6645                                   false /* enable_caching */);
6646   resolver_->RegisterResolveContext(&resolve_context1);
6647   resolver_->RegisterResolveContext(&resolve_context2);
6648 
6649   // Configure the resolver and underlying mock to attempt a secure query iff
6650   // the context has marked a DoH server available and otherwise attempt a
6651   // non-secure query.
6652   set_allow_fallback_to_systemtask(false);
6653   ChangeDnsConfig(CreateValidDnsConfig());
6654   DnsConfigOverrides overrides;
6655   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6656   resolver_->SetDnsConfigOverrides(overrides);
6657   dns_client_->SetForceDohServerAvailable(false);
6658 
6659   // Mark a DoH server successful only for |resolve_context2|. Note that this
6660   // must come after the resolver's configuration is set because this relies on
6661   // the specific configuration containing a DoH server.
6662   resolve_context2.RecordServerSuccess(0u /* server_index */,
6663                                        true /* is_doh_server */,
6664                                        dns_client_->GetCurrentSession());
6665 
6666   // No available DoH servers for |resolve_context1|, so expect a non-secure
6667   // request. Non-secure requests for "secure" will fail with
6668   // ERR_NAME_NOT_RESOLVED.
6669   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
6670       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6671       absl::nullopt, &resolve_context1, resolve_context_->host_cache()));
6672   ASSERT_THAT(response_secure.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
6673 
6674   // One available DoH server for |resolve_context2|, so expect a secure
6675   // request. Secure requests for "secure" will succeed.
6676   ResolveHostResponseHelper response_secure2(resolver_->CreateRequest(
6677       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6678       absl::nullopt, &resolve_context2, nullptr /* host_cache */));
6679   ASSERT_THAT(response_secure2.result_error(), IsOk());
6680 
6681   resolver_->DeregisterResolveContext(&resolve_context1);
6682   resolver_->DeregisterResolveContext(&resolve_context2);
6683 }
6684 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_Stale)6685 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic_Stale) {
6686   ChangeDnsConfig(CreateValidDnsConfig());
6687   DnsConfigOverrides overrides;
6688   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6689   resolver_->SetDnsConfigOverrides(overrides);
6690 
6691   // Populate cache with insecure entry.
6692   HostCache::Key cached_stale_key = HostCache::Key(
6693       "automatic_stale", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6694       HostResolverSource::ANY, NetworkAnonymizationKey());
6695   IPEndPoint kExpectedStaleIP = CreateExpected("192.168.1.102", 80);
6696   PopulateCache(cached_stale_key, kExpectedStaleIP);
6697   MakeCacheStale();
6698 
6699   HostResolver::ResolveHostParameters stale_allowed_parameters;
6700   stale_allowed_parameters.cache_usage =
6701       HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
6702 
6703   // The insecure cache should be checked before secure requests are made since
6704   // stale results are allowed.
6705   ResolveHostResponseHelper response_stale(resolver_->CreateRequest(
6706       HostPortPair("automatic_stale", 80), NetworkAnonymizationKey(),
6707       NetLogWithSource(), stale_allowed_parameters, resolve_context_.get(),
6708       resolve_context_->host_cache()));
6709   EXPECT_THAT(response_stale.result_error(), IsOk());
6710   EXPECT_FALSE(
6711       response_stale.request()->GetResolveErrorInfo().is_secure_network_error);
6712   EXPECT_THAT(response_stale.request()->GetAddressResults()->endpoints(),
6713               testing::ElementsAre(kExpectedStaleIP));
6714   EXPECT_THAT(response_stale.request()->GetEndpointResults(),
6715               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6716                   testing::ElementsAre(kExpectedStaleIP)))));
6717   EXPECT_TRUE(response_stale.request()->GetStaleInfo()->is_stale());
6718 }
6719 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_InsecureAsyncDisabled)6720 TEST_F(HostResolverManagerDnsTest,
6721        SecureDnsMode_Automatic_InsecureAsyncDisabled) {
6722   proc_->AddRuleForAllFamilies("insecure_automatic", "192.168.1.100");
6723   ChangeDnsConfig(CreateValidDnsConfig());
6724   resolver_->SetInsecureDnsClientEnabled(
6725       /*enabled=*/false,
6726       /*additional_dns_types_enabled=*/false);
6727   DnsConfigOverrides overrides;
6728   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6729   resolver_->SetDnsConfigOverrides(overrides);
6730 
6731   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
6732 
6733   // The secure part of the dns client should be enabled.
6734   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
6735       HostPortPair("automatic", 80), NetworkAnonymizationKey(),
6736       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6737       resolve_context_->host_cache()));
6738   ASSERT_THAT(response_secure.result_error(), IsOk());
6739   EXPECT_THAT(response_secure.request()->GetAddressResults()->endpoints(),
6740               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6741                                             CreateExpected("::1", 80)));
6742   EXPECT_THAT(
6743       response_secure.request()->GetEndpointResults(),
6744       testing::Pointee(testing::ElementsAre(
6745           ExpectEndpointResult(testing::UnorderedElementsAre(
6746               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6747   HostCache::Key secure_key = HostCache::Key(
6748       "automatic", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6749       HostResolverSource::ANY, NetworkAnonymizationKey());
6750   secure_key.secure = true;
6751   cache_result = GetCacheHit(secure_key);
6752   EXPECT_TRUE(!!cache_result);
6753 
6754   // The insecure part of the dns client is disabled so insecure requests
6755   // should be skipped.
6756   ResolveHostResponseHelper response_insecure(resolver_->CreateRequest(
6757       HostPortPair("insecure_automatic", 80), NetworkAnonymizationKey(),
6758       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6759       resolve_context_->host_cache()));
6760   proc_->SignalMultiple(1u);
6761   ASSERT_THAT(response_insecure.result_error(), IsOk());
6762   EXPECT_THAT(response_insecure.request()->GetAddressResults()->endpoints(),
6763               testing::ElementsAre(CreateExpected("192.168.1.100", 80)));
6764   EXPECT_THAT(response_insecure.request()->GetEndpointResults(),
6765               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6766                   testing::ElementsAre(CreateExpected("192.168.1.100", 80))))));
6767   HostCache::Key insecure_key =
6768       HostCache::Key("insecure_automatic", DnsQueryType::UNSPECIFIED,
6769                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6770                      NetworkAnonymizationKey());
6771   cache_result = GetCacheHit(insecure_key);
6772   EXPECT_TRUE(!!cache_result);
6773 
6774   HostCache::Key cached_insecure_key =
6775       HostCache::Key("insecure_automatic_cached", DnsQueryType::UNSPECIFIED,
6776                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6777                      NetworkAnonymizationKey());
6778   IPEndPoint kExpectedInsecureIP = CreateExpected("192.168.1.101", 80);
6779   PopulateCache(cached_insecure_key, kExpectedInsecureIP);
6780 
6781   // The insecure cache should still be checked even if the insecure part of
6782   // the dns client is disabled.
6783   ResolveHostResponseHelper response_insecure_cached(resolver_->CreateRequest(
6784       HostPortPair("insecure_automatic_cached", 80), NetworkAnonymizationKey(),
6785       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6786       resolve_context_->host_cache()));
6787   EXPECT_THAT(response_insecure_cached.result_error(), IsOk());
6788   EXPECT_THAT(
6789       response_insecure_cached.request()->GetAddressResults()->endpoints(),
6790       testing::ElementsAre(kExpectedInsecureIP));
6791   EXPECT_THAT(response_insecure_cached.request()->GetEndpointResults(),
6792               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6793                   testing::ElementsAre(kExpectedInsecureIP)))));
6794 }
6795 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Automatic_DotActive)6796 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Automatic_DotActive) {
6797   proc_->AddRuleForAllFamilies("insecure_automatic", "192.168.1.100");
6798   DnsConfig config = CreateValidDnsConfig();
6799   config.dns_over_tls_active = true;
6800   ChangeDnsConfig(config);
6801   DnsConfigOverrides overrides;
6802   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
6803   resolver_->SetDnsConfigOverrides(overrides);
6804 
6805   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
6806 
6807   // The secure part of the dns client should be enabled.
6808   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
6809       HostPortPair("automatic", 80), NetworkAnonymizationKey(),
6810       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6811       resolve_context_->host_cache()));
6812   ASSERT_THAT(response_secure.result_error(), IsOk());
6813   EXPECT_THAT(response_secure.request()->GetAddressResults()->endpoints(),
6814               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
6815                                             CreateExpected("::1", 80)));
6816   EXPECT_THAT(
6817       response_secure.request()->GetEndpointResults(),
6818       testing::Pointee(testing::ElementsAre(
6819           ExpectEndpointResult(testing::UnorderedElementsAre(
6820               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
6821   HostCache::Key secure_key = HostCache::Key(
6822       "automatic", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6823       HostResolverSource::ANY, NetworkAnonymizationKey());
6824   secure_key.secure = true;
6825   cache_result = GetCacheHit(secure_key);
6826   EXPECT_TRUE(!!cache_result);
6827 
6828   // Insecure async requests should be skipped since the system resolver
6829   // requests will be secure.
6830   ResolveHostResponseHelper response_insecure(resolver_->CreateRequest(
6831       HostPortPair("insecure_automatic", 80), NetworkAnonymizationKey(),
6832       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6833       resolve_context_->host_cache()));
6834   proc_->SignalMultiple(1u);
6835   ASSERT_THAT(response_insecure.result_error(), IsOk());
6836   EXPECT_FALSE(response_insecure.request()
6837                    ->GetResolveErrorInfo()
6838                    .is_secure_network_error);
6839   EXPECT_THAT(response_insecure.request()->GetAddressResults()->endpoints(),
6840               testing::ElementsAre(CreateExpected("192.168.1.100", 80)));
6841   EXPECT_THAT(response_insecure.request()->GetEndpointResults(),
6842               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6843                   testing::ElementsAre(CreateExpected("192.168.1.100", 80))))));
6844   HostCache::Key insecure_key =
6845       HostCache::Key("insecure_automatic", DnsQueryType::UNSPECIFIED,
6846                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6847                      NetworkAnonymizationKey());
6848   cache_result = GetCacheHit(insecure_key);
6849   EXPECT_TRUE(!!cache_result);
6850 
6851   HostCache::Key cached_insecure_key =
6852       HostCache::Key("insecure_automatic_cached", DnsQueryType::UNSPECIFIED,
6853                      0 /* host_resolver_flags */, HostResolverSource::ANY,
6854                      NetworkAnonymizationKey());
6855   IPEndPoint kExpectedInsecureIP = CreateExpected("192.168.1.101", 80);
6856   PopulateCache(cached_insecure_key, kExpectedInsecureIP);
6857 
6858   // The insecure cache should still be checked.
6859   ResolveHostResponseHelper response_insecure_cached(resolver_->CreateRequest(
6860       HostPortPair("insecure_automatic_cached", 80), NetworkAnonymizationKey(),
6861       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6862       resolve_context_->host_cache()));
6863   EXPECT_THAT(response_insecure_cached.result_error(), IsOk());
6864   EXPECT_FALSE(response_insecure_cached.request()
6865                    ->GetResolveErrorInfo()
6866                    .is_secure_network_error);
6867   EXPECT_THAT(
6868       response_insecure_cached.request()->GetAddressResults()->endpoints(),
6869       testing::ElementsAre(kExpectedInsecureIP));
6870   EXPECT_THAT(response_insecure_cached.request()->GetEndpointResults(),
6871               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
6872                   testing::ElementsAre(kExpectedInsecureIP)))));
6873 }
6874 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Secure)6875 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Secure) {
6876   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.100");
6877   set_allow_fallback_to_systemtask(true);
6878 
6879   ChangeDnsConfig(CreateValidDnsConfig());
6880   DnsConfigOverrides overrides;
6881   overrides.secure_dns_mode = SecureDnsMode::kSecure;
6882   resolver_->SetDnsConfigOverrides(overrides);
6883   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
6884 
6885   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
6886       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6887       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6888   ASSERT_THAT(response_secure.result_error(), IsOk());
6889   EXPECT_FALSE(
6890       response_secure.request()->GetResolveErrorInfo().is_secure_network_error);
6891   HostCache::Key secure_key = HostCache::Key(
6892       "secure", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6893       HostResolverSource::ANY, NetworkAnonymizationKey());
6894   secure_key.secure = true;
6895   cache_result = GetCacheHit(secure_key);
6896   EXPECT_TRUE(!!cache_result);
6897 
6898   ResolveHostResponseHelper response_insecure(resolver_->CreateRequest(
6899       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6900       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6901   ASSERT_THAT(response_insecure.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
6902   EXPECT_TRUE(response_insecure.request()
6903                   ->GetResolveErrorInfo()
6904                   .is_secure_network_error);
6905   HostCache::Key insecure_key = HostCache::Key(
6906       "ok", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6907       HostResolverSource::ANY, NetworkAnonymizationKey());
6908   cache_result = GetCacheHit(insecure_key);
6909   EXPECT_FALSE(!!cache_result);
6910 
6911   // Fallback to HostResolverSystemTask not allowed in SECURE mode.
6912   ResolveHostResponseHelper response_system(resolver_->CreateRequest(
6913       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
6914       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
6915       resolve_context_->host_cache()));
6916   proc_->SignalMultiple(1u);
6917   EXPECT_THAT(response_system.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
6918   EXPECT_TRUE(
6919       response_system.request()->GetResolveErrorInfo().is_secure_network_error);
6920 }
6921 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Secure_InsecureAsyncDisabled)6922 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Secure_InsecureAsyncDisabled) {
6923   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.100");
6924   set_allow_fallback_to_systemtask(true);
6925   resolver_->SetInsecureDnsClientEnabled(
6926       /*enabled=*/false,
6927       /*additional_dns_types_enabled=*/false);
6928 
6929   ChangeDnsConfig(CreateValidDnsConfig());
6930   DnsConfigOverrides overrides;
6931   overrides.secure_dns_mode = SecureDnsMode::kSecure;
6932   resolver_->SetDnsConfigOverrides(overrides);
6933   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
6934 
6935   // The secure part of the dns client should be enabled.
6936   ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
6937       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
6938       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
6939   ASSERT_THAT(response_secure.result_error(), IsOk());
6940   HostCache::Key secure_key = HostCache::Key(
6941       "secure", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6942       HostResolverSource::ANY, NetworkAnonymizationKey());
6943   secure_key.secure = true;
6944   cache_result = GetCacheHit(secure_key);
6945   EXPECT_TRUE(!!cache_result);
6946 }
6947 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Secure_Local_CacheMiss)6948 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Secure_Local_CacheMiss) {
6949   ChangeDnsConfig(CreateValidDnsConfig());
6950   DnsConfigOverrides overrides;
6951   overrides.secure_dns_mode = SecureDnsMode::kSecure;
6952   resolver_->SetDnsConfigOverrides(overrides);
6953 
6954   HostResolver::ResolveHostParameters source_none_parameters;
6955   source_none_parameters.source = HostResolverSource::LOCAL_ONLY;
6956 
6957   // Populate cache with an insecure entry.
6958   HostCache::Key cached_insecure_key = HostCache::Key(
6959       "automatic", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6960       HostResolverSource::ANY, NetworkAnonymizationKey());
6961   IPEndPoint kExpectedInsecureIP = CreateExpected("192.168.1.102", 80);
6962   PopulateCache(cached_insecure_key, kExpectedInsecureIP);
6963 
6964   // NONE query expected to complete synchronously with a cache miss since
6965   // the insecure cache should not be checked.
6966   ResolveHostResponseHelper cache_miss_request(resolver_->CreateRequest(
6967       HostPortPair("automatic", 80), NetworkAnonymizationKey(),
6968       NetLogWithSource(), source_none_parameters, resolve_context_.get(),
6969       resolve_context_->host_cache()));
6970   EXPECT_TRUE(cache_miss_request.complete());
6971   EXPECT_THAT(cache_miss_request.result_error(), IsError(ERR_DNS_CACHE_MISS));
6972   EXPECT_FALSE(cache_miss_request.request()
6973                    ->GetResolveErrorInfo()
6974                    .is_secure_network_error);
6975   EXPECT_FALSE(cache_miss_request.request()->GetAddressResults());
6976   EXPECT_FALSE(cache_miss_request.request()->GetEndpointResults());
6977   EXPECT_FALSE(cache_miss_request.request()->GetStaleInfo());
6978 }
6979 
TEST_F(HostResolverManagerDnsTest,SecureDnsMode_Secure_Local_CacheHit)6980 TEST_F(HostResolverManagerDnsTest, SecureDnsMode_Secure_Local_CacheHit) {
6981   ChangeDnsConfig(CreateValidDnsConfig());
6982   DnsConfigOverrides overrides;
6983   overrides.secure_dns_mode = SecureDnsMode::kSecure;
6984   resolver_->SetDnsConfigOverrides(overrides);
6985 
6986   HostResolver::ResolveHostParameters source_none_parameters;
6987   source_none_parameters.source = HostResolverSource::LOCAL_ONLY;
6988 
6989   // Populate cache with a secure entry.
6990   HostCache::Key cached_secure_key = HostCache::Key(
6991       "secure", DnsQueryType::UNSPECIFIED, 0 /* host_resolver_flags */,
6992       HostResolverSource::ANY, NetworkAnonymizationKey());
6993   cached_secure_key.secure = true;
6994   IPEndPoint kExpectedSecureIP = CreateExpected("192.168.1.103", 80);
6995   PopulateCache(cached_secure_key, kExpectedSecureIP);
6996 
6997   // NONE query expected to complete synchronously with a cache hit from the
6998   // secure cache.
6999   ResolveHostResponseHelper response_cached(resolver_->CreateRequest(
7000       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7001       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7002   EXPECT_TRUE(response_cached.complete());
7003   EXPECT_THAT(response_cached.result_error(), IsOk());
7004   EXPECT_FALSE(
7005       response_cached.request()->GetResolveErrorInfo().is_secure_network_error);
7006   EXPECT_THAT(response_cached.request()->GetAddressResults()->endpoints(),
7007               testing::ElementsAre(kExpectedSecureIP));
7008   EXPECT_THAT(response_cached.request()->GetEndpointResults(),
7009               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7010                   testing::ElementsAre(kExpectedSecureIP)))));
7011 }
7012 
7013 // On an IPv6 network, if we get A results and the AAAA response is SERVFAIL, we
7014 // fail the whole DnsTask rather than proceeding with just the A results. In
7015 // SECURE mode, fallback to the system resolver is disabled. See
7016 // https://crbug.com/1292324.
TEST_F(HostResolverManagerDnsTest,SecureDnsModeIsSecureAndAAAAServfailCausesFailDespiteAResults)7017 TEST_F(HostResolverManagerDnsTest,
7018        SecureDnsModeIsSecureAndAAAAServfailCausesFailDespiteAResults) {
7019   constexpr char kName[] = "name.test";
7020 
7021   MockDnsClientRuleList rules;
7022   rules.emplace_back(
7023       kName, dns_protocol::kTypeA, /*secure=*/true,
7024       MockDnsClientRule::Result(
7025           MockDnsClientRule::ResultType::kOk,
7026           BuildTestDnsAddressResponse(kName, IPAddress(192, 168, 1, 103))),
7027       /*delay=*/false);
7028   rules.emplace_back(
7029       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
7030       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
7031       /*delay=*/false);
7032 
7033   DnsConfig config = CreateValidDnsConfig();
7034   config.use_local_ipv6 = true;
7035 
7036   CreateResolver();
7037   UseMockDnsClient(config, std::move(rules));
7038   DnsConfigOverrides overrides;
7039   overrides.secure_dns_mode = SecureDnsMode::kSecure;
7040   resolver_->SetDnsConfigOverrides(overrides);
7041 
7042   ResolveHostResponseHelper response(resolver_->CreateRequest(
7043       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
7044       NetworkAnonymizationKey(), NetLogWithSource(),
7045       /*optional_parameters=*/absl::nullopt, resolve_context_.get(),
7046       resolve_context_->host_cache()));
7047   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
7048   EXPECT_FALSE(response.request()->GetEndpointResults());
7049   EXPECT_FALSE(response.request()->GetTextResults());
7050   EXPECT_FALSE(response.request()->GetHostnameResults());
7051   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
7052 
7053   // Expect result not cached.
7054   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
7055 }
7056 
7057 // Test for a resolve with a transaction that takes longer than usual to
7058 // complete. With the typical behavior of using fast timeouts, this is expected
7059 // to timeout and fallback to the system resolver.
TEST_F(HostResolverManagerDnsTest,SlowResolve)7060 TEST_F(HostResolverManagerDnsTest, SlowResolve) {
7061   // Add a successful fallback result.
7062   proc_->AddRuleForAllFamilies("slow_succeed", "192.168.1.211");
7063 
7064   MockDnsClientRuleList rules = CreateDefaultDnsRules();
7065   AddDnsRule(&rules, "slow_fail", dns_protocol::kTypeA,
7066              MockDnsClientRule::ResultType::kSlow, false /* delay */);
7067   AddDnsRule(&rules, "slow_fail", dns_protocol::kTypeAAAA,
7068              MockDnsClientRule::ResultType::kSlow, false /* delay */);
7069   AddDnsRule(&rules, "slow_succeed", dns_protocol::kTypeA,
7070              MockDnsClientRule::ResultType::kSlow, false /* delay */);
7071   AddDnsRule(&rules, "slow_succeed", dns_protocol::kTypeAAAA,
7072              MockDnsClientRule::ResultType::kSlow, false /* delay */);
7073   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
7074 
7075   ResolveHostResponseHelper response0(resolver_->CreateRequest(
7076       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7077       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7078   ResolveHostResponseHelper response1(resolver_->CreateRequest(
7079       HostPortPair("slow_fail", 80), NetworkAnonymizationKey(),
7080       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7081       resolve_context_->host_cache()));
7082   ResolveHostResponseHelper response2(resolver_->CreateRequest(
7083       HostPortPair("slow_succeed", 80), NetworkAnonymizationKey(),
7084       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7085       resolve_context_->host_cache()));
7086   proc_->SignalMultiple(3u);
7087 
7088   EXPECT_THAT(response0.result_error(), IsOk());
7089   EXPECT_THAT(response0.request()->GetAddressResults()->endpoints(),
7090               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
7091                                             CreateExpected("::1", 80)));
7092   EXPECT_THAT(
7093       response0.request()->GetEndpointResults(),
7094       testing::Pointee(testing::ElementsAre(
7095           ExpectEndpointResult(testing::UnorderedElementsAre(
7096               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
7097   EXPECT_THAT(response1.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
7098   EXPECT_THAT(response2.result_error(), IsOk());
7099   EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
7100               testing::ElementsAre(CreateExpected("192.168.1.211", 80)));
7101   EXPECT_THAT(response2.request()->GetEndpointResults(),
7102               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7103                   testing::ElementsAre(CreateExpected("192.168.1.211", 80))))));
7104 }
7105 
7106 // Test for a resolve with a secure transaction that takes longer than usual to
7107 // complete. In automatic mode, because fallback to insecure is available, the
7108 // secure transaction is expected to quickly timeout and fallback to insecure.
TEST_F(HostResolverManagerDnsTest,SlowSecureResolve_AutomaticMode)7109 TEST_F(HostResolverManagerDnsTest, SlowSecureResolve_AutomaticMode) {
7110   set_allow_fallback_to_systemtask(false);
7111 
7112   MockDnsClientRuleList rules = CreateDefaultDnsRules();
7113   AddSecureDnsRule(&rules, "slow_fail", dns_protocol::kTypeA,
7114                    MockDnsClientRule::ResultType::kSlow, false /* delay */);
7115   AddSecureDnsRule(&rules, "slow_fail", dns_protocol::kTypeAAAA,
7116                    MockDnsClientRule::ResultType::kSlow, false /* delay */);
7117   AddSecureDnsRule(&rules, "slow_succeed", dns_protocol::kTypeA,
7118                    MockDnsClientRule::ResultType::kSlow, false /* delay */);
7119   AddSecureDnsRule(&rules, "slow_succeed", dns_protocol::kTypeAAAA,
7120                    MockDnsClientRule::ResultType::kSlow, false /* delay */);
7121   AddDnsRule(&rules, "slow_succeed", dns_protocol::kTypeA,
7122              IPAddress(111, 222, 112, 223), false /* delay */);
7123   AddDnsRule(&rules, "slow_succeed", dns_protocol::kTypeAAAA,
7124              MockDnsClientRule::ResultType::kEmpty, false /* delay */);
7125   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
7126 
7127   DnsConfigOverrides overrides;
7128   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
7129   resolver_->SetDnsConfigOverrides(overrides);
7130 
7131   ResolveHostResponseHelper response0(resolver_->CreateRequest(
7132       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7133       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7134   ResolveHostResponseHelper response1(resolver_->CreateRequest(
7135       HostPortPair("slow_fail", 80), NetworkAnonymizationKey(),
7136       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7137       resolve_context_->host_cache()));
7138   ResolveHostResponseHelper response2(resolver_->CreateRequest(
7139       HostPortPair("slow_succeed", 80), NetworkAnonymizationKey(),
7140       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7141       resolve_context_->host_cache()));
7142 
7143   EXPECT_THAT(response0.result_error(), IsOk());
7144   EXPECT_THAT(response0.request()->GetAddressResults()->endpoints(),
7145               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
7146                                             CreateExpected("::1", 80)));
7147   EXPECT_THAT(
7148       response0.request()->GetEndpointResults(),
7149       testing::Pointee(testing::ElementsAre(
7150           ExpectEndpointResult(testing::UnorderedElementsAre(
7151               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
7152   EXPECT_THAT(response1.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
7153   EXPECT_THAT(response2.result_error(), IsOk());
7154   EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
7155               testing::ElementsAre(CreateExpected("111.222.112.223", 80)));
7156   EXPECT_THAT(
7157       response2.request()->GetEndpointResults(),
7158       testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7159           testing::ElementsAre(CreateExpected("111.222.112.223", 80))))));
7160 }
7161 
7162 // Test for a resolve with a secure transaction that takes longer than usual to
7163 // complete. In secure mode, because no fallback is available, this is expected
7164 // to wait longer before timeout and complete successfully.
TEST_F(HostResolverManagerDnsTest,SlowSecureResolve_SecureMode)7165 TEST_F(HostResolverManagerDnsTest, SlowSecureResolve_SecureMode) {
7166   MockDnsClientRuleList rules = CreateDefaultDnsRules();
7167   AddSecureDnsRule(&rules, "slow", dns_protocol::kTypeA,
7168                    MockDnsClientRule::ResultType::kSlow, false /* delay */);
7169   AddSecureDnsRule(&rules, "slow", dns_protocol::kTypeAAAA,
7170                    MockDnsClientRule::ResultType::kSlow, false /* delay */);
7171   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
7172 
7173   DnsConfigOverrides overrides;
7174   overrides.secure_dns_mode = SecureDnsMode::kSecure;
7175   resolver_->SetDnsConfigOverrides(overrides);
7176 
7177   ResolveHostResponseHelper response0(resolver_->CreateRequest(
7178       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7179       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7180   ResolveHostResponseHelper response1(resolver_->CreateRequest(
7181       HostPortPair("slow", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7182       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7183 
7184   EXPECT_THAT(response0.result_error(), IsOk());
7185   EXPECT_THAT(response1.result_error(), IsOk());
7186 }
7187 
7188 // Test the case where only a single transaction slot is available.
TEST_F(HostResolverManagerDnsTest,SerialResolver)7189 TEST_F(HostResolverManagerDnsTest, SerialResolver) {
7190   CreateSerialResolver();
7191   set_allow_fallback_to_systemtask(false);
7192   ChangeDnsConfig(CreateValidDnsConfig());
7193 
7194   ResolveHostResponseHelper response(resolver_->CreateRequest(
7195       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7196       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7197   EXPECT_FALSE(response.complete());
7198   EXPECT_EQ(1u, num_running_dispatcher_jobs());
7199 
7200   base::RunLoop().RunUntilIdle();
7201   EXPECT_TRUE(response.complete());
7202   EXPECT_THAT(response.result_error(), IsOk());
7203   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
7204               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
7205                                             CreateExpected("::1", 80)));
7206   EXPECT_THAT(
7207       response.request()->GetEndpointResults(),
7208       testing::Pointee(testing::ElementsAre(
7209           ExpectEndpointResult(testing::UnorderedElementsAre(
7210               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
7211 }
7212 
7213 // Test the case where subsequent transactions are handled on transaction
7214 // completion when only part of a multi-transaction request could be initially
7215 // started.
TEST_F(HostResolverManagerDnsTest,AAAAStartsAfterOtherJobFinishes)7216 TEST_F(HostResolverManagerDnsTest, AAAAStartsAfterOtherJobFinishes) {
7217   CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_),
7218                                     true /* ipv6_reachable */,
7219                                     true /* check_ipv6_on_wifi */);
7220   set_allow_fallback_to_systemtask(false);
7221   ChangeDnsConfig(CreateValidDnsConfig());
7222 
7223   ResolveHostResponseHelper response0(resolver_->CreateRequest(
7224       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7225       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7226   EXPECT_EQ(2u, num_running_dispatcher_jobs());
7227   ResolveHostResponseHelper response1(resolver_->CreateRequest(
7228       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
7229       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7230       resolve_context_->host_cache()));
7231   EXPECT_EQ(3u, num_running_dispatcher_jobs());
7232 
7233   // Request 0's transactions should complete, starting Request 1's second
7234   // transaction, which should also complete.
7235   base::RunLoop().RunUntilIdle();
7236   EXPECT_EQ(1u, num_running_dispatcher_jobs());
7237   EXPECT_TRUE(response0.complete());
7238   EXPECT_FALSE(response1.complete());
7239 
7240   dns_client_->CompleteDelayedTransactions();
7241   EXPECT_THAT(response1.result_error(), IsOk());
7242   EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
7243               testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
7244                                             CreateExpected("::1", 80)));
7245   EXPECT_THAT(
7246       response1.request()->GetEndpointResults(),
7247       testing::Pointee(testing::ElementsAre(
7248           ExpectEndpointResult(testing::UnorderedElementsAre(
7249               CreateExpected("::1", 80), CreateExpected("127.0.0.1", 80))))));
7250 }
7251 
7252 // Tests the case that a Job with a single transaction receives an empty address
7253 // list, triggering fallback to HostResolverSystemTask.
TEST_F(HostResolverManagerDnsTest,IPv4EmptyFallback)7254 TEST_F(HostResolverManagerDnsTest, IPv4EmptyFallback) {
7255   // Disable ipv6 to ensure we'll only try a single transaction for the host.
7256   CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_),
7257                                     false /* ipv6_reachable */,
7258                                     true /* check_ipv6_on_wifi */);
7259   DnsConfig config = CreateValidDnsConfig();
7260   config.use_local_ipv6 = false;
7261   ChangeDnsConfig(config);
7262 
7263   proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1",
7264                                HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
7265   proc_->SignalMultiple(1u);
7266 
7267   ResolveHostResponseHelper response(resolver_->CreateRequest(
7268       HostPortPair("empty_fallback", 80), NetworkAnonymizationKey(),
7269       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7270       resolve_context_->host_cache()));
7271   EXPECT_THAT(response.result_error(), IsOk());
7272   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
7273               testing::ElementsAre(CreateExpected("192.168.0.1", 80)));
7274   EXPECT_THAT(response.request()->GetEndpointResults(),
7275               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7276                   testing::ElementsAre(CreateExpected("192.168.0.1", 80))))));
7277 }
7278 
7279 // Tests the case that a Job with two transactions receives two empty address
7280 // lists, triggering fallback to HostResolverSystemTask.
TEST_F(HostResolverManagerDnsTest,UnspecEmptyFallback)7281 TEST_F(HostResolverManagerDnsTest, UnspecEmptyFallback) {
7282   ChangeDnsConfig(CreateValidDnsConfig());
7283   proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
7284   proc_->SignalMultiple(1u);
7285 
7286   ResolveHostResponseHelper response(resolver_->CreateRequest(
7287       HostPortPair("empty_fallback", 80), NetworkAnonymizationKey(),
7288       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7289       resolve_context_->host_cache()));
7290 
7291   EXPECT_THAT(response.result_error(), IsOk());
7292   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
7293               testing::ElementsAre(CreateExpected("192.168.0.1", 80)));
7294   EXPECT_THAT(response.request()->GetEndpointResults(),
7295               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7296                   testing::ElementsAre(CreateExpected("192.168.0.1", 80))))));
7297 }
7298 
7299 // Tests getting a new invalid DnsConfig while there are active DnsTasks.
TEST_F(HostResolverManagerDnsTest,InvalidDnsConfigWithPendingRequests)7300 TEST_F(HostResolverManagerDnsTest, InvalidDnsConfigWithPendingRequests) {
7301   // At most 3 jobs active at once.  This number is important, since we want
7302   // to make sure that aborting the first HostResolverManager::Job does not
7303   // trigger another DnsTransaction on the second Job when it releases its
7304   // second prioritized dispatcher slot.
7305   CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_),
7306                                     true /* ipv6_reachable */,
7307                                     true /* check_ipv6_on_wifi */);
7308 
7309   ChangeDnsConfig(CreateValidDnsConfig());
7310 
7311   proc_->AddRuleForAllFamilies("slow_nx1", "192.168.0.1");
7312   proc_->AddRuleForAllFamilies("slow_nx2", "192.168.0.2");
7313   proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
7314 
7315   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
7316   // First active job gets two slots.
7317   responses.emplace_back(
7318       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
7319           HostPortPair("slow_nx1", 80), NetworkAnonymizationKey(),
7320           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7321           resolve_context_->host_cache())));
7322   // Next job gets one slot, and waits on another.
7323   responses.emplace_back(
7324       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
7325           HostPortPair("slow_nx2", 80), NetworkAnonymizationKey(),
7326           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7327           resolve_context_->host_cache())));
7328   responses.emplace_back(
7329       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
7330           HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7331           absl::nullopt, resolve_context_.get(),
7332           resolve_context_->host_cache())));
7333 
7334   EXPECT_EQ(3u, num_running_dispatcher_jobs());
7335   for (auto& response : responses) {
7336     EXPECT_FALSE(response->complete());
7337   }
7338 
7339   // Clear DNS config. Fully in-progress, partially in-progress, and queued
7340   // requests should all be aborted.
7341   InvalidateDnsConfig();
7342   for (auto& response : responses) {
7343     EXPECT_THAT(response->result_error(), IsError(ERR_NETWORK_CHANGED));
7344   }
7345 }
7346 
7347 // Test that initial DNS config read signals do not abort pending requests
7348 // when using DnsClient.
TEST_F(HostResolverManagerDnsTest,DontAbortOnInitialDNSConfigRead)7349 TEST_F(HostResolverManagerDnsTest, DontAbortOnInitialDNSConfigRead) {
7350   // DnsClient is enabled, but there's no DnsConfig, so the request should start
7351   // using HostResolverSystemTask.
7352   ResolveHostResponseHelper response(resolver_->CreateRequest(
7353       HostPortPair("host1", 70), NetworkAnonymizationKey(), NetLogWithSource(),
7354       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7355   EXPECT_FALSE(response.complete());
7356 
7357   EXPECT_TRUE(proc_->WaitFor(1u));
7358   // Send the initial config read signal, with a valid config.
7359   SetInitialDnsConfig(CreateValidDnsConfig());
7360   proc_->SignalAll();
7361 
7362   EXPECT_THAT(response.result_error(), IsOk());
7363 }
7364 
7365 // Tests the case that the insecure part of the DnsClient is automatically
7366 // disabled due to failures while there are active DnsTasks.
TEST_F(HostResolverManagerDnsTest,AutomaticallyDisableInsecureDnsClientWithPendingRequests)7367 TEST_F(HostResolverManagerDnsTest,
7368        AutomaticallyDisableInsecureDnsClientWithPendingRequests) {
7369   // Trying different limits is important for this test:  Different limits
7370   // result in different behavior when aborting in-progress DnsTasks.  Having
7371   // a DnsTask that has one job active and one in the queue when another job
7372   // occupying two slots has its DnsTask aborted is the case most likely to run
7373   // into problems.  Try limits between [1, 2 * # of non failure requests].
7374   for (size_t limit = 1u; limit < 10u; ++limit) {
7375     CreateResolverWithLimitsAndParams(limit, DefaultParams(proc_),
7376                                       true /* ipv6_reachable */,
7377                                       true /* check_ipv6_on_wifi */);
7378 
7379     // Set the resolver in automatic-secure mode.
7380     net::DnsConfig config = CreateValidDnsConfig();
7381     config.secure_dns_mode = SecureDnsMode::kAutomatic;
7382     ChangeDnsConfig(config);
7383 
7384     // Start with request parameters that disable Secure DNS.
7385     HostResolver::ResolveHostParameters parameters;
7386     parameters.secure_dns_policy = SecureDnsPolicy::kDisable;
7387 
7388     // Queue up enough failures to disable insecure DnsTasks.  These will all
7389     // fall back to HostResolverSystemTasks, and succeed there.
7390     std::vector<std::unique_ptr<ResolveHostResponseHelper>> failure_responses;
7391     for (unsigned i = 0u; i < maximum_insecure_dns_task_failures(); ++i) {
7392       std::string host = base::StringPrintf("nx%u", i);
7393       proc_->AddRuleForAllFamilies(host, "192.168.0.1");
7394       failure_responses.emplace_back(
7395           std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
7396               HostPortPair(host, 80), NetworkAnonymizationKey(),
7397               NetLogWithSource(), parameters, resolve_context_.get(),
7398               resolve_context_->host_cache())));
7399       EXPECT_FALSE(failure_responses[i]->complete());
7400     }
7401 
7402     // These requests should all bypass insecure DnsTasks, due to the above
7403     // failures, so should end up using HostResolverSystemTasks.
7404     proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2");
7405     ResolveHostResponseHelper response0(resolver_->CreateRequest(
7406         HostPortPair("slow_ok1", 80), NetworkAnonymizationKey(),
7407         NetLogWithSource(), parameters, resolve_context_.get(),
7408         resolve_context_->host_cache()));
7409     EXPECT_FALSE(response0.complete());
7410     proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3");
7411     ResolveHostResponseHelper response1(resolver_->CreateRequest(
7412         HostPortPair("slow_ok2", 80), NetworkAnonymizationKey(),
7413         NetLogWithSource(), parameters, resolve_context_.get(),
7414         resolve_context_->host_cache()));
7415     EXPECT_FALSE(response1.complete());
7416     proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4");
7417     ResolveHostResponseHelper response2(resolver_->CreateRequest(
7418         HostPortPair("slow_ok3", 80), NetworkAnonymizationKey(),
7419         NetLogWithSource(), parameters, resolve_context_.get(),
7420         resolve_context_->host_cache()));
7421     EXPECT_FALSE(response2.complete());
7422 
7423     // Requests specifying DNS source cannot fallback to HostResolverSystemTask,
7424     // so they should be unaffected.
7425     parameters.source = HostResolverSource::DNS;
7426     ResolveHostResponseHelper response_dns(resolver_->CreateRequest(
7427         HostPortPair("6slow_ok", 80), NetworkAnonymizationKey(),
7428         NetLogWithSource(), parameters, resolve_context_.get(),
7429         resolve_context_->host_cache()));
7430     EXPECT_FALSE(response_dns.complete());
7431 
7432     // Requests specifying SYSTEM source should be unaffected by disabling
7433     // DnsClient.
7434     proc_->AddRuleForAllFamilies("nx_ok", "192.168.0.5");
7435     parameters.source = HostResolverSource::SYSTEM;
7436     ResolveHostResponseHelper response_system(resolver_->CreateRequest(
7437         HostPortPair("nx_ok", 80), NetworkAnonymizationKey(),
7438         NetLogWithSource(), parameters, resolve_context_.get(),
7439         resolve_context_->host_cache()));
7440     EXPECT_FALSE(response_system.complete());
7441 
7442     // Secure DnsTasks should not be affected.
7443     ResolveHostResponseHelper response_secure(resolver_->CreateRequest(
7444         HostPortPair("automatic", 80), NetworkAnonymizationKey(),
7445         NetLogWithSource(), /* optional_parameters=*/absl::nullopt,
7446         resolve_context_.get(), resolve_context_->host_cache()));
7447     EXPECT_FALSE(response_secure.complete());
7448 
7449     proc_->SignalMultiple(maximum_insecure_dns_task_failures() + 4);
7450 
7451     for (size_t i = 0u; i < maximum_insecure_dns_task_failures(); ++i) {
7452       EXPECT_THAT(failure_responses[i]->result_error(), IsOk());
7453       EXPECT_THAT(
7454           failure_responses[i]->request()->GetAddressResults()->endpoints(),
7455           testing::ElementsAre(CreateExpected("192.168.0.1", 80)));
7456       EXPECT_THAT(
7457           failure_responses[i]->request()->GetEndpointResults(),
7458           testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7459               testing::ElementsAre(CreateExpected("192.168.0.1", 80))))));
7460     }
7461 
7462     EXPECT_THAT(response0.result_error(), IsOk());
7463     EXPECT_THAT(response0.request()->GetAddressResults()->endpoints(),
7464                 testing::ElementsAre(CreateExpected("192.168.0.2", 80)));
7465     EXPECT_THAT(response0.request()->GetEndpointResults(),
7466                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7467                     testing::ElementsAre(CreateExpected("192.168.0.2", 80))))));
7468     EXPECT_THAT(response1.result_error(), IsOk());
7469     EXPECT_THAT(response1.request()->GetAddressResults()->endpoints(),
7470                 testing::ElementsAre(CreateExpected("192.168.0.3", 80)));
7471     EXPECT_THAT(response1.request()->GetEndpointResults(),
7472                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7473                     testing::ElementsAre(CreateExpected("192.168.0.3", 80))))));
7474     EXPECT_THAT(response2.result_error(), IsOk());
7475     EXPECT_THAT(response2.request()->GetAddressResults()->endpoints(),
7476                 testing::ElementsAre(CreateExpected("192.168.0.4", 80)));
7477     EXPECT_THAT(response2.request()->GetEndpointResults(),
7478                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7479                     testing::ElementsAre(CreateExpected("192.168.0.4", 80))))));
7480 
7481     dns_client_->CompleteDelayedTransactions();
7482     EXPECT_THAT(response_dns.result_error(), IsOk());
7483 
7484     EXPECT_THAT(response_system.result_error(), IsOk());
7485     EXPECT_THAT(response_system.request()->GetAddressResults()->endpoints(),
7486                 testing::ElementsAre(CreateExpected("192.168.0.5", 80)));
7487     EXPECT_THAT(response_system.request()->GetEndpointResults(),
7488                 testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7489                     testing::ElementsAre(CreateExpected("192.168.0.5", 80))))));
7490 
7491     EXPECT_THAT(response_secure.result_error(), IsOk());
7492   }
7493 }
7494 
7495 // Tests a call to SetDnsClient while there are active DnsTasks.
TEST_F(HostResolverManagerDnsTest,ManuallyDisableDnsClientWithPendingRequests)7496 TEST_F(HostResolverManagerDnsTest,
7497        ManuallyDisableDnsClientWithPendingRequests) {
7498   // At most 3 jobs active at once.  This number is important, since we want to
7499   // make sure that aborting the first HostResolverManager::Job does not trigger
7500   // another DnsTransaction on the second Job when it releases its second
7501   // prioritized dispatcher slot.
7502   CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_),
7503                                     true /* ipv6_reachable */,
7504                                     true /* check_ipv6_on_wifi */);
7505 
7506   ChangeDnsConfig(CreateValidDnsConfig());
7507 
7508   proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.1");
7509   proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2");
7510   proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
7511 
7512   std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
7513   // First active job gets two slots.
7514   responses.emplace_back(
7515       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
7516           HostPortPair("slow_ok1", 80), NetworkAnonymizationKey(),
7517           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7518           resolve_context_->host_cache())));
7519   EXPECT_FALSE(responses[0]->complete());
7520   // Next job gets one slot, and waits on another.
7521   responses.emplace_back(
7522       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
7523           HostPortPair("slow_ok2", 80), NetworkAnonymizationKey(),
7524           NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7525           resolve_context_->host_cache())));
7526   EXPECT_FALSE(responses[1]->complete());
7527   // Next one is queued.
7528   responses.emplace_back(
7529       std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
7530           HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7531           absl::nullopt, resolve_context_.get(),
7532           resolve_context_->host_cache())));
7533   EXPECT_FALSE(responses[2]->complete());
7534 
7535   EXPECT_EQ(3u, num_running_dispatcher_jobs());
7536 
7537   // Clear DnsClient.  The two in-progress jobs should fall back to a
7538   // HostResolverSystemTask, and the next one should be started with a
7539   // HostResolverSystemTask.
7540   resolver_->SetInsecureDnsClientEnabled(
7541       /*enabled=*/false,
7542       /*additional_dns_types_enabled=*/false);
7543 
7544   // All three in-progress requests should now be running a
7545   // HostResolverSystemTask.
7546   EXPECT_EQ(3u, num_running_dispatcher_jobs());
7547   proc_->SignalMultiple(3u);
7548 
7549   for (auto& response : responses) {
7550     EXPECT_THAT(response->result_error(), IsOk());
7551   }
7552   EXPECT_THAT(responses[0]->request()->GetAddressResults()->endpoints(),
7553               testing::ElementsAre(CreateExpected("192.168.0.1", 80)));
7554   EXPECT_THAT(responses[0]->request()->GetEndpointResults(),
7555               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7556                   testing::ElementsAre(CreateExpected("192.168.0.1", 80))))));
7557   EXPECT_THAT(responses[1]->request()->GetAddressResults()->endpoints(),
7558               testing::ElementsAre(CreateExpected("192.168.0.2", 80)));
7559   EXPECT_THAT(responses[1]->request()->GetEndpointResults(),
7560               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7561                   testing::ElementsAre(CreateExpected("192.168.0.2", 80))))));
7562   EXPECT_THAT(responses[2]->request()->GetAddressResults()->endpoints(),
7563               testing::ElementsAre(CreateExpected("192.168.0.3", 80)));
7564   EXPECT_THAT(responses[2]->request()->GetEndpointResults(),
7565               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7566                   testing::ElementsAre(CreateExpected("192.168.0.3", 80))))));
7567 }
7568 
7569 // When explicitly requesting source=DNS, no fallback allowed, so doing so with
7570 // DnsClient disabled should result in an error.
TEST_F(HostResolverManagerDnsTest,DnsCallsWithDisabledDnsClient)7571 TEST_F(HostResolverManagerDnsTest, DnsCallsWithDisabledDnsClient) {
7572   ChangeDnsConfig(CreateValidDnsConfig());
7573   resolver_->SetInsecureDnsClientEnabled(
7574       /*enabled=*/false,
7575       /*additional_dns_types_enabled=*/false);
7576 
7577   HostResolver::ResolveHostParameters params;
7578   params.source = HostResolverSource::DNS;
7579   ResolveHostResponseHelper response(resolver_->CreateRequest(
7580       HostPortPair("host", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7581       params, resolve_context_.get(), resolve_context_->host_cache()));
7582 
7583   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_CACHE_MISS));
7584 }
7585 
TEST_F(HostResolverManagerDnsTest,DnsCallsWithDisabledDnsClient_DisabledAtConstruction)7586 TEST_F(HostResolverManagerDnsTest,
7587        DnsCallsWithDisabledDnsClient_DisabledAtConstruction) {
7588   HostResolver::ManagerOptions options = DefaultOptions();
7589   options.insecure_dns_client_enabled = false;
7590   CreateResolverWithOptionsAndParams(std::move(options), DefaultParams(proc_),
7591                                      true /* ipv6_reachable */);
7592   ChangeDnsConfig(CreateValidDnsConfig());
7593 
7594   HostResolver::ResolveHostParameters params;
7595   params.source = HostResolverSource::DNS;
7596   ResolveHostResponseHelper response(resolver_->CreateRequest(
7597       HostPortPair("host", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7598       params, resolve_context_.get(), resolve_context_->host_cache()));
7599 
7600   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_CACHE_MISS));
7601 }
7602 
7603 // Same as DnsClient disabled, requests with source=DNS and no usable DnsConfig
7604 // should result in an error.
TEST_F(HostResolverManagerDnsTest,DnsCallsWithNoDnsConfig)7605 TEST_F(HostResolverManagerDnsTest, DnsCallsWithNoDnsConfig) {
7606   InvalidateDnsConfig();
7607 
7608   HostResolver::ResolveHostParameters params;
7609   params.source = HostResolverSource::DNS;
7610   ResolveHostResponseHelper response(resolver_->CreateRequest(
7611       HostPortPair("host", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7612       params, resolve_context_.get(), resolve_context_->host_cache()));
7613 
7614   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_CACHE_MISS));
7615 }
7616 
TEST_F(HostResolverManagerDnsTest,NoCheckIpv6OnWifi)7617 TEST_F(HostResolverManagerDnsTest, NoCheckIpv6OnWifi) {
7618   // CreateSerialResolver will destroy the current resolver_ which will attempt
7619   // to remove itself from the NetworkChangeNotifier. If this happens after a
7620   // new NetworkChangeNotifier is active, then it will not remove itself from
7621   // the old NetworkChangeNotifier which is a potential use-after-free.
7622   DestroyResolver();
7623   test::ScopedMockNetworkChangeNotifier notifier;
7624   // Serial resolver to guarantee order of resolutions.
7625   CreateSerialResolver(false /* check_ipv6_on_wifi */);
7626 
7627   notifier.mock_network_change_notifier()->SetConnectionType(
7628       NetworkChangeNotifier::CONNECTION_WIFI);
7629   // Needed so IPv6 availability check isn't skipped.
7630   ChangeDnsConfig(CreateValidDnsConfig());
7631 
7632   proc_->AddRule("h1", ADDRESS_FAMILY_UNSPECIFIED, "::3");
7633   proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1");
7634   proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1",
7635                  HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
7636   proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2");
7637 
7638   ResolveHostResponseHelper response(resolver_->CreateRequest(
7639       HostPortPair("h1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7640       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7641   HostResolver::ResolveHostParameters parameters;
7642   parameters.dns_query_type = DnsQueryType::A;
7643   ResolveHostResponseHelper v4_response(resolver_->CreateRequest(
7644       HostPortPair("h1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7645       parameters, resolve_context_.get(), resolve_context_->host_cache()));
7646   parameters.dns_query_type = DnsQueryType::AAAA;
7647   ResolveHostResponseHelper v6_response(resolver_->CreateRequest(
7648       HostPortPair("h1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7649       parameters, resolve_context_.get(), resolve_context_->host_cache()));
7650 
7651   proc_->SignalMultiple(3u);
7652 
7653   // Should revert to only IPV4 request.
7654   EXPECT_THAT(response.result_error(), IsOk());
7655   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
7656               testing::ElementsAre(CreateExpected("1.0.0.1", 80)));
7657   EXPECT_THAT(response.request()->GetEndpointResults(),
7658               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7659                   testing::ElementsAre(CreateExpected("1.0.0.1", 80))))));
7660 
7661   EXPECT_THAT(v4_response.result_error(), IsOk());
7662   EXPECT_THAT(v4_response.request()->GetAddressResults()->endpoints(),
7663               testing::ElementsAre(CreateExpected("1.0.0.1", 80)));
7664   EXPECT_THAT(v4_response.request()->GetEndpointResults(),
7665               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7666                   testing::ElementsAre(CreateExpected("1.0.0.1", 80))))));
7667   EXPECT_THAT(v6_response.result_error(), IsOk());
7668   EXPECT_THAT(v6_response.request()->GetAddressResults()->endpoints(),
7669               testing::ElementsAre(CreateExpected("::2", 80)));
7670   EXPECT_THAT(v6_response.request()->GetEndpointResults(),
7671               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7672                   testing::ElementsAre(CreateExpected("::2", 80))))));
7673 
7674   // Now repeat the test on non-wifi to check that IPv6 is used as normal
7675   // after the network changes.
7676   notifier.mock_network_change_notifier()->SetConnectionType(
7677       NetworkChangeNotifier::CONNECTION_4G);
7678   base::RunLoop().RunUntilIdle();  // Wait for NetworkChangeNotifier.
7679 
7680   ResolveHostResponseHelper no_wifi_response(resolver_->CreateRequest(
7681       HostPortPair("h1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7682       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7683   parameters.dns_query_type = DnsQueryType::A;
7684   ResolveHostResponseHelper no_wifi_v4_response(resolver_->CreateRequest(
7685       HostPortPair("h1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7686       parameters, resolve_context_.get(), resolve_context_->host_cache()));
7687   parameters.dns_query_type = DnsQueryType::AAAA;
7688   ResolveHostResponseHelper no_wifi_v6_response(resolver_->CreateRequest(
7689       HostPortPair("h1", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7690       parameters, resolve_context_.get(), resolve_context_->host_cache()));
7691 
7692   proc_->SignalMultiple(3u);
7693 
7694   // IPV6 should be available.
7695   EXPECT_THAT(no_wifi_response.result_error(), IsOk());
7696   EXPECT_THAT(no_wifi_response.request()->GetAddressResults()->endpoints(),
7697               testing::ElementsAre(CreateExpected("::3", 80)));
7698   EXPECT_THAT(no_wifi_response.request()->GetEndpointResults(),
7699               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7700                   testing::ElementsAre(CreateExpected("::3", 80))))));
7701 
7702   EXPECT_THAT(no_wifi_v4_response.result_error(), IsOk());
7703   EXPECT_THAT(no_wifi_v4_response.request()->GetAddressResults()->endpoints(),
7704               testing::ElementsAre(CreateExpected("1.0.0.1", 80)));
7705   EXPECT_THAT(no_wifi_v4_response.request()->GetEndpointResults(),
7706               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7707                   testing::ElementsAre(CreateExpected("1.0.0.1", 80))))));
7708   EXPECT_THAT(no_wifi_v6_response.result_error(), IsOk());
7709   EXPECT_THAT(no_wifi_v6_response.request()->GetAddressResults()->endpoints(),
7710               testing::ElementsAre(CreateExpected("::2", 80)));
7711   EXPECT_THAT(no_wifi_v6_response.request()->GetEndpointResults(),
7712               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
7713                   testing::ElementsAre(CreateExpected("::2", 80))))));
7714 }
7715 
TEST_F(HostResolverManagerDnsTest,NotFoundTTL)7716 TEST_F(HostResolverManagerDnsTest, NotFoundTTL) {
7717   CreateResolver();
7718   set_allow_fallback_to_systemtask(false);
7719   ChangeDnsConfig(CreateValidDnsConfig());
7720 
7721   // NODATA
7722   ResolveHostResponseHelper no_data_response(resolver_->CreateRequest(
7723       HostPortPair("empty", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7724       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
7725   EXPECT_THAT(no_data_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
7726   EXPECT_FALSE(no_data_response.request()->GetAddressResults());
7727   EXPECT_FALSE(no_data_response.request()->GetEndpointResults());
7728   HostCache::Key key("empty", DnsQueryType::UNSPECIFIED, 0,
7729                      HostResolverSource::ANY, NetworkAnonymizationKey());
7730   HostCache::EntryStaleness staleness;
7731   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
7732       resolve_context_->host_cache()->Lookup(key, base::TimeTicks::Now(),
7733                                              false /* ignore_secure */);
7734   EXPECT_TRUE(!!cache_result);
7735   EXPECT_TRUE(cache_result->second.has_ttl());
7736   EXPECT_THAT(cache_result->second.ttl(), base::Seconds(86400));
7737 
7738   // NXDOMAIN
7739   ResolveHostResponseHelper no_domain_response(resolver_->CreateRequest(
7740       HostPortPair("nodomain", 80), NetworkAnonymizationKey(),
7741       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7742       resolve_context_->host_cache()));
7743   EXPECT_THAT(no_domain_response.result_error(),
7744               IsError(ERR_NAME_NOT_RESOLVED));
7745   EXPECT_FALSE(no_domain_response.request()->GetAddressResults());
7746   EXPECT_FALSE(no_domain_response.request()->GetEndpointResults());
7747   HostCache::Key nxkey("nodomain", DnsQueryType::UNSPECIFIED, 0,
7748                        HostResolverSource::ANY, NetworkAnonymizationKey());
7749   cache_result = resolve_context_->host_cache()->Lookup(
7750       nxkey, base::TimeTicks::Now(), false /* ignore_secure */);
7751   EXPECT_TRUE(!!cache_result);
7752   EXPECT_TRUE(cache_result->second.has_ttl());
7753   EXPECT_THAT(cache_result->second.ttl(), base::Seconds(86400));
7754 }
7755 
TEST_F(HostResolverManagerDnsTest,CachedError)7756 TEST_F(HostResolverManagerDnsTest, CachedError) {
7757   proc_->AddRuleForAllFamilies(std::string(),
7758                                "0.0.0.1");  // Default to failures.
7759   proc_->SignalMultiple(1u);
7760 
7761   CreateResolver();
7762   set_allow_fallback_to_systemtask(true);
7763   ChangeDnsConfig(CreateValidDnsConfig());
7764 
7765   HostResolver::ResolveHostParameters cache_only_parameters;
7766   cache_only_parameters.source = HostResolverSource::LOCAL_ONLY;
7767 
7768   // Expect cache initially empty.
7769   ResolveHostResponseHelper cache_miss_response0(resolver_->CreateRequest(
7770       HostPortPair("nodomain", 80), NetworkAnonymizationKey(),
7771       NetLogWithSource(), cache_only_parameters, resolve_context_.get(),
7772       resolve_context_->host_cache()));
7773   EXPECT_THAT(cache_miss_response0.result_error(), IsError(ERR_DNS_CACHE_MISS));
7774   EXPECT_FALSE(cache_miss_response0.request()->GetStaleInfo());
7775 
7776   // The cache should not be populate with an error because fallback to
7777   // HostResolverSystemTask was available.
7778   ResolveHostResponseHelper no_domain_response_with_fallback(
7779       resolver_->CreateRequest(HostPortPair("nodomain", 80),
7780                                NetworkAnonymizationKey(), NetLogWithSource(),
7781                                absl::nullopt, resolve_context_.get(),
7782                                resolve_context_->host_cache()));
7783   EXPECT_THAT(no_domain_response_with_fallback.result_error(),
7784               IsError(ERR_NAME_NOT_RESOLVED));
7785 
7786   // Expect cache still empty.
7787   ResolveHostResponseHelper cache_miss_response1(resolver_->CreateRequest(
7788       HostPortPair("nodomain", 80), NetworkAnonymizationKey(),
7789       NetLogWithSource(), cache_only_parameters, resolve_context_.get(),
7790       resolve_context_->host_cache()));
7791   EXPECT_THAT(cache_miss_response1.result_error(), IsError(ERR_DNS_CACHE_MISS));
7792   EXPECT_FALSE(cache_miss_response1.request()->GetStaleInfo());
7793 
7794   // Disable fallback to systemtask
7795   set_allow_fallback_to_systemtask(false);
7796 
7797   // Populate cache with an error.
7798   ResolveHostResponseHelper no_domain_response(resolver_->CreateRequest(
7799       HostPortPair("nodomain", 80), NetworkAnonymizationKey(),
7800       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7801       resolve_context_->host_cache()));
7802   EXPECT_THAT(no_domain_response.result_error(),
7803               IsError(ERR_NAME_NOT_RESOLVED));
7804 
7805   // Expect the error result can be resolved from the cache.
7806   ResolveHostResponseHelper cache_hit_response(resolver_->CreateRequest(
7807       HostPortPair("nodomain", 80), NetworkAnonymizationKey(),
7808       NetLogWithSource(), cache_only_parameters, resolve_context_.get(),
7809       resolve_context_->host_cache()));
7810   EXPECT_THAT(cache_hit_response.result_error(),
7811               IsError(ERR_NAME_NOT_RESOLVED));
7812   EXPECT_FALSE(cache_hit_response.request()->GetStaleInfo().value().is_stale());
7813 }
7814 
TEST_F(HostResolverManagerDnsTest,CachedError_AutomaticMode)7815 TEST_F(HostResolverManagerDnsTest, CachedError_AutomaticMode) {
7816   CreateResolver();
7817   set_allow_fallback_to_systemtask(false);
7818   ChangeDnsConfig(CreateValidDnsConfig());
7819 
7820   // Switch to automatic mode.
7821   DnsConfigOverrides overrides;
7822   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
7823   resolver_->SetDnsConfigOverrides(overrides);
7824 
7825   HostCache::Key insecure_key =
7826       HostCache::Key("automatic_nodomain", DnsQueryType::UNSPECIFIED,
7827                      0 /* host_resolver_flags */, HostResolverSource::ANY,
7828                      NetworkAnonymizationKey());
7829   HostCache::Key secure_key =
7830       HostCache::Key("automatic_nodomain", DnsQueryType::UNSPECIFIED,
7831                      0 /* host_resolver_flags */, HostResolverSource::ANY,
7832                      NetworkAnonymizationKey());
7833   secure_key.secure = true;
7834 
7835   // Expect cache initially empty.
7836   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
7837   cache_result = GetCacheHit(secure_key);
7838   EXPECT_FALSE(!!cache_result);
7839   cache_result = GetCacheHit(insecure_key);
7840   EXPECT_FALSE(!!cache_result);
7841 
7842   // Populate both secure and insecure caches with an error.
7843   ResolveHostResponseHelper no_domain_response(resolver_->CreateRequest(
7844       HostPortPair("automatic_nodomain", 80), NetworkAnonymizationKey(),
7845       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7846       resolve_context_->host_cache()));
7847   EXPECT_THAT(no_domain_response.result_error(),
7848               IsError(ERR_NAME_NOT_RESOLVED));
7849 
7850   // Expect both secure and insecure caches to have the error result.
7851   cache_result = GetCacheHit(secure_key);
7852   EXPECT_TRUE(!!cache_result);
7853   cache_result = GetCacheHit(insecure_key);
7854   EXPECT_TRUE(!!cache_result);
7855 }
7856 
TEST_F(HostResolverManagerDnsTest,CachedError_SecureMode)7857 TEST_F(HostResolverManagerDnsTest, CachedError_SecureMode) {
7858   CreateResolver();
7859   set_allow_fallback_to_systemtask(false);
7860   ChangeDnsConfig(CreateValidDnsConfig());
7861 
7862   // Switch to secure mode.
7863   DnsConfigOverrides overrides;
7864   overrides.secure_dns_mode = SecureDnsMode::kSecure;
7865   resolver_->SetDnsConfigOverrides(overrides);
7866 
7867   HostCache::Key insecure_key =
7868       HostCache::Key("automatic_nodomain", DnsQueryType::UNSPECIFIED,
7869                      0 /* host_resolver_flags */, HostResolverSource::ANY,
7870                      NetworkAnonymizationKey());
7871   HostCache::Key secure_key =
7872       HostCache::Key("automatic_nodomain", DnsQueryType::UNSPECIFIED,
7873                      0 /* host_resolver_flags */, HostResolverSource::ANY,
7874                      NetworkAnonymizationKey());
7875   secure_key.secure = true;
7876 
7877   // Expect cache initially empty.
7878   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result;
7879   cache_result = GetCacheHit(secure_key);
7880   EXPECT_FALSE(!!cache_result);
7881   cache_result = GetCacheHit(insecure_key);
7882   EXPECT_FALSE(!!cache_result);
7883 
7884   // Populate secure cache with an error.
7885   ResolveHostResponseHelper no_domain_response(resolver_->CreateRequest(
7886       HostPortPair("automatic_nodomain", 80), NetworkAnonymizationKey(),
7887       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
7888       resolve_context_->host_cache()));
7889   EXPECT_THAT(no_domain_response.result_error(),
7890               IsError(ERR_NAME_NOT_RESOLVED));
7891 
7892   // Expect only the secure cache to have the error result.
7893   cache_result = GetCacheHit(secure_key);
7894   EXPECT_TRUE(!!cache_result);
7895   cache_result = GetCacheHit(insecure_key);
7896   EXPECT_FALSE(!!cache_result);
7897 }
7898 
7899 // Test that if one of A and AAAA completes successfully and the other fails,
7900 // the failure is not cached.
TEST_F(HostResolverManagerDnsTest,TtlNotSharedBetweenQtypes)7901 TEST_F(HostResolverManagerDnsTest, TtlNotSharedBetweenQtypes) {
7902   CreateResolver();
7903   set_allow_fallback_to_systemtask(false);
7904   ChangeDnsConfig(CreateValidDnsConfig());
7905 
7906   ResolveHostResponseHelper response(resolver_->CreateRequest(
7907       HostPortPair("4slow_4timeout", 80), NetworkAnonymizationKey(),
7908       NetLogWithSource(), absl::nullopt /* optional_parameters */,
7909       resolve_context_.get(), resolve_context_->host_cache()));
7910 
7911   // Ensure success completes before the timeout result.
7912   base::RunLoop().RunUntilIdle();
7913   EXPECT_FALSE(response.complete());
7914 
7915   dns_client_->CompleteDelayedTransactions();
7916   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_TIMED_OUT));
7917 
7918   // Expect failure not cached.
7919   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
7920 }
7921 
TEST_F(HostResolverManagerDnsTest,CanonicalName)7922 TEST_F(HostResolverManagerDnsTest, CanonicalName) {
7923   MockDnsClientRuleList rules;
7924   AddDnsRule(&rules, "alias", dns_protocol::kTypeA, IPAddress::IPv4Localhost(),
7925              "canonical", false /* delay */);
7926   AddDnsRule(&rules, "alias", dns_protocol::kTypeAAAA,
7927              IPAddress::IPv6Localhost(), "canonical", false /* delay */);
7928 
7929   CreateResolver();
7930   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
7931   set_allow_fallback_to_systemtask(false);
7932 
7933   HostResolver::ResolveHostParameters params;
7934   params.source = HostResolverSource::DNS;
7935   ResolveHostResponseHelper response(resolver_->CreateRequest(
7936       HostPortPair("alias", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7937       params, resolve_context_.get(), resolve_context_->host_cache()));
7938   ASSERT_THAT(response.result_error(), IsOk());
7939 
7940   EXPECT_THAT(
7941       response.request()->GetDnsAliasResults(),
7942       testing::Pointee(testing::UnorderedElementsAre("canonical", "alias")));
7943 }
7944 
TEST_F(HostResolverManagerDnsTest,CanonicalName_PreferV6)7945 TEST_F(HostResolverManagerDnsTest, CanonicalName_PreferV6) {
7946   MockDnsClientRuleList rules;
7947   AddDnsRule(&rules, "alias", dns_protocol::kTypeA, IPAddress::IPv4Localhost(),
7948              "wrong", false /* delay */);
7949   AddDnsRule(&rules, "alias", dns_protocol::kTypeAAAA,
7950              IPAddress::IPv6Localhost(), "correct", true /* delay */);
7951 
7952   CreateResolver();
7953   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
7954   set_allow_fallback_to_systemtask(false);
7955 
7956   HostResolver::ResolveHostParameters params;
7957   params.source = HostResolverSource::DNS;
7958   ResolveHostResponseHelper response(resolver_->CreateRequest(
7959       HostPortPair("alias", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7960       params, resolve_context_.get(), resolve_context_->host_cache()));
7961   ASSERT_FALSE(response.complete());
7962   base::RunLoop().RunUntilIdle();
7963   dns_client_->CompleteDelayedTransactions();
7964   ASSERT_THAT(response.result_error(), IsOk());
7965 
7966   // GetDnsAliasResults() includes all aliases from all families.
7967   EXPECT_THAT(response.request()->GetDnsAliasResults(),
7968               testing::Pointee(
7969                   testing::UnorderedElementsAre("correct", "alias", "wrong")));
7970 }
7971 
TEST_F(HostResolverManagerDnsTest,CanonicalName_V4Only)7972 TEST_F(HostResolverManagerDnsTest, CanonicalName_V4Only) {
7973   MockDnsClientRuleList rules;
7974   AddDnsRule(&rules, "alias", dns_protocol::kTypeA, IPAddress::IPv4Localhost(),
7975              "correct", false /* delay */);
7976   CreateResolver();
7977   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
7978   set_allow_fallback_to_systemtask(false);
7979 
7980   HostResolver::ResolveHostParameters params;
7981   params.dns_query_type = DnsQueryType::A;
7982   params.source = HostResolverSource::DNS;
7983   ResolveHostResponseHelper response(resolver_->CreateRequest(
7984       HostPortPair("alias", 80), NetworkAnonymizationKey(), NetLogWithSource(),
7985       params, resolve_context_.get(), resolve_context_->host_cache()));
7986   ASSERT_THAT(response.result_error(), IsOk());
7987   EXPECT_THAT(
7988       response.request()->GetDnsAliasResults(),
7989       testing::Pointee(testing::UnorderedElementsAre("correct", "alias")));
7990 }
7991 
7992 // Test that responses containing CNAME records but no address results are fine
7993 // and treated as normal NODATA responses.
TEST_F(HostResolverManagerDnsTest,CanonicalNameWithoutResults)7994 TEST_F(HostResolverManagerDnsTest, CanonicalNameWithoutResults) {
7995   MockDnsClientRuleList rules;
7996 
7997   DnsResponse a_response =
7998       BuildTestDnsResponse("a.test", dns_protocol::kTypeA,
7999                            {BuildTestCnameRecord("c.test", "d.test"),
8000                             BuildTestCnameRecord("b.test", "c.test"),
8001                             BuildTestCnameRecord("a.test", "b.test")});
8002   AddDnsRule(&rules, "a.test", dns_protocol::kTypeA, std::move(a_response),
8003              /*delay=*/false);
8004 
8005   DnsResponse aaaa_response =
8006       BuildTestDnsResponse("a.test", dns_protocol::kTypeAAAA,
8007                            {BuildTestCnameRecord("c.test", "d.test"),
8008                             BuildTestCnameRecord("b.test", "c.test"),
8009                             BuildTestCnameRecord("a.test", "b.test")});
8010   AddDnsRule(&rules, "a.test", dns_protocol::kTypeAAAA,
8011              std::move(aaaa_response), /*delay=*/false);
8012 
8013   CreateResolver();
8014   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
8015   set_allow_fallback_to_systemtask(false);
8016 
8017   ResolveHostResponseHelper response(resolver_->CreateRequest(
8018       HostPortPair("a.test", 80), NetworkAnonymizationKey(), NetLogWithSource(),
8019       /*optional_parameters=*/absl::nullopt, resolve_context_.get(),
8020       resolve_context_->host_cache()));
8021 
8022   ASSERT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
8023   EXPECT_FALSE(response.request()->GetDnsAliasResults());
8024 
8025   // Underlying error should be the typical no-results error
8026   // (ERR_NAME_NOT_RESOLVED), not anything more exotic like
8027   // ERR_DNS_MALFORMED_RESPONSE.
8028   EXPECT_EQ(response.request()->GetResolveErrorInfo().error,
8029             ERR_NAME_NOT_RESOLVED);
8030 }
8031 
8032 // Test that if the response for one address family contains CNAME records but
8033 // no address results, it doesn't interfere with the other address family
8034 // receiving address results (as would happen if such a response were
8035 // incorrectly treated as a malformed response error).
TEST_F(HostResolverManagerDnsTest,CanonicalNameWithResultsForOnlyOneFamily)8036 TEST_F(HostResolverManagerDnsTest, CanonicalNameWithResultsForOnlyOneFamily) {
8037   MockDnsClientRuleList rules;
8038 
8039   DnsResponse a_response =
8040       BuildTestDnsResponse("a.test", dns_protocol::kTypeA,
8041                            {BuildTestCnameRecord("c.test", "d.test"),
8042                             BuildTestCnameRecord("b.test", "c.test"),
8043                             BuildTestCnameRecord("a.test", "b.test")});
8044   AddDnsRule(&rules, "a.test", dns_protocol::kTypeA, std::move(a_response),
8045              /*delay=*/false);
8046 
8047   DnsResponse aaaa_response = BuildTestDnsResponse(
8048       "a.test", dns_protocol::kTypeAAAA,
8049       {BuildTestAddressRecord("d.test", IPAddress::IPv6Localhost()),
8050        BuildTestCnameRecord("c.test", "d.test"),
8051        BuildTestCnameRecord("b.test", "c.test"),
8052        BuildTestCnameRecord("a.test", "b.test")});
8053   AddDnsRule(&rules, "a.test", dns_protocol::kTypeAAAA,
8054              std::move(aaaa_response), /*delay=*/false);
8055 
8056   CreateResolver();
8057   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
8058 
8059   ResolveHostResponseHelper response(resolver_->CreateRequest(
8060       HostPortPair("a.test", 80), NetworkAnonymizationKey(), NetLogWithSource(),
8061       /*optional_parameters=*/absl::nullopt, resolve_context_.get(),
8062       resolve_context_->host_cache()));
8063 
8064   ASSERT_THAT(response.result_error(), IsOk());
8065 
8066   ASSERT_TRUE(response.request()->GetAddressResults());
8067   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
8068               testing::ElementsAre(IPEndPoint(IPAddress::IPv6Localhost(), 80)));
8069   EXPECT_THAT(
8070       response.request()->GetEndpointResults(),
8071       testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
8072           testing::ElementsAre(IPEndPoint(IPAddress::IPv6Localhost(), 80))))));
8073 }
8074 
8075 // Test that without specifying source, a request that would otherwise be
8076 // handled by DNS is sent to the system resolver if cannonname is requested.
TEST_F(HostResolverManagerDnsTest,CanonicalNameForcesProc)8077 TEST_F(HostResolverManagerDnsTest, CanonicalNameForcesProc) {
8078   // Disable fallback to ensure system resolver is used directly, not via
8079   // fallback.
8080   set_allow_fallback_to_systemtask(false);
8081 
8082   proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102",
8083                                HOST_RESOLVER_CANONNAME, "canonical");
8084   proc_->SignalMultiple(1u);
8085 
8086   ChangeDnsConfig(CreateValidDnsConfig());
8087 
8088   HostResolver::ResolveHostParameters params;
8089   params.include_canonical_name = true;
8090   ResolveHostResponseHelper response(resolver_->CreateRequest(
8091       HostPortPair("nx_succeed", 80), NetworkAnonymizationKey(),
8092       NetLogWithSource(), params, resolve_context_.get(),
8093       resolve_context_->host_cache()));
8094   ASSERT_THAT(response.result_error(), IsOk());
8095 
8096   EXPECT_THAT(response.request()->GetDnsAliasResults(),
8097               testing::Pointee(testing::UnorderedElementsAre("canonical")));
8098 }
8099 
TEST_F(HostResolverManagerDnsTest,DnsAliases)8100 TEST_F(HostResolverManagerDnsTest, DnsAliases) {
8101   MockDnsClientRuleList rules;
8102 
8103   DnsResponse expected_A_response = BuildTestDnsResponse(
8104       "first.test", dns_protocol::kTypeA,
8105       {BuildTestAddressRecord("fourth.test", IPAddress::IPv4Localhost()),
8106        BuildTestCnameRecord("third.test", "fourth.test"),
8107        BuildTestCnameRecord("second.test", "third.test"),
8108        BuildTestCnameRecord("first.test", "second.test")});
8109 
8110   AddDnsRule(&rules, "first.test", dns_protocol::kTypeA,
8111              std::move(expected_A_response), false /* delay */);
8112 
8113   DnsResponse expected_AAAA_response = BuildTestDnsResponse(
8114       "first.test", dns_protocol::kTypeAAAA,
8115       {BuildTestAddressRecord("fourth.test", IPAddress::IPv6Localhost()),
8116        BuildTestCnameRecord("third.test", "fourth.test"),
8117        BuildTestCnameRecord("second.test", "third.test"),
8118        BuildTestCnameRecord("first.test", "second.test")});
8119 
8120   AddDnsRule(&rules, "first.test", dns_protocol::kTypeAAAA,
8121              std::move(expected_AAAA_response), false /* delay */);
8122 
8123   CreateResolver();
8124   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
8125   set_allow_fallback_to_systemtask(false);
8126   HostResolver::ResolveHostParameters params;
8127   params.source = HostResolverSource::DNS;
8128 
8129   ResolveHostResponseHelper response(resolver_->CreateRequest(
8130       HostPortPair("first.test", 80), NetworkAnonymizationKey(),
8131       NetLogWithSource(), params, resolve_context_.get(),
8132       resolve_context_->host_cache()));
8133 
8134   ASSERT_THAT(response.result_error(), IsOk());
8135   ASSERT_TRUE(response.request()->GetAddressResults());
8136   EXPECT_THAT(response.request()->GetAddressResults()->dns_aliases(),
8137               testing::UnorderedElementsAre("fourth.test", "third.test",
8138                                             "second.test", "first.test"));
8139 
8140   EXPECT_THAT(response.request()->GetDnsAliasResults(),
8141               testing::Pointee(testing::UnorderedElementsAre(
8142                   "fourth.test", "third.test", "second.test", "first.test")));
8143 }
8144 
TEST_F(HostResolverManagerDnsTest,DnsAliasesAreFixedUp)8145 TEST_F(HostResolverManagerDnsTest, DnsAliasesAreFixedUp) {
8146   MockDnsClientRuleList rules;
8147 
8148   // Need to manually encode non-URL-canonical names because DNSDomainFromDot()
8149   // requires URL-canonical names.
8150   constexpr char kNonCanonicalName[] = "\005HOST2\004test\000";
8151 
8152   DnsResponse expected_A_response = BuildTestDnsResponse(
8153       "host.test", dns_protocol::kTypeA,
8154       {BuildTestAddressRecord("localhost", IPAddress::IPv4Localhost()),
8155        BuildTestCnameRecord("host2.test", "localhost"),
8156        BuildTestDnsRecord(
8157            "host.test", dns_protocol::kTypeCNAME,
8158            std::string(kNonCanonicalName, sizeof(kNonCanonicalName) - 1))});
8159 
8160   AddDnsRule(&rules, "host.test", dns_protocol::kTypeA,
8161              std::move(expected_A_response), false /* delay */);
8162 
8163   DnsResponse expected_AAAA_response = BuildTestDnsResponse(
8164       "host.test", dns_protocol::kTypeAAAA,
8165       {BuildTestAddressRecord("localhost", IPAddress::IPv6Localhost()),
8166        BuildTestCnameRecord("host2.test", "localhost"),
8167        BuildTestDnsRecord(
8168            "host.test", dns_protocol::kTypeCNAME,
8169            std::string(kNonCanonicalName, sizeof(kNonCanonicalName) - 1))});
8170 
8171   AddDnsRule(&rules, "host.test", dns_protocol::kTypeAAAA,
8172              std::move(expected_AAAA_response), false /* delay */);
8173 
8174   CreateResolver();
8175   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
8176   set_allow_fallback_to_systemtask(false);
8177   HostResolver::ResolveHostParameters params;
8178   params.source = HostResolverSource::DNS;
8179 
8180   ResolveHostResponseHelper response(resolver_->CreateRequest(
8181       HostPortPair("host.test", 80), NetworkAnonymizationKey(),
8182       NetLogWithSource(), params, resolve_context_.get(),
8183       resolve_context_->host_cache()));
8184 
8185   ASSERT_THAT(response.result_error(), IsOk());
8186   ASSERT_TRUE(response.request()->GetAddressResults());
8187   // AddressList results may or may not be fixed, depending on whether or not
8188   // they were built from endpoint results.
8189   EXPECT_THAT(
8190       response.request()->GetAddressResults()->dns_aliases(),
8191       testing::AnyOf(testing::UnorderedElementsAre("host2.test", "host.test"),
8192                      testing::UnorderedElementsAre("localhost", "HOST2.test",
8193                                                    "host.test")));
8194   EXPECT_THAT(response.request()->GetDnsAliasResults(),
8195               testing::Pointee(
8196                   testing::UnorderedElementsAre("host2.test", "host.test")));
8197 }
8198 
TEST_F(HostResolverManagerDnsTest,NoAdditionalDnsAliases)8199 TEST_F(HostResolverManagerDnsTest, NoAdditionalDnsAliases) {
8200   MockDnsClientRuleList rules;
8201 
8202   AddDnsRule(&rules, "first.test", dns_protocol::kTypeA,
8203              IPAddress::IPv4Localhost(), false /* delay */);
8204 
8205   AddDnsRule(&rules, "first.test", dns_protocol::kTypeAAAA,
8206              IPAddress::IPv6Localhost(), false /* delay */);
8207 
8208   CreateResolver();
8209   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
8210   set_allow_fallback_to_systemtask(false);
8211   HostResolver::ResolveHostParameters params;
8212   params.source = HostResolverSource::DNS;
8213 
8214   ResolveHostResponseHelper response(resolver_->CreateRequest(
8215       HostPortPair("first.test", 80), NetworkAnonymizationKey(),
8216       NetLogWithSource(), params, resolve_context_.get(),
8217       resolve_context_->host_cache()));
8218 
8219   ASSERT_THAT(response.result_error(), IsOk());
8220   ASSERT_TRUE(response.request()->GetAddressResults());
8221   EXPECT_THAT(response.request()->GetAddressResults()->dns_aliases(),
8222               testing::ElementsAre("first.test"));
8223   EXPECT_THAT(response.request()->GetDnsAliasResults(),
8224               testing::Pointee(testing::UnorderedElementsAre("first.test")));
8225 }
8226 
TEST_F(HostResolverManagerTest,ResolveLocalHostname)8227 TEST_F(HostResolverManagerTest, ResolveLocalHostname) {
8228   std::vector<IPEndPoint> addresses;
8229 
8230   TestBothLoopbackIPs("localhost");
8231   TestBothLoopbackIPs("localhoST");
8232   TestBothLoopbackIPs("localhost.");
8233   TestBothLoopbackIPs("localhoST.");
8234   TestBothLoopbackIPs("foo.localhost");
8235   TestBothLoopbackIPs("foo.localhOSt");
8236   TestBothLoopbackIPs("foo.localhost.");
8237   TestBothLoopbackIPs("foo.localhOSt.");
8238 
8239   // Legacy localhost names.
8240   EXPECT_FALSE(ResolveLocalHostname("localhost.localdomain", &addresses));
8241   EXPECT_FALSE(ResolveLocalHostname("localhost.localdomAIn", &addresses));
8242   EXPECT_FALSE(ResolveLocalHostname("localhost.localdomain.", &addresses));
8243   EXPECT_FALSE(ResolveLocalHostname("localhost.localdomAIn.", &addresses));
8244   EXPECT_FALSE(ResolveLocalHostname("localhost6", &addresses));
8245   EXPECT_FALSE(ResolveLocalHostname("localhoST6", &addresses));
8246   EXPECT_FALSE(ResolveLocalHostname("localhost6.", &addresses));
8247   EXPECT_FALSE(ResolveLocalHostname("localhost6.localdomain6", &addresses));
8248   EXPECT_FALSE(ResolveLocalHostname("localhost6.localdomain6.", &addresses));
8249 
8250   EXPECT_FALSE(ResolveLocalHostname("127.0.0.1", &addresses));
8251   EXPECT_FALSE(ResolveLocalHostname("::1", &addresses));
8252   EXPECT_FALSE(ResolveLocalHostname("0:0:0:0:0:0:0:1", &addresses));
8253   EXPECT_FALSE(ResolveLocalHostname("localhostx", &addresses));
8254   EXPECT_FALSE(ResolveLocalHostname("localhost.x", &addresses));
8255   EXPECT_FALSE(ResolveLocalHostname("foo.localdomain", &addresses));
8256   EXPECT_FALSE(ResolveLocalHostname("foo.localdomain.x", &addresses));
8257   EXPECT_FALSE(ResolveLocalHostname("localhost6x", &addresses));
8258   EXPECT_FALSE(ResolveLocalHostname("localhost.localdomain6", &addresses));
8259   EXPECT_FALSE(ResolveLocalHostname("localhost6.localdomain", &addresses));
8260   EXPECT_FALSE(ResolveLocalHostname("127.0.0.1.1", &addresses));
8261   EXPECT_FALSE(ResolveLocalHostname(".127.0.0.255", &addresses));
8262   EXPECT_FALSE(ResolveLocalHostname("::2", &addresses));
8263   EXPECT_FALSE(ResolveLocalHostname("::1:1", &addresses));
8264   EXPECT_FALSE(ResolveLocalHostname("0:0:0:0:1:0:0:1", &addresses));
8265   EXPECT_FALSE(ResolveLocalHostname("::1:1", &addresses));
8266   EXPECT_FALSE(ResolveLocalHostname("0:0:0:0:0:0:0:0:1", &addresses));
8267   EXPECT_FALSE(ResolveLocalHostname("foo.localhost.com", &addresses));
8268   EXPECT_FALSE(ResolveLocalHostname("foo.localhoste", &addresses));
8269 }
8270 
TEST_F(HostResolverManagerDnsTest,AddDnsOverHttpsServerAfterConfig)8271 TEST_F(HostResolverManagerDnsTest, AddDnsOverHttpsServerAfterConfig) {
8272   DestroyResolver();
8273   test::ScopedMockNetworkChangeNotifier notifier;
8274   CreateSerialResolver();  // To guarantee order of resolutions.
8275   notifier.mock_network_change_notifier()->SetConnectionType(
8276       NetworkChangeNotifier::CONNECTION_WIFI);
8277   ChangeDnsConfig(CreateValidDnsConfig());
8278 
8279   std::string server("https://dnsserver.example.net/dns-query{?dns}");
8280   DnsConfigOverrides overrides;
8281   overrides.dns_over_https_config = *DnsOverHttpsConfig::FromString(server);
8282   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
8283   resolver_->SetDnsConfigOverrides(overrides);
8284   const auto* config = dns_client_->GetEffectiveConfig();
8285   ASSERT_TRUE(config);
8286   EXPECT_EQ(overrides.dns_over_https_config, config->doh_config);
8287   EXPECT_EQ(SecureDnsMode::kAutomatic, config->secure_dns_mode);
8288 }
8289 
TEST_F(HostResolverManagerDnsTest,AddDnsOverHttpsServerBeforeConfig)8290 TEST_F(HostResolverManagerDnsTest, AddDnsOverHttpsServerBeforeConfig) {
8291   DestroyResolver();
8292   test::ScopedMockNetworkChangeNotifier notifier;
8293   CreateSerialResolver();  // To guarantee order of resolutions.
8294   std::string server("https://dnsserver.example.net/dns-query{?dns}");
8295   DnsConfigOverrides overrides;
8296   overrides.dns_over_https_config = *DnsOverHttpsConfig::FromString(server);
8297   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
8298   resolver_->SetDnsConfigOverrides(overrides);
8299 
8300   notifier.mock_network_change_notifier()->SetConnectionType(
8301       NetworkChangeNotifier::CONNECTION_WIFI);
8302   ChangeDnsConfig(CreateValidDnsConfig());
8303 
8304   const auto* config = dns_client_->GetEffectiveConfig();
8305   ASSERT_TRUE(config);
8306   EXPECT_EQ(overrides.dns_over_https_config, config->doh_config);
8307   EXPECT_EQ(SecureDnsMode::kAutomatic, config->secure_dns_mode);
8308 }
8309 
TEST_F(HostResolverManagerDnsTest,AddDnsOverHttpsServerBeforeClient)8310 TEST_F(HostResolverManagerDnsTest, AddDnsOverHttpsServerBeforeClient) {
8311   DestroyResolver();
8312   test::ScopedMockNetworkChangeNotifier notifier;
8313   CreateSerialResolver();  // To guarantee order of resolutions.
8314   std::string server("https://dnsserver.example.net/dns-query{?dns}");
8315   DnsConfigOverrides overrides;
8316   overrides.dns_over_https_config = *DnsOverHttpsConfig::FromString(server);
8317   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
8318   resolver_->SetDnsConfigOverrides(overrides);
8319 
8320   notifier.mock_network_change_notifier()->SetConnectionType(
8321       NetworkChangeNotifier::CONNECTION_WIFI);
8322   ChangeDnsConfig(CreateValidDnsConfig());
8323 
8324   const auto* config = dns_client_->GetEffectiveConfig();
8325   ASSERT_TRUE(config);
8326   EXPECT_EQ(overrides.dns_over_https_config, config->doh_config);
8327   EXPECT_EQ(SecureDnsMode::kAutomatic, config->secure_dns_mode);
8328 }
8329 
TEST_F(HostResolverManagerDnsTest,AddDnsOverHttpsServerAndThenRemove)8330 TEST_F(HostResolverManagerDnsTest, AddDnsOverHttpsServerAndThenRemove) {
8331   DestroyResolver();
8332   test::ScopedMockNetworkChangeNotifier notifier;
8333   CreateSerialResolver();  // To guarantee order of resolutions.
8334   std::string server("https://dns.example.com/");
8335   DnsConfigOverrides overrides;
8336   overrides.dns_over_https_config = *DnsOverHttpsConfig::FromString(server);
8337   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
8338   resolver_->SetDnsConfigOverrides(overrides);
8339 
8340   notifier.mock_network_change_notifier()->SetConnectionType(
8341       NetworkChangeNotifier::CONNECTION_WIFI);
8342   DnsConfig network_dns_config = CreateValidDnsConfig();
8343   network_dns_config.doh_config = {};
8344   ChangeDnsConfig(network_dns_config);
8345 
8346   const auto* config = dns_client_->GetEffectiveConfig();
8347   ASSERT_TRUE(config);
8348   EXPECT_EQ(overrides.dns_over_https_config, config->doh_config);
8349   EXPECT_EQ(SecureDnsMode::kAutomatic, config->secure_dns_mode);
8350 
8351   resolver_->SetDnsConfigOverrides(DnsConfigOverrides());
8352   config = dns_client_->GetEffectiveConfig();
8353   ASSERT_TRUE(config);
8354   EXPECT_EQ(0u, config->doh_config.servers().size());
8355   EXPECT_EQ(SecureDnsMode::kOff, config->secure_dns_mode);
8356 }
8357 
8358 // Basic test socket factory that allows creation of UDP sockets, but those
8359 // sockets are mocks with no data and are not expected to be usable.
8360 class AlwaysFailSocketFactory : public MockClientSocketFactory {
8361  public:
CreateDatagramClientSocket(DatagramSocket::BindType bind_type,NetLog * net_log,const NetLogSource & source)8362   std::unique_ptr<DatagramClientSocket> CreateDatagramClientSocket(
8363       DatagramSocket::BindType bind_type,
8364       NetLog* net_log,
8365       const NetLogSource& source) override {
8366     return std::make_unique<MockUDPClientSocket>();
8367   }
8368 };
8369 
8370 class TestDnsObserver : public NetworkChangeNotifier::DNSObserver {
8371  public:
OnDNSChanged()8372   void OnDNSChanged() override { ++dns_changed_calls_; }
8373 
dns_changed_calls() const8374   int dns_changed_calls() const { return dns_changed_calls_; }
8375 
8376  private:
8377   int dns_changed_calls_ = 0;
8378 };
8379 
8380 // Built-in client and config overrides not available on iOS.
8381 #if !BUILDFLAG(IS_IOS)
TEST_F(HostResolverManagerDnsTest,SetDnsConfigOverrides)8382 TEST_F(HostResolverManagerDnsTest, SetDnsConfigOverrides) {
8383   test::ScopedMockNetworkChangeNotifier mock_network_change_notifier;
8384   TestDnsObserver config_observer;
8385   NetworkChangeNotifier::AddDNSObserver(&config_observer);
8386 
8387   // Use a real DnsClient to test config-handling behavior.
8388   AlwaysFailSocketFactory socket_factory;
8389   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8390   DnsClient* client_ptr = client.get();
8391   resolver_->SetDnsClientForTesting(std::move(client));
8392 
8393   DnsConfig original_config = CreateValidDnsConfig();
8394   original_config.hosts = {
8395       {DnsHostsKey("host", ADDRESS_FAMILY_IPV4), IPAddress(192, 168, 1, 1)}};
8396   ChangeDnsConfig(original_config);
8397 
8398   // Confirm pre-override state.
8399   ASSERT_EQ(original_config, *client_ptr->GetEffectiveConfig());
8400 
8401   DnsConfigOverrides overrides;
8402   const std::vector<IPEndPoint> nameservers = {
8403       CreateExpected("192.168.0.1", 92)};
8404   overrides.nameservers = nameservers;
8405   overrides.dns_over_tls_active = true;
8406   const std::string dns_over_tls_hostname = "dns.example.com";
8407   overrides.dns_over_tls_hostname = dns_over_tls_hostname;
8408   const std::vector<std::string> search = {"str"};
8409   overrides.search = search;
8410   overrides.append_to_multi_label_name = false;
8411   const int ndots = 5;
8412   overrides.ndots = ndots;
8413   const base::TimeDelta fallback_period = base::Seconds(10);
8414   overrides.fallback_period = fallback_period;
8415   const int attempts = 20;
8416   overrides.attempts = attempts;
8417   const int doh_attempts = 19;
8418   overrides.doh_attempts = doh_attempts;
8419   overrides.rotate = true;
8420   overrides.use_local_ipv6 = true;
8421   auto doh_config = *DnsOverHttpsConfig::FromString("https://dns.example.com/");
8422   overrides.dns_over_https_config = doh_config;
8423   const SecureDnsMode secure_dns_mode = SecureDnsMode::kSecure;
8424   overrides.secure_dns_mode = secure_dns_mode;
8425   overrides.allow_dns_over_https_upgrade = true;
8426   overrides.clear_hosts = true;
8427 
8428   // This test is expected to test overriding all fields.
8429   EXPECT_TRUE(overrides.OverridesEverything());
8430 
8431   EXPECT_EQ(0, config_observer.dns_changed_calls());
8432 
8433   resolver_->SetDnsConfigOverrides(overrides);
8434 
8435   const DnsConfig* overridden_config = client_ptr->GetEffectiveConfig();
8436   ASSERT_TRUE(overridden_config);
8437   EXPECT_EQ(nameservers, overridden_config->nameservers);
8438   EXPECT_TRUE(overridden_config->dns_over_tls_active);
8439   EXPECT_EQ(dns_over_tls_hostname, overridden_config->dns_over_tls_hostname);
8440   EXPECT_EQ(search, overridden_config->search);
8441   EXPECT_FALSE(overridden_config->append_to_multi_label_name);
8442   EXPECT_EQ(ndots, overridden_config->ndots);
8443   EXPECT_EQ(fallback_period, overridden_config->fallback_period);
8444   EXPECT_EQ(attempts, overridden_config->attempts);
8445   EXPECT_EQ(doh_attempts, overridden_config->doh_attempts);
8446   EXPECT_TRUE(overridden_config->rotate);
8447   EXPECT_TRUE(overridden_config->use_local_ipv6);
8448   EXPECT_EQ(doh_config, overridden_config->doh_config);
8449   EXPECT_EQ(secure_dns_mode, overridden_config->secure_dns_mode);
8450   EXPECT_TRUE(overridden_config->allow_dns_over_https_upgrade);
8451   EXPECT_THAT(overridden_config->hosts, testing::IsEmpty());
8452 
8453   base::RunLoop().RunUntilIdle();  // Notifications are async.
8454   EXPECT_EQ(1, config_observer.dns_changed_calls());
8455 
8456   NetworkChangeNotifier::RemoveDNSObserver(&config_observer);
8457 }
8458 
TEST_F(HostResolverManagerDnsTest,SetDnsConfigOverrides_OverrideEverythingCreation)8459 TEST_F(HostResolverManagerDnsTest,
8460        SetDnsConfigOverrides_OverrideEverythingCreation) {
8461   // Use a real DnsClient to test config-handling behavior.
8462   AlwaysFailSocketFactory socket_factory;
8463   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8464   DnsClient* client_ptr = client.get();
8465   resolver_->SetDnsClientForTesting(std::move(client));
8466 
8467   DnsConfig original_config = CreateValidDnsConfig();
8468   ChangeDnsConfig(original_config);
8469 
8470   // Confirm pre-override state.
8471   ASSERT_EQ(original_config, *client_ptr->GetEffectiveConfig());
8472   ASSERT_FALSE(original_config.Equals(DnsConfig()));
8473 
8474   DnsConfigOverrides overrides =
8475       DnsConfigOverrides::CreateOverridingEverythingWithDefaults();
8476   EXPECT_TRUE(overrides.OverridesEverything());
8477 
8478   // Ensure config is valid by setting a nameserver.
8479   std::vector<IPEndPoint> nameservers = {CreateExpected("1.2.3.4", 50)};
8480   overrides.nameservers = nameservers;
8481   EXPECT_TRUE(overrides.OverridesEverything());
8482 
8483   resolver_->SetDnsConfigOverrides(overrides);
8484 
8485   DnsConfig expected;
8486   expected.nameservers = nameservers;
8487   EXPECT_THAT(client_ptr->GetEffectiveConfig(), testing::Pointee(expected));
8488 }
8489 
TEST_F(HostResolverManagerDnsTest,SetDnsConfigOverrides_PartialOverride)8490 TEST_F(HostResolverManagerDnsTest, SetDnsConfigOverrides_PartialOverride) {
8491   // Use a real DnsClient to test config-handling behavior.
8492   AlwaysFailSocketFactory socket_factory;
8493   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8494   DnsClient* client_ptr = client.get();
8495   resolver_->SetDnsClientForTesting(std::move(client));
8496 
8497   DnsConfig original_config = CreateValidDnsConfig();
8498   ChangeDnsConfig(original_config);
8499 
8500   // Confirm pre-override state.
8501   ASSERT_EQ(original_config, *client_ptr->GetEffectiveConfig());
8502 
8503   DnsConfigOverrides overrides;
8504   const std::vector<IPEndPoint> nameservers = {
8505       CreateExpected("192.168.0.2", 192)};
8506   overrides.nameservers = nameservers;
8507   overrides.rotate = true;
8508   EXPECT_FALSE(overrides.OverridesEverything());
8509 
8510   resolver_->SetDnsConfigOverrides(overrides);
8511 
8512   const DnsConfig* overridden_config = client_ptr->GetEffectiveConfig();
8513   ASSERT_TRUE(overridden_config);
8514   EXPECT_EQ(nameservers, overridden_config->nameservers);
8515   EXPECT_EQ(original_config.search, overridden_config->search);
8516   EXPECT_EQ(original_config.hosts, overridden_config->hosts);
8517   EXPECT_TRUE(overridden_config->append_to_multi_label_name);
8518   EXPECT_EQ(original_config.ndots, overridden_config->ndots);
8519   EXPECT_EQ(original_config.fallback_period,
8520             overridden_config->fallback_period);
8521   EXPECT_EQ(original_config.attempts, overridden_config->attempts);
8522   EXPECT_TRUE(overridden_config->rotate);
8523   EXPECT_FALSE(overridden_config->use_local_ipv6);
8524   EXPECT_EQ(original_config.doh_config, overridden_config->doh_config);
8525   EXPECT_EQ(original_config.secure_dns_mode,
8526             overridden_config->secure_dns_mode);
8527 }
8528 
8529 // Test that overridden configs are reapplied over a changed underlying system
8530 // config.
TEST_F(HostResolverManagerDnsTest,SetDnsConfigOverrides_NewConfig)8531 TEST_F(HostResolverManagerDnsTest, SetDnsConfigOverrides_NewConfig) {
8532   // Use a real DnsClient to test config-handling behavior.
8533   AlwaysFailSocketFactory socket_factory;
8534   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8535   DnsClient* client_ptr = client.get();
8536   resolver_->SetDnsClientForTesting(std::move(client));
8537 
8538   DnsConfig original_config = CreateValidDnsConfig();
8539   ChangeDnsConfig(original_config);
8540 
8541   // Confirm pre-override state.
8542   ASSERT_EQ(original_config, *client_ptr->GetEffectiveConfig());
8543 
8544   DnsConfigOverrides overrides;
8545   const std::vector<IPEndPoint> nameservers = {
8546       CreateExpected("192.168.0.2", 192)};
8547   overrides.nameservers = nameservers;
8548 
8549   resolver_->SetDnsConfigOverrides(overrides);
8550   ASSERT_TRUE(client_ptr->GetEffectiveConfig());
8551   ASSERT_EQ(nameservers, client_ptr->GetEffectiveConfig()->nameservers);
8552 
8553   DnsConfig new_config = original_config;
8554   new_config.attempts = 103;
8555   ASSERT_NE(nameservers, new_config.nameservers);
8556   ChangeDnsConfig(new_config);
8557 
8558   const DnsConfig* overridden_config = client_ptr->GetEffectiveConfig();
8559   ASSERT_TRUE(overridden_config);
8560   EXPECT_EQ(nameservers, overridden_config->nameservers);
8561   EXPECT_EQ(new_config.attempts, overridden_config->attempts);
8562 }
8563 
TEST_F(HostResolverManagerDnsTest,SetDnsConfigOverrides_ClearOverrides)8564 TEST_F(HostResolverManagerDnsTest, SetDnsConfigOverrides_ClearOverrides) {
8565   // Use a real DnsClient to test config-handling behavior.
8566   AlwaysFailSocketFactory socket_factory;
8567   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8568   DnsClient* client_ptr = client.get();
8569   resolver_->SetDnsClientForTesting(std::move(client));
8570 
8571   DnsConfig original_config = CreateValidDnsConfig();
8572   ChangeDnsConfig(original_config);
8573 
8574   DnsConfigOverrides overrides;
8575   overrides.attempts = 245;
8576   resolver_->SetDnsConfigOverrides(overrides);
8577 
8578   ASSERT_THAT(client_ptr->GetEffectiveConfig(),
8579               testing::Not(testing::Pointee(original_config)));
8580 
8581   resolver_->SetDnsConfigOverrides(DnsConfigOverrides());
8582   EXPECT_THAT(client_ptr->GetEffectiveConfig(),
8583               testing::Pointee(original_config));
8584 }
8585 
TEST_F(HostResolverManagerDnsTest,SetDnsConfigOverrides_NoChange)8586 TEST_F(HostResolverManagerDnsTest, SetDnsConfigOverrides_NoChange) {
8587   test::ScopedMockNetworkChangeNotifier mock_network_change_notifier;
8588   TestDnsObserver config_observer;
8589   NetworkChangeNotifier::AddDNSObserver(&config_observer);
8590 
8591   // Use a real DnsClient to test config-handling behavior.
8592   AlwaysFailSocketFactory socket_factory;
8593   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8594   DnsClient* client_ptr = client.get();
8595   resolver_->SetDnsClientForTesting(std::move(client));
8596 
8597   DnsConfig original_config = CreateValidDnsConfig();
8598   ChangeDnsConfig(original_config);
8599 
8600   // Confirm pre-override state.
8601   ASSERT_EQ(original_config, *client_ptr->GetEffectiveConfig());
8602 
8603   DnsConfigOverrides overrides;
8604   overrides.nameservers = original_config.nameservers;
8605 
8606   EXPECT_EQ(0, config_observer.dns_changed_calls());
8607 
8608   resolver_->SetDnsConfigOverrides(overrides);
8609   EXPECT_THAT(client_ptr->GetEffectiveConfig(),
8610               testing::Pointee(original_config));
8611 
8612   base::RunLoop().RunUntilIdle();  // Notifications are async.
8613   EXPECT_EQ(0,
8614             config_observer.dns_changed_calls());  // No expected notification
8615 
8616   NetworkChangeNotifier::RemoveDNSObserver(&config_observer);
8617 }
8618 
8619 // No effect or notifications expected using partial overrides without a base
8620 // system config.
TEST_F(HostResolverManagerDnsTest,NoBaseConfig_PartialOverrides)8621 TEST_F(HostResolverManagerDnsTest, NoBaseConfig_PartialOverrides) {
8622   test::ScopedMockNetworkChangeNotifier mock_network_change_notifier;
8623   TestDnsObserver config_observer;
8624   NetworkChangeNotifier::AddDNSObserver(&config_observer);
8625 
8626   // Use a real DnsClient to test config-handling behavior.
8627   AlwaysFailSocketFactory socket_factory;
8628   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8629   DnsClient* client_ptr = client.get();
8630   resolver_->SetDnsClientForTesting(std::move(client));
8631 
8632   client_ptr->SetSystemConfig(absl::nullopt);
8633 
8634   DnsConfigOverrides overrides;
8635   overrides.nameservers.emplace({CreateExpected("192.168.0.3", 193)});
8636   resolver_->SetDnsConfigOverrides(overrides);
8637   base::RunLoop().RunUntilIdle();  // Potential notifications are async.
8638 
8639   EXPECT_FALSE(client_ptr->GetEffectiveConfig());
8640   EXPECT_EQ(0, config_observer.dns_changed_calls());
8641 
8642   NetworkChangeNotifier::RemoveDNSObserver(&config_observer);
8643 }
8644 
TEST_F(HostResolverManagerDnsTest,NoBaseConfig_OverridesEverything)8645 TEST_F(HostResolverManagerDnsTest, NoBaseConfig_OverridesEverything) {
8646   test::ScopedMockNetworkChangeNotifier mock_network_change_notifier;
8647   TestDnsObserver config_observer;
8648   NetworkChangeNotifier::AddDNSObserver(&config_observer);
8649 
8650   // Use a real DnsClient to test config-handling behavior.
8651   AlwaysFailSocketFactory socket_factory;
8652   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8653   DnsClient* client_ptr = client.get();
8654   resolver_->SetDnsClientForTesting(std::move(client));
8655 
8656   client_ptr->SetSystemConfig(absl::nullopt);
8657 
8658   DnsConfigOverrides overrides =
8659       DnsConfigOverrides::CreateOverridingEverythingWithDefaults();
8660   const std::vector<IPEndPoint> nameservers = {
8661       CreateExpected("192.168.0.4", 194)};
8662   overrides.nameservers = nameservers;
8663   resolver_->SetDnsConfigOverrides(overrides);
8664   base::RunLoop().RunUntilIdle();  // Notifications are async.
8665 
8666   DnsConfig expected;
8667   expected.nameservers = nameservers;
8668 
8669   EXPECT_THAT(client_ptr->GetEffectiveConfig(), testing::Pointee(expected));
8670   EXPECT_EQ(1, config_observer.dns_changed_calls());
8671 
8672   NetworkChangeNotifier::RemoveDNSObserver(&config_observer);
8673 }
8674 
TEST_F(HostResolverManagerDnsTest,DohMapping)8675 TEST_F(HostResolverManagerDnsTest, DohMapping) {
8676   // Use a real DnsClient to test config-handling behavior.
8677   AlwaysFailSocketFactory socket_factory;
8678   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8679   DnsClient* client_ptr = client.get();
8680   resolver_->SetDnsClientForTesting(std::move(client));
8681 
8682   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8683   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8684   // not associated with hardcoded DoH services.
8685   DnsConfig original_config = CreateUpgradableDnsConfig();
8686   ChangeDnsConfig(original_config);
8687 
8688   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8689   EXPECT_EQ(original_config.nameservers, fetched_config->nameservers);
8690   auto expected_doh_config = *DnsOverHttpsConfig::FromTemplatesForTesting(
8691       {"https://chrome.cloudflare-dns.com/dns-query",
8692        "https://doh.cleanbrowsing.org/doh/family-filter{?dns}",
8693        "https://doh.cleanbrowsing.org/doh/security-filter{?dns}"});
8694   EXPECT_EQ(expected_doh_config, fetched_config->doh_config);
8695 }
8696 
TEST_F(HostResolverManagerDnsTest,DohMappingDisabled)8697 TEST_F(HostResolverManagerDnsTest, DohMappingDisabled) {
8698   // Use a real DnsClient to test config-handling behavior.
8699   AlwaysFailSocketFactory socket_factory;
8700   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8701   DnsClient* client_ptr = client.get();
8702   resolver_->SetDnsClientForTesting(std::move(client));
8703 
8704   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8705   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8706   // not associated with hardcoded DoH services.
8707   DnsConfig original_config = CreateUpgradableDnsConfig();
8708   original_config.allow_dns_over_https_upgrade = false;
8709   ChangeDnsConfig(original_config);
8710 
8711   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8712   EXPECT_EQ(original_config.nameservers, fetched_config->nameservers);
8713   EXPECT_THAT(fetched_config->doh_config.servers(), IsEmpty());
8714 }
8715 
TEST_F(HostResolverManagerDnsTest,DohMappingModeIneligibleForUpgrade)8716 TEST_F(HostResolverManagerDnsTest, DohMappingModeIneligibleForUpgrade) {
8717   // Use a real DnsClient to test config-handling behavior.
8718   AlwaysFailSocketFactory socket_factory;
8719   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8720   DnsClient* client_ptr = client.get();
8721   resolver_->SetDnsClientForTesting(std::move(client));
8722 
8723   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8724   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8725   // not associated with hardcoded DoH services.
8726   DnsConfig original_config = CreateUpgradableDnsConfig();
8727   original_config.secure_dns_mode = SecureDnsMode::kSecure;
8728   ChangeDnsConfig(original_config);
8729 
8730   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8731   EXPECT_EQ(original_config.nameservers, fetched_config->nameservers);
8732   EXPECT_THAT(fetched_config->doh_config.servers(), IsEmpty());
8733 }
8734 
TEST_F(HostResolverManagerDnsTest,DohMappingUnhandledOptionsIneligibleForUpgrade)8735 TEST_F(HostResolverManagerDnsTest,
8736        DohMappingUnhandledOptionsIneligibleForUpgrade) {
8737   // Use a real DnsClient to test config-handling behavior.
8738   AlwaysFailSocketFactory socket_factory;
8739   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8740   DnsClient* client_ptr = client.get();
8741   resolver_->SetDnsClientForTesting(std::move(client));
8742 
8743   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8744   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8745   // not associated with hardcoded DoH services.
8746   DnsConfig original_config = CreateUpgradableDnsConfig();
8747   original_config.unhandled_options = true;
8748   ChangeDnsConfig(original_config);
8749 
8750   EXPECT_FALSE(client_ptr->GetEffectiveConfig());
8751 }
8752 
TEST_F(HostResolverManagerDnsTest,DohMappingWithExclusion)8753 TEST_F(HostResolverManagerDnsTest, DohMappingWithExclusion) {
8754   // Use a real DnsClient to test config-handling behavior.
8755   AlwaysFailSocketFactory socket_factory;
8756   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8757   DnsClient* client_ptr = client.get();
8758   resolver_->SetDnsClientForTesting(std::move(client));
8759 
8760   base::test::ScopedFeatureList feature_list;
8761   feature_list.InitWithFeatures(
8762       /*enabled_features=*/{}, /*disabled_features=*/{
8763           GetDohProviderEntryForTesting("CleanBrowsingSecure").feature,
8764           GetDohProviderEntryForTesting("Cloudflare").feature});
8765 
8766   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8767   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8768   // not associated with hardcoded DoH services.
8769   DnsConfig original_config = CreateUpgradableDnsConfig();
8770   ChangeDnsConfig(original_config);
8771 
8772   // A DoH upgrade should be attempted on the DNS servers in the config, but
8773   // only for permitted providers.
8774   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8775   EXPECT_EQ(original_config.nameservers, fetched_config->nameservers);
8776   auto expected_doh_config = *DnsOverHttpsConfig::FromString(
8777       "https://doh.cleanbrowsing.org/doh/family-filter{?dns}");
8778   EXPECT_EQ(expected_doh_config, fetched_config->doh_config);
8779 }
8780 
TEST_F(HostResolverManagerDnsTest,DohMappingIgnoredIfTemplateSpecified)8781 TEST_F(HostResolverManagerDnsTest, DohMappingIgnoredIfTemplateSpecified) {
8782   // Use a real DnsClient to test config-handling behavior.
8783   AlwaysFailSocketFactory socket_factory;
8784   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8785   DnsClient* client_ptr = client.get();
8786   resolver_->SetDnsClientForTesting(std::move(client));
8787 
8788   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8789   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8790   // not associated with hardcoded DoH services.
8791   DnsConfig original_config = CreateUpgradableDnsConfig();
8792   ChangeDnsConfig(original_config);
8793 
8794   // If the overrides contains DoH servers, no DoH upgrade should be attempted.
8795   DnsConfigOverrides overrides;
8796   const auto dns_over_https_config_override =
8797       *DnsOverHttpsConfig::FromString("https://doh.server.override.com/");
8798   overrides.dns_over_https_config = dns_over_https_config_override;
8799   resolver_->SetDnsConfigOverrides(overrides);
8800   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8801   EXPECT_EQ(original_config.nameservers, fetched_config->nameservers);
8802   EXPECT_EQ(dns_over_https_config_override, fetched_config->doh_config);
8803 }
8804 
TEST_F(HostResolverManagerDnsTest,DohMappingUnhandledOptionsAndTemplateSpecified)8805 TEST_F(HostResolverManagerDnsTest,
8806        DohMappingUnhandledOptionsAndTemplateSpecified) {
8807   // Use a real DnsClient to test config-handling behavior.
8808   AlwaysFailSocketFactory socket_factory;
8809   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8810   DnsClient* client_ptr = client.get();
8811   resolver_->SetDnsClientForTesting(std::move(client));
8812 
8813   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8814   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8815   // not associated with hardcoded DoH services.
8816   DnsConfig original_config = CreateUpgradableDnsConfig();
8817   original_config.unhandled_options = true;
8818   ChangeDnsConfig(original_config);
8819 
8820   // If the overrides contains DoH servers, no DoH upgrade should be attempted.
8821   DnsConfigOverrides overrides;
8822   const auto dns_over_https_config_override =
8823       *DnsOverHttpsConfig::FromString("https://doh.server.override.com/");
8824   overrides.dns_over_https_config = dns_over_https_config_override;
8825   resolver_->SetDnsConfigOverrides(overrides);
8826   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8827   EXPECT_TRUE(fetched_config->nameservers.empty());
8828   EXPECT_FALSE(client_ptr->CanUseInsecureDnsTransactions());
8829   EXPECT_EQ(dns_over_https_config_override, fetched_config->doh_config);
8830   EXPECT_TRUE(client_ptr->CanUseSecureDnsTransactions());
8831 }
8832 
TEST_F(HostResolverManagerDnsTest,DohMappingWithAutomaticDot)8833 TEST_F(HostResolverManagerDnsTest, DohMappingWithAutomaticDot) {
8834   // Use a real DnsClient to test config-handling behavior.
8835   AlwaysFailSocketFactory socket_factory;
8836   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8837   DnsClient* client_ptr = client.get();
8838   resolver_->SetDnsClientForTesting(std::move(client));
8839 
8840   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8841   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8842   // not associated with hardcoded DoH services.
8843   DnsConfig original_config = CreateUpgradableDnsConfig();
8844   original_config.dns_over_tls_active = true;
8845   ChangeDnsConfig(original_config);
8846 
8847   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8848   EXPECT_EQ(original_config.nameservers, fetched_config->nameservers);
8849   auto expected_doh_config = *DnsOverHttpsConfig::FromTemplatesForTesting(
8850       {"https://chrome.cloudflare-dns.com/dns-query",
8851        "https://doh.cleanbrowsing.org/doh/family-filter{?dns}",
8852        "https://doh.cleanbrowsing.org/doh/security-filter{?dns}"});
8853   EXPECT_EQ(expected_doh_config, fetched_config->doh_config);
8854 }
8855 
TEST_F(HostResolverManagerDnsTest,DohMappingWithStrictDot)8856 TEST_F(HostResolverManagerDnsTest, DohMappingWithStrictDot) {
8857   // Use a real DnsClient to test config-handling behavior.
8858   AlwaysFailSocketFactory socket_factory;
8859   auto client = DnsClient::CreateClient(nullptr /* net_log */);
8860   DnsClient* client_ptr = client.get();
8861   resolver_->SetDnsClientForTesting(std::move(client));
8862 
8863   // Create a DnsConfig containing IP addresses associated with Cloudflare,
8864   // SafeBrowsing family filter, SafeBrowsing security filter, and other IPs
8865   // not associated with hardcoded DoH services.
8866   DnsConfig original_config = CreateUpgradableDnsConfig();
8867   original_config.secure_dns_mode = SecureDnsMode::kAutomatic;
8868   original_config.dns_over_tls_active = true;
8869 
8870   // Google DoT hostname
8871   original_config.dns_over_tls_hostname = "dns.google";
8872   ChangeDnsConfig(original_config);
8873   const DnsConfig* fetched_config = client_ptr->GetEffectiveConfig();
8874   EXPECT_EQ(original_config.nameservers, fetched_config->nameservers);
8875   auto expected_doh_config =
8876       *DnsOverHttpsConfig::FromString("https://dns.google/dns-query{?dns}");
8877   EXPECT_EQ(expected_doh_config, fetched_config->doh_config);
8878 }
8879 
8880 #endif  // !BUILDFLAG(IS_IOS)
8881 
TEST_F(HostResolverManagerDnsTest,FlushCacheOnDnsConfigOverridesChange)8882 TEST_F(HostResolverManagerDnsTest, FlushCacheOnDnsConfigOverridesChange) {
8883   ChangeDnsConfig(CreateValidDnsConfig());
8884 
8885   HostResolver::ResolveHostParameters local_source_parameters;
8886   local_source_parameters.source = HostResolverSource::LOCAL_ONLY;
8887 
8888   // Populate cache.
8889   ResolveHostResponseHelper initial_response(resolver_->CreateRequest(
8890       HostPortPair("ok", 70), NetworkAnonymizationKey(), NetLogWithSource(),
8891       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
8892   EXPECT_THAT(initial_response.result_error(), IsOk());
8893 
8894   // Confirm result now cached.
8895   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
8896       HostPortPair("ok", 75), NetworkAnonymizationKey(), NetLogWithSource(),
8897       local_source_parameters, resolve_context_.get(),
8898       resolve_context_->host_cache()));
8899   ASSERT_THAT(cached_response.result_error(), IsOk());
8900   ASSERT_TRUE(cached_response.request()->GetStaleInfo());
8901 
8902   // Flush cache by triggering a DnsConfigOverrides change.
8903   DnsConfigOverrides overrides;
8904   overrides.attempts = 4;
8905   resolver_->SetDnsConfigOverrides(overrides);
8906 
8907   // Expect no longer cached
8908   ResolveHostResponseHelper flushed_response(resolver_->CreateRequest(
8909       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
8910       local_source_parameters, resolve_context_.get(),
8911       resolve_context_->host_cache()));
8912   EXPECT_THAT(flushed_response.result_error(), IsError(ERR_DNS_CACHE_MISS));
8913 }
8914 
TEST_F(HostResolverManagerDnsTest,FlushContextSessionDataOnDnsConfigOverridesChange)8915 TEST_F(HostResolverManagerDnsTest,
8916        FlushContextSessionDataOnDnsConfigOverridesChange) {
8917   ChangeDnsConfig(CreateValidDnsConfig());
8918 
8919   DnsSession* session_before = dns_client_->GetCurrentSession();
8920   resolve_context_->RecordServerSuccess(
8921       0u /* server_index */, true /* is_doh_server */, session_before);
8922   ASSERT_TRUE(resolve_context_->GetDohServerAvailability(0u, session_before));
8923 
8924   // Flush data by triggering a DnsConfigOverrides change.
8925   DnsConfigOverrides overrides;
8926   overrides.attempts = 4;
8927   resolver_->SetDnsConfigOverrides(overrides);
8928 
8929   DnsSession* session_after = dns_client_->GetCurrentSession();
8930   EXPECT_NE(session_before, session_after);
8931 
8932   EXPECT_FALSE(resolve_context_->GetDohServerAvailability(0u, session_after));
8933 
8934   // Confirm new session is in use.
8935   resolve_context_->RecordServerSuccess(
8936       0u /* server_index */, true /* is_doh_server */, session_after);
8937   EXPECT_TRUE(resolve_context_->GetDohServerAvailability(0u, session_after));
8938 }
8939 
8940 // Test that even when using config overrides, a change to the base system
8941 // config cancels pending requests.
TEST_F(HostResolverManagerDnsTest,CancellationOnBaseConfigChange)8942 TEST_F(HostResolverManagerDnsTest, CancellationOnBaseConfigChange) {
8943   DnsConfig original_config = CreateValidDnsConfig();
8944   ChangeDnsConfig(original_config);
8945 
8946   DnsConfigOverrides overrides;
8947   overrides.nameservers.emplace({CreateExpected("123.123.123.123", 80)});
8948   ASSERT_FALSE(overrides.OverridesEverything());
8949   resolver_->SetDnsConfigOverrides(overrides);
8950 
8951   ResolveHostResponseHelper response(resolver_->CreateRequest(
8952       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
8953       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
8954       resolve_context_->host_cache()));
8955   ASSERT_FALSE(response.complete());
8956 
8957   DnsConfig new_config = original_config;
8958   new_config.attempts = 103;
8959   ChangeDnsConfig(new_config);
8960 
8961   EXPECT_THAT(response.result_error(), IsError(ERR_NETWORK_CHANGED));
8962 }
8963 
8964 // Test that when all configuration is overridden, system configuration changes
8965 // do not cancel requests.
TEST_F(HostResolverManagerDnsTest,CancellationOnBaseConfigChange_OverridesEverything)8966 TEST_F(HostResolverManagerDnsTest,
8967        CancellationOnBaseConfigChange_OverridesEverything) {
8968   DnsConfig original_config = CreateValidDnsConfig();
8969   ChangeDnsConfig(original_config);
8970 
8971   DnsConfigOverrides overrides =
8972       DnsConfigOverrides::CreateOverridingEverythingWithDefaults();
8973   overrides.nameservers.emplace({CreateExpected("123.123.123.123", 80)});
8974   ASSERT_TRUE(overrides.OverridesEverything());
8975   resolver_->SetDnsConfigOverrides(overrides);
8976 
8977   ResolveHostResponseHelper response(resolver_->CreateRequest(
8978       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
8979       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
8980       resolve_context_->host_cache()));
8981   ASSERT_FALSE(response.complete());
8982 
8983   DnsConfig new_config = original_config;
8984   new_config.attempts = 103;
8985   ChangeDnsConfig(new_config);
8986 
8987   dns_client_->CompleteDelayedTransactions();
8988   EXPECT_THAT(response.result_error(), IsOk());
8989 }
8990 
8991 // Test that in-progress queries are cancelled on applying new DNS config
8992 // overrides, same as receiving a new DnsConfig from the system.
TEST_F(HostResolverManagerDnsTest,CancelQueriesOnSettingOverrides)8993 TEST_F(HostResolverManagerDnsTest, CancelQueriesOnSettingOverrides) {
8994   ChangeDnsConfig(CreateValidDnsConfig());
8995   ResolveHostResponseHelper response(resolver_->CreateRequest(
8996       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
8997       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
8998       resolve_context_->host_cache()));
8999   ASSERT_FALSE(response.complete());
9000 
9001   DnsConfigOverrides overrides;
9002   overrides.attempts = 123;
9003   resolver_->SetDnsConfigOverrides(overrides);
9004 
9005   EXPECT_THAT(response.result_error(), IsError(ERR_NETWORK_CHANGED));
9006 }
9007 
9008 // Queries should not be cancelled if equal overrides are set.
TEST_F(HostResolverManagerDnsTest,CancelQueriesOnSettingOverrides_SameOverrides)9009 TEST_F(HostResolverManagerDnsTest,
9010        CancelQueriesOnSettingOverrides_SameOverrides) {
9011   ChangeDnsConfig(CreateValidDnsConfig());
9012   DnsConfigOverrides overrides;
9013   overrides.attempts = 123;
9014   resolver_->SetDnsConfigOverrides(overrides);
9015 
9016   ResolveHostResponseHelper response(resolver_->CreateRequest(
9017       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
9018       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
9019       resolve_context_->host_cache()));
9020   ASSERT_FALSE(response.complete());
9021 
9022   resolver_->SetDnsConfigOverrides(overrides);
9023 
9024   dns_client_->CompleteDelayedTransactions();
9025   EXPECT_THAT(response.result_error(), IsOk());
9026 }
9027 
9028 // Test that in-progress queries are cancelled on clearing DNS config overrides,
9029 // same as receiving a new DnsConfig from the system.
TEST_F(HostResolverManagerDnsTest,CancelQueriesOnClearingOverrides)9030 TEST_F(HostResolverManagerDnsTest, CancelQueriesOnClearingOverrides) {
9031   ChangeDnsConfig(CreateValidDnsConfig());
9032   DnsConfigOverrides overrides;
9033   overrides.attempts = 123;
9034   resolver_->SetDnsConfigOverrides(overrides);
9035 
9036   ResolveHostResponseHelper response(resolver_->CreateRequest(
9037       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
9038       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
9039       resolve_context_->host_cache()));
9040   ASSERT_FALSE(response.complete());
9041 
9042   resolver_->SetDnsConfigOverrides(DnsConfigOverrides());
9043 
9044   EXPECT_THAT(response.result_error(), IsError(ERR_NETWORK_CHANGED));
9045 }
9046 
9047 // Queries should not be cancelled on clearing overrides if there were not any
9048 // overrides.
TEST_F(HostResolverManagerDnsTest,CancelQueriesOnClearingOverrides_NoOverrides)9049 TEST_F(HostResolverManagerDnsTest,
9050        CancelQueriesOnClearingOverrides_NoOverrides) {
9051   ChangeDnsConfig(CreateValidDnsConfig());
9052   ResolveHostResponseHelper response(resolver_->CreateRequest(
9053       HostPortPair("4slow_ok", 80), NetworkAnonymizationKey(),
9054       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
9055       resolve_context_->host_cache()));
9056   ASSERT_FALSE(response.complete());
9057 
9058   resolver_->SetDnsConfigOverrides(DnsConfigOverrides());
9059 
9060   dns_client_->CompleteDelayedTransactions();
9061   EXPECT_THAT(response.result_error(), IsOk());
9062 }
9063 
TEST_F(HostResolverManagerDnsTest,FlushContextSessionDataOnSystemConfigChange)9064 TEST_F(HostResolverManagerDnsTest,
9065        FlushContextSessionDataOnSystemConfigChange) {
9066   DnsConfig original_config = CreateValidDnsConfig();
9067   ChangeDnsConfig(original_config);
9068 
9069   DnsSession* session_before = dns_client_->GetCurrentSession();
9070   resolve_context_->RecordServerSuccess(
9071       0u /* server_index */, true /* is_doh_server */, session_before);
9072   ASSERT_TRUE(resolve_context_->GetDohServerAvailability(0u, session_before));
9073 
9074   // Flush data by triggering a config change.
9075   DnsConfig new_config = original_config;
9076   new_config.attempts = 103;
9077   ChangeDnsConfig(new_config);
9078 
9079   DnsSession* session_after = dns_client_->GetCurrentSession();
9080   EXPECT_NE(session_before, session_after);
9081 
9082   EXPECT_FALSE(resolve_context_->GetDohServerAvailability(0u, session_after));
9083 
9084   // Confirm new session is in use.
9085   resolve_context_->RecordServerSuccess(
9086       0u /* server_index */, true /* is_doh_server */, session_after);
9087   EXPECT_TRUE(resolve_context_->GetDohServerAvailability(0u, session_after));
9088 }
9089 
TEST_F(HostResolverManagerDnsTest,TxtQuery)9090 TEST_F(HostResolverManagerDnsTest, TxtQuery) {
9091   // Simulate two separate DNS records, each with multiple strings.
9092   std::vector<std::string> foo_records = {"foo1", "foo2", "foo3"};
9093   std::vector<std::string> bar_records = {"bar1", "bar2"};
9094   std::vector<std::vector<std::string>> text_records = {foo_records,
9095                                                         bar_records};
9096 
9097   MockDnsClientRuleList rules;
9098   rules.emplace_back("host", dns_protocol::kTypeTXT, false /* secure */,
9099                      MockDnsClientRule::Result(BuildTestDnsTextResponse(
9100                          "host", std::move(text_records))),
9101                      false /* delay */);
9102 
9103   CreateResolver();
9104   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9105 
9106   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9107 
9108   HostResolver::ResolveHostParameters parameters;
9109   parameters.dns_query_type = DnsQueryType::TXT;
9110 
9111   ResolveHostResponseHelper response(resolver_->CreateRequest(
9112       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9113       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9114   EXPECT_THAT(response.result_error(), IsOk());
9115   EXPECT_FALSE(response.request()->GetAddressResults());
9116   EXPECT_FALSE(response.request()->GetEndpointResults());
9117   EXPECT_FALSE(response.request()->GetHostnameResults());
9118   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9119 
9120   // Order between separate DNS records is undefined, but each record should
9121   // stay in order as that order may be meaningful.
9122   ASSERT_THAT(response.request()->GetTextResults(),
9123               testing::Optional(testing::UnorderedElementsAre(
9124                   "foo1", "foo2", "foo3", "bar1", "bar2")));
9125   std::vector<std::string> results =
9126       response.request()->GetTextResults().value();
9127   EXPECT_NE(results.end(), base::ranges::search(results, foo_records));
9128   EXPECT_NE(results.end(), base::ranges::search(results, bar_records));
9129 
9130   // Expect result to be cached.
9131   EXPECT_EQ(resolve_context_->host_cache()->size(), 1u);
9132   parameters.source = HostResolverSource::LOCAL_ONLY;
9133   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
9134       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9135       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9136   EXPECT_THAT(cached_response.result_error(), IsOk());
9137   ASSERT_THAT(cached_response.request()->GetTextResults(),
9138               testing::Optional(testing::UnorderedElementsAre(
9139                   "foo1", "foo2", "foo3", "bar1", "bar2")));
9140   results = cached_response.request()->GetTextResults().value();
9141   EXPECT_NE(results.end(), base::ranges::search(results, foo_records));
9142   EXPECT_NE(results.end(), base::ranges::search(results, bar_records));
9143 }
9144 
TEST_F(HostResolverManagerDnsTest,TxtQueryRejectsIpLiteral)9145 TEST_F(HostResolverManagerDnsTest, TxtQueryRejectsIpLiteral) {
9146   MockDnsClientRuleList rules;
9147 
9148   // Entry that would resolve if DNS is mistakenly queried to ensure that does
9149   // not happen.
9150   rules.emplace_back("8.8.8.8", dns_protocol::kTypeTXT, /*secure=*/false,
9151                      MockDnsClientRule::Result(
9152                          BuildTestDnsTextResponse("8.8.8.8", {{"text"}})),
9153                      /*delay=*/false);
9154 
9155   CreateResolver();
9156   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9157 
9158   HostResolver::ResolveHostParameters parameters;
9159   parameters.dns_query_type = DnsQueryType::TXT;
9160 
9161   ResolveHostResponseHelper response(resolver_->CreateRequest(
9162       HostPortPair("8.8.8.8", 108), NetworkAnonymizationKey(),
9163       NetLogWithSource(), parameters, resolve_context_.get(),
9164       resolve_context_->host_cache()));
9165   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9166   EXPECT_FALSE(response.request()->GetAddressResults());
9167   EXPECT_FALSE(response.request()->GetEndpointResults());
9168   EXPECT_FALSE(response.request()->GetTextResults());
9169   EXPECT_FALSE(response.request()->GetHostnameResults());
9170   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9171 }
9172 
9173 // Test that TXT records can be extracted from a response that also contains
9174 // unrecognized record types.
TEST_F(HostResolverManagerDnsTest,TxtQuery_MixedWithUnrecognizedType)9175 TEST_F(HostResolverManagerDnsTest, TxtQuery_MixedWithUnrecognizedType) {
9176   std::vector<std::string> text_strings = {"foo"};
9177 
9178   MockDnsClientRuleList rules;
9179   rules.emplace_back(
9180       "host", dns_protocol::kTypeTXT, false /* secure */,
9181       MockDnsClientRule::Result(BuildTestDnsResponse(
9182           "host", dns_protocol::kTypeTXT,
9183           {BuildTestDnsRecord("host", 3u /* type */, "fake rdata 1"),
9184            BuildTestTextRecord("host", std::move(text_strings)),
9185            BuildTestDnsRecord("host", 3u /* type */, "fake rdata 2")})),
9186       false /* delay */);
9187 
9188   CreateResolver();
9189   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9190 
9191   HostResolver::ResolveHostParameters parameters;
9192   parameters.dns_query_type = DnsQueryType::TXT;
9193 
9194   ResolveHostResponseHelper response(resolver_->CreateRequest(
9195       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9196       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9197   EXPECT_THAT(response.result_error(), IsOk());
9198   EXPECT_FALSE(response.request()->GetAddressResults());
9199   EXPECT_FALSE(response.request()->GetEndpointResults());
9200   EXPECT_FALSE(response.request()->GetHostnameResults());
9201   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9202 
9203   EXPECT_THAT(response.request()->GetTextResults(),
9204               testing::Optional(testing::ElementsAre("foo")));
9205 }
9206 
TEST_F(HostResolverManagerDnsTest,TxtQuery_InvalidConfig)9207 TEST_F(HostResolverManagerDnsTest, TxtQuery_InvalidConfig) {
9208   set_allow_fallback_to_systemtask(false);
9209   // Set empty DnsConfig.
9210   InvalidateDnsConfig();
9211 
9212   HostResolver::ResolveHostParameters parameters;
9213   parameters.dns_query_type = DnsQueryType::TXT;
9214 
9215   ResolveHostResponseHelper response(resolver_->CreateRequest(
9216       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9217       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9218   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_CACHE_MISS));
9219 }
9220 
TEST_F(HostResolverManagerDnsTest,TxtQuery_NonexistentDomain)9221 TEST_F(HostResolverManagerDnsTest, TxtQuery_NonexistentDomain) {
9222   // Setup fallback to confirm it is not used for non-address results.
9223   set_allow_fallback_to_systemtask(true);
9224   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9225   proc_->SignalMultiple(1u);
9226 
9227   MockDnsClientRuleList rules;
9228   rules.emplace_back(
9229       "host", dns_protocol::kTypeTXT, false /* secure */,
9230       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kNoDomain),
9231       false /* delay */);
9232 
9233   CreateResolver();
9234   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9235 
9236   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9237 
9238   HostResolver::ResolveHostParameters parameters;
9239   parameters.dns_query_type = DnsQueryType::TXT;
9240 
9241   ResolveHostResponseHelper response(resolver_->CreateRequest(
9242       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9243       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9244   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9245   EXPECT_FALSE(response.request()->GetAddressResults());
9246   EXPECT_FALSE(response.request()->GetEndpointResults());
9247   EXPECT_FALSE(response.request()->GetTextResults());
9248   EXPECT_FALSE(response.request()->GetHostnameResults());
9249   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9250 
9251   // Expect result to be cached.
9252   EXPECT_EQ(resolve_context_->host_cache()->size(), 1u);
9253   parameters.source = HostResolverSource::LOCAL_ONLY;
9254   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
9255       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9256       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9257   EXPECT_THAT(cached_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9258   EXPECT_FALSE(cached_response.request()->GetAddressResults());
9259   EXPECT_FALSE(cached_response.request()->GetEndpointResults());
9260   EXPECT_FALSE(cached_response.request()->GetTextResults());
9261   EXPECT_FALSE(cached_response.request()->GetHostnameResults());
9262   EXPECT_FALSE(cached_response.request()->GetExperimentalResultsForTesting());
9263 }
9264 
TEST_F(HostResolverManagerDnsTest,TxtQuery_Failure)9265 TEST_F(HostResolverManagerDnsTest, TxtQuery_Failure) {
9266   // Setup fallback to confirm it is not used for non-address results.
9267   set_allow_fallback_to_systemtask(true);
9268   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9269   proc_->SignalMultiple(1u);
9270 
9271   MockDnsClientRuleList rules;
9272   rules.emplace_back(
9273       "host", dns_protocol::kTypeTXT, false /* secure */,
9274       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
9275       false /* delay */);
9276 
9277   CreateResolver();
9278   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9279 
9280   HostResolver::ResolveHostParameters parameters;
9281   parameters.dns_query_type = DnsQueryType::TXT;
9282 
9283   ResolveHostResponseHelper response(resolver_->CreateRequest(
9284       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9285       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9286   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9287   EXPECT_FALSE(response.request()->GetAddressResults());
9288   EXPECT_FALSE(response.request()->GetEndpointResults());
9289   EXPECT_FALSE(response.request()->GetTextResults());
9290   EXPECT_FALSE(response.request()->GetHostnameResults());
9291   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9292 
9293   // Expect result not cached.
9294   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9295 }
9296 
TEST_F(HostResolverManagerDnsTest,TxtQuery_Timeout)9297 TEST_F(HostResolverManagerDnsTest, TxtQuery_Timeout) {
9298   // Setup fallback to confirm it is not used for non-address results.
9299   set_allow_fallback_to_systemtask(true);
9300   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9301   proc_->SignalMultiple(1u);
9302 
9303   MockDnsClientRuleList rules;
9304   rules.emplace_back(
9305       "host", dns_protocol::kTypeTXT, false /* secure */,
9306       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kTimeout),
9307       false /* delay */);
9308 
9309   CreateResolver();
9310   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9311 
9312   HostResolver::ResolveHostParameters parameters;
9313   parameters.dns_query_type = DnsQueryType::TXT;
9314 
9315   ResolveHostResponseHelper response(resolver_->CreateRequest(
9316       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9317       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9318   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_TIMED_OUT));
9319   EXPECT_FALSE(response.request()->GetAddressResults());
9320   EXPECT_FALSE(response.request()->GetEndpointResults());
9321   EXPECT_FALSE(response.request()->GetTextResults());
9322   EXPECT_FALSE(response.request()->GetHostnameResults());
9323   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9324 
9325   // Expect result not cached.
9326   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9327 }
9328 
TEST_F(HostResolverManagerDnsTest,TxtQuery_Empty)9329 TEST_F(HostResolverManagerDnsTest, TxtQuery_Empty) {
9330   // Setup fallback to confirm it is not used for non-address results.
9331   set_allow_fallback_to_systemtask(true);
9332   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9333   proc_->SignalMultiple(1u);
9334 
9335   MockDnsClientRuleList rules;
9336   rules.emplace_back(
9337       "host", dns_protocol::kTypeTXT, false /* secure */,
9338       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
9339       false /* delay */);
9340 
9341   CreateResolver();
9342   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9343 
9344   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9345 
9346   HostResolver::ResolveHostParameters parameters;
9347   parameters.dns_query_type = DnsQueryType::TXT;
9348 
9349   ResolveHostResponseHelper response(resolver_->CreateRequest(
9350       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9351       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9352   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9353   EXPECT_FALSE(response.request()->GetAddressResults());
9354   EXPECT_FALSE(response.request()->GetEndpointResults());
9355   EXPECT_FALSE(response.request()->GetTextResults());
9356   EXPECT_FALSE(response.request()->GetHostnameResults());
9357   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9358 
9359   // Expect result to be cached.
9360   EXPECT_EQ(resolve_context_->host_cache()->size(), 1u);
9361   parameters.source = HostResolverSource::LOCAL_ONLY;
9362   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
9363       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9364       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9365   EXPECT_THAT(cached_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9366   EXPECT_FALSE(cached_response.request()->GetAddressResults());
9367   EXPECT_FALSE(cached_response.request()->GetEndpointResults());
9368   EXPECT_FALSE(cached_response.request()->GetTextResults());
9369   EXPECT_FALSE(cached_response.request()->GetHostnameResults());
9370   EXPECT_FALSE(cached_response.request()->GetExperimentalResultsForTesting());
9371 }
9372 
TEST_F(HostResolverManagerDnsTest,TxtQuery_Malformed)9373 TEST_F(HostResolverManagerDnsTest, TxtQuery_Malformed) {
9374   // Setup fallback to confirm it is not used for non-address results.
9375   set_allow_fallback_to_systemtask(true);
9376   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9377   proc_->SignalMultiple(1u);
9378 
9379   MockDnsClientRuleList rules;
9380   rules.emplace_back(
9381       "host", dns_protocol::kTypeTXT, false /* secure */,
9382       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kMalformed),
9383       false /* delay */);
9384 
9385   CreateResolver();
9386   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9387 
9388   HostResolver::ResolveHostParameters parameters;
9389   parameters.dns_query_type = DnsQueryType::TXT;
9390 
9391   ResolveHostResponseHelper response(resolver_->CreateRequest(
9392       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9393       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9394   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_MALFORMED_RESPONSE));
9395   EXPECT_FALSE(response.request()->GetAddressResults());
9396   EXPECT_FALSE(response.request()->GetEndpointResults());
9397   EXPECT_FALSE(response.request()->GetTextResults());
9398   EXPECT_FALSE(response.request()->GetHostnameResults());
9399   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9400 
9401   // Expect result not cached.
9402   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9403 }
9404 
TEST_F(HostResolverManagerDnsTest,TxtQuery_MismatchedName)9405 TEST_F(HostResolverManagerDnsTest, TxtQuery_MismatchedName) {
9406   std::vector<std::vector<std::string>> text_records = {{"text"}};
9407   MockDnsClientRuleList rules;
9408   rules.emplace_back("host", dns_protocol::kTypeTXT, false /* secure */,
9409                      MockDnsClientRule::Result(BuildTestDnsTextResponse(
9410                          "host", std::move(text_records), "not.host")),
9411                      false /* delay */);
9412 
9413   CreateResolver();
9414   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9415 
9416   HostResolver::ResolveHostParameters parameters;
9417   parameters.dns_query_type = DnsQueryType::TXT;
9418 
9419   ResolveHostResponseHelper response(resolver_->CreateRequest(
9420       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9421       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9422   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_MALFORMED_RESPONSE));
9423   EXPECT_FALSE(response.request()->GetAddressResults());
9424   EXPECT_FALSE(response.request()->GetEndpointResults());
9425   EXPECT_FALSE(response.request()->GetTextResults());
9426   EXPECT_FALSE(response.request()->GetHostnameResults());
9427   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9428 
9429   // Expect result not cached.
9430   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9431 }
9432 
TEST_F(HostResolverManagerDnsTest,TxtQuery_WrongType)9433 TEST_F(HostResolverManagerDnsTest, TxtQuery_WrongType) {
9434   // Respond to a TXT query with an A response.
9435   MockDnsClientRuleList rules;
9436   rules.emplace_back(
9437       "host", dns_protocol::kTypeTXT, false /* secure */,
9438       MockDnsClientRule::Result(BuildTestDnsResponse(
9439           "host", dns_protocol::kTypeTXT,
9440           {BuildTestAddressRecord("host", IPAddress(1, 2, 3, 4))})),
9441       false /* delay */);
9442 
9443   CreateResolver();
9444   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9445 
9446   HostResolver::ResolveHostParameters parameters;
9447   parameters.dns_query_type = DnsQueryType::TXT;
9448 
9449   // Responses for the wrong type should be ignored.
9450   ResolveHostResponseHelper response(resolver_->CreateRequest(
9451       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9452       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9453   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9454   EXPECT_FALSE(response.request()->GetAddressResults());
9455   EXPECT_FALSE(response.request()->GetEndpointResults());
9456   EXPECT_FALSE(response.request()->GetTextResults());
9457   EXPECT_FALSE(response.request()->GetHostnameResults());
9458   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9459 
9460   // Expect result not cached.
9461   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9462 }
9463 
TEST_F(HostResolverManagerDnsTest,TxtInsecureQueryDisallowedWhenAdditionalTypesDisallowed)9464 TEST_F(HostResolverManagerDnsTest,
9465        TxtInsecureQueryDisallowedWhenAdditionalTypesDisallowed) {
9466   const std::string kName = "txt.test";
9467 
9468   ChangeDnsConfig(CreateValidDnsConfig());
9469   DnsConfigOverrides overrides;
9470   overrides.secure_dns_mode = SecureDnsMode::kOff;
9471   resolver_->SetDnsConfigOverrides(overrides);
9472   resolver_->SetInsecureDnsClientEnabled(
9473       /*enabled=*/true,
9474       /*additional_dns_types_enabled=*/false);
9475 
9476   HostResolver::ResolveHostParameters parameters;
9477   parameters.dns_query_type = DnsQueryType::TXT;
9478 
9479   ResolveHostResponseHelper response(resolver_->CreateRequest(
9480       HostPortPair(kName, 108), NetworkAnonymizationKey(), NetLogWithSource(),
9481       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9482   // No non-local work is done, so ERR_DNS_CACHE_MISS is the result.
9483   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_CACHE_MISS));
9484   EXPECT_FALSE(response.request()->GetAddressResults());
9485   EXPECT_FALSE(response.request()->GetEndpointResults());
9486   EXPECT_FALSE(response.request()->GetHostnameResults());
9487   EXPECT_FALSE(response.request()->GetTextResults());
9488   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9489 }
9490 
9491 // Same as TxtQuery except we specify DNS HostResolverSource instead of relying
9492 // on automatic determination.  Expect same results since DNS should be what we
9493 // automatically determine, but some slightly different logic paths are
9494 // involved.
TEST_F(HostResolverManagerDnsTest,TxtDnsQuery)9495 TEST_F(HostResolverManagerDnsTest, TxtDnsQuery) {
9496   // Simulate two separate DNS records, each with multiple strings.
9497   std::vector<std::string> foo_records = {"foo1", "foo2", "foo3"};
9498   std::vector<std::string> bar_records = {"bar1", "bar2"};
9499   std::vector<std::vector<std::string>> text_records = {foo_records,
9500                                                         bar_records};
9501 
9502   MockDnsClientRuleList rules;
9503   rules.emplace_back("host", dns_protocol::kTypeTXT, false /* secure */,
9504                      MockDnsClientRule::Result(BuildTestDnsTextResponse(
9505                          "host", std::move(text_records))),
9506                      false /* delay */);
9507 
9508   CreateResolver();
9509   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9510 
9511   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
9512 
9513   HostResolver::ResolveHostParameters parameters;
9514   parameters.source = HostResolverSource::DNS;
9515   parameters.dns_query_type = DnsQueryType::TXT;
9516 
9517   ResolveHostResponseHelper response(resolver_->CreateRequest(
9518       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9519       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9520   EXPECT_THAT(response.result_error(), IsOk());
9521   EXPECT_FALSE(response.request()->GetAddressResults());
9522   EXPECT_FALSE(response.request()->GetEndpointResults());
9523   EXPECT_FALSE(response.request()->GetHostnameResults());
9524   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9525 
9526   // Order between separate DNS records is undefined, but each record should
9527   // stay in order as that order may be meaningful.
9528   ASSERT_THAT(response.request()->GetTextResults(),
9529               testing::Optional(testing::UnorderedElementsAre(
9530                   "foo1", "foo2", "foo3", "bar1", "bar2")));
9531   std::vector<std::string> results =
9532       response.request()->GetTextResults().value();
9533   EXPECT_NE(results.end(), base::ranges::search(results, foo_records));
9534   EXPECT_NE(results.end(), base::ranges::search(results, bar_records));
9535 
9536   // Expect result to be cached.
9537   EXPECT_EQ(resolve_context_->host_cache()->size(), 1u);
9538   ResolveHostResponseHelper cached_response(resolver_->CreateRequest(
9539       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9540       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9541   EXPECT_THAT(cached_response.result_error(), IsOk());
9542   EXPECT_TRUE(cached_response.request()->GetStaleInfo());
9543   ASSERT_THAT(cached_response.request()->GetTextResults(),
9544               testing::Optional(testing::UnorderedElementsAre(
9545                   "foo1", "foo2", "foo3", "bar1", "bar2")));
9546   results = cached_response.request()->GetTextResults().value();
9547   EXPECT_NE(results.end(), base::ranges::search(results, foo_records));
9548   EXPECT_NE(results.end(), base::ranges::search(results, bar_records));
9549 }
9550 
TEST_F(HostResolverManagerDnsTest,PtrQuery)9551 TEST_F(HostResolverManagerDnsTest, PtrQuery) {
9552   MockDnsClientRuleList rules;
9553   rules.emplace_back("host", dns_protocol::kTypePTR, false /* secure */,
9554                      MockDnsClientRule::Result(BuildTestDnsPointerResponse(
9555                          "host", {"foo.com", "bar.com"})),
9556                      false /* delay */);
9557 
9558   CreateResolver();
9559   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9560 
9561   HostResolver::ResolveHostParameters parameters;
9562   parameters.dns_query_type = DnsQueryType::PTR;
9563 
9564   ResolveHostResponseHelper response(resolver_->CreateRequest(
9565       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9566       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9567   EXPECT_THAT(response.result_error(), IsOk());
9568   EXPECT_FALSE(response.request()->GetAddressResults());
9569   EXPECT_FALSE(response.request()->GetEndpointResults());
9570   EXPECT_FALSE(response.request()->GetTextResults());
9571   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9572 
9573   // Order between separate records is undefined.
9574   EXPECT_THAT(response.request()->GetHostnameResults(),
9575               testing::Optional(testing::UnorderedElementsAre(
9576                   HostPortPair("foo.com", 108), HostPortPair("bar.com", 108))));
9577 }
9578 
TEST_F(HostResolverManagerDnsTest,PtrQueryRejectsIpLiteral)9579 TEST_F(HostResolverManagerDnsTest, PtrQueryRejectsIpLiteral) {
9580   MockDnsClientRuleList rules;
9581 
9582   // Entry that would resolve if DNS is mistakenly queried to ensure that does
9583   // not happen.
9584   rules.emplace_back("8.8.8.8", dns_protocol::kTypePTR, /*secure=*/false,
9585                      MockDnsClientRule::Result(BuildTestDnsPointerResponse(
9586                          "8.8.8.8", {"foo.com", "bar.com"})),
9587                      /*delay=*/false);
9588 
9589   CreateResolver();
9590   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9591 
9592   HostResolver::ResolveHostParameters parameters;
9593   parameters.dns_query_type = DnsQueryType::PTR;
9594 
9595   ResolveHostResponseHelper response(resolver_->CreateRequest(
9596       HostPortPair("8.8.8.8", 108), NetworkAnonymizationKey(),
9597       NetLogWithSource(), parameters, resolve_context_.get(),
9598       resolve_context_->host_cache()));
9599   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9600   EXPECT_FALSE(response.request()->GetAddressResults());
9601   EXPECT_FALSE(response.request()->GetEndpointResults());
9602   EXPECT_FALSE(response.request()->GetTextResults());
9603   EXPECT_FALSE(response.request()->GetHostnameResults());
9604   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9605 }
9606 
TEST_F(HostResolverManagerDnsTest,PtrQueryHandlesReverseIpLookup)9607 TEST_F(HostResolverManagerDnsTest, PtrQueryHandlesReverseIpLookup) {
9608   const char kHostname[] = "8.8.8.8.in-addr.arpa";
9609 
9610   MockDnsClientRuleList rules;
9611   rules.emplace_back(kHostname, dns_protocol::kTypePTR, /*secure=*/false,
9612                      MockDnsClientRule::Result(BuildTestDnsPointerResponse(
9613                          kHostname, {"dns.google.test", "foo.test"})),
9614                      /*delay=*/false);
9615 
9616   CreateResolver();
9617   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9618 
9619   HostResolver::ResolveHostParameters parameters;
9620   parameters.dns_query_type = DnsQueryType::PTR;
9621 
9622   ResolveHostResponseHelper response(resolver_->CreateRequest(
9623       HostPortPair(kHostname, 108), NetworkAnonymizationKey(),
9624       NetLogWithSource(), parameters, resolve_context_.get(),
9625       resolve_context_->host_cache()));
9626   EXPECT_THAT(response.result_error(), IsOk());
9627   EXPECT_FALSE(response.request()->GetAddressResults());
9628   EXPECT_FALSE(response.request()->GetEndpointResults());
9629   EXPECT_FALSE(response.request()->GetTextResults());
9630   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9631 
9632   // Order between separate records is undefined.
9633   EXPECT_THAT(response.request()->GetHostnameResults(),
9634               testing::Optional(testing::UnorderedElementsAre(
9635                   HostPortPair("dns.google.test", 108),
9636                   HostPortPair("foo.test", 108))));
9637 }
9638 
TEST_F(HostResolverManagerDnsTest,PtrQuery_NonexistentDomain)9639 TEST_F(HostResolverManagerDnsTest, PtrQuery_NonexistentDomain) {
9640   // Setup fallback to confirm it is not used for non-address results.
9641   set_allow_fallback_to_systemtask(true);
9642   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9643   proc_->SignalMultiple(1u);
9644 
9645   MockDnsClientRuleList rules;
9646   rules.emplace_back(
9647       "host", dns_protocol::kTypePTR, false /* secure */,
9648       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kNoDomain),
9649       false /* delay */);
9650 
9651   CreateResolver();
9652   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9653 
9654   HostResolver::ResolveHostParameters parameters;
9655   parameters.dns_query_type = DnsQueryType::PTR;
9656 
9657   ResolveHostResponseHelper response(resolver_->CreateRequest(
9658       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9659       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9660   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9661   EXPECT_FALSE(response.request()->GetAddressResults());
9662   EXPECT_FALSE(response.request()->GetEndpointResults());
9663   EXPECT_FALSE(response.request()->GetTextResults());
9664   EXPECT_FALSE(response.request()->GetHostnameResults());
9665   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9666 }
9667 
TEST_F(HostResolverManagerDnsTest,PtrQuery_Failure)9668 TEST_F(HostResolverManagerDnsTest, PtrQuery_Failure) {
9669   // Setup fallback to confirm it is not used for non-address results.
9670   set_allow_fallback_to_systemtask(true);
9671   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9672   proc_->SignalMultiple(1u);
9673 
9674   MockDnsClientRuleList rules;
9675   rules.emplace_back(
9676       "host", dns_protocol::kTypePTR, false /* secure */,
9677       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
9678       false /* delay */);
9679 
9680   CreateResolver();
9681   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9682 
9683   HostResolver::ResolveHostParameters parameters;
9684   parameters.dns_query_type = DnsQueryType::PTR;
9685 
9686   ResolveHostResponseHelper response(resolver_->CreateRequest(
9687       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9688       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9689   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9690   EXPECT_FALSE(response.request()->GetAddressResults());
9691   EXPECT_FALSE(response.request()->GetEndpointResults());
9692   EXPECT_FALSE(response.request()->GetTextResults());
9693   EXPECT_FALSE(response.request()->GetHostnameResults());
9694   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9695 }
9696 
TEST_F(HostResolverManagerDnsTest,PtrQuery_Timeout)9697 TEST_F(HostResolverManagerDnsTest, PtrQuery_Timeout) {
9698   // Setup fallback to confirm it is not used for non-address results.
9699   set_allow_fallback_to_systemtask(true);
9700   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9701   proc_->SignalMultiple(1u);
9702 
9703   MockDnsClientRuleList rules;
9704   rules.emplace_back(
9705       "host", dns_protocol::kTypePTR, false /* secure */,
9706       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kTimeout),
9707       false /* delay */);
9708 
9709   CreateResolver();
9710   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9711 
9712   HostResolver::ResolveHostParameters parameters;
9713   parameters.dns_query_type = DnsQueryType::PTR;
9714 
9715   ResolveHostResponseHelper response(resolver_->CreateRequest(
9716       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9717       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9718   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_TIMED_OUT));
9719   EXPECT_FALSE(response.request()->GetAddressResults());
9720   EXPECT_FALSE(response.request()->GetEndpointResults());
9721   EXPECT_FALSE(response.request()->GetTextResults());
9722   EXPECT_FALSE(response.request()->GetHostnameResults());
9723   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9724 }
9725 
TEST_F(HostResolverManagerDnsTest,PtrQuery_Empty)9726 TEST_F(HostResolverManagerDnsTest, PtrQuery_Empty) {
9727   // Setup fallback to confirm it is not used for non-address results.
9728   set_allow_fallback_to_systemtask(true);
9729   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9730   proc_->SignalMultiple(1u);
9731 
9732   MockDnsClientRuleList rules;
9733   rules.emplace_back(
9734       "host", dns_protocol::kTypePTR, false /* secure */,
9735       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
9736       false /* delay */);
9737 
9738   CreateResolver();
9739   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9740 
9741   HostResolver::ResolveHostParameters parameters;
9742   parameters.dns_query_type = DnsQueryType::PTR;
9743 
9744   ResolveHostResponseHelper response(resolver_->CreateRequest(
9745       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9746       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9747   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9748   EXPECT_FALSE(response.request()->GetAddressResults());
9749   EXPECT_FALSE(response.request()->GetEndpointResults());
9750   EXPECT_FALSE(response.request()->GetTextResults());
9751   EXPECT_FALSE(response.request()->GetHostnameResults());
9752   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9753 }
9754 
TEST_F(HostResolverManagerDnsTest,PtrQuery_Malformed)9755 TEST_F(HostResolverManagerDnsTest, PtrQuery_Malformed) {
9756   // Setup fallback to confirm it is not used for non-address results.
9757   set_allow_fallback_to_systemtask(true);
9758   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
9759   proc_->SignalMultiple(1u);
9760 
9761   MockDnsClientRuleList rules;
9762   rules.emplace_back(
9763       "host", dns_protocol::kTypePTR, false /* secure */,
9764       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kMalformed),
9765       false /* delay */);
9766 
9767   CreateResolver();
9768   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9769 
9770   HostResolver::ResolveHostParameters parameters;
9771   parameters.dns_query_type = DnsQueryType::PTR;
9772 
9773   ResolveHostResponseHelper response(resolver_->CreateRequest(
9774       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9775       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9776   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_MALFORMED_RESPONSE));
9777   EXPECT_FALSE(response.request()->GetAddressResults());
9778   EXPECT_FALSE(response.request()->GetEndpointResults());
9779   EXPECT_FALSE(response.request()->GetTextResults());
9780   EXPECT_FALSE(response.request()->GetHostnameResults());
9781   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9782 }
9783 
TEST_F(HostResolverManagerDnsTest,PtrQuery_MismatchedName)9784 TEST_F(HostResolverManagerDnsTest, PtrQuery_MismatchedName) {
9785   std::vector<std::string> ptr_records = {{"foo.com"}};
9786   MockDnsClientRuleList rules;
9787   rules.emplace_back("host", dns_protocol::kTypePTR, false /* secure */,
9788                      MockDnsClientRule::Result(BuildTestDnsPointerResponse(
9789                          "host", std::move(ptr_records), "not.host")),
9790                      false /* delay */);
9791 
9792   CreateResolver();
9793   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9794 
9795   HostResolver::ResolveHostParameters parameters;
9796   parameters.dns_query_type = DnsQueryType::PTR;
9797 
9798   ResolveHostResponseHelper response(resolver_->CreateRequest(
9799       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9800       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9801   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_MALFORMED_RESPONSE));
9802   EXPECT_FALSE(response.request()->GetAddressResults());
9803   EXPECT_FALSE(response.request()->GetEndpointResults());
9804   EXPECT_FALSE(response.request()->GetTextResults());
9805   EXPECT_FALSE(response.request()->GetHostnameResults());
9806   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9807 }
9808 
TEST_F(HostResolverManagerDnsTest,PtrQuery_WrongType)9809 TEST_F(HostResolverManagerDnsTest, PtrQuery_WrongType) {
9810   // Respond to a TXT query with an A response.
9811   MockDnsClientRuleList rules;
9812   rules.emplace_back(
9813       "host", dns_protocol::kTypePTR, false /* secure */,
9814       MockDnsClientRule::Result(BuildTestDnsResponse(
9815           "host", dns_protocol::kTypePTR,
9816           {BuildTestAddressRecord("host", IPAddress(1, 2, 3, 4))})),
9817       false /* delay */);
9818 
9819   CreateResolver();
9820   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9821 
9822   HostResolver::ResolveHostParameters parameters;
9823   parameters.dns_query_type = DnsQueryType::PTR;
9824 
9825   // Responses for the wrong type should be ignored.
9826   ResolveHostResponseHelper response(resolver_->CreateRequest(
9827       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9828       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9829   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9830   EXPECT_FALSE(response.request()->GetAddressResults());
9831   EXPECT_FALSE(response.request()->GetEndpointResults());
9832   EXPECT_FALSE(response.request()->GetTextResults());
9833   EXPECT_FALSE(response.request()->GetHostnameResults());
9834   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9835 }
9836 
TEST_F(HostResolverManagerDnsTest,PtrInsecureQueryDisallowedWhenAdditionalTypesDisallowed)9837 TEST_F(HostResolverManagerDnsTest,
9838        PtrInsecureQueryDisallowedWhenAdditionalTypesDisallowed) {
9839   const std::string kName = "ptr.test";
9840 
9841   ChangeDnsConfig(CreateValidDnsConfig());
9842   DnsConfigOverrides overrides;
9843   overrides.secure_dns_mode = SecureDnsMode::kOff;
9844   resolver_->SetDnsConfigOverrides(overrides);
9845   resolver_->SetInsecureDnsClientEnabled(
9846       /*enabled=*/true,
9847       /*additional_dns_types_enabled=*/false);
9848 
9849   HostResolver::ResolveHostParameters parameters;
9850   parameters.dns_query_type = DnsQueryType::PTR;
9851 
9852   ResolveHostResponseHelper response(resolver_->CreateRequest(
9853       HostPortPair(kName, 108), NetworkAnonymizationKey(), NetLogWithSource(),
9854       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9855   // No non-local work is done, so ERR_DNS_CACHE_MISS is the result.
9856   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_CACHE_MISS));
9857   EXPECT_FALSE(response.request()->GetAddressResults());
9858   EXPECT_FALSE(response.request()->GetEndpointResults());
9859   EXPECT_FALSE(response.request()->GetHostnameResults());
9860   EXPECT_FALSE(response.request()->GetTextResults());
9861   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9862 }
9863 
9864 // Same as PtrQuery except we specify DNS HostResolverSource instead of relying
9865 // on automatic determination.  Expect same results since DNS should be what we
9866 // automatically determine, but some slightly different logic paths are
9867 // involved.
TEST_F(HostResolverManagerDnsTest,PtrDnsQuery)9868 TEST_F(HostResolverManagerDnsTest, PtrDnsQuery) {
9869   MockDnsClientRuleList rules;
9870   rules.emplace_back("host", dns_protocol::kTypePTR, false /* secure */,
9871                      MockDnsClientRule::Result(BuildTestDnsPointerResponse(
9872                          "host", {"foo.com", "bar.com"})),
9873                      false /* delay */);
9874 
9875   CreateResolver();
9876   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9877 
9878   HostResolver::ResolveHostParameters parameters;
9879   parameters.source = HostResolverSource::DNS;
9880   parameters.dns_query_type = DnsQueryType::PTR;
9881 
9882   ResolveHostResponseHelper response(resolver_->CreateRequest(
9883       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9884       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9885   EXPECT_THAT(response.result_error(), IsOk());
9886   EXPECT_FALSE(response.request()->GetAddressResults());
9887   EXPECT_FALSE(response.request()->GetEndpointResults());
9888   EXPECT_FALSE(response.request()->GetTextResults());
9889   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9890 
9891   // Order between separate records is undefined.
9892   EXPECT_THAT(response.request()->GetHostnameResults(),
9893               testing::Optional(testing::UnorderedElementsAre(
9894                   HostPortPair("foo.com", 108), HostPortPair("bar.com", 108))));
9895 }
9896 
TEST_F(HostResolverManagerDnsTest,SrvQuery)9897 TEST_F(HostResolverManagerDnsTest, SrvQuery) {
9898   const TestServiceRecord kRecord1 = {2, 3, 1223, "foo.com"};
9899   const TestServiceRecord kRecord2 = {5, 10, 80, "bar.com"};
9900   const TestServiceRecord kRecord3 = {5, 1, 5, "google.com"};
9901   const TestServiceRecord kRecord4 = {2, 100, 12345, "chromium.org"};
9902   MockDnsClientRuleList rules;
9903   rules.emplace_back("host", dns_protocol::kTypeSRV, false /* secure */,
9904                      MockDnsClientRule::Result(BuildTestDnsServiceResponse(
9905                          "host", {kRecord1, kRecord2, kRecord3, kRecord4})),
9906                      false /* delay */);
9907 
9908   CreateResolver();
9909   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9910 
9911   HostResolver::ResolveHostParameters parameters;
9912   parameters.dns_query_type = DnsQueryType::SRV;
9913 
9914   ResolveHostResponseHelper response(resolver_->CreateRequest(
9915       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9916       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9917   EXPECT_THAT(response.result_error(), IsOk());
9918   EXPECT_FALSE(response.request()->GetAddressResults());
9919   EXPECT_FALSE(response.request()->GetEndpointResults());
9920   EXPECT_FALSE(response.request()->GetTextResults());
9921   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9922 
9923   // Expect ordered by priority, and random within a priority.
9924   absl::optional<std::vector<HostPortPair>> results =
9925       response.request()->GetHostnameResults();
9926   ASSERT_THAT(
9927       results,
9928       testing::Optional(testing::UnorderedElementsAre(
9929           HostPortPair("foo.com", 1223), HostPortPair("bar.com", 80),
9930           HostPortPair("google.com", 5), HostPortPair("chromium.org", 12345))));
9931   auto priority2 = std::vector<HostPortPair>(results.value().begin(),
9932                                              results.value().begin() + 2);
9933   EXPECT_THAT(priority2, testing::UnorderedElementsAre(
9934                              HostPortPair("foo.com", 1223),
9935                              HostPortPair("chromium.org", 12345)));
9936   auto priority5 = std::vector<HostPortPair>(results.value().begin() + 2,
9937                                              results.value().end());
9938   EXPECT_THAT(priority5,
9939               testing::UnorderedElementsAre(HostPortPair("bar.com", 80),
9940                                             HostPortPair("google.com", 5)));
9941 }
9942 
TEST_F(HostResolverManagerDnsTest,SrvQueryRejectsIpLiteral)9943 TEST_F(HostResolverManagerDnsTest, SrvQueryRejectsIpLiteral) {
9944   MockDnsClientRuleList rules;
9945 
9946   // Entry that would resolve if DNS is mistakenly queried to ensure that does
9947   // not happen.
9948   rules.emplace_back("8.8.8.8", dns_protocol::kTypeSRV, /*secure=*/false,
9949                      MockDnsClientRule::Result(BuildTestDnsServiceResponse(
9950                          "8.8.8.8", {{/*priority=*/4, /*weight=*/0, /*port=*/90,
9951                                       /*target=*/"google.test"}})),
9952                      /*delay=*/false);
9953 
9954   CreateResolver();
9955   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9956 
9957   HostResolver::ResolveHostParameters parameters;
9958   parameters.dns_query_type = DnsQueryType::SRV;
9959 
9960   ResolveHostResponseHelper response(resolver_->CreateRequest(
9961       HostPortPair("8.8.8.8", 108), NetworkAnonymizationKey(),
9962       NetLogWithSource(), parameters, resolve_context_.get(),
9963       resolve_context_->host_cache()));
9964   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
9965   EXPECT_FALSE(response.request()->GetAddressResults());
9966   EXPECT_FALSE(response.request()->GetEndpointResults());
9967   EXPECT_FALSE(response.request()->GetTextResults());
9968   EXPECT_FALSE(response.request()->GetHostnameResults());
9969   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9970 }
9971 
9972 // 0-weight services are allowed. Ensure that we can handle such records,
9973 // especially the case where all entries have weight 0.
TEST_F(HostResolverManagerDnsTest,SrvQuery_ZeroWeight)9974 TEST_F(HostResolverManagerDnsTest, SrvQuery_ZeroWeight) {
9975   const TestServiceRecord kRecord1 = {5, 0, 80, "bar.com"};
9976   const TestServiceRecord kRecord2 = {5, 0, 5, "google.com"};
9977   MockDnsClientRuleList rules;
9978   rules.emplace_back("host", dns_protocol::kTypeSRV, false /* secure */,
9979                      MockDnsClientRule::Result(BuildTestDnsServiceResponse(
9980                          "host", {kRecord1, kRecord2})),
9981                      false /* delay */);
9982 
9983   CreateResolver();
9984   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
9985 
9986   HostResolver::ResolveHostParameters parameters;
9987   parameters.dns_query_type = DnsQueryType::SRV;
9988 
9989   ResolveHostResponseHelper response(resolver_->CreateRequest(
9990       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
9991       parameters, resolve_context_.get(), resolve_context_->host_cache()));
9992   EXPECT_THAT(response.result_error(), IsOk());
9993   EXPECT_FALSE(response.request()->GetAddressResults());
9994   EXPECT_FALSE(response.request()->GetEndpointResults());
9995   EXPECT_FALSE(response.request()->GetTextResults());
9996   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
9997 
9998   // Expect ordered by priority, and random within a priority.
9999   EXPECT_THAT(response.request()->GetHostnameResults(),
10000               testing::Optional(testing::UnorderedElementsAre(
10001                   HostPortPair("bar.com", 80), HostPortPair("google.com", 5))));
10002 }
10003 
TEST_F(HostResolverManagerDnsTest,SrvQuery_NonexistentDomain)10004 TEST_F(HostResolverManagerDnsTest, SrvQuery_NonexistentDomain) {
10005   // Setup fallback to confirm it is not used for non-address results.
10006   set_allow_fallback_to_systemtask(true);
10007   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
10008   proc_->SignalMultiple(1u);
10009 
10010   MockDnsClientRuleList rules;
10011   rules.emplace_back(
10012       "host", dns_protocol::kTypeSRV, false /* secure */,
10013       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kNoDomain),
10014       false /* delay */);
10015 
10016   CreateResolver();
10017   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10018 
10019   HostResolver::ResolveHostParameters parameters;
10020   parameters.dns_query_type = DnsQueryType::SRV;
10021 
10022   ResolveHostResponseHelper response(resolver_->CreateRequest(
10023       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10024       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10025   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
10026   EXPECT_FALSE(response.request()->GetAddressResults());
10027   EXPECT_FALSE(response.request()->GetEndpointResults());
10028   EXPECT_FALSE(response.request()->GetTextResults());
10029   EXPECT_FALSE(response.request()->GetHostnameResults());
10030   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10031 }
10032 
TEST_F(HostResolverManagerDnsTest,SrvQuery_Failure)10033 TEST_F(HostResolverManagerDnsTest, SrvQuery_Failure) {
10034   // Setup fallback to confirm it is not used for non-address results.
10035   set_allow_fallback_to_systemtask(true);
10036   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
10037   proc_->SignalMultiple(1u);
10038 
10039   MockDnsClientRuleList rules;
10040   rules.emplace_back(
10041       "host", dns_protocol::kTypeSRV, false /* secure */,
10042       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
10043       false /* delay */);
10044 
10045   CreateResolver();
10046   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10047 
10048   HostResolver::ResolveHostParameters parameters;
10049   parameters.dns_query_type = DnsQueryType::SRV;
10050 
10051   ResolveHostResponseHelper response(resolver_->CreateRequest(
10052       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10053       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10054   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
10055   EXPECT_FALSE(response.request()->GetAddressResults());
10056   EXPECT_FALSE(response.request()->GetEndpointResults());
10057   EXPECT_FALSE(response.request()->GetTextResults());
10058   EXPECT_FALSE(response.request()->GetHostnameResults());
10059   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10060 }
10061 
TEST_F(HostResolverManagerDnsTest,SrvQuery_Timeout)10062 TEST_F(HostResolverManagerDnsTest, SrvQuery_Timeout) {
10063   // Setup fallback to confirm it is not used for non-address results.
10064   set_allow_fallback_to_systemtask(true);
10065   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
10066   proc_->SignalMultiple(1u);
10067 
10068   MockDnsClientRuleList rules;
10069   rules.emplace_back(
10070       "host", dns_protocol::kTypeSRV, false /* secure */,
10071       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kTimeout),
10072       false /* delay */);
10073 
10074   CreateResolver();
10075   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10076 
10077   HostResolver::ResolveHostParameters parameters;
10078   parameters.dns_query_type = DnsQueryType::SRV;
10079 
10080   ResolveHostResponseHelper response(resolver_->CreateRequest(
10081       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10082       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10083   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_TIMED_OUT));
10084   EXPECT_FALSE(response.request()->GetAddressResults());
10085   EXPECT_FALSE(response.request()->GetEndpointResults());
10086   EXPECT_FALSE(response.request()->GetTextResults());
10087   EXPECT_FALSE(response.request()->GetHostnameResults());
10088   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10089 }
10090 
TEST_F(HostResolverManagerDnsTest,SrvQuery_Empty)10091 TEST_F(HostResolverManagerDnsTest, SrvQuery_Empty) {
10092   // Setup fallback to confirm it is not used for non-address results.
10093   set_allow_fallback_to_systemtask(true);
10094   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
10095   proc_->SignalMultiple(1u);
10096 
10097   MockDnsClientRuleList rules;
10098   rules.emplace_back(
10099       "host", dns_protocol::kTypeSRV, false /* secure */,
10100       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
10101       false /* delay */);
10102 
10103   CreateResolver();
10104   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10105 
10106   HostResolver::ResolveHostParameters parameters;
10107   parameters.dns_query_type = DnsQueryType::SRV;
10108 
10109   ResolveHostResponseHelper response(resolver_->CreateRequest(
10110       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10111       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10112   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
10113   EXPECT_FALSE(response.request()->GetAddressResults());
10114   EXPECT_FALSE(response.request()->GetEndpointResults());
10115   EXPECT_FALSE(response.request()->GetTextResults());
10116   EXPECT_FALSE(response.request()->GetHostnameResults());
10117   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10118 }
10119 
TEST_F(HostResolverManagerDnsTest,SrvQuery_Malformed)10120 TEST_F(HostResolverManagerDnsTest, SrvQuery_Malformed) {
10121   // Setup fallback to confirm it is not used for non-address results.
10122   set_allow_fallback_to_systemtask(true);
10123   proc_->AddRuleForAllFamilies("host", "192.168.1.102");
10124   proc_->SignalMultiple(1u);
10125 
10126   MockDnsClientRuleList rules;
10127   rules.emplace_back(
10128       "host", dns_protocol::kTypeSRV, false /* secure */,
10129       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kMalformed),
10130       false /* delay */);
10131 
10132   CreateResolver();
10133   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10134 
10135   HostResolver::ResolveHostParameters parameters;
10136   parameters.dns_query_type = DnsQueryType::SRV;
10137 
10138   ResolveHostResponseHelper response(resolver_->CreateRequest(
10139       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10140       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10141   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_MALFORMED_RESPONSE));
10142   EXPECT_FALSE(response.request()->GetAddressResults());
10143   EXPECT_FALSE(response.request()->GetEndpointResults());
10144   EXPECT_FALSE(response.request()->GetTextResults());
10145   EXPECT_FALSE(response.request()->GetHostnameResults());
10146   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10147 }
10148 
TEST_F(HostResolverManagerDnsTest,SrvQuery_MismatchedName)10149 TEST_F(HostResolverManagerDnsTest, SrvQuery_MismatchedName) {
10150   std::vector<TestServiceRecord> srv_records = {{1, 2, 3, "foo.com"}};
10151   MockDnsClientRuleList rules;
10152   rules.emplace_back("host", dns_protocol::kTypeSRV, false /* secure */,
10153                      MockDnsClientRule::Result(BuildTestDnsServiceResponse(
10154                          "host", std::move(srv_records), "not.host")),
10155                      false /* delay */);
10156 
10157   CreateResolver();
10158   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10159 
10160   HostResolver::ResolveHostParameters parameters;
10161   parameters.dns_query_type = DnsQueryType::SRV;
10162 
10163   ResolveHostResponseHelper response(resolver_->CreateRequest(
10164       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10165       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10166   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_MALFORMED_RESPONSE));
10167   EXPECT_FALSE(response.request()->GetAddressResults());
10168   EXPECT_FALSE(response.request()->GetEndpointResults());
10169   EXPECT_FALSE(response.request()->GetTextResults());
10170   EXPECT_FALSE(response.request()->GetHostnameResults());
10171   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10172 }
10173 
TEST_F(HostResolverManagerDnsTest,SrvQuery_WrongType)10174 TEST_F(HostResolverManagerDnsTest, SrvQuery_WrongType) {
10175   // Respond to a SRV query with an A response.
10176   MockDnsClientRuleList rules;
10177   rules.emplace_back(
10178       "host", dns_protocol::kTypeSRV, false /* secure */,
10179       MockDnsClientRule::Result(BuildTestDnsResponse(
10180           "host", dns_protocol::kTypeSRV,
10181           {BuildTestAddressRecord("host", IPAddress(1, 2, 3, 4))})),
10182       false /* delay */);
10183 
10184   CreateResolver();
10185   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10186 
10187   HostResolver::ResolveHostParameters parameters;
10188   parameters.dns_query_type = DnsQueryType::SRV;
10189 
10190   // Responses for the wrong type should be ignored.
10191   ResolveHostResponseHelper response(resolver_->CreateRequest(
10192       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10193       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10194   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
10195   EXPECT_FALSE(response.request()->GetAddressResults());
10196   EXPECT_FALSE(response.request()->GetEndpointResults());
10197   EXPECT_FALSE(response.request()->GetTextResults());
10198   EXPECT_FALSE(response.request()->GetHostnameResults());
10199   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10200 }
10201 
TEST_F(HostResolverManagerDnsTest,SrvInsecureQueryDisallowedWhenAdditionalTypesDisallowed)10202 TEST_F(HostResolverManagerDnsTest,
10203        SrvInsecureQueryDisallowedWhenAdditionalTypesDisallowed) {
10204   const std::string kName = "srv.test";
10205 
10206   ChangeDnsConfig(CreateValidDnsConfig());
10207   DnsConfigOverrides overrides;
10208   overrides.secure_dns_mode = SecureDnsMode::kOff;
10209   resolver_->SetDnsConfigOverrides(overrides);
10210   resolver_->SetInsecureDnsClientEnabled(
10211       /*enabled=*/true,
10212       /*additional_dns_types_enabled=*/false);
10213 
10214   HostResolver::ResolveHostParameters parameters;
10215   parameters.dns_query_type = DnsQueryType::SRV;
10216 
10217   ResolveHostResponseHelper response(resolver_->CreateRequest(
10218       HostPortPair(kName, 108), NetworkAnonymizationKey(), NetLogWithSource(),
10219       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10220   // No non-local work is done, so ERR_DNS_CACHE_MISS is the result.
10221   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_CACHE_MISS));
10222   EXPECT_FALSE(response.request()->GetAddressResults());
10223   EXPECT_FALSE(response.request()->GetEndpointResults());
10224   EXPECT_FALSE(response.request()->GetHostnameResults());
10225   EXPECT_FALSE(response.request()->GetTextResults());
10226   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10227 }
10228 
10229 // Same as SrvQuery except we specify DNS HostResolverSource instead of relying
10230 // on automatic determination.  Expect same results since DNS should be what we
10231 // automatically determine, but some slightly different logic paths are
10232 // involved.
TEST_F(HostResolverManagerDnsTest,SrvDnsQuery)10233 TEST_F(HostResolverManagerDnsTest, SrvDnsQuery) {
10234   const TestServiceRecord kRecord1 = {2, 3, 1223, "foo.com"};
10235   const TestServiceRecord kRecord2 = {5, 10, 80, "bar.com"};
10236   const TestServiceRecord kRecord3 = {5, 1, 5, "google.com"};
10237   const TestServiceRecord kRecord4 = {2, 100, 12345, "chromium.org"};
10238   MockDnsClientRuleList rules;
10239   rules.emplace_back("host", dns_protocol::kTypeSRV, false /* secure */,
10240                      MockDnsClientRule::Result(BuildTestDnsServiceResponse(
10241                          "host", {kRecord1, kRecord2, kRecord3, kRecord4})),
10242                      false /* delay */);
10243 
10244   CreateResolver();
10245   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10246 
10247   HostResolver::ResolveHostParameters parameters;
10248   parameters.source = HostResolverSource::DNS;
10249   parameters.dns_query_type = DnsQueryType::SRV;
10250 
10251   ResolveHostResponseHelper response(resolver_->CreateRequest(
10252       HostPortPair("host", 108), NetworkAnonymizationKey(), NetLogWithSource(),
10253       parameters, resolve_context_.get(), resolve_context_->host_cache()));
10254   EXPECT_THAT(response.result_error(), IsOk());
10255   EXPECT_FALSE(response.request()->GetAddressResults());
10256   EXPECT_FALSE(response.request()->GetEndpointResults());
10257   EXPECT_FALSE(response.request()->GetTextResults());
10258   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10259 
10260   // Expect ordered by priority, and random within a priority.
10261   absl::optional<std::vector<HostPortPair>> results =
10262       response.request()->GetHostnameResults();
10263   ASSERT_THAT(
10264       results,
10265       testing::Optional(testing::UnorderedElementsAre(
10266           HostPortPair("foo.com", 1223), HostPortPair("bar.com", 80),
10267           HostPortPair("google.com", 5), HostPortPair("chromium.org", 12345))));
10268   auto priority2 = std::vector<HostPortPair>(results.value().begin(),
10269                                              results.value().begin() + 2);
10270   EXPECT_THAT(priority2, testing::UnorderedElementsAre(
10271                              HostPortPair("foo.com", 1223),
10272                              HostPortPair("chromium.org", 12345)));
10273   auto priority5 = std::vector<HostPortPair>(results.value().begin() + 2,
10274                                              results.value().end());
10275   EXPECT_THAT(priority5,
10276               testing::UnorderedElementsAre(HostPortPair("bar.com", 80),
10277                                             HostPortPair("google.com", 5)));
10278 }
10279 
TEST_F(HostResolverManagerDnsTest,HttpsQuery)10280 TEST_F(HostResolverManagerDnsTest, HttpsQuery) {
10281   const std::string kName = "https.test";
10282 
10283   MockDnsClientRuleList rules;
10284   std::vector<DnsResourceRecord> records = {
10285       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
10286                                   /*params=*/{})};
10287   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
10288                      MockDnsClientRule::Result(BuildTestDnsResponse(
10289                          kName, dns_protocol::kTypeHttps, records)),
10290                      /*delay=*/false);
10291 
10292   CreateResolver();
10293   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10294 
10295   HostResolver::ResolveHostParameters parameters;
10296   parameters.dns_query_type = DnsQueryType::HTTPS;
10297 
10298   ResolveHostResponseHelper response(resolver_->CreateRequest(
10299       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10300       NetworkAnonymizationKey(), NetLogWithSource(), parameters,
10301       resolve_context_.get(), resolve_context_->host_cache()));
10302   EXPECT_THAT(response.result_error(), IsOk());
10303   EXPECT_FALSE(response.request()->GetAddressResults());
10304   EXPECT_FALSE(response.request()->GetEndpointResults());
10305   EXPECT_FALSE(response.request()->GetHostnameResults());
10306   EXPECT_FALSE(response.request()->GetTextResults());
10307   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10308               testing::Pointee(testing::ElementsAre(true)));
10309 }
10310 
TEST_F(HostResolverManagerDnsTest,HttpsQueryForNonStandardPort)10311 TEST_F(HostResolverManagerDnsTest, HttpsQueryForNonStandardPort) {
10312   const std::string kName = "https.test";
10313   const std::string kExpectedQueryName = "_1111._https." + kName;
10314 
10315   MockDnsClientRuleList rules;
10316   std::vector<DnsResourceRecord> records = {BuildTestHttpsServiceRecord(
10317       kExpectedQueryName, /*priority=*/1, /*service_name=*/kName,
10318       /*params=*/{})};
10319   rules.emplace_back(
10320       kExpectedQueryName, dns_protocol::kTypeHttps,
10321       /*secure=*/false,
10322       MockDnsClientRule::Result(BuildTestDnsResponse(
10323           kExpectedQueryName, dns_protocol::kTypeHttps, records)),
10324       /*delay=*/false);
10325 
10326   CreateResolver();
10327   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10328 
10329   HostResolver::ResolveHostParameters parameters;
10330   parameters.dns_query_type = DnsQueryType::HTTPS;
10331 
10332   ResolveHostResponseHelper response(resolver_->CreateRequest(
10333       url::SchemeHostPort(url::kHttpsScheme, kName, 1111),
10334       NetworkAnonymizationKey(), NetLogWithSource(), parameters,
10335       resolve_context_.get(), resolve_context_->host_cache()));
10336   EXPECT_THAT(response.result_error(), IsOk());
10337   EXPECT_FALSE(response.request()->GetAddressResults());
10338   EXPECT_FALSE(response.request()->GetEndpointResults());
10339   EXPECT_FALSE(response.request()->GetHostnameResults());
10340   EXPECT_FALSE(response.request()->GetTextResults());
10341   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10342               testing::Pointee(testing::ElementsAre(true)));
10343 }
10344 
TEST_F(HostResolverManagerDnsTest,HttpsQueryForHttpUpgrade)10345 TEST_F(HostResolverManagerDnsTest, HttpsQueryForHttpUpgrade) {
10346   const std::string kName = "https.test";
10347 
10348   MockDnsClientRuleList rules;
10349   std::vector<DnsResourceRecord> records = {
10350       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
10351                                   /*params=*/{})};
10352   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
10353                      MockDnsClientRule::Result(BuildTestDnsResponse(
10354                          kName, dns_protocol::kTypeHttps, records)),
10355                      /*delay=*/false);
10356 
10357   CreateResolver();
10358   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10359 
10360   HostResolver::ResolveHostParameters parameters;
10361   parameters.dns_query_type = DnsQueryType::HTTPS;
10362 
10363   ResolveHostResponseHelper response(resolver_->CreateRequest(
10364       url::SchemeHostPort(url::kHttpScheme, kName, 80),
10365       NetworkAnonymizationKey(), NetLogWithSource(), parameters,
10366       resolve_context_.get(), resolve_context_->host_cache()));
10367   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
10368   EXPECT_FALSE(response.request()->GetAddressResults());
10369   EXPECT_FALSE(response.request()->GetEndpointResults());
10370   EXPECT_FALSE(response.request()->GetHostnameResults());
10371   EXPECT_FALSE(response.request()->GetTextResults());
10372   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10373 }
10374 
10375 // Test that HTTPS requests for an http host with port 443 will result in a
10376 // transaction hostname without prepending port and scheme, despite not having
10377 // the default port for an http host. The request host ("http://https.test:443")
10378 // will be mapped to the equivalent https upgrade host
10379 // ("https://https.test:443") at port 443, which is the default port for an
10380 // https host, so port and scheme are not prefixed.
TEST_F(HostResolverManagerDnsTest,HttpsQueryForHttpUpgradeFromHttpsPort)10381 TEST_F(HostResolverManagerDnsTest, HttpsQueryForHttpUpgradeFromHttpsPort) {
10382   const std::string kName = "https.test";
10383 
10384   MockDnsClientRuleList rules;
10385   std::vector<DnsResourceRecord> records = {
10386       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
10387                                   /*params=*/{})};
10388   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
10389                      MockDnsClientRule::Result(BuildTestDnsResponse(
10390                          kName, dns_protocol::kTypeHttps, records)),
10391                      /*delay=*/false);
10392 
10393   CreateResolver();
10394   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10395 
10396   HostResolver::ResolveHostParameters parameters;
10397   parameters.dns_query_type = DnsQueryType::HTTPS;
10398 
10399   ResolveHostResponseHelper response(resolver_->CreateRequest(
10400       url::SchemeHostPort(url::kHttpScheme, kName, 443),
10401       NetworkAnonymizationKey(), NetLogWithSource(), parameters,
10402       resolve_context_.get(), resolve_context_->host_cache()));
10403   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
10404   EXPECT_FALSE(response.request()->GetAddressResults());
10405   EXPECT_FALSE(response.request()->GetEndpointResults());
10406   EXPECT_FALSE(response.request()->GetHostnameResults());
10407   EXPECT_FALSE(response.request()->GetTextResults());
10408   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10409 }
10410 
TEST_F(HostResolverManagerDnsTest,HttpsQueryForHttpUpgradeWithNonStandardPort)10411 TEST_F(HostResolverManagerDnsTest,
10412        HttpsQueryForHttpUpgradeWithNonStandardPort) {
10413   const std::string kName = "https.test";
10414   const std::string kExpectedQueryName = "_1111._https." + kName;
10415 
10416   MockDnsClientRuleList rules;
10417   std::vector<DnsResourceRecord> records = {BuildTestHttpsServiceRecord(
10418       kExpectedQueryName, /*priority=*/1, /*service_name=*/kName,
10419       /*params=*/{})};
10420   rules.emplace_back(
10421       kExpectedQueryName, dns_protocol::kTypeHttps,
10422       /*secure=*/false,
10423       MockDnsClientRule::Result(BuildTestDnsResponse(
10424           kExpectedQueryName, dns_protocol::kTypeHttps, records)),
10425       /*delay=*/false);
10426 
10427   CreateResolver();
10428   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10429 
10430   HostResolver::ResolveHostParameters parameters;
10431   parameters.dns_query_type = DnsQueryType::HTTPS;
10432 
10433   ResolveHostResponseHelper response(resolver_->CreateRequest(
10434       url::SchemeHostPort(url::kHttpScheme, kName, 1111),
10435       NetworkAnonymizationKey(), NetLogWithSource(), parameters,
10436       resolve_context_.get(), resolve_context_->host_cache()));
10437   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
10438   EXPECT_FALSE(response.request()->GetAddressResults());
10439   EXPECT_FALSE(response.request()->GetEndpointResults());
10440   EXPECT_FALSE(response.request()->GetHostnameResults());
10441   EXPECT_FALSE(response.request()->GetTextResults());
10442   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10443 }
10444 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQuery)10445 TEST_F(HostResolverManagerDnsTest, HttpsInAddressQuery) {
10446   const char kName[] = "name.test";
10447 
10448   base::test::ScopedFeatureList features(features::kUseDnsHttpsSvcb);
10449 
10450   MockDnsClientRuleList rules;
10451   std::vector<DnsResourceRecord> records = {
10452       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
10453                                   /*params=*/{})};
10454   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
10455                      MockDnsClientRule::Result(BuildTestDnsResponse(
10456                          kName, dns_protocol::kTypeHttps, records)),
10457                      /*delay=*/false);
10458   rules.emplace_back(
10459       kName, dns_protocol::kTypeA, /*secure=*/true,
10460       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10461       /*delay=*/false);
10462   rules.emplace_back(
10463       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10464       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10465       /*delay=*/false);
10466 
10467   CreateResolver();
10468   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10469   DnsConfigOverrides overrides;
10470   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
10471   resolver_->SetDnsConfigOverrides(overrides);
10472 
10473   ResolveHostResponseHelper response(resolver_->CreateRequest(
10474       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10475       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10476       resolve_context_.get(), resolve_context_->host_cache()));
10477   EXPECT_THAT(response.result_error(), IsOk());
10478   EXPECT_TRUE(response.request()->GetAddressResults());
10479   EXPECT_THAT(
10480       response.request()->GetEndpointResults(),
10481       testing::Pointee(testing::ElementsAre(
10482           ExpectEndpointResult(
10483               testing::SizeIs(2),
10484               ExpectConnectionEndpointMetadata(
10485                   testing::ElementsAre(dns_protocol::kHttpsServiceDefaultAlpn),
10486                   testing::IsEmpty(), kName)),
10487           ExpectEndpointResult(testing::SizeIs(2)))));
10488   EXPECT_FALSE(response.request()->GetTextResults());
10489   EXPECT_FALSE(response.request()->GetHostnameResults());
10490   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10491               testing::Pointee(testing::ElementsAre(true)));
10492 }
10493 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithNonstandardPort)10494 TEST_F(HostResolverManagerDnsTest, HttpsInAddressQueryWithNonstandardPort) {
10495   const char kName[] = "name.test";
10496   const char kExpectedHttpsQueryName[] = "_108._https.name.test";
10497 
10498   base::test::ScopedFeatureList features;
10499   features.InitAndEnableFeatureWithParameters(
10500       features::kUseDnsHttpsSvcb,
10501       {// Disable timeouts.
10502        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10503        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10504        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10505        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10506        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10507        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10508 
10509   MockDnsClientRuleList rules;
10510   std::vector<DnsResourceRecord> records = {BuildTestHttpsServiceRecord(
10511       kExpectedHttpsQueryName, /*priority=*/1, /*service_name=*/kName,
10512       /*params=*/{})};
10513   rules.emplace_back(
10514       kExpectedHttpsQueryName, dns_protocol::kTypeHttps,
10515       /*secure=*/true,
10516       MockDnsClientRule::Result(BuildTestDnsResponse(
10517           kExpectedHttpsQueryName, dns_protocol::kTypeHttps, records)),
10518       /*delay=*/false);
10519   rules.emplace_back(
10520       kName, dns_protocol::kTypeA, /*secure=*/true,
10521       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10522       /*delay=*/false);
10523   rules.emplace_back(
10524       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10525       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10526       /*delay=*/false);
10527 
10528   CreateResolver();
10529   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10530   DnsConfigOverrides overrides;
10531   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
10532   resolver_->SetDnsConfigOverrides(overrides);
10533 
10534   ResolveHostResponseHelper response(resolver_->CreateRequest(
10535       url::SchemeHostPort(url::kHttpsScheme, kName, 108),
10536       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10537       resolve_context_.get(), resolve_context_->host_cache()));
10538   EXPECT_THAT(response.result_error(), IsOk());
10539   EXPECT_TRUE(response.request()->GetAddressResults());
10540   EXPECT_THAT(
10541       response.request()->GetEndpointResults(),
10542       testing::Pointee(testing::ElementsAre(
10543           ExpectEndpointResult(
10544               testing::SizeIs(2),
10545               ExpectConnectionEndpointMetadata(
10546                   testing::ElementsAre(dns_protocol::kHttpsServiceDefaultAlpn),
10547                   testing::IsEmpty(), kName)),
10548           ExpectEndpointResult(testing::SizeIs(2)))));
10549   EXPECT_FALSE(response.request()->GetTextResults());
10550   EXPECT_FALSE(response.request()->GetHostnameResults());
10551   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10552               testing::Pointee(testing::ElementsAre(true)));
10553 }
10554 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithNonstandardPortAndDefaultServiceName)10555 TEST_F(HostResolverManagerDnsTest,
10556        HttpsInAddressQueryWithNonstandardPortAndDefaultServiceName) {
10557   const char kName[] = "name.test";
10558   const char kExpectedHttpsQueryName[] = "_108._https.name.test";
10559 
10560   base::test::ScopedFeatureList features;
10561   features.InitAndEnableFeatureWithParameters(
10562       features::kUseDnsHttpsSvcb,
10563       {// Disable timeouts.
10564        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10565        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10566        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10567        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10568        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10569        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10570 
10571   MockDnsClientRuleList rules;
10572   std::vector<DnsResourceRecord> records = {BuildTestHttpsServiceRecord(
10573       kExpectedHttpsQueryName, /*priority=*/1, /*service_name=*/".",
10574       /*params=*/{})};
10575   rules.emplace_back(
10576       kExpectedHttpsQueryName, dns_protocol::kTypeHttps,
10577       /*secure=*/true,
10578       MockDnsClientRule::Result(BuildTestDnsResponse(
10579           kExpectedHttpsQueryName, dns_protocol::kTypeHttps, records)),
10580       /*delay=*/false);
10581   rules.emplace_back(
10582       kName, dns_protocol::kTypeA, /*secure=*/true,
10583       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10584       /*delay=*/false);
10585   rules.emplace_back(
10586       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10587       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10588       /*delay=*/false);
10589 
10590   CreateResolver();
10591   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10592   DnsConfigOverrides overrides;
10593   overrides.secure_dns_mode = SecureDnsMode::kSecure;
10594   resolver_->SetDnsConfigOverrides(overrides);
10595 
10596   ResolveHostResponseHelper response(resolver_->CreateRequest(
10597       url::SchemeHostPort(url::kHttpsScheme, kName, 108),
10598       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10599       resolve_context_.get(), resolve_context_->host_cache()));
10600   EXPECT_THAT(response.result_error(), IsOk());
10601   EXPECT_TRUE(response.request()->GetAddressResults());
10602   // Expect only A/AAAA results without metadata because the HTTPS service
10603   // target name matches the port-prefixed name which does not match the A/AAAA
10604   // name and is thus not supported due to requiring followup queries.
10605   EXPECT_THAT(response.request()->GetEndpointResults(),
10606               testing::Pointee(testing::ElementsAre(
10607                   ExpectEndpointResult(testing::SizeIs(2)))));
10608   EXPECT_FALSE(response.request()->GetTextResults());
10609   EXPECT_FALSE(response.request()->GetHostnameResults());
10610   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10611               testing::Pointee(testing::ElementsAre(true)));
10612 }
10613 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithAlpnAndEch)10614 TEST_F(HostResolverManagerDnsTest, HttpsInAddressQueryWithAlpnAndEch) {
10615   const char kName[] = "name.test";
10616   const uint8_t kEch[] = "ECH is neato!";
10617 
10618   base::test::ScopedFeatureList features;
10619   features.InitAndEnableFeatureWithParameters(
10620       features::kUseDnsHttpsSvcb,
10621       {// Disable timeouts.
10622        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10623        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10624        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10625        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10626        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10627        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10628 
10629   MockDnsClientRuleList rules;
10630   std::vector<DnsResourceRecord> records = {BuildTestHttpsServiceRecord(
10631       kName, /*priority=*/8, /*service_name=*/".",
10632       /*params=*/
10633       {BuildTestHttpsServiceAlpnParam({"foo1", "foo2"}),
10634        BuildTestHttpsServiceEchConfigParam(kEch)})};
10635   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
10636                      MockDnsClientRule::Result(BuildTestDnsResponse(
10637                          kName, dns_protocol::kTypeHttps, records)),
10638                      /*delay=*/false);
10639   rules.emplace_back(
10640       kName, dns_protocol::kTypeA, /*secure=*/true,
10641       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10642       /*delay=*/false);
10643   rules.emplace_back(
10644       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10645       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10646       /*delay=*/false);
10647 
10648   CreateResolver();
10649   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10650   DnsConfigOverrides overrides;
10651   overrides.secure_dns_mode = SecureDnsMode::kSecure;
10652   resolver_->SetDnsConfigOverrides(overrides);
10653 
10654   ResolveHostResponseHelper response(resolver_->CreateRequest(
10655       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10656       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10657       resolve_context_.get(), resolve_context_->host_cache()));
10658   EXPECT_THAT(response.result_error(), IsOk());
10659   EXPECT_TRUE(response.request()->GetAddressResults());
10660   EXPECT_THAT(
10661       response.request()->GetEndpointResults(),
10662       testing::Pointee(testing::ElementsAre(
10663           ExpectEndpointResult(
10664               testing::SizeIs(2),
10665               ExpectConnectionEndpointMetadata(
10666                   testing::UnorderedElementsAre(
10667                       "foo1", "foo2", dns_protocol::kHttpsServiceDefaultAlpn),
10668                   testing::ElementsAreArray(kEch), kName)),
10669           ExpectEndpointResult(testing::SizeIs(2)))));
10670   EXPECT_FALSE(response.request()->GetTextResults());
10671   EXPECT_FALSE(response.request()->GetHostnameResults());
10672   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10673               testing::Pointee(testing::ElementsAre(true)));
10674 }
10675 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithNonMatchingPort)10676 TEST_F(HostResolverManagerDnsTest, HttpsInAddressQueryWithNonMatchingPort) {
10677   const char kName[] = "name.test";
10678 
10679   base::test::ScopedFeatureList features;
10680   features.InitAndEnableFeatureWithParameters(
10681       features::kUseDnsHttpsSvcb,
10682       {// Disable timeouts.
10683        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10684        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10685        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10686        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10687        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10688        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10689 
10690   MockDnsClientRuleList rules;
10691   std::vector<DnsResourceRecord> records = {
10692       BuildTestHttpsServiceRecord(kName, /*priority=*/8, /*service_name=*/".",
10693                                   /*params=*/
10694                                   {BuildTestHttpsServicePortParam(3000)})};
10695   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
10696                      MockDnsClientRule::Result(BuildTestDnsResponse(
10697                          kName, dns_protocol::kTypeHttps, records)),
10698                      /*delay=*/false);
10699   rules.emplace_back(
10700       kName, dns_protocol::kTypeA, /*secure=*/true,
10701       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10702       /*delay=*/false);
10703   rules.emplace_back(
10704       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10705       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10706       /*delay=*/false);
10707 
10708   CreateResolver();
10709   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10710   DnsConfigOverrides overrides;
10711   overrides.secure_dns_mode = SecureDnsMode::kSecure;
10712   resolver_->SetDnsConfigOverrides(overrides);
10713 
10714   ResolveHostResponseHelper response(resolver_->CreateRequest(
10715       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10716       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10717       resolve_context_.get(), resolve_context_->host_cache()));
10718   EXPECT_THAT(response.result_error(), IsOk());
10719   EXPECT_TRUE(response.request()->GetAddressResults());
10720   EXPECT_THAT(response.request()->GetEndpointResults(),
10721               testing::Pointee(testing::ElementsAre(
10722                   ExpectEndpointResult(testing::SizeIs(2)))));
10723   EXPECT_FALSE(response.request()->GetTextResults());
10724   EXPECT_FALSE(response.request()->GetHostnameResults());
10725   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10726               testing::Pointee(testing::ElementsAre(true)));
10727 }
10728 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithMatchingPort)10729 TEST_F(HostResolverManagerDnsTest, HttpsInAddressQueryWithMatchingPort) {
10730   const char kName[] = "name.test";
10731 
10732   base::test::ScopedFeatureList features;
10733   features.InitAndEnableFeatureWithParameters(
10734       features::kUseDnsHttpsSvcb,
10735       {// Disable timeouts.
10736        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10737        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10738        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10739        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10740        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10741        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10742 
10743   MockDnsClientRuleList rules;
10744   std::vector<DnsResourceRecord> records = {
10745       BuildTestHttpsServiceRecord(kName, /*priority=*/8, /*service_name=*/".",
10746                                   /*params=*/
10747                                   {BuildTestHttpsServicePortParam(443)})};
10748   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
10749                      MockDnsClientRule::Result(BuildTestDnsResponse(
10750                          kName, dns_protocol::kTypeHttps, records)),
10751                      /*delay=*/false);
10752   rules.emplace_back(
10753       kName, dns_protocol::kTypeA, /*secure=*/true,
10754       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10755       /*delay=*/false);
10756   rules.emplace_back(
10757       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10758       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10759       /*delay=*/false);
10760 
10761   CreateResolver();
10762   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10763   DnsConfigOverrides overrides;
10764   overrides.secure_dns_mode = SecureDnsMode::kSecure;
10765   resolver_->SetDnsConfigOverrides(overrides);
10766 
10767   ResolveHostResponseHelper response(resolver_->CreateRequest(
10768       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10769       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10770       resolve_context_.get(), resolve_context_->host_cache()));
10771   EXPECT_THAT(response.result_error(), IsOk());
10772   EXPECT_TRUE(response.request()->GetAddressResults());
10773   EXPECT_THAT(
10774       response.request()->GetEndpointResults(),
10775       testing::Pointee(testing::ElementsAre(
10776           ExpectEndpointResult(
10777               testing::SizeIs(2),
10778               ExpectConnectionEndpointMetadata(
10779                   testing::ElementsAre(dns_protocol::kHttpsServiceDefaultAlpn),
10780                   testing::IsEmpty(), kName)),
10781           ExpectEndpointResult(testing::SizeIs(2)))));
10782   EXPECT_FALSE(response.request()->GetTextResults());
10783   EXPECT_FALSE(response.request()->GetHostnameResults());
10784   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10785               testing::Pointee(testing::ElementsAre(true)));
10786 }
10787 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithoutAddresses)10788 TEST_F(HostResolverManagerDnsTest, HttpsInAddressQueryWithoutAddresses) {
10789   const char kName[] = "name.test";
10790 
10791   base::test::ScopedFeatureList features;
10792   features.InitAndEnableFeatureWithParameters(
10793       features::kUseDnsHttpsSvcb,
10794       {// Disable timeouts.
10795        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10796        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10797        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10798        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10799        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10800        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10801 
10802   MockDnsClientRuleList rules;
10803   std::vector<DnsResourceRecord> records = {
10804       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
10805                                   /*params=*/{})};
10806   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
10807                      MockDnsClientRule::Result(BuildTestDnsResponse(
10808                          kName, dns_protocol::kTypeHttps, records)),
10809                      /*delay=*/false);
10810   rules.emplace_back(
10811       kName, dns_protocol::kTypeA, /*secure=*/true,
10812       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
10813       /*delay=*/false);
10814   rules.emplace_back(
10815       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10816       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
10817       /*delay=*/false);
10818 
10819   // Will fall back to insecure due to lack of addresses.
10820   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
10821                      MockDnsClientRule::Result(BuildTestDnsResponse(
10822                          kName, dns_protocol::kTypeHttps, records)),
10823                      /*delay=*/false);
10824   rules.emplace_back(
10825       kName, dns_protocol::kTypeA, /*secure=*/false,
10826       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
10827       /*delay=*/false);
10828   rules.emplace_back(
10829       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
10830       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
10831       /*delay=*/false);
10832 
10833   // Will fall back to system resolver due to lack of addresses.
10834   proc_->AddRuleForAllFamilies("just.testing", "");
10835   proc_->SignalMultiple(1u);
10836 
10837   CreateResolver();
10838   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10839   DnsConfigOverrides overrides;
10840   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
10841   resolver_->SetDnsConfigOverrides(overrides);
10842 
10843   ResolveHostResponseHelper response(resolver_->CreateRequest(
10844       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10845       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10846       resolve_context_.get(), resolve_context_->host_cache()));
10847   // No address results overrides overall result.
10848   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
10849   EXPECT_FALSE(response.request()->GetAddressResults());
10850   EXPECT_FALSE(response.request()->GetEndpointResults());
10851   EXPECT_FALSE(response.request()->GetTextResults());
10852   EXPECT_FALSE(response.request()->GetHostnameResults());
10853   // No results maintained when overall error is ERR_NAME_NOT_RESOLVED (and also
10854   // because of the fallback to system resolver).
10855   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
10856 }
10857 
TEST_F(HostResolverManagerDnsTest,HttpsQueriedInAddressQueryButNoResults)10858 TEST_F(HostResolverManagerDnsTest, HttpsQueriedInAddressQueryButNoResults) {
10859   const char kName[] = "name.test";
10860 
10861   base::test::ScopedFeatureList features;
10862   features.InitAndEnableFeatureWithParameters(
10863       features::kUseDnsHttpsSvcb,
10864       {// Disable timeouts.
10865        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10866        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10867        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10868        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10869        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10870        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10871 
10872   MockDnsClientRuleList rules;
10873   rules.emplace_back(
10874       kName, dns_protocol::kTypeHttps, /*secure=*/true,
10875       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
10876       /*delay=*/false);
10877   rules.emplace_back(
10878       kName, dns_protocol::kTypeA, /*secure=*/true,
10879       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10880       /*delay=*/false);
10881   rules.emplace_back(
10882       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10883       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10884       /*delay=*/false);
10885 
10886   CreateResolver();
10887   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10888   DnsConfigOverrides overrides;
10889   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
10890   resolver_->SetDnsConfigOverrides(overrides);
10891 
10892   ResolveHostResponseHelper response(resolver_->CreateRequest(
10893       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10894       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10895       resolve_context_.get(), resolve_context_->host_cache()));
10896   EXPECT_THAT(response.result_error(), IsOk());
10897   EXPECT_TRUE(response.request()->GetAddressResults());
10898   EXPECT_THAT(response.request()->GetEndpointResults(),
10899               testing::Pointee(testing::ElementsAre(
10900                   ExpectEndpointResult(testing::SizeIs(2)))));
10901   EXPECT_FALSE(response.request()->GetTextResults());
10902   EXPECT_FALSE(response.request()->GetHostnameResults());
10903   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10904               testing::Pointee(testing::IsEmpty()));
10905 }
10906 
10907 // For a response where DnsTransaction can at least do its basic parsing and
10908 // return a DnsResponse object to HostResolverManager.  See
10909 // `UnparsableHttpsInAddressRequestIsFatal` for a response so unparsable that
10910 // DnsTransaction couldn't do that.
TEST_F(HostResolverManagerDnsTest,MalformedHttpsInResponseInAddressRequestIsIgnored)10911 TEST_F(HostResolverManagerDnsTest,
10912        MalformedHttpsInResponseInAddressRequestIsIgnored) {
10913   const char kName[] = "name.test";
10914 
10915   base::test::ScopedFeatureList features;
10916   features.InitAndEnableFeatureWithParameters(
10917       features::kUseDnsHttpsSvcb,
10918       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
10919        // Disable timeouts.
10920        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10921        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10922        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10923        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10924        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10925        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10926 
10927   MockDnsClientRuleList rules;
10928   rules.emplace_back(
10929       kName, dns_protocol::kTypeHttps, /*secure=*/true,
10930       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kMalformed),
10931       /*delay=*/false);
10932   rules.emplace_back(
10933       kName, dns_protocol::kTypeA, /*secure=*/true,
10934       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10935       /*delay=*/false);
10936   rules.emplace_back(
10937       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10938       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10939       /*delay=*/false);
10940 
10941   CreateResolver();
10942   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10943   DnsConfigOverrides overrides;
10944   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
10945   resolver_->SetDnsConfigOverrides(overrides);
10946 
10947   ResolveHostResponseHelper response(resolver_->CreateRequest(
10948       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
10949       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
10950       resolve_context_.get(), resolve_context_->host_cache()));
10951   EXPECT_THAT(response.result_error(), IsOk());
10952   EXPECT_TRUE(response.request()->GetAddressResults());
10953   EXPECT_THAT(response.request()->GetEndpointResults(),
10954               testing::Pointee(testing::ElementsAre(
10955                   ExpectEndpointResult(testing::SizeIs(2)))));
10956   EXPECT_FALSE(response.request()->GetTextResults());
10957   EXPECT_FALSE(response.request()->GetHostnameResults());
10958   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
10959               testing::Pointee(testing::IsEmpty()));
10960 }
10961 
TEST_F(HostResolverManagerDnsTest,MalformedHttpsRdataInAddressRequestIsIgnored)10962 TEST_F(HostResolverManagerDnsTest,
10963        MalformedHttpsRdataInAddressRequestIsIgnored) {
10964   const char kName[] = "name.test";
10965 
10966   base::test::ScopedFeatureList features;
10967   features.InitAndEnableFeatureWithParameters(
10968       features::kUseDnsHttpsSvcb,
10969       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
10970        // Disable timeouts.
10971        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
10972        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
10973        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
10974        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
10975        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
10976        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
10977 
10978   MockDnsClientRuleList rules;
10979   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
10980                      MockDnsClientRule::Result(BuildTestDnsResponse(
10981                          kName, dns_protocol::kTypeHttps, /*answers=*/
10982                          {BuildTestDnsRecord(kName, dns_protocol::kTypeHttps,
10983                                              /*rdata=*/"malformed rdata")})),
10984                      /*delay=*/false);
10985   rules.emplace_back(
10986       kName, dns_protocol::kTypeA, /*secure=*/true,
10987       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10988       /*delay=*/false);
10989   rules.emplace_back(
10990       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
10991       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
10992       /*delay=*/false);
10993 
10994   CreateResolver();
10995   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
10996   DnsConfigOverrides overrides;
10997   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
10998   resolver_->SetDnsConfigOverrides(overrides);
10999 
11000   ResolveHostResponseHelper response(resolver_->CreateRequest(
11001       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11002       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11003       resolve_context_.get(), resolve_context_->host_cache()));
11004   EXPECT_THAT(response.result_error(), IsOk());
11005   EXPECT_TRUE(response.request()->GetAddressResults());
11006   EXPECT_THAT(response.request()->GetEndpointResults(),
11007               testing::Pointee(testing::ElementsAre(
11008                   ExpectEndpointResult(testing::SizeIs(2)))));
11009   EXPECT_FALSE(response.request()->GetTextResults());
11010   EXPECT_FALSE(response.request()->GetHostnameResults());
11011   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
11012               testing::Pointee(testing::IsEmpty()));
11013 }
11014 
TEST_F(HostResolverManagerDnsTest,FailedHttpsInAddressRequestIsFatalWhenFeatureEnabled)11015 TEST_F(HostResolverManagerDnsTest,
11016        FailedHttpsInAddressRequestIsFatalWhenFeatureEnabled) {
11017   const char kName[] = "name.test";
11018 
11019   base::test::ScopedFeatureList features;
11020   features.InitAndEnableFeatureWithParameters(
11021       features::kUseDnsHttpsSvcb,
11022       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
11023        // Disable timeouts.
11024        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11025        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11026        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11027        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11028        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11029        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11030 
11031   MockDnsClientRuleList rules;
11032   rules.emplace_back(
11033       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11034       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
11035       /*delay=*/false);
11036   rules.emplace_back(
11037       kName, dns_protocol::kTypeA, /*secure=*/true,
11038       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11039       /*delay=*/false);
11040   rules.emplace_back(
11041       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11042       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11043       /*delay=*/false);
11044 
11045   CreateResolver();
11046   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11047   DnsConfigOverrides overrides;
11048   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11049   resolver_->SetDnsConfigOverrides(overrides);
11050 
11051   ResolveHostResponseHelper response(resolver_->CreateRequest(
11052       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11053       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11054       resolve_context_.get(), resolve_context_->host_cache()));
11055   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
11056   EXPECT_FALSE(response.request()->GetAddressResults());
11057   EXPECT_FALSE(response.request()->GetEndpointResults());
11058   EXPECT_FALSE(response.request()->GetTextResults());
11059   EXPECT_FALSE(response.request()->GetHostnameResults());
11060   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11061 
11062   // Expect result not cached.
11063   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
11064 }
11065 
TEST_F(HostResolverManagerDnsTest,FailedHttpsInAddressRequestIgnoredWhenFeatureDisabled)11066 TEST_F(HostResolverManagerDnsTest,
11067        FailedHttpsInAddressRequestIgnoredWhenFeatureDisabled) {
11068   const char kName[] = "name.test";
11069 
11070   base::test::ScopedFeatureList features;
11071   features.InitAndEnableFeatureWithParameters(
11072       features::kUseDnsHttpsSvcb,
11073       {{"UseDnsHttpsSvcbEnforceSecureResponse", "false"},
11074        // Disable timeouts.
11075        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11076        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11077        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11078        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11079        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11080        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11081 
11082   MockDnsClientRuleList rules;
11083   rules.emplace_back(
11084       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11085       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
11086       /*delay=*/false);
11087   rules.emplace_back(
11088       kName, dns_protocol::kTypeA, /*secure=*/true,
11089       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11090       /*delay=*/false);
11091   rules.emplace_back(
11092       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11093       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11094       /*delay=*/false);
11095 
11096   CreateResolver();
11097   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11098   DnsConfigOverrides overrides;
11099   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11100   resolver_->SetDnsConfigOverrides(overrides);
11101 
11102   ResolveHostResponseHelper response(resolver_->CreateRequest(
11103       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11104       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11105       resolve_context_.get(), resolve_context_->host_cache()));
11106   EXPECT_THAT(response.result_error(), IsOk());
11107   EXPECT_TRUE(response.request()->GetAddressResults());
11108   EXPECT_THAT(response.request()->GetEndpointResults(),
11109               testing::Pointee(testing::ElementsAre(
11110                   ExpectEndpointResult(testing::SizeIs(2)))));
11111   EXPECT_FALSE(response.request()->GetTextResults());
11112   EXPECT_FALSE(response.request()->GetHostnameResults());
11113   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
11114               testing::Pointee(testing::IsEmpty()));
11115 }
11116 
TEST_F(HostResolverManagerDnsTest,FailedHttpsInAddressRequestAfterAddressFailureIsFatalWhenFeatureEnabled)11117 TEST_F(
11118     HostResolverManagerDnsTest,
11119     FailedHttpsInAddressRequestAfterAddressFailureIsFatalWhenFeatureEnabled) {
11120   const char kName[] = "name.test";
11121 
11122   base::test::ScopedFeatureList features;
11123   features.InitAndEnableFeatureWithParameters(
11124       features::kUseDnsHttpsSvcb,
11125       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
11126        // Disable timeouts.
11127        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11128        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11129        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11130        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11131        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11132        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11133 
11134   MockDnsClientRuleList rules;
11135   // Delay HTTPS result to ensure it comes after A failure.
11136   rules.emplace_back(
11137       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11138       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
11139       /*delay=*/true);
11140   rules.emplace_back(
11141       kName, dns_protocol::kTypeA, /*secure=*/true,
11142       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
11143       /*delay=*/false);
11144   // Delay AAAA result to ensure it is cancelled after A failure.
11145   rules.emplace_back(
11146       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11147       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kUnexpected),
11148       /*delay=*/true);
11149 
11150   CreateResolver();
11151   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11152   DnsConfigOverrides overrides;
11153   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11154   resolver_->SetDnsConfigOverrides(overrides);
11155 
11156   ResolveHostResponseHelper response(resolver_->CreateRequest(
11157       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11158       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11159       resolve_context_.get(), resolve_context_->host_cache()));
11160 
11161   base::RunLoop().RunUntilIdle();
11162   EXPECT_FALSE(response.complete());
11163   dns_client_->CompleteDelayedTransactions();
11164 
11165   EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
11166   EXPECT_FALSE(response.request()->GetAddressResults());
11167   EXPECT_FALSE(response.request()->GetEndpointResults());
11168   EXPECT_FALSE(response.request()->GetTextResults());
11169   EXPECT_FALSE(response.request()->GetHostnameResults());
11170   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11171 
11172   // Expect result not cached.
11173   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
11174 }
11175 
TEST_F(HostResolverManagerDnsTest,FailedHttpsInAddressRequestAfterAddressFailureIgnoredWhenFeatureDisabled)11176 TEST_F(
11177     HostResolverManagerDnsTest,
11178     FailedHttpsInAddressRequestAfterAddressFailureIgnoredWhenFeatureDisabled) {
11179   const char kName[] = "name.test";
11180 
11181   base::test::ScopedFeatureList features;
11182   features.InitAndEnableFeatureWithParameters(
11183       features::kUseDnsHttpsSvcb,
11184       {{"UseDnsHttpsSvcbEnforceSecureResponse", "false"},
11185        // Disable timeouts.
11186        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11187        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11188        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11189        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11190        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11191        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11192 
11193   MockDnsClientRuleList rules;
11194   // Delay HTTPS result to ensure it is cancelled after AAAA failure.
11195   rules.emplace_back(
11196       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11197       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kUnexpected),
11198       /*delay=*/true);
11199   // Delay A result to ensure it is cancelled after AAAA failure.
11200   rules.emplace_back(
11201       kName, dns_protocol::kTypeA, /*secure=*/true,
11202       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kUnexpected),
11203       /*delay=*/true);
11204   rules.emplace_back(
11205       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11206       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
11207       /*delay=*/false);
11208 
11209   // Expect fall back to insecure due to AAAA failure.
11210   rules.emplace_back(
11211       kName, dns_protocol::kTypeHttps, /*secure=*/false,
11212       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
11213       /*delay=*/false);
11214   rules.emplace_back(
11215       kName, dns_protocol::kTypeA, /*secure=*/false,
11216       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11217       /*delay=*/false);
11218   rules.emplace_back(
11219       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
11220       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11221       /*delay=*/false);
11222 
11223   CreateResolver();
11224   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11225   DnsConfigOverrides overrides;
11226   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11227   resolver_->SetDnsConfigOverrides(overrides);
11228 
11229   ResolveHostResponseHelper response(resolver_->CreateRequest(
11230       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11231       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11232       resolve_context_.get(), resolve_context_->host_cache()));
11233 
11234   base::RunLoop().RunUntilIdle();
11235   // Unnecessary to complete delayed transactions because they should be
11236   // cancelled after first failure (AAAA).
11237   EXPECT_TRUE(response.complete());
11238 
11239   EXPECT_THAT(response.result_error(), IsOk());
11240   EXPECT_TRUE(response.request()->GetAddressResults());
11241   EXPECT_TRUE(response.request()->GetEndpointResults());
11242   EXPECT_FALSE(response.request()->GetTextResults());
11243   EXPECT_FALSE(response.request()->GetHostnameResults());
11244   EXPECT_TRUE(response.request()->GetExperimentalResultsForTesting());
11245 }
11246 
TEST_F(HostResolverManagerDnsTest,TimeoutHttpsInAddressRequestIsFatal)11247 TEST_F(HostResolverManagerDnsTest, TimeoutHttpsInAddressRequestIsFatal) {
11248   const char kName[] = "name.test";
11249 
11250   base::test::ScopedFeatureList features;
11251   features.InitAndEnableFeatureWithParameters(
11252       features::kUseDnsHttpsSvcb,
11253       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
11254        // Disable timeouts.
11255        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11256        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11257        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11258        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11259        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11260        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11261 
11262   MockDnsClientRuleList rules;
11263   rules.emplace_back(
11264       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11265       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kTimeout),
11266       /*delay=*/false);
11267   rules.emplace_back(
11268       kName, dns_protocol::kTypeA, /*secure=*/true,
11269       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11270       /*delay=*/false);
11271   rules.emplace_back(
11272       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11273       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11274       /*delay=*/false);
11275 
11276   CreateResolver();
11277   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11278   DnsConfigOverrides overrides;
11279   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11280   resolver_->SetDnsConfigOverrides(overrides);
11281 
11282   ResolveHostResponseHelper response(resolver_->CreateRequest(
11283       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11284       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11285       resolve_context_.get(), resolve_context_->host_cache()));
11286   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_TIMED_OUT));
11287   EXPECT_FALSE(response.request()->GetAddressResults());
11288   EXPECT_FALSE(response.request()->GetEndpointResults());
11289   EXPECT_FALSE(response.request()->GetTextResults());
11290   EXPECT_FALSE(response.request()->GetHostnameResults());
11291   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11292 
11293   // Expect result not cached.
11294   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
11295 }
11296 
TEST_F(HostResolverManagerDnsTest,ServfailHttpsInAddressRequestIsFatal)11297 TEST_F(HostResolverManagerDnsTest, ServfailHttpsInAddressRequestIsFatal) {
11298   const char kName[] = "name.test";
11299 
11300   base::test::ScopedFeatureList features;
11301   features.InitAndEnableFeatureWithParameters(
11302       features::kUseDnsHttpsSvcb,
11303       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
11304        // Disable timeouts.
11305        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11306        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11307        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11308        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11309        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11310        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11311 
11312   MockDnsClientRuleList rules;
11313   rules.emplace_back(
11314       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11315       MockDnsClientRule::Result(
11316           MockDnsClientRule::ResultType::kFail,
11317           BuildTestDnsResponse(kName, dns_protocol::kTypeHttps, /*answers=*/{},
11318                                /*authority=*/{}, /*additional=*/{},
11319                                dns_protocol::kRcodeSERVFAIL),
11320           ERR_DNS_SERVER_FAILED),
11321       /*delay=*/false);
11322   rules.emplace_back(
11323       kName, dns_protocol::kTypeA, /*secure=*/true,
11324       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11325       /*delay=*/false);
11326   rules.emplace_back(
11327       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11328       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11329       /*delay=*/false);
11330 
11331   CreateResolver();
11332   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11333   DnsConfigOverrides overrides;
11334   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11335   resolver_->SetDnsConfigOverrides(overrides);
11336 
11337   ResolveHostResponseHelper response(resolver_->CreateRequest(
11338       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11339       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11340       resolve_context_.get(), resolve_context_->host_cache()));
11341   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_SERVER_FAILED));
11342   EXPECT_FALSE(response.request()->GetAddressResults());
11343   EXPECT_FALSE(response.request()->GetEndpointResults());
11344   EXPECT_FALSE(response.request()->GetTextResults());
11345   EXPECT_FALSE(response.request()->GetHostnameResults());
11346   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11347 
11348   // Expect result not cached.
11349   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
11350 }
11351 
11352 // For a response so malformed that DnsTransaction can't do its basic parsing to
11353 // determine an RCODE and return a DnsResponse object to HostResolverManager.
11354 // Essentially equivalent to a network error. See
11355 // `MalformedHttpsInResponseInAddressRequestIsFatal` for a malformed response
11356 // that can at least send a DnsResponse to HostResolverManager.
TEST_F(HostResolverManagerDnsTest,UnparsableHttpsInAddressRequestIsFatal)11357 TEST_F(HostResolverManagerDnsTest, UnparsableHttpsInAddressRequestIsFatal) {
11358   const char kName[] = "name.test";
11359 
11360   base::test::ScopedFeatureList features;
11361   features.InitAndEnableFeatureWithParameters(
11362       features::kUseDnsHttpsSvcb,
11363       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
11364        // Disable timeouts.
11365        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11366        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11367        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11368        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11369        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11370        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11371 
11372   MockDnsClientRuleList rules;
11373   rules.emplace_back(
11374       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11375       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail,
11376                                 /*response=*/absl::nullopt,
11377                                 ERR_DNS_MALFORMED_RESPONSE),
11378       /*delay=*/false);
11379   rules.emplace_back(
11380       kName, dns_protocol::kTypeA, /*secure=*/true,
11381       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11382       /*delay=*/false);
11383   rules.emplace_back(
11384       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11385       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11386       /*delay=*/false);
11387 
11388   CreateResolver();
11389   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11390   DnsConfigOverrides overrides;
11391   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11392   resolver_->SetDnsConfigOverrides(overrides);
11393 
11394   ResolveHostResponseHelper response(resolver_->CreateRequest(
11395       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11396       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11397       resolve_context_.get(), resolve_context_->host_cache()));
11398   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_MALFORMED_RESPONSE));
11399   EXPECT_FALSE(response.request()->GetAddressResults());
11400   EXPECT_FALSE(response.request()->GetEndpointResults());
11401   EXPECT_FALSE(response.request()->GetTextResults());
11402   EXPECT_FALSE(response.request()->GetHostnameResults());
11403   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11404 
11405   // Expect result not cached.
11406   EXPECT_EQ(resolve_context_->host_cache()->size(), 0u);
11407 }
11408 
TEST_F(HostResolverManagerDnsTest,RefusedHttpsInAddressRequestIsIgnored)11409 TEST_F(HostResolverManagerDnsTest, RefusedHttpsInAddressRequestIsIgnored) {
11410   const char kName[] = "name.test";
11411 
11412   base::test::ScopedFeatureList features;
11413   features.InitAndEnableFeatureWithParameters(
11414       features::kUseDnsHttpsSvcb,
11415       {{"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
11416        // Disable timeouts.
11417        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11418        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11419        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11420        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11421        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11422        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11423 
11424   MockDnsClientRuleList rules;
11425   rules.emplace_back(
11426       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11427       MockDnsClientRule::Result(
11428           MockDnsClientRule::ResultType::kFail,
11429           BuildTestDnsResponse(kName, dns_protocol::kTypeHttps, /*answers=*/{},
11430                                /*authority=*/{}, /*additional=*/{},
11431                                dns_protocol::kRcodeREFUSED),
11432           ERR_DNS_SERVER_FAILED),
11433       /*delay=*/false);
11434   rules.emplace_back(
11435       kName, dns_protocol::kTypeA, /*secure=*/true,
11436       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11437       /*delay=*/false);
11438   rules.emplace_back(
11439       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11440       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11441       /*delay=*/false);
11442 
11443   CreateResolver();
11444   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11445   DnsConfigOverrides overrides;
11446   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11447   resolver_->SetDnsConfigOverrides(overrides);
11448 
11449   ResolveHostResponseHelper response(resolver_->CreateRequest(
11450       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11451       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11452       resolve_context_.get(), resolve_context_->host_cache()));
11453   EXPECT_THAT(response.result_error(), IsOk());
11454   EXPECT_TRUE(response.request()->GetAddressResults());
11455   EXPECT_THAT(response.request()->GetEndpointResults(),
11456               testing::Pointee(testing::ElementsAre(
11457                   ExpectEndpointResult(testing::SizeIs(2)))));
11458   EXPECT_FALSE(response.request()->GetTextResults());
11459   EXPECT_FALSE(response.request()->GetHostnameResults());
11460   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
11461               testing::Pointee(testing::IsEmpty()));
11462 }
11463 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryForWssScheme)11464 TEST_F(HostResolverManagerDnsTest, HttpsInAddressQueryForWssScheme) {
11465   const char kName[] = "name.test";
11466 
11467   base::test::ScopedFeatureList features;
11468   features.InitAndEnableFeatureWithParameters(
11469       features::kUseDnsHttpsSvcb,
11470       {// Disable timeouts.
11471        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11472        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11473        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11474        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11475        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11476        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11477 
11478   MockDnsClientRuleList rules;
11479   std::vector<DnsResourceRecord> records = {
11480       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
11481                                   /*params=*/{})};
11482   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
11483                      MockDnsClientRule::Result(BuildTestDnsResponse(
11484                          kName, dns_protocol::kTypeHttps, records)),
11485                      /*delay=*/false);
11486   rules.emplace_back(
11487       kName, dns_protocol::kTypeA, /*secure=*/true,
11488       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11489       /*delay=*/false);
11490   rules.emplace_back(
11491       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11492       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11493       /*delay=*/false);
11494 
11495   CreateResolver();
11496   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11497   DnsConfigOverrides overrides;
11498   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11499   resolver_->SetDnsConfigOverrides(overrides);
11500 
11501   ResolveHostResponseHelper response(resolver_->CreateRequest(
11502       url::SchemeHostPort(url::kWssScheme, kName, 443),
11503       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11504       resolve_context_.get(), resolve_context_->host_cache()));
11505   EXPECT_THAT(response.result_error(), IsOk());
11506   EXPECT_TRUE(response.request()->GetAddressResults());
11507   EXPECT_THAT(
11508       response.request()->GetEndpointResults(),
11509       testing::Pointee(testing::ElementsAre(
11510           ExpectEndpointResult(
11511               testing::SizeIs(2),
11512               ExpectConnectionEndpointMetadata(
11513                   testing::ElementsAre(dns_protocol::kHttpsServiceDefaultAlpn),
11514                   testing::IsEmpty(), kName)),
11515           ExpectEndpointResult(testing::SizeIs(2)))));
11516   EXPECT_FALSE(response.request()->GetTextResults());
11517   EXPECT_FALSE(response.request()->GetHostnameResults());
11518   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
11519               testing::Pointee(testing::ElementsAre(true)));
11520 }
11521 
TEST_F(HostResolverManagerDnsTest,NoHttpsInAddressQueryWithoutScheme)11522 TEST_F(HostResolverManagerDnsTest, NoHttpsInAddressQueryWithoutScheme) {
11523   const char kName[] = "name.test";
11524 
11525   base::test::ScopedFeatureList features;
11526   features.InitAndEnableFeatureWithParameters(
11527       features::kUseDnsHttpsSvcb,
11528       {// Disable timeouts.
11529        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11530        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11531        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11532        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11533        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11534        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11535 
11536   MockDnsClientRuleList rules;
11537   rules.emplace_back(
11538       kName, dns_protocol::kTypeA, /*secure=*/true,
11539       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11540       /*delay=*/false);
11541   rules.emplace_back(
11542       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11543       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11544       /*delay=*/false);
11545   // Should not be queried.
11546   rules.emplace_back(
11547       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11548       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kUnexpected),
11549       /*delay=*/false);
11550 
11551   CreateResolver();
11552   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11553   DnsConfigOverrides overrides;
11554   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11555   resolver_->SetDnsConfigOverrides(overrides);
11556 
11557   ResolveHostResponseHelper response(resolver_->CreateRequest(
11558       HostPortPair(kName, 443), NetworkAnonymizationKey(), NetLogWithSource(),
11559       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
11560   EXPECT_THAT(response.result_error(), IsOk());
11561   EXPECT_TRUE(response.request()->GetAddressResults());
11562   EXPECT_THAT(response.request()->GetEndpointResults(),
11563               testing::Pointee(testing::ElementsAre(
11564                   ExpectEndpointResult(testing::SizeIs(2)))));
11565   EXPECT_FALSE(response.request()->GetTextResults());
11566   EXPECT_FALSE(response.request()->GetHostnameResults());
11567   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11568 }
11569 
TEST_F(HostResolverManagerDnsTest,NoHttpsInAddressQueryForNonHttpScheme)11570 TEST_F(HostResolverManagerDnsTest, NoHttpsInAddressQueryForNonHttpScheme) {
11571   const char kName[] = "name.test";
11572 
11573   base::test::ScopedFeatureList features;
11574   features.InitAndEnableFeatureWithParameters(
11575       features::kUseDnsHttpsSvcb,
11576       {// Disable timeouts.
11577        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11578        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11579        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11580        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11581        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11582        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11583 
11584   MockDnsClientRuleList rules;
11585   rules.emplace_back(
11586       kName, dns_protocol::kTypeA, /*secure=*/true,
11587       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11588       /*delay=*/false);
11589   rules.emplace_back(
11590       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11591       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11592       /*delay=*/false);
11593   // Should not be queried.
11594   rules.emplace_back(
11595       kName, dns_protocol::kTypeHttps, /*secure=*/true,
11596       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kUnexpected),
11597       /*delay=*/false);
11598 
11599   CreateResolver();
11600   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11601   DnsConfigOverrides overrides;
11602   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11603   resolver_->SetDnsConfigOverrides(overrides);
11604 
11605   ResolveHostResponseHelper response(resolver_->CreateRequest(
11606       url::SchemeHostPort(url::kFtpScheme, kName, 443),
11607       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11608       resolve_context_.get(), resolve_context_->host_cache()));
11609   EXPECT_THAT(response.result_error(), IsOk());
11610   EXPECT_TRUE(response.request()->GetAddressResults());
11611   EXPECT_THAT(response.request()->GetEndpointResults(),
11612               testing::Pointee(testing::ElementsAre(
11613                   ExpectEndpointResult(testing::SizeIs(2)))));
11614   EXPECT_FALSE(response.request()->GetTextResults());
11615   EXPECT_FALSE(response.request()->GetHostnameResults());
11616   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11617 }
11618 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabled)11619 TEST_F(HostResolverManagerDnsTest,
11620        HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabled) {
11621   const char kName[] = "name.test";
11622 
11623   base::test::ScopedFeatureList features;
11624   features.InitAndEnableFeatureWithParameters(
11625       features::kUseDnsHttpsSvcb,
11626       {// Disable timeouts.
11627        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11628        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11629        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11630        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11631        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11632        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11633 
11634   MockDnsClientRuleList rules;
11635   std::vector<DnsResourceRecord> records = {
11636       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
11637                                   /*params=*/{})};
11638   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
11639                      MockDnsClientRule::Result(BuildTestDnsResponse(
11640                          kName, dns_protocol::kTypeHttps, records)),
11641                      /*delay=*/false);
11642   rules.emplace_back(
11643       kName, dns_protocol::kTypeA, /*secure=*/true,
11644       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11645       /*delay=*/false);
11646   rules.emplace_back(
11647       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11648       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11649       /*delay=*/false);
11650 
11651   CreateResolver();
11652   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11653   DnsConfigOverrides overrides;
11654   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11655   resolver_->SetDnsConfigOverrides(overrides);
11656 
11657   ResolveHostResponseHelper response(resolver_->CreateRequest(
11658       url::SchemeHostPort(url::kHttpScheme, kName, 80),
11659       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11660       resolve_context_.get(), resolve_context_->host_cache()));
11661 
11662   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
11663   EXPECT_FALSE(response.request()->GetAddressResults());
11664   EXPECT_FALSE(response.request()->GetEndpointResults());
11665   EXPECT_FALSE(response.request()->GetTextResults());
11666   EXPECT_FALSE(response.request()->GetHostnameResults());
11667   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11668 }
11669 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabledWithAliasRecord)11670 TEST_F(HostResolverManagerDnsTest,
11671        HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabledWithAliasRecord) {
11672   const char kName[] = "name.test";
11673 
11674   base::test::ScopedFeatureList features;
11675   features.InitAndEnableFeatureWithParameters(
11676       features::kUseDnsHttpsSvcb,
11677       {// Disable timeouts.
11678        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11679        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11680        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11681        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11682        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11683        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11684 
11685   MockDnsClientRuleList rules;
11686   std::vector<DnsResourceRecord> records = {
11687       BuildTestHttpsAliasRecord(kName, "alias.test")};
11688   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
11689                      MockDnsClientRule::Result(BuildTestDnsResponse(
11690                          kName, dns_protocol::kTypeHttps, records)),
11691                      /*delay=*/false);
11692   rules.emplace_back(
11693       kName, dns_protocol::kTypeA, /*secure=*/true,
11694       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11695       /*delay=*/false);
11696   rules.emplace_back(
11697       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11698       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11699       /*delay=*/false);
11700 
11701   CreateResolver();
11702   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11703   DnsConfigOverrides overrides;
11704   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11705   resolver_->SetDnsConfigOverrides(overrides);
11706 
11707   ResolveHostResponseHelper response(resolver_->CreateRequest(
11708       url::SchemeHostPort(url::kHttpScheme, kName, 80),
11709       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11710       resolve_context_.get(), resolve_context_->host_cache()));
11711 
11712   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
11713   EXPECT_FALSE(response.request()->GetAddressResults());
11714   EXPECT_FALSE(response.request()->GetEndpointResults());
11715   EXPECT_FALSE(response.request()->GetTextResults());
11716   EXPECT_FALSE(response.request()->GetHostnameResults());
11717   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11718 }
11719 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabledWithIncompatibleServiceRecord)11720 TEST_F(
11721     HostResolverManagerDnsTest,
11722     HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabledWithIncompatibleServiceRecord) {
11723   const char kName[] = "name.test";
11724   const uint16_t kMadeUpParam = 65300;  // From the private-use block.
11725 
11726   base::test::ScopedFeatureList features;
11727   features.InitAndEnableFeatureWithParameters(
11728       features::kUseDnsHttpsSvcb,
11729       {// Disable timeouts.
11730        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11731        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11732        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11733        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11734        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11735        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11736 
11737   MockDnsClientRuleList rules;
11738   std::vector<DnsResourceRecord> records = {BuildTestHttpsServiceRecord(
11739       kName, /*priority=*/1, /*service_name=*/".",
11740       /*params=*/
11741       {BuildTestHttpsServiceMandatoryParam({kMadeUpParam}),
11742        {kMadeUpParam, "foo"}})};
11743   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
11744                      MockDnsClientRule::Result(BuildTestDnsResponse(
11745                          kName, dns_protocol::kTypeHttps, records)),
11746                      /*delay=*/false);
11747   rules.emplace_back(
11748       kName, dns_protocol::kTypeA, /*secure=*/true,
11749       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11750       /*delay=*/false);
11751   rules.emplace_back(
11752       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11753       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11754       /*delay=*/false);
11755 
11756   CreateResolver();
11757   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11758   DnsConfigOverrides overrides;
11759   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11760   resolver_->SetDnsConfigOverrides(overrides);
11761 
11762   ResolveHostResponseHelper response(resolver_->CreateRequest(
11763       url::SchemeHostPort(url::kHttpScheme, kName, 80),
11764       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11765       resolve_context_.get(), resolve_context_->host_cache()));
11766 
11767   // Expect incompatible HTTPS record to have no effect on results (except
11768   // `GetExperimentalResultsForTesting()` which returns the record
11769   // compatibility).
11770   EXPECT_THAT(response.result_error(), IsOk());
11771   EXPECT_TRUE(response.request()->GetAddressResults());
11772   EXPECT_TRUE(response.request()->GetEndpointResults());
11773   EXPECT_FALSE(response.request()->GetTextResults());
11774   EXPECT_FALSE(response.request()->GetHostnameResults());
11775   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
11776               testing::Pointee(testing::ElementsAre(false)));
11777 }
11778 
11779 // Even if no addresses are received for a request, finding an HTTPS record
11780 // should still force an HTTP->HTTPS upgrade.
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabledWithoutAddresses)11781 TEST_F(HostResolverManagerDnsTest,
11782        HttpsInAddressQueryForHttpSchemeWhenUpgradeEnabledWithoutAddresses) {
11783   const char kName[] = "name.test";
11784 
11785   base::test::ScopedFeatureList features;
11786   features.InitAndEnableFeatureWithParameters(
11787       features::kUseDnsHttpsSvcb,
11788       {// Disable timeouts.
11789        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11790        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11791        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11792        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11793        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11794        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11795 
11796   MockDnsClientRuleList rules;
11797   std::vector<DnsResourceRecord> records = {
11798       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
11799                                   /*params=*/{})};
11800   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
11801                      MockDnsClientRule::Result(BuildTestDnsResponse(
11802                          kName, dns_protocol::kTypeHttps, records)),
11803                      /*delay=*/false);
11804   rules.emplace_back(
11805       kName, dns_protocol::kTypeA, /*secure=*/true,
11806       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
11807       /*delay=*/false);
11808   rules.emplace_back(
11809       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11810       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kEmpty),
11811       /*delay=*/false);
11812 
11813   CreateResolver();
11814   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11815   DnsConfigOverrides overrides;
11816   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
11817   resolver_->SetDnsConfigOverrides(overrides);
11818 
11819   ResolveHostResponseHelper response(resolver_->CreateRequest(
11820       url::SchemeHostPort(url::kHttpScheme, kName, 80),
11821       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11822       resolve_context_.get(), resolve_context_->host_cache()));
11823 
11824   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
11825   EXPECT_FALSE(response.request()->GetAddressResults());
11826   EXPECT_FALSE(response.request()->GetEndpointResults());
11827   EXPECT_FALSE(response.request()->GetTextResults());
11828   EXPECT_FALSE(response.request()->GetHostnameResults());
11829   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11830 }
11831 
TEST_F(HostResolverManagerDnsTest,HttpsInSecureModeAddressQuery)11832 TEST_F(HostResolverManagerDnsTest, HttpsInSecureModeAddressQuery) {
11833   const char kName[] = "name.test";
11834 
11835   base::test::ScopedFeatureList features;
11836   features.InitAndEnableFeatureWithParameters(
11837       features::kUseDnsHttpsSvcb,
11838       {// Disable timeouts.
11839        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11840        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11841        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11842        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11843        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11844        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11845 
11846   MockDnsClientRuleList rules;
11847   std::vector<DnsResourceRecord> records = {
11848       BuildTestHttpsAliasRecord(kName, "alias.test")};
11849   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
11850                      MockDnsClientRule::Result(BuildTestDnsResponse(
11851                          kName, dns_protocol::kTypeHttps, records)),
11852                      /*delay=*/false);
11853   rules.emplace_back(
11854       kName, dns_protocol::kTypeA, /*secure=*/true,
11855       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11856       /*delay=*/false);
11857   rules.emplace_back(
11858       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11859       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11860       /*delay=*/false);
11861 
11862   CreateResolver();
11863   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11864   DnsConfigOverrides overrides;
11865   overrides.secure_dns_mode = SecureDnsMode::kSecure;
11866   resolver_->SetDnsConfigOverrides(overrides);
11867 
11868   ResolveHostResponseHelper response(resolver_->CreateRequest(
11869       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11870       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11871       resolve_context_.get(), resolve_context_->host_cache()));
11872 
11873   EXPECT_THAT(response.result_error(), IsOk());
11874   EXPECT_TRUE(response.request()->GetAddressResults());
11875   EXPECT_TRUE(response.request()->GetEndpointResults());
11876   EXPECT_FALSE(response.request()->GetTextResults());
11877   EXPECT_FALSE(response.request()->GetHostnameResults());
11878   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
11879               testing::Pointee(testing::ElementsAre(true)));
11880 }
11881 
TEST_F(HostResolverManagerDnsTest,HttpsInSecureModeAddressQueryForHttpScheme)11882 TEST_F(HostResolverManagerDnsTest, HttpsInSecureModeAddressQueryForHttpScheme) {
11883   const char kName[] = "name.test";
11884 
11885   base::test::ScopedFeatureList features;
11886   features.InitAndEnableFeatureWithParameters(
11887       features::kUseDnsHttpsSvcb,
11888       {// Disable timeouts.
11889        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11890        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11891        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11892        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11893        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11894        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11895 
11896   MockDnsClientRuleList rules;
11897   std::vector<DnsResourceRecord> records = {
11898       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
11899                                   /*params=*/{})};
11900   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
11901                      MockDnsClientRule::Result(BuildTestDnsResponse(
11902                          kName, dns_protocol::kTypeHttps, records)),
11903                      /*delay=*/false);
11904   rules.emplace_back(
11905       kName, dns_protocol::kTypeA, /*secure=*/true,
11906       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11907       /*delay=*/false);
11908   rules.emplace_back(
11909       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
11910       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11911       /*delay=*/false);
11912 
11913   CreateResolver();
11914   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11915   DnsConfigOverrides overrides;
11916   overrides.secure_dns_mode = SecureDnsMode::kSecure;
11917   resolver_->SetDnsConfigOverrides(overrides);
11918 
11919   ResolveHostResponseHelper response(resolver_->CreateRequest(
11920       url::SchemeHostPort(url::kHttpScheme, kName, 80),
11921       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11922       resolve_context_.get(), resolve_context_->host_cache()));
11923 
11924   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
11925   EXPECT_FALSE(response.request()->GetAddressResults());
11926   EXPECT_FALSE(response.request()->GetEndpointResults());
11927   EXPECT_FALSE(response.request()->GetTextResults());
11928   EXPECT_FALSE(response.request()->GetHostnameResults());
11929   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
11930 }
11931 
TEST_F(HostResolverManagerDnsTest,HttpsInInsecureAddressQuery)11932 TEST_F(HostResolverManagerDnsTest, HttpsInInsecureAddressQuery) {
11933   const char kName[] = "name.test";
11934 
11935   base::test::ScopedFeatureList features;
11936   features.InitAndEnableFeatureWithParameters(
11937       features::kUseDnsHttpsSvcb,
11938       {// Disable timeouts.
11939        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11940        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11941        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11942        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11943        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
11944        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
11945 
11946   MockDnsClientRuleList rules;
11947   std::vector<DnsResourceRecord> records = {
11948       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
11949                                   /*params=*/{})};
11950   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
11951                      MockDnsClientRule::Result(BuildTestDnsResponse(
11952                          kName, dns_protocol::kTypeHttps, records)),
11953                      /*delay=*/false);
11954   rules.emplace_back(
11955       kName, dns_protocol::kTypeA, /*secure=*/false,
11956       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11957       /*delay=*/false);
11958   rules.emplace_back(
11959       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
11960       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
11961       /*delay=*/false);
11962 
11963   CreateResolver();
11964   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
11965 
11966   ResolveHostResponseHelper response(resolver_->CreateRequest(
11967       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
11968       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
11969       resolve_context_.get(), resolve_context_->host_cache()));
11970 
11971   EXPECT_THAT(response.result_error(), IsOk());
11972   EXPECT_TRUE(response.request()->GetAddressResults());
11973   EXPECT_THAT(
11974       response.request()->GetEndpointResults(),
11975       testing::Pointee(testing::ElementsAre(
11976           ExpectEndpointResult(
11977               testing::SizeIs(2),
11978               ExpectConnectionEndpointMetadata(
11979                   testing::ElementsAre(dns_protocol::kHttpsServiceDefaultAlpn),
11980                   testing::IsEmpty(), kName)),
11981           ExpectEndpointResult(testing::SizeIs(2)))));
11982   EXPECT_FALSE(response.request()->GetTextResults());
11983   EXPECT_FALSE(response.request()->GetHostnameResults());
11984   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
11985               testing::Pointee(testing::ElementsAre(true)));
11986 }
11987 
TEST_F(HostResolverManagerDnsTest,HttpsInInsecureAddressQueryForHttpScheme)11988 TEST_F(HostResolverManagerDnsTest, HttpsInInsecureAddressQueryForHttpScheme) {
11989   const char kName[] = "name.test";
11990 
11991   base::test::ScopedFeatureList features;
11992   features.InitAndEnableFeatureWithParameters(
11993       features::kUseDnsHttpsSvcb,
11994       {// Disable timeouts.
11995        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
11996        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
11997        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
11998        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
11999        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12000        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12001 
12002   MockDnsClientRuleList rules;
12003   std::vector<DnsResourceRecord> records = {
12004       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12005                                   /*params=*/{})};
12006   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
12007                      MockDnsClientRule::Result(BuildTestDnsResponse(
12008                          kName, dns_protocol::kTypeHttps, records)),
12009                      /*delay=*/false);
12010   rules.emplace_back(
12011       kName, dns_protocol::kTypeA, /*secure=*/false,
12012       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12013       /*delay=*/false);
12014   rules.emplace_back(
12015       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12016       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12017       /*delay=*/false);
12018 
12019   CreateResolver();
12020   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12021 
12022   ResolveHostResponseHelper response(resolver_->CreateRequest(
12023       url::SchemeHostPort(url::kHttpScheme, kName, 80),
12024       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12025       resolve_context_.get(), resolve_context_->host_cache()));
12026 
12027   EXPECT_THAT(response.result_error(), IsError(ERR_DNS_NAME_HTTPS_ONLY));
12028   EXPECT_FALSE(response.request()->GetAddressResults());
12029   EXPECT_FALSE(response.request()->GetEndpointResults());
12030   EXPECT_FALSE(response.request()->GetTextResults());
12031   EXPECT_FALSE(response.request()->GetHostnameResults());
12032   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12033 }
12034 
TEST_F(HostResolverManagerDnsTest,FailedHttpsInInsecureAddressRequestIgnored)12035 TEST_F(HostResolverManagerDnsTest, FailedHttpsInInsecureAddressRequestIgnored) {
12036   const char kName[] = "name.test";
12037 
12038   base::test::ScopedFeatureList features;
12039   features.InitAndEnableFeatureWithParameters(
12040       features::kUseDnsHttpsSvcb,
12041       {// Disable timeouts.
12042        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12043        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12044        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12045        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12046        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12047        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12048 
12049   MockDnsClientRuleList rules;
12050   rules.emplace_back(
12051       kName, dns_protocol::kTypeHttps, /*secure=*/false,
12052       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail),
12053       /*delay=*/false);
12054   rules.emplace_back(
12055       kName, dns_protocol::kTypeA, /*secure=*/false,
12056       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12057       /*delay=*/false);
12058   rules.emplace_back(
12059       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12060       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12061       /*delay=*/false);
12062 
12063   CreateResolver();
12064   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12065 
12066   ResolveHostResponseHelper response(resolver_->CreateRequest(
12067       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12068       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12069       resolve_context_.get(), resolve_context_->host_cache()));
12070   EXPECT_THAT(response.result_error(), IsOk());
12071   EXPECT_TRUE(response.request()->GetAddressResults());
12072   EXPECT_THAT(response.request()->GetEndpointResults(),
12073               testing::Pointee(testing::ElementsAre(
12074                   ExpectEndpointResult(testing::SizeIs(2)))));
12075   EXPECT_FALSE(response.request()->GetTextResults());
12076   EXPECT_FALSE(response.request()->GetHostnameResults());
12077   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
12078               testing::Pointee(testing::IsEmpty()));
12079 }
12080 
TEST_F(HostResolverManagerDnsTest,TimeoutHttpsInInsecureAddressRequestIgnored)12081 TEST_F(HostResolverManagerDnsTest,
12082        TimeoutHttpsInInsecureAddressRequestIgnored) {
12083   const char kName[] = "name.test";
12084 
12085   base::test::ScopedFeatureList features;
12086   features.InitAndEnableFeatureWithParameters(
12087       features::kUseDnsHttpsSvcb,
12088       {// Disable timeouts.
12089        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12090        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12091        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12092        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12093        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12094        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12095 
12096   MockDnsClientRuleList rules;
12097   rules.emplace_back(
12098       kName, dns_protocol::kTypeHttps, /*secure=*/false,
12099       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kTimeout),
12100       /*delay=*/false);
12101   rules.emplace_back(
12102       kName, dns_protocol::kTypeA, /*secure=*/false,
12103       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12104       /*delay=*/false);
12105   rules.emplace_back(
12106       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12107       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12108       /*delay=*/false);
12109 
12110   CreateResolver();
12111   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12112 
12113   ResolveHostResponseHelper response(resolver_->CreateRequest(
12114       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12115       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12116       resolve_context_.get(), resolve_context_->host_cache()));
12117   EXPECT_THAT(response.result_error(), IsOk());
12118   EXPECT_TRUE(response.request()->GetAddressResults());
12119   EXPECT_THAT(response.request()->GetEndpointResults(),
12120               testing::Pointee(testing::ElementsAre(
12121                   ExpectEndpointResult(testing::SizeIs(2)))));
12122   EXPECT_FALSE(response.request()->GetTextResults());
12123   EXPECT_FALSE(response.request()->GetHostnameResults());
12124   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
12125               testing::Pointee(testing::IsEmpty()));
12126 }
12127 
TEST_F(HostResolverManagerDnsTest,ServfailHttpsInInsecureAddressRequestIgnored)12128 TEST_F(HostResolverManagerDnsTest,
12129        ServfailHttpsInInsecureAddressRequestIgnored) {
12130   const char kName[] = "name.test";
12131 
12132   base::test::ScopedFeatureList features;
12133   features.InitAndEnableFeatureWithParameters(
12134       features::kUseDnsHttpsSvcb,
12135       {// Disable timeouts.
12136        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12137        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12138        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12139        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12140        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12141        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12142 
12143   MockDnsClientRuleList rules;
12144   rules.emplace_back(
12145       kName, dns_protocol::kTypeHttps, /*secure=*/false,
12146       MockDnsClientRule::Result(
12147           MockDnsClientRule::ResultType::kFail,
12148           BuildTestDnsResponse(kName, dns_protocol::kTypeHttps, /*answers=*/{},
12149                                /*authority=*/{}, /*additional=*/{},
12150                                dns_protocol::kRcodeSERVFAIL),
12151           ERR_DNS_SERVER_FAILED),
12152       /*delay=*/false);
12153   rules.emplace_back(
12154       kName, dns_protocol::kTypeA, /*secure=*/false,
12155       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12156       /*delay=*/false);
12157   rules.emplace_back(
12158       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12159       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12160       /*delay=*/false);
12161 
12162   CreateResolver();
12163   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12164 
12165   ResolveHostResponseHelper response(resolver_->CreateRequest(
12166       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12167       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12168       resolve_context_.get(), resolve_context_->host_cache()));
12169   EXPECT_THAT(response.result_error(), IsOk());
12170   EXPECT_TRUE(response.request()->GetAddressResults());
12171   EXPECT_THAT(response.request()->GetEndpointResults(),
12172               testing::Pointee(testing::ElementsAre(
12173                   ExpectEndpointResult(testing::SizeIs(2)))));
12174   EXPECT_FALSE(response.request()->GetTextResults());
12175   EXPECT_FALSE(response.request()->GetHostnameResults());
12176   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
12177               testing::Pointee(testing::IsEmpty()));
12178 }
12179 
TEST_F(HostResolverManagerDnsTest,UnparsableHttpsInInsecureAddressRequestIgnored)12180 TEST_F(HostResolverManagerDnsTest,
12181        UnparsableHttpsInInsecureAddressRequestIgnored) {
12182   const char kName[] = "name.test";
12183 
12184   base::test::ScopedFeatureList features;
12185   features.InitAndEnableFeatureWithParameters(
12186       features::kUseDnsHttpsSvcb,
12187       {// Disable timeouts.
12188        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12189        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12190        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12191        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12192        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12193        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12194 
12195   MockDnsClientRuleList rules;
12196   rules.emplace_back(
12197       kName, dns_protocol::kTypeHttps, /*secure=*/false,
12198       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kFail,
12199                                 /*response=*/absl::nullopt,
12200                                 ERR_DNS_MALFORMED_RESPONSE),
12201       /*delay=*/false);
12202   rules.emplace_back(
12203       kName, dns_protocol::kTypeA, /*secure=*/false,
12204       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12205       /*delay=*/false);
12206   rules.emplace_back(
12207       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12208       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12209       /*delay=*/false);
12210 
12211   CreateResolver();
12212   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12213 
12214   ResolveHostResponseHelper response(resolver_->CreateRequest(
12215       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12216       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12217       resolve_context_.get(), resolve_context_->host_cache()));
12218   EXPECT_THAT(response.result_error(), IsOk());
12219   EXPECT_TRUE(response.request()->GetAddressResults());
12220   EXPECT_THAT(response.request()->GetEndpointResults(),
12221               testing::Pointee(testing::ElementsAre(
12222                   ExpectEndpointResult(testing::SizeIs(2)))));
12223   EXPECT_FALSE(response.request()->GetTextResults());
12224   EXPECT_FALSE(response.request()->GetHostnameResults());
12225   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
12226               testing::Pointee(testing::IsEmpty()));
12227 }
12228 
12229 // Test that when additional HTTPS timeout Feature params are disabled, the task
12230 // does not timeout until the transactions themselves timeout.
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWaitsWithoutAdditionalTimeout)12231 TEST_F(HostResolverManagerDnsTest,
12232        HttpsInAddressQueryWaitsWithoutAdditionalTimeout) {
12233   const char kName[] = "name.test";
12234 
12235   base::test::ScopedFeatureList features;
12236   features.InitAndEnableFeatureWithParameters(
12237       features::kUseDnsHttpsSvcb,
12238       {// Disable timeouts.
12239        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12240        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12241        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12242        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12243        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12244        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12245 
12246   MockDnsClientRuleList rules;
12247   rules.emplace_back(
12248       kName, dns_protocol::kTypeHttps, /*secure=*/true,
12249       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kTimeout),
12250       /*delay=*/true);
12251   rules.emplace_back(
12252       kName, dns_protocol::kTypeA, /*secure=*/true,
12253       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12254       /*delay=*/false);
12255   rules.emplace_back(
12256       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12257       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12258       /*delay=*/false);
12259 
12260   CreateResolver();
12261   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12262   DnsConfigOverrides overrides;
12263   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
12264   resolver_->SetDnsConfigOverrides(overrides);
12265 
12266   ResolveHostResponseHelper response(resolver_->CreateRequest(
12267       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12268       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12269       resolve_context_.get(), resolve_context_->host_cache()));
12270   RunUntilIdle();
12271   EXPECT_FALSE(response.complete());
12272 
12273   // Wait an absurd amount of time (1 hour) and expect the request to not
12274   // complete because it is waiting on the transaction, where the mock is
12275   // delaying completion.
12276   FastForwardBy(base::Hours(1));
12277   RunUntilIdle();
12278   EXPECT_FALSE(response.complete());
12279 
12280   dns_client_->CompleteDelayedTransactions();
12281   EXPECT_THAT(response.result_error(), IsOk());
12282   EXPECT_TRUE(response.request()->GetAddressResults());
12283   EXPECT_THAT(response.request()->GetEndpointResults(),
12284               testing::Pointee(testing::ElementsAre(
12285                   ExpectEndpointResult(testing::SizeIs(2)))));
12286   EXPECT_FALSE(response.request()->GetTextResults());
12287   EXPECT_FALSE(response.request()->GetHostnameResults());
12288   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
12289               testing::Pointee(testing::IsEmpty()));
12290 }
12291 
TEST_F(HostResolverManagerDnsTest,HttpsInSecureAddressQueryWithOnlyMinTimeout)12292 TEST_F(HostResolverManagerDnsTest,
12293        HttpsInSecureAddressQueryWithOnlyMinTimeout) {
12294   const char kName[] = "name.test";
12295 
12296   base::test::ScopedFeatureList features;
12297   features.InitAndEnableFeatureWithParameters(
12298       features::kUseDnsHttpsSvcb,
12299       {{"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12300        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12301        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "30m"},
12302        // Set a Secure absolute timeout of 10 minutes via the "min" param.
12303        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12304        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12305        {"UseDnsHttpsSvcbSecureExtraTimeMin", "10m"}});
12306 
12307   MockDnsClientRuleList rules;
12308   std::vector<DnsResourceRecord> records = {
12309       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12310                                   /*params=*/{})};
12311   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
12312                      MockDnsClientRule::Result(BuildTestDnsResponse(
12313                          kName, dns_protocol::kTypeHttps, records)),
12314                      /*delay=*/true);
12315   rules.emplace_back(
12316       kName, dns_protocol::kTypeA, /*secure=*/true,
12317       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12318       /*delay=*/false);
12319   rules.emplace_back(
12320       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12321       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12322       /*delay=*/false);
12323 
12324   CreateResolver();
12325   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12326   DnsConfigOverrides overrides;
12327   overrides.secure_dns_mode = SecureDnsMode::kSecure;
12328   resolver_->SetDnsConfigOverrides(overrides);
12329 
12330   ResolveHostResponseHelper response(resolver_->CreateRequest(
12331       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12332       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12333       resolve_context_.get(), resolve_context_->host_cache()));
12334   RunUntilIdle();
12335   EXPECT_FALSE(response.complete());
12336 
12337   // Wait until 1 second before expected timeout.
12338   FastForwardBy(base::Minutes(10) - base::Seconds(1));
12339   RunUntilIdle();
12340   EXPECT_FALSE(response.complete());
12341 
12342   // Exceed expected timeout.
12343   FastForwardBy(base::Seconds(2));
12344 
12345   EXPECT_THAT(response.result_error(), IsOk());
12346   EXPECT_TRUE(response.request()->GetAddressResults());
12347   EXPECT_THAT(response.request()->GetEndpointResults(),
12348               testing::Pointee(testing::ElementsAre(
12349                   ExpectEndpointResult(testing::SizeIs(2)))));
12350   EXPECT_FALSE(response.request()->GetTextResults());
12351   EXPECT_FALSE(response.request()->GetHostnameResults());
12352   // No experimental results if transaction did not complete.
12353   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12354 }
12355 
TEST_F(HostResolverManagerDnsTest,HttpsInSecureAddressQueryWithOnlyMaxTimeout)12356 TEST_F(HostResolverManagerDnsTest,
12357        HttpsInSecureAddressQueryWithOnlyMaxTimeout) {
12358   const char kName[] = "name.test";
12359 
12360   base::test::ScopedFeatureList features;
12361   features.InitAndEnableFeatureWithParameters(
12362       features::kUseDnsHttpsSvcb,
12363       {{"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12364        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12365        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "30m"},
12366        // Set a Secure absolute timeout of 10 minutes via the "max" param.
12367        {"UseDnsHttpsSvcbSecureExtraTimeMax", "10m"},
12368        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12369        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12370 
12371   MockDnsClientRuleList rules;
12372   std::vector<DnsResourceRecord> records = {
12373       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12374                                   /*params=*/{})};
12375   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
12376                      MockDnsClientRule::Result(BuildTestDnsResponse(
12377                          kName, dns_protocol::kTypeHttps, records)),
12378                      /*delay=*/true);
12379   rules.emplace_back(
12380       kName, dns_protocol::kTypeA, /*secure=*/true,
12381       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12382       /*delay=*/false);
12383   rules.emplace_back(
12384       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12385       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12386       /*delay=*/false);
12387 
12388   CreateResolver();
12389   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12390   DnsConfigOverrides overrides;
12391   overrides.secure_dns_mode = SecureDnsMode::kSecure;
12392   resolver_->SetDnsConfigOverrides(overrides);
12393 
12394   ResolveHostResponseHelper response(resolver_->CreateRequest(
12395       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12396       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12397       resolve_context_.get(), resolve_context_->host_cache()));
12398   RunUntilIdle();
12399   EXPECT_FALSE(response.complete());
12400 
12401   // Wait until 1 second before expected timeout.
12402   FastForwardBy(base::Minutes(10) - base::Seconds(1));
12403   RunUntilIdle();
12404   EXPECT_FALSE(response.complete());
12405 
12406   // Exceed expected timeout.
12407   FastForwardBy(base::Seconds(2));
12408 
12409   EXPECT_THAT(response.result_error(), IsOk());
12410   EXPECT_TRUE(response.request()->GetAddressResults());
12411   EXPECT_THAT(response.request()->GetEndpointResults(),
12412               testing::Pointee(testing::ElementsAre(
12413                   ExpectEndpointResult(testing::SizeIs(2)))));
12414   EXPECT_FALSE(response.request()->GetTextResults());
12415   EXPECT_FALSE(response.request()->GetHostnameResults());
12416   // No experimental results if transaction did not complete.
12417   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12418 }
12419 
TEST_F(HostResolverManagerDnsTest,HttpsInSecureAddressQueryWithRelativeTimeout)12420 TEST_F(HostResolverManagerDnsTest,
12421        HttpsInSecureAddressQueryWithRelativeTimeout) {
12422   const char kName[] = "name.test";
12423 
12424   base::test::ScopedFeatureList features;
12425   features.InitAndEnableFeatureWithParameters(
12426       features::kUseDnsHttpsSvcb,
12427       {{"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12428        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12429        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "30m"},
12430        // Set a Secure relative timeout of 10%.
12431        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12432        {"UseDnsHttpsSvcbSecureExtraTimePercent", "10"},
12433        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12434 
12435   MockDnsClientRuleList rules;
12436   std::vector<DnsResourceRecord> records = {
12437       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12438                                   /*params=*/{})};
12439   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
12440                      MockDnsClientRule::Result(BuildTestDnsResponse(
12441                          kName, dns_protocol::kTypeHttps, records)),
12442                      /*delay=*/true);
12443   rules.emplace_back(
12444       kName, dns_protocol::kTypeA, /*secure=*/true,
12445       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12446       /*delay=*/true);
12447   rules.emplace_back(
12448       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12449       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12450       /*delay=*/true);
12451 
12452   CreateResolver();
12453   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12454   DnsConfigOverrides overrides;
12455   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
12456   resolver_->SetDnsConfigOverrides(overrides);
12457 
12458   ResolveHostResponseHelper response(resolver_->CreateRequest(
12459       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12460       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12461       resolve_context_.get(), resolve_context_->host_cache()));
12462   RunUntilIdle();
12463   EXPECT_FALSE(response.complete());
12464 
12465   // Complete final address transaction after 100 seconds total.
12466   FastForwardBy(base::Seconds(50));
12467   ASSERT_TRUE(
12468       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::A));
12469   FastForwardBy(base::Seconds(50));
12470   ASSERT_TRUE(
12471       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::AAAA));
12472   RunUntilIdle();
12473   EXPECT_FALSE(response.complete());
12474 
12475   // Expect timeout at additional 10 seconds.
12476   FastForwardBy(base::Seconds(9));
12477   RunUntilIdle();
12478   EXPECT_FALSE(response.complete());
12479 
12480   FastForwardBy(base::Seconds(2));
12481   EXPECT_THAT(response.result_error(), IsOk());
12482   EXPECT_TRUE(response.request()->GetAddressResults());
12483   EXPECT_THAT(response.request()->GetEndpointResults(),
12484               testing::Pointee(testing::ElementsAre(
12485                   ExpectEndpointResult(testing::SizeIs(2)))));
12486   EXPECT_FALSE(response.request()->GetTextResults());
12487   EXPECT_FALSE(response.request()->GetHostnameResults());
12488   // No experimental results if transaction did not complete.
12489   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12490 }
12491 
TEST_F(HostResolverManagerDnsTest,HttpsInSecureAddressQueryWithMaxTimeoutFirst)12492 TEST_F(HostResolverManagerDnsTest,
12493        HttpsInSecureAddressQueryWithMaxTimeoutFirst) {
12494   const char kName[] = "name.test";
12495 
12496   base::test::ScopedFeatureList features;
12497   features.InitAndEnableFeatureWithParameters(
12498       features::kUseDnsHttpsSvcb,
12499       {{"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12500        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12501        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12502        // Set a Secure max timeout of 30s and a relative timeout of 100%.
12503        {"UseDnsHttpsSvcbSecureExtraTimeMax", "30s"},
12504        {"UseDnsHttpsSvcbSecureExtraTimePercent", "100"},
12505        {"UseDnsHttpsSvcbSecureExtraTimeMin", "10s"}});
12506 
12507   MockDnsClientRuleList rules;
12508   std::vector<DnsResourceRecord> records = {
12509       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12510                                   /*params=*/{})};
12511   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
12512                      MockDnsClientRule::Result(BuildTestDnsResponse(
12513                          kName, dns_protocol::kTypeHttps, records)),
12514                      /*delay=*/true);
12515   rules.emplace_back(
12516       kName, dns_protocol::kTypeA, /*secure=*/true,
12517       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12518       /*delay=*/true);
12519   rules.emplace_back(
12520       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12521       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12522       /*delay=*/true);
12523 
12524   CreateResolver();
12525   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12526   DnsConfigOverrides overrides;
12527   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
12528   resolver_->SetDnsConfigOverrides(overrides);
12529 
12530   ResolveHostResponseHelper response(resolver_->CreateRequest(
12531       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12532       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12533       resolve_context_.get(), resolve_context_->host_cache()));
12534   RunUntilIdle();
12535   EXPECT_FALSE(response.complete());
12536 
12537   // Complete final address transaction after 4 minutes total.
12538   FastForwardBy(base::Minutes(2));
12539   ASSERT_TRUE(
12540       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::A));
12541   FastForwardBy(base::Minutes(2));
12542   ASSERT_TRUE(
12543       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::AAAA));
12544   RunUntilIdle();
12545   EXPECT_FALSE(response.complete());
12546 
12547   // Wait until 1 second before expected timeout (from the max timeout).
12548   FastForwardBy(base::Seconds(29));
12549   RunUntilIdle();
12550   EXPECT_FALSE(response.complete());
12551 
12552   // Exceed expected timeout.
12553   FastForwardBy(base::Seconds(2));
12554 
12555   EXPECT_THAT(response.result_error(), IsOk());
12556   EXPECT_TRUE(response.request()->GetAddressResults());
12557   EXPECT_THAT(response.request()->GetEndpointResults(),
12558               testing::Pointee(testing::ElementsAre(
12559                   ExpectEndpointResult(testing::SizeIs(2)))));
12560   EXPECT_FALSE(response.request()->GetTextResults());
12561   EXPECT_FALSE(response.request()->GetHostnameResults());
12562   // No experimental results if transaction did not complete.
12563   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12564 }
12565 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithRelativeTimeoutFirst)12566 TEST_F(HostResolverManagerDnsTest,
12567        HttpsInAddressQueryWithRelativeTimeoutFirst) {
12568   const char kName[] = "name.test";
12569 
12570   base::test::ScopedFeatureList features;
12571   features.InitAndEnableFeatureWithParameters(
12572       features::kUseDnsHttpsSvcb,
12573       {{"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12574        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12575        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12576        // Set a Secure max timeout of 20 minutes and a relative timeout of 10%.
12577        {"UseDnsHttpsSvcbSecureExtraTimeMax", "20m"},
12578        {"UseDnsHttpsSvcbSecureExtraTimePercent", "10"},
12579        {"UseDnsHttpsSvcbSecureExtraTimeMin", "1s"}});
12580 
12581   MockDnsClientRuleList rules;
12582   std::vector<DnsResourceRecord> records = {
12583       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12584                                   /*params=*/{})};
12585   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
12586                      MockDnsClientRule::Result(BuildTestDnsResponse(
12587                          kName, dns_protocol::kTypeHttps, records)),
12588                      /*delay=*/true);
12589   rules.emplace_back(
12590       kName, dns_protocol::kTypeA, /*secure=*/true,
12591       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12592       /*delay=*/true);
12593   rules.emplace_back(
12594       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12595       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12596       /*delay=*/true);
12597 
12598   CreateResolver();
12599   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12600   DnsConfigOverrides overrides;
12601   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
12602   resolver_->SetDnsConfigOverrides(overrides);
12603 
12604   ResolveHostResponseHelper response(resolver_->CreateRequest(
12605       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12606       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12607       resolve_context_.get(), resolve_context_->host_cache()));
12608   RunUntilIdle();
12609   EXPECT_FALSE(response.complete());
12610 
12611   // Complete final address transaction after 100 seconds total.
12612   FastForwardBy(base::Seconds(50));
12613   ASSERT_TRUE(
12614       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::A));
12615   FastForwardBy(base::Seconds(50));
12616   ASSERT_TRUE(
12617       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::AAAA));
12618   RunUntilIdle();
12619   EXPECT_FALSE(response.complete());
12620 
12621   // Expect timeout at additional 10 seconds (from the relative timeout).
12622   FastForwardBy(base::Seconds(9));
12623   RunUntilIdle();
12624   EXPECT_FALSE(response.complete());
12625 
12626   FastForwardBy(base::Seconds(2));
12627   EXPECT_THAT(response.result_error(), IsOk());
12628   EXPECT_TRUE(response.request()->GetAddressResults());
12629   EXPECT_THAT(response.request()->GetEndpointResults(),
12630               testing::Pointee(testing::ElementsAre(
12631                   ExpectEndpointResult(testing::SizeIs(2)))));
12632   EXPECT_FALSE(response.request()->GetTextResults());
12633   EXPECT_FALSE(response.request()->GetHostnameResults());
12634   // No experimental results if transaction did not complete.
12635   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12636 }
12637 
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWithRelativeTimeoutShorterThanMinTimeout)12638 TEST_F(HostResolverManagerDnsTest,
12639        HttpsInAddressQueryWithRelativeTimeoutShorterThanMinTimeout) {
12640   const char kName[] = "name.test";
12641 
12642   base::test::ScopedFeatureList features;
12643   features.InitAndEnableFeatureWithParameters(
12644       features::kUseDnsHttpsSvcb,
12645       {{"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12646        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12647        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12648        // Set a Secure min timeout of 1 minute and a relative timeout of 10%.
12649        {"UseDnsHttpsSvcbSecureExtraTimeMax", "20m"},
12650        {"UseDnsHttpsSvcbSecureExtraTimePercent", "10"},
12651        {"UseDnsHttpsSvcbSecureExtraTimeMin", "1m"}});
12652 
12653   MockDnsClientRuleList rules;
12654   std::vector<DnsResourceRecord> records = {
12655       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12656                                   /*params=*/{})};
12657   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
12658                      MockDnsClientRule::Result(BuildTestDnsResponse(
12659                          kName, dns_protocol::kTypeHttps, records)),
12660                      /*delay=*/true);
12661   rules.emplace_back(
12662       kName, dns_protocol::kTypeA, /*secure=*/true,
12663       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12664       /*delay=*/true);
12665   rules.emplace_back(
12666       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12667       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12668       /*delay=*/true);
12669 
12670   CreateResolver();
12671   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12672   DnsConfigOverrides overrides;
12673   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
12674   resolver_->SetDnsConfigOverrides(overrides);
12675 
12676   ResolveHostResponseHelper response(resolver_->CreateRequest(
12677       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12678       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12679       resolve_context_.get(), resolve_context_->host_cache()));
12680   RunUntilIdle();
12681   EXPECT_FALSE(response.complete());
12682 
12683   // Complete final address transaction after 100 seconds total.
12684   FastForwardBy(base::Seconds(50));
12685   ASSERT_TRUE(
12686       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::A));
12687   FastForwardBy(base::Seconds(50));
12688   ASSERT_TRUE(
12689       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::AAAA));
12690   RunUntilIdle();
12691   EXPECT_FALSE(response.complete());
12692 
12693   // Expect timeout at additional 1 minute (from the min timeout).
12694   FastForwardBy(base::Minutes(1) - base::Seconds(1));
12695   RunUntilIdle();
12696   EXPECT_FALSE(response.complete());
12697 
12698   FastForwardBy(base::Seconds(2));
12699   EXPECT_THAT(response.result_error(), IsOk());
12700   EXPECT_TRUE(response.request()->GetAddressResults());
12701   EXPECT_THAT(response.request()->GetEndpointResults(),
12702               testing::Pointee(testing::ElementsAre(
12703                   ExpectEndpointResult(testing::SizeIs(2)))));
12704   EXPECT_FALSE(response.request()->GetTextResults());
12705   EXPECT_FALSE(response.request()->GetHostnameResults());
12706   // No experimental results if transaction did not complete.
12707   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12708 }
12709 
TEST_F(HostResolverManagerDnsTest,HttpsInInsecureAddressQueryWithOnlyMinTimeout)12710 TEST_F(HostResolverManagerDnsTest,
12711        HttpsInInsecureAddressQueryWithOnlyMinTimeout) {
12712   const char kName[] = "name.test";
12713 
12714   base::test::ScopedFeatureList features;
12715   features.InitAndEnableFeatureWithParameters(
12716       features::kUseDnsHttpsSvcb,
12717       {// Set an Insecure absolute timeout of 10 minutes via the "min" param.
12718        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12719        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12720        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "10m"},
12721        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12722        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12723        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12724 
12725   MockDnsClientRuleList rules;
12726   std::vector<DnsResourceRecord> records = {
12727       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12728                                   /*params=*/{})};
12729   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
12730                      MockDnsClientRule::Result(BuildTestDnsResponse(
12731                          kName, dns_protocol::kTypeHttps, records)),
12732                      /*delay=*/true);
12733   rules.emplace_back(
12734       kName, dns_protocol::kTypeA, /*secure=*/false,
12735       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12736       /*delay=*/false);
12737   rules.emplace_back(
12738       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12739       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12740       /*delay=*/false);
12741 
12742   CreateResolver();
12743   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12744 
12745   ResolveHostResponseHelper response(resolver_->CreateRequest(
12746       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12747       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12748       resolve_context_.get(), resolve_context_->host_cache()));
12749   RunUntilIdle();
12750   EXPECT_FALSE(response.complete());
12751 
12752   // Wait until 1 second before expected timeout.
12753   FastForwardBy(base::Minutes(10) - base::Seconds(1));
12754   RunUntilIdle();
12755   EXPECT_FALSE(response.complete());
12756 
12757   // Exceed expected timeout.
12758   FastForwardBy(base::Seconds(2));
12759 
12760   EXPECT_THAT(response.result_error(), IsOk());
12761   EXPECT_TRUE(response.request()->GetAddressResults());
12762   EXPECT_THAT(response.request()->GetEndpointResults(),
12763               testing::Pointee(testing::ElementsAre(
12764                   ExpectEndpointResult(testing::SizeIs(2)))));
12765   EXPECT_FALSE(response.request()->GetTextResults());
12766   EXPECT_FALSE(response.request()->GetHostnameResults());
12767   // No experimental results if transaction did not complete.
12768   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12769 }
12770 
TEST_F(HostResolverManagerDnsTest,HttpsInInsecureAddressQueryWithOnlyMaxTimeout)12771 TEST_F(HostResolverManagerDnsTest,
12772        HttpsInInsecureAddressQueryWithOnlyMaxTimeout) {
12773   const char kName[] = "name.test";
12774 
12775   base::test::ScopedFeatureList features;
12776   features.InitAndEnableFeatureWithParameters(
12777       features::kUseDnsHttpsSvcb,
12778       {// Set an Insecure absolute timeout of 10 minutes via the "max" param.
12779        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "10m"},
12780        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12781        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12782        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12783        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12784        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12785 
12786   MockDnsClientRuleList rules;
12787   std::vector<DnsResourceRecord> records = {
12788       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12789                                   /*params=*/{})};
12790   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
12791                      MockDnsClientRule::Result(BuildTestDnsResponse(
12792                          kName, dns_protocol::kTypeHttps, records)),
12793                      /*delay=*/true);
12794   rules.emplace_back(
12795       kName, dns_protocol::kTypeA, /*secure=*/false,
12796       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12797       /*delay=*/false);
12798   rules.emplace_back(
12799       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12800       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12801       /*delay=*/false);
12802 
12803   CreateResolver();
12804   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12805 
12806   ResolveHostResponseHelper response(resolver_->CreateRequest(
12807       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12808       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12809       resolve_context_.get(), resolve_context_->host_cache()));
12810   RunUntilIdle();
12811   EXPECT_FALSE(response.complete());
12812 
12813   // Wait until 1 second before expected timeout.
12814   FastForwardBy(base::Minutes(10) - base::Seconds(1));
12815   RunUntilIdle();
12816   EXPECT_FALSE(response.complete());
12817 
12818   // Exceed expected timeout.
12819   FastForwardBy(base::Seconds(2));
12820 
12821   EXPECT_THAT(response.result_error(), IsOk());
12822   EXPECT_TRUE(response.request()->GetAddressResults());
12823   EXPECT_THAT(response.request()->GetEndpointResults(),
12824               testing::Pointee(testing::ElementsAre(
12825                   ExpectEndpointResult(testing::SizeIs(2)))));
12826   EXPECT_FALSE(response.request()->GetTextResults());
12827   EXPECT_FALSE(response.request()->GetHostnameResults());
12828   // No experimental results if transaction did not complete.
12829   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12830 }
12831 
TEST_F(HostResolverManagerDnsTest,HttpsInInsecureAddressQueryWithRelativeTimeout)12832 TEST_F(HostResolverManagerDnsTest,
12833        HttpsInInsecureAddressQueryWithRelativeTimeout) {
12834   const char kName[] = "name.test";
12835 
12836   base::test::ScopedFeatureList features;
12837   features.InitAndEnableFeatureWithParameters(
12838       features::kUseDnsHttpsSvcb,
12839       {// Set an Insecure relative timeout of 10%.
12840        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12841        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "10"},
12842        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12843        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12844        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12845        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12846 
12847   MockDnsClientRuleList rules;
12848   std::vector<DnsResourceRecord> records = {
12849       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12850                                   /*params=*/{})};
12851   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
12852                      MockDnsClientRule::Result(BuildTestDnsResponse(
12853                          kName, dns_protocol::kTypeHttps, records)),
12854                      /*delay=*/true);
12855   rules.emplace_back(
12856       kName, dns_protocol::kTypeA, /*secure=*/false,
12857       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12858       /*delay=*/true);
12859   rules.emplace_back(
12860       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
12861       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12862       /*delay=*/true);
12863 
12864   CreateResolver();
12865   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12866 
12867   ResolveHostResponseHelper response(resolver_->CreateRequest(
12868       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12869       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12870       resolve_context_.get(), resolve_context_->host_cache()));
12871   RunUntilIdle();
12872   EXPECT_FALSE(response.complete());
12873 
12874   // Complete final address transaction after 100 seconds total.
12875   FastForwardBy(base::Seconds(50));
12876   ASSERT_TRUE(
12877       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::A));
12878   FastForwardBy(base::Seconds(50));
12879   ASSERT_TRUE(
12880       dns_client_->CompleteOneDelayedTransactionOfType(DnsQueryType::AAAA));
12881   RunUntilIdle();
12882   EXPECT_FALSE(response.complete());
12883 
12884   // Expect timeout at additional 10 seconds.
12885   FastForwardBy(base::Seconds(9));
12886   RunUntilIdle();
12887   EXPECT_FALSE(response.complete());
12888 
12889   FastForwardBy(base::Seconds(2));
12890   EXPECT_THAT(response.result_error(), IsOk());
12891   EXPECT_TRUE(response.request()->GetAddressResults());
12892   EXPECT_THAT(response.request()->GetEndpointResults(),
12893               testing::Pointee(testing::ElementsAre(
12894                   ExpectEndpointResult(testing::SizeIs(2)))));
12895   EXPECT_FALSE(response.request()->GetTextResults());
12896   EXPECT_FALSE(response.request()->GetHostnameResults());
12897   // No experimental results if transaction did not complete.
12898   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
12899 }
12900 
12901 // Test that HTTPS timeouts are not used when fatal for the request.
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryWaitsWithoutTimeoutIfFatal)12902 TEST_F(HostResolverManagerDnsTest,
12903        HttpsInAddressQueryWaitsWithoutTimeoutIfFatal) {
12904   const char kName[] = "name.test";
12905 
12906   base::test::ScopedFeatureList features;
12907   features.InitAndEnableFeatureWithParameters(
12908       features::kUseDnsHttpsSvcb,
12909       {// Set timeouts but also enforce secure responses.
12910        {"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
12911        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12912        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12913        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
12914        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12915        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12916        {"UseDnsHttpsSvcbSecureExtraTimeMin", "20m"}});
12917 
12918   MockDnsClientRuleList rules;
12919   std::vector<DnsResourceRecord> records = {
12920       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12921                                   /*params=*/{})};
12922   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/true,
12923                      MockDnsClientRule::Result(BuildTestDnsResponse(
12924                          kName, dns_protocol::kTypeHttps, records)),
12925                      /*delay=*/true);
12926   rules.emplace_back(
12927       kName, dns_protocol::kTypeA, /*secure=*/true,
12928       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12929       /*delay=*/false);
12930   rules.emplace_back(
12931       kName, dns_protocol::kTypeAAAA, /*secure=*/true,
12932       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
12933       /*delay=*/false);
12934 
12935   CreateResolver();
12936   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
12937   DnsConfigOverrides overrides;
12938   overrides.secure_dns_mode = SecureDnsMode::kAutomatic;
12939   resolver_->SetDnsConfigOverrides(overrides);
12940 
12941   ResolveHostResponseHelper response(resolver_->CreateRequest(
12942       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
12943       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
12944       resolve_context_.get(), resolve_context_->host_cache()));
12945   RunUntilIdle();
12946   EXPECT_FALSE(response.complete());
12947 
12948   // Wait an absurd amount of time (1 hour) and expect the request to not
12949   // complete because it is waiting on the transaction, where the mock is
12950   // delaying completion.
12951   FastForwardBy(base::Hours(1));
12952   RunUntilIdle();
12953   EXPECT_FALSE(response.complete());
12954 
12955   dns_client_->CompleteDelayedTransactions();
12956   EXPECT_THAT(response.result_error(), IsOk());
12957   EXPECT_TRUE(response.request()->GetAddressResults());
12958   EXPECT_THAT(
12959       response.request()->GetEndpointResults(),
12960       testing::Pointee(testing::ElementsAre(
12961           ExpectEndpointResult(
12962               testing::SizeIs(2),
12963               ExpectConnectionEndpointMetadata(
12964                   testing::ElementsAre(dns_protocol::kHttpsServiceDefaultAlpn),
12965                   testing::IsEmpty(), kName)),
12966           ExpectEndpointResult(testing::SizeIs(2)))));
12967   EXPECT_FALSE(response.request()->GetTextResults());
12968   EXPECT_FALSE(response.request()->GetHostnameResults());
12969   EXPECT_THAT(response.request()->GetExperimentalResultsForTesting(),
12970               testing::Pointee(testing::ElementsAre(true)));
12971 }
12972 
12973 // Test that HTTPS timeouts are always respected for insecure requests.
TEST_F(HostResolverManagerDnsTest,HttpsInAddressQueryAlwaysRespectsTimeoutsForInsecure)12974 TEST_F(HostResolverManagerDnsTest,
12975        HttpsInAddressQueryAlwaysRespectsTimeoutsForInsecure) {
12976   const char kName[] = "name.test";
12977 
12978   base::test::ScopedFeatureList features;
12979   features.InitAndEnableFeatureWithParameters(
12980       features::kUseDnsHttpsSvcb,
12981       {// Set timeouts but also enforce secure responses.
12982        {"UseDnsHttpsSvcbEnforceSecureResponse", "true"},
12983        {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
12984        {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
12985        {"UseDnsHttpsSvcbInsecureExtraTimeMin", "20m"},
12986        {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
12987        {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
12988        {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
12989 
12990   MockDnsClientRuleList rules;
12991   std::vector<DnsResourceRecord> records = {
12992       BuildTestHttpsServiceRecord(kName, /*priority=*/1, /*service_name=*/".",
12993                                   /*params=*/{})};
12994   rules.emplace_back(kName, dns_protocol::kTypeHttps, /*secure=*/false,
12995                      MockDnsClientRule::Result(BuildTestDnsResponse(
12996                          kName, dns_protocol::kTypeHttps, records)),
12997                      /*delay=*/true);
12998   rules.emplace_back(
12999       kName, dns_protocol::kTypeA, /*secure=*/false,
13000       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
13001       /*delay=*/false);
13002   rules.emplace_back(
13003       kName, dns_protocol::kTypeAAAA, /*secure=*/false,
13004       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
13005       /*delay=*/false);
13006 
13007   CreateResolver();
13008   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
13009 
13010   ResolveHostResponseHelper response(resolver_->CreateRequest(
13011       url::SchemeHostPort(url::kHttpsScheme, kName, 443),
13012       NetworkAnonymizationKey(), NetLogWithSource(), absl::nullopt,
13013       resolve_context_.get(), resolve_context_->host_cache()));
13014   RunUntilIdle();
13015   EXPECT_FALSE(response.complete());
13016 
13017   // Wait until 1s before expected timeout.
13018   FastForwardBy(base::Minutes(20) - base::Seconds(1));
13019   RunUntilIdle();
13020   EXPECT_FALSE(response.complete());
13021 
13022   FastForwardBy(base::Seconds(2));
13023   EXPECT_THAT(response.result_error(), IsOk());
13024   EXPECT_TRUE(response.request()->GetAddressResults());
13025   EXPECT_THAT(response.request()->GetEndpointResults(),
13026               testing::Pointee(testing::ElementsAre(
13027                   ExpectEndpointResult(testing::SizeIs(2)))));
13028   EXPECT_FALSE(response.request()->GetTextResults());
13029   EXPECT_FALSE(response.request()->GetHostnameResults());
13030   // No experimental results if transaction did not complete.
13031   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
13032 }
13033 
TEST_F(HostResolverManagerDnsTest,UnsolicitedHttps)13034 TEST_F(HostResolverManagerDnsTest, UnsolicitedHttps) {
13035   const char kName[] = "unsolicited.test";
13036 
13037   MockDnsClientRuleList rules;
13038   std::vector<DnsResourceRecord> records = {
13039       BuildTestAddressRecord(kName, IPAddress(1, 2, 3, 4))};
13040   std::vector<DnsResourceRecord> additional = {BuildTestHttpsServiceRecord(
13041       kName, /*priority=*/1, /*service_name=*/".", /*params=*/{})};
13042   rules.emplace_back(kName, dns_protocol::kTypeA, true /* secure */,
13043                      MockDnsClientRule::Result(BuildTestDnsResponse(
13044                          kName, dns_protocol::kTypeA, records,
13045                          {} /* authority */, additional)),
13046                      false /* delay */);
13047   rules.emplace_back(
13048       kName, dns_protocol::kTypeAAAA, true /* secure */,
13049       MockDnsClientRule::Result(MockDnsClientRule::ResultType::kOk),
13050       false /* delay */);
13051 
13052   CreateResolver();
13053   UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
13054   DnsConfigOverrides overrides;
13055   overrides.secure_dns_mode = SecureDnsMode::kSecure;
13056   resolver_->SetDnsConfigOverrides(overrides);
13057 
13058   ResolveHostResponseHelper response(resolver_->CreateRequest(
13059       HostPortPair(kName, 108), NetworkAnonymizationKey(), NetLogWithSource(),
13060       absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
13061   EXPECT_THAT(response.result_error(), IsOk());
13062   EXPECT_TRUE(response.request()->GetAddressResults());
13063   EXPECT_THAT(response.request()->GetEndpointResults(),
13064               testing::Pointee(testing::ElementsAre(
13065                   ExpectEndpointResult(testing::SizeIs(2)))));
13066   EXPECT_FALSE(response.request()->GetTextResults());
13067   EXPECT_FALSE(response.request()->GetHostnameResults());
13068   // Unsolicited records not included in results.
13069   EXPECT_FALSE(response.request()->GetExperimentalResultsForTesting());
13070 }
13071 
TEST_F(HostResolverManagerDnsTest,DohProbeRequest)13072 TEST_F(HostResolverManagerDnsTest, DohProbeRequest) {
13073   ChangeDnsConfig(CreateValidDnsConfig());
13074 
13075   EXPECT_FALSE(dns_client_->factory()->doh_probes_running());
13076 
13077   std::unique_ptr<HostResolver::ProbeRequest> request =
13078       resolver_->CreateDohProbeRequest(resolve_context_.get());
13079   EXPECT_THAT(request->Start(), IsError(ERR_IO_PENDING));
13080 
13081   EXPECT_TRUE(dns_client_->factory()->doh_probes_running());
13082 
13083   request.reset();
13084 
13085   EXPECT_FALSE(dns_client_->factory()->doh_probes_running());
13086 }
13087 
TEST_F(HostResolverManagerDnsTest,DohProbeRequest_BeforeConfig)13088 TEST_F(HostResolverManagerDnsTest, DohProbeRequest_BeforeConfig) {
13089   InvalidateDnsConfig();
13090 
13091   std::unique_ptr<HostResolver::ProbeRequest> request =
13092       resolver_->CreateDohProbeRequest(resolve_context_.get());
13093   EXPECT_THAT(request->Start(), IsError(ERR_IO_PENDING));
13094   EXPECT_FALSE(dns_client_->factory()->doh_probes_running());
13095 
13096   ChangeDnsConfig(CreateValidDnsConfig());
13097   EXPECT_TRUE(dns_client_->factory()->doh_probes_running());
13098 }
13099 
TEST_F(HostResolverManagerDnsTest,DohProbeRequest_InvalidateConfig)13100 TEST_F(HostResolverManagerDnsTest, DohProbeRequest_InvalidateConfig) {
13101   ChangeDnsConfig(CreateValidDnsConfig());
13102 
13103   std::unique_ptr<HostResolver::ProbeRequest> request =
13104       resolver_->CreateDohProbeRequest(resolve_context_.get());
13105   EXPECT_THAT(request->Start(), IsError(ERR_IO_PENDING));
13106   ASSERT_TRUE(dns_client_->factory()->doh_probes_running());
13107 
13108   InvalidateDnsConfig();
13109 
13110   EXPECT_FALSE(dns_client_->factory()->doh_probes_running());
13111 }
13112 
TEST_F(HostResolverManagerDnsTest,DohProbeRequest_RestartOnConnectionChange)13113 TEST_F(HostResolverManagerDnsTest, DohProbeRequest_RestartOnConnectionChange) {
13114   DestroyResolver();
13115   test::ScopedMockNetworkChangeNotifier notifier;
13116   CreateSerialResolver();
13117   notifier.mock_network_change_notifier()->SetConnectionType(
13118       NetworkChangeNotifier::CONNECTION_NONE);
13119   ChangeDnsConfig(CreateValidDnsConfig());
13120 
13121   std::unique_ptr<HostResolver::ProbeRequest> request =
13122       resolver_->CreateDohProbeRequest(resolve_context_.get());
13123   EXPECT_THAT(request->Start(), IsError(ERR_IO_PENDING));
13124   EXPECT_TRUE(dns_client_->factory()->doh_probes_running());
13125   dns_client_->factory()->CompleteDohProbeRuners();
13126   ASSERT_FALSE(dns_client_->factory()->doh_probes_running());
13127 
13128   notifier.mock_network_change_notifier()->SetConnectionTypeAndNotifyObservers(
13129       NetworkChangeNotifier::CONNECTION_NONE);
13130 
13131   EXPECT_TRUE(dns_client_->factory()->doh_probes_running());
13132 }
13133 
TEST_F(HostResolverManagerDnsTest,MultipleDohProbeRequests)13134 TEST_F(HostResolverManagerDnsTest, MultipleDohProbeRequests) {
13135   ChangeDnsConfig(CreateValidDnsConfig());
13136 
13137   EXPECT_FALSE(dns_client_->factory()->doh_probes_running());
13138 
13139   std::unique_ptr<HostResolver::ProbeRequest> request1 =
13140       resolver_->CreateDohProbeRequest(resolve_context_.get());
13141   EXPECT_THAT(request1->Start(), IsError(ERR_IO_PENDING));
13142   std::unique_ptr<HostResolver::ProbeRequest> request2 =
13143       resolver_->CreateDohProbeRequest(resolve_context_.get());
13144   EXPECT_THAT(request2->Start(), IsError(ERR_IO_PENDING));
13145 
13146   EXPECT_TRUE(dns_client_->factory()->doh_probes_running());
13147 
13148   request1.reset();
13149   EXPECT_TRUE(dns_client_->factory()->doh_probes_running());
13150 
13151   request2.reset();
13152   EXPECT_FALSE(dns_client_->factory()->doh_probes_running());
13153 }
13154 
13155 // Test that a newly-registered ResolveContext is immediately usable with a DNS
13156 // configuration loaded before the context registration.
TEST_F(HostResolverManagerDnsTest,NewlyRegisteredContext_ConfigBeforeRegistration)13157 TEST_F(HostResolverManagerDnsTest,
13158        NewlyRegisteredContext_ConfigBeforeRegistration) {
13159   ResolveContext context(nullptr /* url_request_context */,
13160                          true /* enable_caching */);
13161   set_allow_fallback_to_systemtask(false);
13162   ChangeDnsConfig(CreateValidDnsConfig());
13163   DnsConfigOverrides overrides;
13164   overrides.secure_dns_mode = SecureDnsMode::kSecure;
13165   resolver_->SetDnsConfigOverrides(overrides);
13166 
13167   ASSERT_TRUE(dns_client_->GetCurrentSession());
13168 
13169   resolver_->RegisterResolveContext(&context);
13170   EXPECT_EQ(context.current_session_for_testing(),
13171             dns_client_->GetCurrentSession());
13172 
13173   // Test a SECURE-mode DoH request with SetForceDohServerAvailable(false).
13174   // Should only succeed if a DoH server is marked available in the
13175   // ResolveContext. MockDnsClient skips most other interaction with
13176   // ResolveContext.
13177   dns_client_->SetForceDohServerAvailable(false);
13178   context.RecordServerSuccess(0u /* server_index */, true /* is_doh_server */,
13179                               dns_client_->GetCurrentSession());
13180   ResolveHostResponseHelper response(resolver_->CreateRequest(
13181       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
13182       absl::nullopt, &context, context.host_cache()));
13183   EXPECT_THAT(response.result_error(), IsOk());
13184 
13185   resolver_->DeregisterResolveContext(&context);
13186 }
13187 
13188 // Test interaction with a ResolveContext registered before a DNS config is
13189 // ready.
TEST_F(HostResolverManagerDnsTest,NewlyRegisteredContext_NoConfigAtRegistration)13190 TEST_F(HostResolverManagerDnsTest,
13191        NewlyRegisteredContext_NoConfigAtRegistration) {
13192   ResolveContext context(nullptr /* url_request_context */,
13193                          true /* enable_caching */);
13194   set_allow_fallback_to_systemtask(false);
13195   InvalidateDnsConfig();
13196   DnsConfigOverrides overrides;
13197   overrides.secure_dns_mode = SecureDnsMode::kSecure;
13198   resolver_->SetDnsConfigOverrides(overrides);
13199 
13200   ASSERT_FALSE(dns_client_->GetCurrentSession());
13201 
13202   // Register context before loading a DNS config.
13203   resolver_->RegisterResolveContext(&context);
13204   EXPECT_FALSE(context.current_session_for_testing());
13205 
13206   // Load DNS config and expect the session to be loaded into the ResolveContext
13207   ChangeDnsConfig(CreateValidDnsConfig());
13208   ASSERT_TRUE(dns_client_->GetCurrentSession());
13209   EXPECT_EQ(context.current_session_for_testing(),
13210             dns_client_->GetCurrentSession());
13211 
13212   // Test a SECURE-mode DoH request with SetForceDohServerAvailable(false).
13213   // Should only succeed if a DoH server is marked available in the
13214   // ResolveContext. MockDnsClient skips most other interaction with
13215   // ResolveContext.
13216   dns_client_->SetForceDohServerAvailable(false);
13217   context.RecordServerSuccess(0u /* server_index */, true /* is_doh_server */,
13218                               dns_client_->GetCurrentSession());
13219   ResolveHostResponseHelper response(resolver_->CreateRequest(
13220       HostPortPair("secure", 80), NetworkAnonymizationKey(), NetLogWithSource(),
13221       absl::nullopt, &context, context.host_cache()));
13222   EXPECT_THAT(response.result_error(), IsOk());
13223 
13224   resolver_->DeregisterResolveContext(&context);
13225 }
13226 
13227 // `HostResolver::ResolveHostParameters::avoid_multicast_resolution` not
13228 // currently supported to do anything except with the system resolver. So with
13229 // DnsTask, expect it to be ignored.
TEST_F(HostResolverManagerDnsTest,AvoidMulticastIgnoredWithDnsTask)13230 TEST_F(HostResolverManagerDnsTest, AvoidMulticastIgnoredWithDnsTask) {
13231   ChangeDnsConfig(CreateValidDnsConfig());
13232 
13233   HostResolver::ResolveHostParameters parameters;
13234   parameters.avoid_multicast_resolution = true;
13235 
13236   ResolveHostResponseHelper response(resolver_->CreateRequest(
13237       HostPortPair("ok", 80), NetworkAnonymizationKey(), NetLogWithSource(),
13238       parameters, resolve_context_.get(), resolve_context_->host_cache()));
13239   EXPECT_THAT(response.result_error(), IsOk());
13240 }
13241 
13242 class HostResolverManagerBootstrapTest : public HostResolverManagerDnsTest {
13243  protected:
13244   using MockResult = MockDnsClientRule::ResultType;
13245 
SetUp()13246   void SetUp() override {
13247     // The request host scheme and port are only preserved if the SVCB feature
13248     // is enabled.
13249     features.InitAndEnableFeatureWithParameters(
13250         features::kUseDnsHttpsSvcb,
13251         {// Disable timeouts.
13252          {"UseDnsHttpsSvcbInsecureExtraTimeMax", "0"},
13253          {"UseDnsHttpsSvcbInsecureExtraTimePercent", "0"},
13254          {"UseDnsHttpsSvcbInsecureExtraTimeMin", "0"},
13255          {"UseDnsHttpsSvcbSecureExtraTimeMax", "0"},
13256          {"UseDnsHttpsSvcbSecureExtraTimePercent", "0"},
13257          {"UseDnsHttpsSvcbSecureExtraTimeMin", "0"}});
13258 
13259     HostResolverManagerDnsTest::SetUp();
13260 
13261     // MockHostResolverProc only returns failure if there is at least one
13262     // non-matching rule.
13263     proc_->AddRuleForAllFamilies("other_name", {});
13264     proc_->SignalMultiple(1u);  // Allow up to one proc query.
13265   }
13266 
13267   const NetworkAnonymizationKey kAnonymizationKey;
13268   const url::SchemeHostPort kEndpoint =
13269       url::SchemeHostPort(url::kHttpsScheme, "bootstrap", 443);
13270   const std::vector<IPEndPoint> kCacheAddrs = {
13271       {{0x20, 0x01, 0x0d, 0xb1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 0},
13272       {{192, 0, 2, 1}, 0}};
13273   const std::vector<IPEndPoint> kBootstrapAddrs = {
13274       {{0x20, 0x01, 0x0d, 0xb1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}, 0},
13275       {{192, 0, 2, 2}, 0}};
13276   // The mock DNS client always returns localhost.
13277   const std::vector<IPEndPoint> kRemoteAddrs = {
13278       {IPAddress::IPv6Localhost(), 0},
13279       {IPAddress::IPv4Localhost(), 0}};
13280 
bootstrap_params()13281   static HostResolver::ResolveHostParameters bootstrap_params() {
13282     HostResolver::ResolveHostParameters params;
13283     params.secure_dns_policy = SecureDnsPolicy::kBootstrap;
13284     return params;
13285   }
13286 
ConfigureMockDns(MockResult insecure_result,MockResult secure_result)13287   void ConfigureMockDns(MockResult insecure_result, MockResult secure_result) {
13288     MockDnsClientRuleList rules;
13289     AddDnsRule(&rules, kEndpoint.host(), dns_protocol::kTypeA, insecure_result,
13290                /*delay=*/false);
13291     AddDnsRule(&rules, kEndpoint.host(), dns_protocol::kTypeAAAA,
13292                insecure_result, /*delay=*/false);
13293     AddSecureDnsRule(&rules, kEndpoint.host(), dns_protocol::kTypeA,
13294                      secure_result, /*delay=*/false);
13295     AddSecureDnsRule(&rules, kEndpoint.host(), dns_protocol::kTypeAAAA,
13296                      secure_result, /*delay=*/false);
13297     UseMockDnsClient(CreateValidDnsConfig(), std::move(rules));
13298     dns_client_->set_preset_endpoint(kEndpoint);
13299   }
13300 
MakeCacheKey(bool secure)13301   HostCache::Key MakeCacheKey(bool secure) {
13302     HostCache::Key cache_key(kEndpoint, DnsQueryType::UNSPECIFIED, 0,
13303                              HostResolverSource::ANY, kAnonymizationKey);
13304     cache_key.secure = secure;
13305     return cache_key;
13306   }
13307 
PopulateCache(bool secure)13308   void PopulateCache(bool secure) {
13309     constexpr base::TimeDelta kTtl = base::Seconds(3600);
13310     HostCache::Entry entry(OK, kCacheAddrs, /*aliases=*/{},
13311                            HostCache::Entry::SOURCE_DNS, kTtl);
13312     resolve_context_->host_cache()->Set(MakeCacheKey(secure), std::move(entry),
13313                                         GetMockTickClock()->NowTicks(), kTtl);
13314   }
13315 
13316   base::test::ScopedFeatureList features;
13317 };
13318 
IPAddresses(const std::vector<IPEndPoint> & endpoints)13319 std::vector<IPAddress> IPAddresses(const std::vector<IPEndPoint>& endpoints) {
13320   std::vector<IPAddress> ip_addresses;
13321   base::ranges::transform(endpoints, std::back_inserter(ip_addresses),
13322                           &IPEndPoint::address);
13323   return ip_addresses;
13324 }
13325 
IPAddresses(const AddressList & addresses)13326 std::vector<IPAddress> IPAddresses(const AddressList& addresses) {
13327   return IPAddresses(addresses.endpoints());
13328 }
13329 
13330 MATCHER_P(AddressesMatch, expected, "Matches addresses between AddressLists") {
13331   return testing::Matches(testing::UnorderedElementsAreArray(
13332       IPAddresses(expected)))(IPAddresses(arg));
13333 }
13334 
TEST_F(HostResolverManagerBootstrapTest,BlankSlate)13335 TEST_F(HostResolverManagerBootstrapTest, BlankSlate) {
13336   ConfigureMockDns(/*insecure_result=*/MockResult::kOk,
13337                    /*secure_result=*/MockResult::kUnexpected);
13338 
13339   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13340       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13341       resolve_context_.get(), resolve_context_->host_cache()));
13342 
13343   EXPECT_FALSE(bootstrap_response.complete());
13344   EXPECT_THAT(bootstrap_response.result_error(), IsOk());
13345   EXPECT_THAT(bootstrap_response.request()->GetAddressResults(),
13346               testing::Pointee(AddressesMatch(kRemoteAddrs)));
13347   EXPECT_THAT(bootstrap_response.request()->GetEndpointResults(),
13348               testing::Pointee(testing::ElementsAre(
13349                   ExpectEndpointResult(AddressesMatch(kRemoteAddrs)))));
13350 }
13351 
TEST_F(HostResolverManagerBootstrapTest,InsecureCacheEntry)13352 TEST_F(HostResolverManagerBootstrapTest, InsecureCacheEntry) {
13353   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13354                    /*secure_result=*/MockResult::kUnexpected);
13355   PopulateCache(/*secure=*/false);
13356 
13357   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13358       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13359       resolve_context_.get(), resolve_context_->host_cache()));
13360 
13361   EXPECT_TRUE(bootstrap_response.complete());
13362   EXPECT_THAT(bootstrap_response.result_error(), IsOk());
13363   EXPECT_THAT(bootstrap_response.request()->GetAddressResults(),
13364               testing::Pointee(AddressesMatch(kCacheAddrs)));
13365   EXPECT_THAT(bootstrap_response.request()->GetEndpointResults(),
13366               testing::Pointee(testing::ElementsAre(
13367                   ExpectEndpointResult(AddressesMatch(kCacheAddrs)))));
13368 }
13369 
TEST_F(HostResolverManagerBootstrapTest,SecureCacheEntry)13370 TEST_F(HostResolverManagerBootstrapTest, SecureCacheEntry) {
13371   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13372                    /*secure_result=*/MockResult::kUnexpected);
13373   PopulateCache(/*secure=*/true);
13374 
13375   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13376       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13377       resolve_context_.get(), resolve_context_->host_cache()));
13378 
13379   EXPECT_TRUE(bootstrap_response.complete());
13380   EXPECT_THAT(bootstrap_response.result_error(), IsOk());
13381   EXPECT_THAT(bootstrap_response.request()->GetAddressResults(),
13382               testing::Pointee(AddressesMatch(kCacheAddrs)));
13383   EXPECT_THAT(bootstrap_response.request()->GetEndpointResults(),
13384               testing::Pointee(testing::ElementsAre(
13385                   ExpectEndpointResult(AddressesMatch(kCacheAddrs)))));
13386 }
13387 
TEST_F(HostResolverManagerBootstrapTest,OnlyBootstrap)13388 TEST_F(HostResolverManagerBootstrapTest, OnlyBootstrap) {
13389   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13390                    /*secure_result=*/MockResult::kOk);
13391   dns_client_->set_preset_addrs(kBootstrapAddrs);
13392 
13393   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13394       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13395       resolve_context_.get(), resolve_context_->host_cache()));
13396 
13397   EXPECT_TRUE(bootstrap_response.complete());
13398   EXPECT_THAT(bootstrap_response.result_error(), IsOk());
13399   EXPECT_THAT(bootstrap_response.request()->GetAddressResults(),
13400               testing::Pointee(AddressesMatch(kBootstrapAddrs)));
13401   EXPECT_THAT(bootstrap_response.request()->GetEndpointResults(),
13402               testing::Pointee(testing::ElementsAre(
13403                   ExpectEndpointResult(AddressesMatch(kBootstrapAddrs)))));
13404 
13405   // Run the followup query.
13406   RunUntilIdle();
13407 
13408   // Confirm that the remote addresses are now in the secure cache.
13409   const auto* secure_result = resolve_context_->host_cache()->Lookup(
13410       MakeCacheKey(/*secure=*/true), GetMockTickClock()->NowTicks());
13411   ASSERT_THAT(secure_result, testing::NotNull());
13412   EXPECT_THAT(secure_result->second.GetEndpoints(),
13413               testing::Optional(testing::ElementsAre(
13414                   ExpectEndpointResult(AddressesMatch(kRemoteAddrs)))));
13415 }
13416 
13417 // The insecure cache is ignored, so the results are identical to
13418 // OnlyBootstrap.
TEST_F(HostResolverManagerBootstrapTest,BootstrapAndInsecureCache)13419 TEST_F(HostResolverManagerBootstrapTest, BootstrapAndInsecureCache) {
13420   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13421                    /*secure_result=*/MockResult::kOk);
13422   dns_client_->set_preset_addrs(kBootstrapAddrs);
13423   PopulateCache(/*secure=*/false);
13424 
13425   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13426       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13427       resolve_context_.get(), resolve_context_->host_cache()));
13428 
13429   EXPECT_TRUE(bootstrap_response.complete());
13430   EXPECT_THAT(bootstrap_response.result_error(), IsOk());
13431   EXPECT_THAT(bootstrap_response.request()->GetAddressResults(),
13432               testing::Pointee(AddressesMatch(kBootstrapAddrs)));
13433   EXPECT_THAT(bootstrap_response.request()->GetEndpointResults(),
13434               testing::Pointee(testing::ElementsAre(
13435                   ExpectEndpointResult(AddressesMatch(kBootstrapAddrs)))));
13436 
13437   // Run the followup query.
13438   RunUntilIdle();
13439 
13440   // Confirm that the remote addresses are now in the secure cache.
13441   const auto* secure_result = resolve_context_->host_cache()->Lookup(
13442       MakeCacheKey(/*secure=*/true), GetMockTickClock()->NowTicks());
13443   ASSERT_THAT(secure_result, testing::NotNull());
13444   EXPECT_THAT(secure_result->second.GetEndpoints(),
13445               testing::Optional(testing::ElementsAre(
13446                   ExpectEndpointResult(AddressesMatch(kRemoteAddrs)))));
13447 }
13448 
13449 // The bootstrap addrs are ignored, so the results are identical to
13450 // SecureCacheEntry.
TEST_F(HostResolverManagerBootstrapTest,BootstrapAndSecureCacheEntry)13451 TEST_F(HostResolverManagerBootstrapTest, BootstrapAndSecureCacheEntry) {
13452   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13453                    /*secure_result=*/MockResult::kUnexpected);
13454   dns_client_->set_preset_addrs(kBootstrapAddrs);
13455   PopulateCache(/*secure=*/true);
13456 
13457   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13458       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13459       resolve_context_.get(), resolve_context_->host_cache()));
13460 
13461   EXPECT_TRUE(bootstrap_response.complete());
13462   EXPECT_THAT(bootstrap_response.result_error(), IsOk());
13463   EXPECT_THAT(bootstrap_response.request()->GetAddressResults(),
13464               testing::Pointee(AddressesMatch(kCacheAddrs)));
13465   EXPECT_THAT(bootstrap_response.request()->GetEndpointResults(),
13466               testing::Pointee(testing::ElementsAre(
13467                   ExpectEndpointResult(AddressesMatch(kCacheAddrs)))));
13468 }
13469 
TEST_F(HostResolverManagerBootstrapTest,BlankSlateFailure)13470 TEST_F(HostResolverManagerBootstrapTest, BlankSlateFailure) {
13471   ConfigureMockDns(/*insecure_result=*/MockResult::kFail,
13472                    /*secure_result=*/MockResult::kUnexpected);
13473 
13474   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13475       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13476       resolve_context_.get(), resolve_context_->host_cache()));
13477 
13478   EXPECT_FALSE(bootstrap_response.complete());
13479   EXPECT_THAT(bootstrap_response.result_error(),
13480               IsError(ERR_NAME_NOT_RESOLVED));
13481   EXPECT_FALSE(bootstrap_response.request()
13482                    ->GetResolveErrorInfo()
13483                    .is_secure_network_error);
13484 }
13485 
TEST_F(HostResolverManagerBootstrapTest,BootstrapFollowupFailure)13486 TEST_F(HostResolverManagerBootstrapTest, BootstrapFollowupFailure) {
13487   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13488                    /*secure_result=*/MockResult::kFail);
13489   dns_client_->set_preset_addrs(kBootstrapAddrs);
13490 
13491   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13492       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13493       resolve_context_.get(), resolve_context_->host_cache()));
13494 
13495   EXPECT_TRUE(bootstrap_response.complete());
13496   EXPECT_THAT(bootstrap_response.result_error(), IsOk());
13497   EXPECT_THAT(bootstrap_response.request()->GetAddressResults(),
13498               testing::Pointee(AddressesMatch(kBootstrapAddrs)));
13499   EXPECT_THAT(bootstrap_response.request()->GetEndpointResults(),
13500               testing::Pointee(testing::ElementsAre(
13501                   ExpectEndpointResult(AddressesMatch(kBootstrapAddrs)))));
13502 
13503   // Run the followup query.
13504   RunUntilIdle();
13505 
13506   // Confirm that the secure cache remains empty.
13507   const auto* secure_result = resolve_context_->host_cache()->Lookup(
13508       MakeCacheKey(/*secure=*/true), GetMockTickClock()->NowTicks());
13509   EXPECT_THAT(secure_result, testing::IsNull());
13510 }
13511 
TEST_F(HostResolverManagerBootstrapTest,ContextClose)13512 TEST_F(HostResolverManagerBootstrapTest, ContextClose) {
13513   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13514                    /*secure_result=*/MockResult::kOk);
13515   dns_client_->set_preset_addrs(kBootstrapAddrs);
13516 
13517   // Trigger a followup request.
13518   ResolveHostResponseHelper bootstrap_response(resolver_->CreateRequest(
13519       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13520       resolve_context_.get(), resolve_context_->host_cache()));
13521 
13522   // Deregistering the resolve context should clean up the pending followup job.
13523   EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
13524   resolver_->DeregisterResolveContext(resolve_context_.get());
13525   EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
13526 
13527   resolver_ = nullptr;  // Avoid duplicate Deregister in TearDown.
13528 }
13529 
13530 // Equivalent to OnlyBootstrap + BootstrapAndSecureCacheEntry
TEST_F(HostResolverManagerBootstrapTest,BootstrapAfterFollowup)13531 TEST_F(HostResolverManagerBootstrapTest, BootstrapAfterFollowup) {
13532   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13533                    /*secure_result=*/MockResult::kOk);
13534   dns_client_->set_preset_addrs(kBootstrapAddrs);
13535 
13536   // Run bootstrap and its followup query.
13537   ResolveHostResponseHelper bootstrap_response1(resolver_->CreateRequest(
13538       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13539       resolve_context_.get(), resolve_context_->host_cache()));
13540   RunUntilIdle();
13541 
13542   // The remote addresses are now in the secure cache.
13543   // Rerun bootstrap, which reads the secure cache results.
13544   ResolveHostResponseHelper bootstrap_response2(resolver_->CreateRequest(
13545       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13546       resolve_context_.get(), resolve_context_->host_cache()));
13547 
13548   EXPECT_TRUE(bootstrap_response2.complete());
13549   EXPECT_THAT(bootstrap_response2.result_error(), IsOk());
13550   EXPECT_THAT(bootstrap_response2.request()->GetAddressResults(),
13551               testing::Pointee(AddressesMatch(kRemoteAddrs)));
13552   EXPECT_THAT(bootstrap_response2.request()->GetEndpointResults(),
13553               testing::Pointee(testing::ElementsAre(
13554                   ExpectEndpointResult(AddressesMatch(kRemoteAddrs)))));
13555 }
13556 
TEST_F(HostResolverManagerBootstrapTest,BootstrapFollowupFailureTwice)13557 TEST_F(HostResolverManagerBootstrapTest, BootstrapFollowupFailureTwice) {
13558   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13559                    /*secure_result=*/MockResult::kFail);
13560   dns_client_->set_preset_addrs(kBootstrapAddrs);
13561 
13562   // Run the bootstrap query and the followup, which will fail.
13563   ResolveHostResponseHelper bootstrap_response1(resolver_->CreateRequest(
13564       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13565       resolve_context_.get(), resolve_context_->host_cache()));
13566   RunUntilIdle();
13567 
13568   // Reissue the bootstrap query.
13569   ResolveHostResponseHelper bootstrap_response2(resolver_->CreateRequest(
13570       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13571       resolve_context_.get(), resolve_context_->host_cache()));
13572 
13573   EXPECT_TRUE(bootstrap_response2.complete());
13574   EXPECT_THAT(bootstrap_response2.result_error(), IsOk());
13575   EXPECT_THAT(bootstrap_response2.request()->GetAddressResults(),
13576               testing::Pointee(AddressesMatch(kBootstrapAddrs)));
13577   EXPECT_THAT(bootstrap_response2.request()->GetEndpointResults(),
13578               testing::Pointee(testing::ElementsAre(
13579                   ExpectEndpointResult(AddressesMatch(kBootstrapAddrs)))));
13580 
13581   // Run the followup query again.
13582   RunUntilIdle();
13583 
13584   // Confirm that the secure cache remains empty.
13585   const auto* secure_result = resolve_context_->host_cache()->Lookup(
13586       MakeCacheKey(/*secure=*/true), GetMockTickClock()->NowTicks());
13587   EXPECT_THAT(secure_result, testing::IsNull());
13588 }
13589 
TEST_F(HostResolverManagerBootstrapTest,OnlyBootstrapTwice)13590 TEST_F(HostResolverManagerBootstrapTest, OnlyBootstrapTwice) {
13591   ConfigureMockDns(/*insecure_result=*/MockResult::kUnexpected,
13592                    /*secure_result=*/MockResult::kOk);
13593   dns_client_->set_preset_addrs(kBootstrapAddrs);
13594 
13595   ResolveHostResponseHelper bootstrap_response1(resolver_->CreateRequest(
13596       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13597       resolve_context_.get(), resolve_context_->host_cache()));
13598 
13599   EXPECT_TRUE(bootstrap_response1.complete());
13600   EXPECT_THAT(bootstrap_response1.result_error(), IsOk());
13601   EXPECT_THAT(bootstrap_response1.request()->GetAddressResults(),
13602               testing::Pointee(AddressesMatch(kBootstrapAddrs)));
13603   EXPECT_THAT(bootstrap_response1.request()->GetEndpointResults(),
13604               testing::Pointee(testing::ElementsAre(
13605                   ExpectEndpointResult(AddressesMatch(kBootstrapAddrs)))));
13606 
13607   ResolveHostResponseHelper bootstrap_response2(resolver_->CreateRequest(
13608       kEndpoint, kAnonymizationKey, NetLogWithSource(), bootstrap_params(),
13609       resolve_context_.get(), resolve_context_->host_cache()));
13610 
13611   EXPECT_TRUE(bootstrap_response2.complete());
13612   EXPECT_THAT(bootstrap_response2.result_error(), IsOk());
13613   EXPECT_THAT(bootstrap_response2.request()->GetAddressResults(),
13614               testing::Pointee(AddressesMatch(kBootstrapAddrs)));
13615   EXPECT_THAT(bootstrap_response2.request()->GetEndpointResults(),
13616               testing::Pointee(testing::ElementsAre(
13617                   ExpectEndpointResult(AddressesMatch(kBootstrapAddrs)))));
13618 
13619   // Run the followup query.
13620   RunUntilIdle();
13621 
13622   // Confirm that the remote addresses are now in the secure cache.
13623   const auto* secure_result = resolve_context_->host_cache()->Lookup(
13624       MakeCacheKey(/*secure=*/true), GetMockTickClock()->NowTicks());
13625   ASSERT_THAT(secure_result, testing::NotNull());
13626   EXPECT_THAT(secure_result->second.GetEndpoints(),
13627               testing::Optional(testing::ElementsAre(
13628                   ExpectEndpointResult(AddressesMatch(kRemoteAddrs)))));
13629 }
13630 
IPv4AddressLiteralInIPv6OnlyNetworkTest(bool is_async)13631 void HostResolverManagerTest::IPv4AddressLiteralInIPv6OnlyNetworkTest(
13632     bool is_async) {
13633   base::test::ScopedFeatureList feature_list;
13634   feature_list.InitWithFeatures(
13635       /*enabled_features=*/{features::kUseNAT64ForIPv4Literal},
13636       /*disabled_features=*/{});
13637 
13638   HostResolver::ManagerOptions options = DefaultOptions();
13639   CreateResolverWithOptionsAndParams(std::move(options), DefaultParams(proc_),
13640                                      true /* ipv6_reachable */, is_async,
13641                                      false /* ipv4_reachable */);
13642   proc_->AddRule("ipv4only.arpa", ADDRESS_FAMILY_IPV6,
13643                  "64:ff9b::c000:aa,64:ff9b::c000:ab,2001:db8:43::c000:aa,"
13644                  "2001:db8:43::c000:ab");
13645   proc_->SignalMultiple(1u);
13646 
13647   ResolveHostResponseHelper response(resolver_->CreateRequest(
13648       HostPortPair("192.168.1.42", 80), NetworkAnonymizationKey(),
13649       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
13650       resolve_context_->host_cache()));
13651 
13652   EXPECT_THAT(response.result_error(), IsOk());
13653   EXPECT_THAT(response.top_level_result_error(), IsOk());
13654   EXPECT_THAT(
13655       response.request()->GetAddressResults()->endpoints(),
13656       testing::ElementsAre(CreateExpected("64:ff9b::c0a8:12a", 80),
13657                            CreateExpected("2001:db8:43::c0a8:12a", 80)));
13658   EXPECT_THAT(
13659       response.request()->GetEndpointResults(),
13660       testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
13661           testing::ElementsAre(CreateExpected("64:ff9b::c0a8:12a", 80),
13662                                CreateExpected("2001:db8:43::c0a8:12a", 80))))));
13663   EXPECT_FALSE(response.request()->GetStaleInfo());
13664 
13665   ASSERT_TRUE(!proc_->GetCaptureList().empty());
13666   EXPECT_EQ("ipv4only.arpa", proc_->GetCaptureList()[0].hostname);
13667 
13668   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
13669       GetCacheHit(HostCache::Key(
13670           "ipv4only.arpa", DnsQueryType::AAAA, 0 /* host_resolver_flags */,
13671           HostResolverSource::ANY, NetworkAnonymizationKey()));
13672   EXPECT_TRUE(cache_result);
13673 }
13674 
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkAsync)13675 TEST_F(HostResolverManagerTest, IPv4AddressLiteralInIPv6OnlyNetworkAsync) {
13676   IPv4AddressLiteralInIPv6OnlyNetworkTest(true);
13677 }
13678 
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkSync)13679 TEST_F(HostResolverManagerTest, IPv4AddressLiteralInIPv6OnlyNetworkSync) {
13680   IPv4AddressLiteralInIPv6OnlyNetworkTest(false);
13681 }
13682 
IPv4AddressLiteralInIPv6OnlyNetworkPort443Test(bool is_async)13683 void HostResolverManagerTest::IPv4AddressLiteralInIPv6OnlyNetworkPort443Test(
13684     bool is_async) {
13685   base::test::ScopedFeatureList feature_list;
13686   feature_list.InitWithFeatures(
13687       /*enabled_features=*/{features::kUseNAT64ForIPv4Literal},
13688       /*disabled_features=*/{});
13689 
13690   HostResolver::ManagerOptions options = DefaultOptions();
13691   CreateResolverWithOptionsAndParams(std::move(options), DefaultParams(proc_),
13692                                      true /* ipv6_reachable */, is_async,
13693                                      false /* ipv4_reachable */);
13694   proc_->AddRule("ipv4only.arpa", ADDRESS_FAMILY_IPV6,
13695                  "64:ff9b::c000:aa,64:ff9b::c000:ab,2001:db8:43::c000:aa,"
13696                  "2001:db8:43::c000:ab");
13697   proc_->SignalMultiple(1u);
13698 
13699   ResolveHostResponseHelper response(resolver_->CreateRequest(
13700       HostPortPair("192.168.1.42", 443), NetworkAnonymizationKey(),
13701       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
13702       resolve_context_->host_cache()));
13703 
13704   EXPECT_THAT(response.result_error(), IsOk());
13705   EXPECT_THAT(response.top_level_result_error(), IsOk());
13706   EXPECT_THAT(
13707       response.request()->GetAddressResults()->endpoints(),
13708       testing::ElementsAre(CreateExpected("64:ff9b::c0a8:12a", 443),
13709                            CreateExpected("2001:db8:43::c0a8:12a", 443)));
13710   EXPECT_THAT(response.request()->GetEndpointResults(),
13711               testing::Pointee(testing::ElementsAre(
13712                   ExpectEndpointResult(testing::ElementsAre(
13713                       CreateExpected("64:ff9b::c0a8:12a", 443),
13714                       CreateExpected("2001:db8:43::c0a8:12a", 443))))));
13715   EXPECT_FALSE(response.request()->GetStaleInfo());
13716 
13717   ASSERT_TRUE(!proc_->GetCaptureList().empty());
13718   EXPECT_EQ("ipv4only.arpa", proc_->GetCaptureList()[0].hostname);
13719 
13720   const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
13721       GetCacheHit(HostCache::Key(
13722           "ipv4only.arpa", DnsQueryType::AAAA, 0 /* host_resolver_flags */,
13723           HostResolverSource::ANY, NetworkAnonymizationKey()));
13724   EXPECT_TRUE(cache_result);
13725 }
13726 
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkPort443Async)13727 TEST_F(HostResolverManagerTest,
13728        IPv4AddressLiteralInIPv6OnlyNetworkPort443Async) {
13729   IPv4AddressLiteralInIPv6OnlyNetworkPort443Test(true);
13730 }
13731 
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkPort443Sync)13732 TEST_F(HostResolverManagerTest,
13733        IPv4AddressLiteralInIPv6OnlyNetworkPort443Sync) {
13734   IPv4AddressLiteralInIPv6OnlyNetworkPort443Test(false);
13735 }
13736 
IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Test(bool is_async)13737 void HostResolverManagerTest::IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Test(
13738     bool is_async) {
13739   base::test::ScopedFeatureList feature_list;
13740   feature_list.InitWithFeatures(
13741       /*enabled_features=*/{features::kUseNAT64ForIPv4Literal},
13742       /*disabled_features=*/{});
13743 
13744   HostResolver::ManagerOptions options = DefaultOptions();
13745   CreateResolverWithOptionsAndParams(std::move(options), DefaultParams(proc_),
13746                                      true /* ipv6_reachable */, is_async,
13747                                      false /* ipv4_reachable */);
13748   proc_->AddRule("ipv4only.arpa", ADDRESS_FAMILY_IPV6, std::string());
13749   proc_->SignalMultiple(1u);
13750 
13751   ResolveHostResponseHelper response(resolver_->CreateRequest(
13752       HostPortPair("192.168.1.42", 80), NetworkAnonymizationKey(),
13753       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
13754       resolve_context_->host_cache()));
13755 
13756   EXPECT_THAT(response.result_error(), IsOk());
13757   EXPECT_THAT(response.top_level_result_error(), IsOk());
13758   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
13759               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
13760   EXPECT_THAT(response.request()->GetEndpointResults(),
13761               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
13762                   testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
13763   EXPECT_FALSE(response.request()->GetStaleInfo());
13764 }
13765 
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Async)13766 TEST_F(HostResolverManagerTest,
13767        IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Async) {
13768   IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Test(true);
13769 }
13770 
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Sync)13771 TEST_F(HostResolverManagerTest,
13772        IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Sync) {
13773   IPv4AddressLiteralInIPv6OnlyNetworkNoDns64Test(false);
13774 }
13775 
IPv4AddressLiteralInIPv6OnlyNetworkBadAddressTest(bool is_async)13776 void HostResolverManagerTest::IPv4AddressLiteralInIPv6OnlyNetworkBadAddressTest(
13777     bool is_async) {
13778   base::test::ScopedFeatureList feature_list;
13779   feature_list.InitWithFeatures(
13780       /*enabled_features=*/{features::kUseNAT64ForIPv4Literal},
13781       /*disabled_features=*/{});
13782 
13783   HostResolver::ManagerOptions options = DefaultOptions();
13784   CreateResolverWithOptionsAndParams(std::move(options), DefaultParams(proc_),
13785                                      true /* ipv6_reachable */, is_async,
13786                                      false /* ipv4_reachable */);
13787   proc_->AddRule("ipv4only.arpa", ADDRESS_FAMILY_IPV6, "2001:db8::1");
13788   proc_->SignalMultiple(1u);
13789 
13790   ResolveHostResponseHelper response(resolver_->CreateRequest(
13791       HostPortPair("192.168.1.42", 80), NetworkAnonymizationKey(),
13792       NetLogWithSource(), absl::nullopt, resolve_context_.get(),
13793       resolve_context_->host_cache()));
13794 
13795   EXPECT_THAT(response.result_error(), IsOk());
13796   EXPECT_THAT(response.top_level_result_error(), IsOk());
13797   EXPECT_THAT(response.request()->GetAddressResults()->endpoints(),
13798               testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
13799   EXPECT_THAT(response.request()->GetEndpointResults(),
13800               testing::Pointee(testing::ElementsAre(ExpectEndpointResult(
13801                   testing::ElementsAre(CreateExpected("192.168.1.42", 80))))));
13802   EXPECT_FALSE(response.request()->GetStaleInfo());
13803 }
13804 // Test when DNS returns bad IPv6 address of ipv4only.arpa., and the
13805 // IPv4 address of ipv4only.arpa is not contained in the IPv6 address.
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkBadAddressAsync)13806 TEST_F(HostResolverManagerTest,
13807        IPv4AddressLiteralInIPv6OnlyNetworkBadAddressAsync) {
13808   IPv4AddressLiteralInIPv6OnlyNetworkBadAddressTest(true);
13809 }
13810 
TEST_F(HostResolverManagerTest,IPv4AddressLiteralInIPv6OnlyNetworkBadAddressSync)13811 TEST_F(HostResolverManagerTest,
13812        IPv4AddressLiteralInIPv6OnlyNetworkBadAddressSync) {
13813   IPv4AddressLiteralInIPv6OnlyNetworkBadAddressTest(false);
13814 }
13815 
13816 }  // namespace net
13817