chromium/services/network/network_context_unittest.cc

// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "services/network/network_context.h"

#include <algorithm>
#include <initializer_list>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/barrier_closure.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_source.h"
#include "base/ranges/algorithm.h"
#include "base/run_loop.h"
#include "base/strings/escape.h"
#include "base/strings/strcat.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/default_clock.h"
#include "base/time/default_tick_clock.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/network_session_configurator/browser/network_session_configurator.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/prefs/testing_pref_service.h"
#include "crypto/sha2.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "mojo/public/cpp/system/functions.h"
#include "net/base/cache_type.h"
#include "net/base/features.h"
#include "net/base/hash_value.h"
#include "net/base/host_port_pair.h"
#include "net/base/http_user_agent_settings.h"
#include "net/base/ip_endpoint.h"
#include "net/base/isolation_info.h"
#include "net/base/mock_network_change_notifier.h"
#include "net/base/net_errors.h"
#include "net/base/network_anonymization_key.h"
#include "net/base/network_change_notifier.h"
#include "net/base/network_isolation_key.h"
#include "net/base/proxy_chain.h"
#include "net/base/proxy_server.h"
#include "net/base/proxy_string_util.h"
#include "net/base/test_completion_callback.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/sct_status_flags.h"
#include "net/cert/x509_certificate.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_access_result.h"
#include "net/cookies/cookie_inclusion_status.h"
#include "net/cookies/cookie_options.h"
#include "net/cookies/cookie_setting_override.h"
#include "net/cookies/cookie_store.h"
#include "net/cookies/cookie_store_test_callbacks.h"
#include "net/cookies/cookie_util.h"
#include "net/cookies/site_for_cookies.h"
#include "net/disk_cache/cache_util.h"
#include "net/disk_cache/disk_cache.h"
#include "net/disk_cache/memory/mem_backend_impl.h"
#include "net/dns/context_host_resolver.h"
#include "net/dns/dns_test_util.h"
#include "net/dns/host_resolver_manager.h"
#include "net/dns/mock_host_resolver.h"
#include "net/dns/public/dns_query_type.h"
#include "net/dns/public/host_resolver_results.h"
#include "net/dns/public/host_resolver_source.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/dns/resolve_context.h"
#include "net/http/http_auth.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_session.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_server_properties_manager.h"
#include "net/http/http_status_code.h"
#include "net/http/http_stream_key.h"
#include "net/http/http_stream_pool.h"
#include "net/http/http_stream_pool_group.h"
#include "net/http/http_stream_pool_test_util.h"
#include "net/http/http_transaction_factory.h"
#include "net/http/http_transaction_test_util.h"
#include "net/http/mock_http_cache.h"
#include "net/http/transport_security_state.h"
#include "net/http/transport_security_state_test_util.h"
#include "net/nqe/network_quality_estimator_test_util.h"
#include "net/proxy_resolution/configured_proxy_resolution_service.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_info.h"
#include "net/reporting/reporting_report.h"
#include "net/reporting/reporting_target_type.h"
#include "net/socket/client_socket_pool.h"
#include "net/socket/transport_client_socket_pool.h"
#include "net/storage_access_api/status.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/embedded_test_server_connection_listener.h"
#include "net/test/gtest_util.h"
#include "net/test/scoped_mutually_exclusive_feature_list.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/test/test_data_directory.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/referrer_policy.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_test_util.h"
#include "services/network/cookie_manager.h"
#include "services/network/net_log_exporter.h"
#include "services/network/network_qualities_pref_delegate.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_service_buildflags.h"
#include "services/network/public/cpp/resolve_host_client_base.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/clear_data_filter.mojom.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "services/network/public/mojom/host_resolver.mojom.h"
#include "services/network/public/mojom/net_log.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "services/network/public/mojom/proxy_config.mojom.h"
#include "services/network/public/mojom/url_loader.mojom-shared.h"
#include "services/network/public/mojom/url_loader_factory.mojom-forward.h"
#include "services/network/test/fake_test_cert_verifier_params_factory.h"
#include "services/network/test/test_url_loader_client.h"
#include "services/network/test/test_utils.h"
#include "services/network/test/udp_socket_test_util.h"
#include "services/network/test_mojo_proxy_resolver_factory.h"
#include "services/network/trust_tokens/pending_trust_token_store.h"
#include "services/network/trust_tokens/trust_token_parameterization.h"
#include "services/network/trust_tokens/trust_token_store.h"
#include "services/network/url_request_context_builder_mojo.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/scheme_host_port.h"
#include "url/url_constants.h"

#if BUILDFLAG(ENABLE_REPORTING)
#include "net/network_error_logging/network_error_logging_service.h"
#include "net/reporting/reporting_cache.h"
#include "net/reporting/reporting_context.h"
#include "net/reporting/reporting_report.h"
#include "net/reporting/reporting_service.h"
#include "net/reporting/reporting_test_util.h"
#endif  // BUILDFLAG(ENABLE_REPORTING)

#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "services/network/mock_mojo_dhcp_wpad_url_client.h"
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

#if BUILDFLAG(IS_P2P_ENABLED)
#include "services/network/public/mojom/p2p.mojom.h"
#include "services/network/public/mojom/p2p_trusted.mojom.h"
#endif  // BUILDFLAG(IS_P2P_ENABLED)

#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#endif  // BUILDFLAG(IS_ANDROID)

namespace network {

namespace {

CreateTestURLRequestContextBuilder;
Optional;

constexpr char kMockHost[] =;
constexpr char kTopFrameOriginForFetchRequest[] =;
constexpr char kFrameOriginForFetchRequest[] =;

#if BUILDFLAG(ENABLE_REPORTING)
const base::FilePath::CharType kFilename[] =);
const GURL kUrl_ =;
const url::Origin kOrigin_ =;
const GURL kEndpoint_ =;
const std::string kUserAgent_ =;
const std::string kGroup_ =;
const std::string kType_ =;
const std::optional<base::UnguessableToken> kReportingSource_ =;
const net::NetworkAnonymizationKey kNak_ =;
#endif  // BUILDFLAG(ENABLE_REPORTING)

void StoreValue(base::Value::Dict* result,
                base::OnceClosure callback,
                base::Value::Dict value) {}

void SetContentSetting(const GURL& primary_pattern,
                       const GURL& secondary_pattern,
                       ContentSetting setting,
                       NetworkContext* network_context) {}

void SetDefaultContentSetting(ContentSetting setting,
                              NetworkContext* network_context) {}

void SetNonCookieContentSetting(ContentSettingsPattern primary_pattern,
                                ContentSettingsPattern secondary_pattern,
                                ContentSettingsType settings_type,
                                ContentSetting setting,
                                NetworkContext* network_context) {}

std::unique_ptr<TestURLLoaderClient> FetchRequest(
    const ResourceRequest& request,
    NetworkContext* network_context,
    int url_loader_options = mojom::kURLLoadOptionNone,
    int process_id = mojom::kBrowserProcessId,
    mojom::URLLoaderFactoryParamsPtr params = nullptr) {}

// Looks up disk_cache::Backend used for a given `network_context`. May spin
// the event loop.
disk_cache::Backend* WaitForCacheBackend(NetworkContext& network_context) {}

// proxy_resolver::mojom::ProxyResolverFactory that captures the most recent PAC
// script passed to it, and the most recent URL/NetworkAnonymizationKey passed
// to the GetProxyForUrl() method of proxy_resolver::mojom::ProxyResolver it
// returns.
class CapturingMojoProxyResolverFactory
    : public proxy_resolver::mojom::ProxyResolverFactory,
      public proxy_resolver::mojom::ProxyResolver {};

// ProxyLookupClient that drives proxy lookups and can wait for the responses to
// be received.
class TestProxyLookupClient : public mojom::ProxyLookupClient {};

#if BUILDFLAG(IS_P2P_ENABLED)
class MockP2PTrustedSocketManagerClient
    : public mojom::P2PTrustedSocketManagerClient {};
#endif  // BUILDFLAG(IS_P2P_ENABLED)

class HostResolverFactory final : public net::HostResolver::Factory {};

class NetworkContextTest : public testing::Test {};

class NetworkContextTestWithMockTime : public NetworkContextTest {};

TEST_F(NetworkContextTest, DestroyContextWithLiveRequest) {}

TEST_F(NetworkContextTest, DisableQuic) {}

TEST_F(NetworkContextTest, UserAgentAndLanguage) {}

TEST_F(NetworkContextTest, EnableBrotli) {}

// Confirms that when NetworkContextParams.bound_network is set, the
// NetworkContext properly targets that network.
TEST_F(NetworkContextTest, NetworkBoundNetworkContext) {}

// Confirms that URLLoaderFactories created out of network-bound NetworkContexts
// correctly target that network.
TEST_F(NetworkContextTest, NetworkBoundURLLoaderFactory) {}

TEST_F(NetworkContextTest, UnhandedProtocols) {}

#if BUILDFLAG(ENABLE_REPORTING)
TEST_F(NetworkContextTest, DisableReporting) {}

TEST_F(NetworkContextTest, EnableReportingWithoutStore) {}

TEST_F(NetworkContextTest, EnableReportingWithStore) {}

TEST_F(NetworkContextTest, QueueReport) {}

TEST_F(NetworkContextTest, QueueEnterpriseReport) {}

#if BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS)

TEST_F(NetworkContextTest, DeviceBoundSessionsDefaultParam) {
  mojom::NetworkContextParamsPtr context_params =
      CreateNetworkContextParamsForTesting();

  std::unique_ptr<NetworkContext> network_context =
      CreateContextWithParams(std::move(context_params));
  EXPECT_FALSE(
      network_context->url_request_context()->device_bound_session_service());
}

TEST_F(NetworkContextTest, DeviceBoundSessionsEnableParam) {
  mojom::NetworkContextParamsPtr context_params =
      CreateNetworkContextParamsForTesting();
  context_params->device_bound_sessions_enabled = true;

  std::unique_ptr<NetworkContext> network_context =
      CreateContextWithParams(std::move(context_params));
  EXPECT_TRUE(
      network_context->url_request_context()->device_bound_session_service());
}

TEST_F(NetworkContextTest, DeviceBoundSessionsDisableParam) {
  mojom::NetworkContextParamsPtr context_params =
      CreateNetworkContextParamsForTesting();
  context_params->device_bound_sessions_enabled = false;

  std::unique_ptr<NetworkContext> network_context =
      CreateContextWithParams(std::move(context_params));
  EXPECT_FALSE(
      network_context->url_request_context()->device_bound_session_service());
}

#endif  // BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS)

TEST_F(NetworkContextTest, DisableNetworkErrorLogging) {}

TEST_F(NetworkContextTest, EnableNetworkErrorLoggingWithoutStore) {}

TEST_F(NetworkContextTest, EnableNetworkErrorLoggingWithStore) {}

TEST_F(NetworkContextTest, SetEnterpriseReportingEndpointsWithFeatureEnabled) {}

TEST_F(NetworkContextTest, SetEnterpriseReportingEndpointsWithFeatureDisabled) {}

TEST_F(NetworkContextTest, CheckInitialEnterpriseReportingEndpointsParamSet) {}

TEST_F(NetworkContextTest,
       CheckInitialEnterpriseReportingEndpointsParamNotSet) {}

TEST_F(NetworkContextTest,
       CheckInitialEnterpriseReportingEndpointsParamSetWithFeatureDisabled) {}

#endif  // BUILDFLAG(ENABLE_REPORTING)

TEST_F(NetworkContextTest, DefaultHttpNetworkSessionParams) {}

// Make sure that network_session_configurator is hooked up.
TEST_F(NetworkContextTest, FixedHttpPort) {}

TEST_F(NetworkContextTest, NoCache) {}

TEST_F(NetworkContextTest, MemoryCache) {}

TEST_F(NetworkContextTest, DiskCache) {}

class DiskCacheSizeTest : public NetworkContextTest {};

TEST_F(DiskCacheSizeTest, DiskCacheSize) {}

// This makes sure that network_session_configurator::ChooseCacheType is
// connected to NetworkContext.
TEST_F(NetworkContextTest, SimpleCache) {}

TEST_F(NetworkContextTest, HttpServerPropertiesToDisk) {}

#if BUILDFLAG(IS_DIRECTORY_TRANSFER_REQUIRED)

TEST_F(NetworkContextTest, DataDirectoryAsHandle) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  base::FilePath file_path = temp_dir.GetPath().AppendASCII("foo");
  ASSERT_TRUE(base::CreateDirectory(file_path.DirName()));

  const url::SchemeHostPort kSchemeHostPort("https", "foo", 443);

  // Create a context with on-disk storage of HTTP server properties.
  mojom::NetworkContextParamsPtr context_params =
      CreateNetworkContextParamsForTesting();
  context_params->file_paths = mojom::NetworkContextFilePaths::New();

  // Make |data_directory| into a path-less directory handle.
  // Moving a TransferableDirectory once it's been opened will drop the
  // path from the original.
  context_params->file_paths->data_directory =
      TransferableDirectory(file_path.DirName());
  context_params->file_paths->data_directory.OpenForTransfer();
  EXPECT_TRUE(context_params->file_paths->data_directory.NeedsMount());

  context_params->file_paths->http_server_properties_file_name =
      file_path.BaseName();
  std::unique_ptr<NetworkContext> network_context =
      CreateContextWithParams(std::move(context_params));

  // Wait for properties to load from disk, and sanity check initial state.
  task_environment_.RunUntilIdle();
  EXPECT_FALSE(
      network_context->url_request_context()
          ->http_server_properties()
          ->GetSupportsSpdy(kSchemeHostPort, net::NetworkAnonymizationKey()));

  // Set a property.
  network_context->url_request_context()
      ->http_server_properties()
      ->SetSupportsSpdy(kSchemeHostPort, net::NetworkAnonymizationKey(), true);
  // Deleting the context will cause it to flush state. Wait for the pref
  // service to flush to disk.
  network_context.reset();
  task_environment_.RunUntilIdle();

  // Create a new NetworkContext using the same path for HTTP server properties.
  context_params = CreateNetworkContextParamsForTesting();
  context_params->file_paths = mojom::NetworkContextFilePaths::New();
  context_params->file_paths->data_directory = file_path.DirName();
  context_params->file_paths->http_server_properties_file_name =
      file_path.BaseName();
  network_context = CreateContextWithParams(std::move(context_params));

  // Wait for properties to load from disk.
  task_environment_.RunUntilIdle();

  EXPECT_TRUE(
      network_context->url_request_context()
          ->http_server_properties()
          ->GetSupportsSpdy(kSchemeHostPort, net::NetworkAnonymizationKey()));

  // Now check that ClearNetworkingHistoryBetween clears the data.
  base::RunLoop run_loop2;
  network_context->ClearNetworkingHistoryBetween(
      base::Time::Now() - base::Hours(1), base::Time::Max(),
      run_loop2.QuitClosure());
  run_loop2.Run();
  EXPECT_FALSE(
      network_context->url_request_context()
          ->http_server_properties()
          ->GetSupportsSpdy(kSchemeHostPort, net::NetworkAnonymizationKey()));

  // Destroy the network context and let any pending writes complete before
  // destroying |temp_dir|, to avoid leaking any files.
  network_context.reset();
  task_environment_.RunUntilIdle();
  ASSERT_TRUE(temp_dir.Delete());
}

#endif  // BUILDFLAG(IS_DIRECTORY_TRANSFER_REQUIRED)

// Checks that ClearNetworkingHistoryBetween() clears in-memory pref stores and
// invokes the closure passed to it.
TEST_F(NetworkContextTest, ClearHttpServerPropertiesInMemory) {}

// Checks that ClearNetworkingHistoryBetween() clears network quality prefs.
TEST_F(NetworkContextTest, ClearingNetworkingHistoryClearNetworkQualityPrefs) {}

// Test that TransportSecurity state is persisted (or not) as expected.
TEST_F(NetworkContextTest, TransportSecurityStatePersisted) {}

// Test that host resolution error information is available.
TEST_F(NetworkContextTest, HostResolutionFailure) {}

#if BUILDFLAG(IS_P2P_ENABLED)
// Test the P2PSocketManager::GetHostAddress() works and uses the correct
// NetworkAnonymizationKey.
TEST_F(NetworkContextTest, P2PHostResolution) {}

TEST_F(NetworkContextTest, P2PHostResolutionWithFamily) {}
#endif  // BUILDFLAG(IS_P2P_ENABLED)

// Test that valid referrers are allowed, while invalid ones result in errors.
TEST_F(NetworkContextTest, Referrers) {}

// Validates that clearing the HTTP cache when no cache exists does complete.
TEST_F(NetworkContextTest, ClearHttpCacheWithNoCache) {}

TEST_F(NetworkContextTest, ClearHttpCache) {}

// Checks that when multiple calls are made to clear the HTTP cache, all
// callbacks are invoked.
TEST_F(NetworkContextTest, MultipleClearHttpCacheCalls) {}

TEST_F(NetworkContextTest, NotifyExternalCacheHit) {}

TEST_F(NetworkContextTest, CountHttpCache) {}

TEST_F(NetworkContextTest, ClearCorsPreflightCache) {}

TEST_F(NetworkContextTest, ClearHostCache) {}

TEST_F(NetworkContextTest, ClearHttpAuthCache) {}

TEST_F(NetworkContextTest, ClearAllHttpAuthCache) {}

TEST_F(NetworkContextTest, ClearEmptyHttpAuthCache) {}

std::optional<net::AuthCredentials> GetAuthCredentials(
    NetworkContext* network_context,
    const GURL& origin,
    const net::NetworkAnonymizationKey& network_anonymization_key) {}

TEST_F(NetworkContextTest, LookupServerBasicAuthCredentials) {}

#if BUILDFLAG(IS_CHROMEOS_ASH)
std::optional<net::AuthCredentials> GetProxyAuthCredentials(
    NetworkContext* network_context,
    const net::ProxyServer& proxy_server,
    const std::string& scheme,
    const std::string& realm) {
  base::RunLoop run_loop;
  std::optional<net::AuthCredentials> result;
  network_context->LookupProxyAuthCredentials(
      proxy_server, scheme, realm,
      base::BindLambdaForTesting(
          [&](const std::optional<net::AuthCredentials>& credentials) {
            result = credentials;
            run_loop.Quit();
          }));
  run_loop.Run();
  return result;
}

TEST_F(NetworkContextTest, LookupProxyAuthCredentials) {
  GURL http_proxy("http://bar.test:1080");
  GURL https_proxy("https://bar.test:443");
  GURL http_proxy2("http://bar.test:443");
  GURL server_origin("http://foo.test:3128");

  std::unique_ptr<NetworkContext> network_context =
      CreateContextWithParams(CreateNetworkContextParamsForTesting());
  network_context->SetSplitAuthCacheByNetworkAnonymizationKey(true);
  net::HttpAuthCache* cache = network_context->url_request_context()
                                  ->http_transaction_factory()
                                  ->GetSession()
                                  ->http_auth_cache();

  std::u16string user = u"user";
  std::u16string password = u"pass";
  cache->Add(url::SchemeHostPort(http_proxy), net::HttpAuth::AUTH_PROXY,
             "Realm", net::HttpAuth::AUTH_SCHEME_BASIC,
             net::NetworkAnonymizationKey(), "basic realm=Realm",
             net::AuthCredentials(user, password),
             /* path = */ "");
  cache->Add(url::SchemeHostPort(https_proxy), net::HttpAuth::AUTH_PROXY,
             "Realm", net::HttpAuth::AUTH_SCHEME_BASIC,
             net::NetworkAnonymizationKey(), "basic realm=Realm",
             net::AuthCredentials(user, password),
             /* path = */ "");
  cache->Add(url::SchemeHostPort(server_origin), net::HttpAuth::AUTH_SERVER,
             "Realm", net::HttpAuth::AUTH_SCHEME_BASIC,
             net::NetworkAnonymizationKey(), "basic realm=Realm",
             net::AuthCredentials(user, password),
             /* path = */ "/");
  std::optional<net::AuthCredentials> result = GetProxyAuthCredentials(
      network_context.get(),
      net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTP,
                       net::HostPortPair::FromURL(http_proxy)),
      "bAsIc", "Realm");
  ASSERT_TRUE(result.has_value());
  EXPECT_EQ(user, result->username());
  EXPECT_EQ(password, result->password());

  result = GetProxyAuthCredentials(
      network_context.get(),
      net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTPS,
                       net::HostPortPair::FromURL(https_proxy)),
      "bAsIc", "Realm");
  ASSERT_TRUE(result.has_value());
  EXPECT_EQ(user, result->username());
  EXPECT_EQ(password, result->password());

  // Check that the proxy scheme is taken into account when looking for
  // credentials
  result = GetProxyAuthCredentials(
      network_context.get(),
      net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTP,
                       net::HostPortPair::FromURL(http_proxy2)),
      "basic", "Realm");
  EXPECT_FALSE(result.has_value());

  // Check that the proxy authentication method is taken into account when
  // looking for credentials
  result = GetProxyAuthCredentials(
      network_context.get(),
      net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTP,
                       net::HostPortPair::FromURL(http_proxy)),
      "digest", "Realm");
  EXPECT_FALSE(result.has_value());

  // Check that the realm is taken into account when looking for credentials
  result = GetProxyAuthCredentials(
      network_context.get(),
      net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTP,
                       net::HostPortPair::FromURL(http_proxy)),
      "basic", "Realm 2");
  EXPECT_FALSE(result.has_value());

  // Server credentials should not be returned
  result = GetProxyAuthCredentials(
      network_context.get(),
      net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTP,
                       net::HostPortPair::FromURL(server_origin)),
      "basic", "Realm");
  EXPECT_FALSE(result.has_value());
}
#endif

#if BUILDFLAG(ENABLE_REPORTING)
TEST_F(NetworkContextTest, ClearReportingCacheReports) {}

TEST_F(NetworkContextTest, ClearReportingCacheReportsWithFilter) {}

TEST_F(NetworkContextTest,
       ClearReportingCacheReportsWithNonRegisterableFilter) {}

TEST_F(NetworkContextTest, ClearEmptyReportingCacheReports) {}

TEST_F(NetworkContextTest, ClearReportingCacheReportsWithNoService) {}

TEST_F(NetworkContextTest, ClearReportingCacheClients) {}

TEST_F(NetworkContextTest, ClearReportingCacheClientsWithFilter) {}

TEST_F(NetworkContextTest, ClearEmptyReportingCacheClients) {}

TEST_F(NetworkContextTest, ClearReportingCacheClientsWithNoService) {}

TEST_F(NetworkContextTest, ClearNetworkErrorLogging) {}

TEST_F(NetworkContextTest, ClearNetworkErrorLoggingWithFilter) {}

TEST_F(NetworkContextTest, ClearEmptyNetworkErrorLogging) {}

TEST_F(NetworkContextTest, ClearEmptyNetworkErrorLoggingWithNoService) {}
#endif  // BUILDFLAG(ENABLE_REPORTING)

void SetCookieCallback(base::RunLoop* run_loop,
                       bool* result_out,
                       net::CookieAccessResult result) {}

void GetCookieListCallback(
    base::RunLoop* run_loop,
    net::CookieList* result_out,
    const net::CookieAccessResultList& result,
    const net::CookieAccessResultList& excluded_cookies) {}

bool SetCookieHelper(NetworkContext* network_context,
                     const GURL& url,
                     const std::string& key,
                     const std::string& value) {}

TEST_F(NetworkContextTest, CookieManager) {}

TEST_F(NetworkContextTest, ProxyConfig) {}

// Verify that a proxy config works without a ProxyConfigClient PendingReceiver.
TEST_F(NetworkContextTest, StaticProxyConfig) {}

TEST_F(NetworkContextTest, NoInitialProxyConfig) {}

TEST_F(NetworkContextTest, DestroyedWithoutProxyConfig) {}

TEST_F(NetworkContextTest, CancelPendingProxyLookup) {}

// Test to make sure the NetworkAnonymizationKey passed to LookUpProxyForURL()
// makes it to the proxy resolver.
TEST_F(NetworkContextTest, ProxyLookupWithNetworkIsolationKey) {}

// Test mojom::ProxyResolver that completes calls to GetProxyForUrl() with a
// DIRECT "proxy". It additionally emits a script error on line 42 for every
// call to GetProxyForUrl().
class MockMojoProxyResolver : public proxy_resolver::mojom::ProxyResolver {};

// Test mojom::ProxyResolverFactory implementation that successfully completes
// any CreateResolver() requests, and binds the request to a new
// MockMojoProxyResolver.
class MockMojoProxyResolverFactory
    : public proxy_resolver::mojom::ProxyResolverFactory {};

TEST_F(NetworkContextTest, PacQuickCheck) {}

net::IPEndPoint GetLocalHostWithAnyPort() {}

std::vector<uint8_t> CreateTestMessage(uint8_t initial, size_t size) {}

TEST_F(NetworkContextTest, CreateUDPSocket) {}

TEST_F(NetworkContextTest, CreateRestrictedUDPSocket) {}

TEST_F(NetworkContextTest, CreateNetLogExporter) {}

TEST_F(NetworkContextTest, CreateNetLogExporterUnbounded) {}

TEST_F(NetworkContextTest, CreateNetLogExporterErrors) {}

TEST_F(NetworkContextTest, DestroyNetLogExporterWhileCreatingScratchDir) {}

net::IPEndPoint CreateExpectedEndPoint(const std::string& address,
                                       uint16_t port) {}

class TestResolveHostClient : public ResolveHostClientBase {};

TEST_F(NetworkContextTest, ResolveHost_Sync) {}

TEST_F(NetworkContextTest, ResolveHost_Async) {}

TEST_F(NetworkContextTest, ResolveHost_Failure_Sync) {}

TEST_F(NetworkContextTest, ResolveHost_Failure_Async) {}

TEST_F(NetworkContextTest, ResolveHost_NetworkAnonymizationKey) {}

// Revoke fenced frame network but the resolve request is without the
// NetworkAnonymizationKey. The request should succeed.
TEST_F(NetworkContextTest,
       ResolveSchemeHostPort_RevokeNetwork_WithoutNetworkAnonymizationKey) {}

// Revoke fenced frame network and the resolve request is with the
// NetworkAnonymizationKey. The request should be disabled.
TEST_F(NetworkContextTest,
       ResolveSchemeHostPort_RevokeNetwork_WithNetworkAnonymizationKey) {}

// Revoke fenced frame network but the resolve request is without the
// NetworkAnonymizationKey. The request should succeed.
TEST_F(NetworkContextTest,
       ResolveHostPortPair_RevokeNetwork_WithoutNetworkAnonymizationKey) {}

// Revoke fenced frame network and the resolve request is with the
// NetworkAnonymizationKey. The request should be disabled.
TEST_F(NetworkContextTest,
       ResolveHostPortPair_RevokeNetwork_WithNetworkAnonymizationKey) {}

TEST_F(NetworkContextTest, ResolveHost_NoControlHandle) {}

TEST_F(NetworkContextTest, ResolveHost_CloseControlHandle) {}

TEST_F(NetworkContextTest, ResolveHost_Cancellation) {}

TEST_F(NetworkContextTest, ResolveHost_DestroyContext) {}

TEST_F(NetworkContextTest, ResolveHost_CloseClient) {}

// Test factory of net::HostResolvers. Creates standard (but potentially non-
// caching) net::ContextHostResolver. Keeps pointers to all created resolvers.
class TestResolverFactory : public net::HostResolver::Factory {};

TEST_F(NetworkContextTest, CreateHostResolver) {}

TEST_F(NetworkContextTest, CreateHostResolver_CloseResolver) {}

TEST_F(NetworkContextTest, CreateHostResolver_CloseContext) {}

// Config overrides are not supported on iOS.
#if !BUILDFLAG(IS_IOS)
TEST_F(NetworkContextTest, CreateHostResolverWithConfigOverrides) {}
#endif  // BUILDFLAG(IS_IOS)

TEST_F(NetworkContextTest, ActivateDohProbes) {}

TEST_F(NetworkContextTest, ActivateDohProbes_NotPrimaryContext) {}

TEST_F(NetworkContextTest, PrivacyModeDisabledByDefault) {}

TEST_F(NetworkContextTest, PrivacyModeEnabledIfCookiesBlocked) {}

TEST_F(NetworkContextTest, PrivacyModeDisabledIfCookiesAllowed) {}

TEST_F(NetworkContextTest, PrivacyModeDisabledIfCookiesSettingForOtherURL) {}

TEST_F(NetworkContextTest, PrivacyModeEnabledIfThirdPartyCookiesBlocked) {}

TEST_F(NetworkContextTest, CanSetCookieFalseIfCookiesBlocked) {}

TEST_F(NetworkContextTest, CanSetCookieTrueIfCookiesAllowed) {}

TEST_F(NetworkContextTest,
       AnnotateAndMoveUserBlockedCookies_FalseIfCookiesBlocked) {}

TEST_F(NetworkContextTest,
       AnnotateAndMoveUserBlockedCookies_TrueIfCookiesAllowed) {}

// Gets notified by the EmbeddedTestServer on incoming connections being
// accepted or read from, keeps track of them and exposes that info to
// the tests.
// A port being reused is currently considered an error.  If a test
// needs to verify multiple connections are opened in sequence, that will need
// to be changed.
class ConnectionListener
    : public net::test_server::EmbeddedTestServerConnectionListener {};

TEST_F(NetworkContextTest, PreconnectOne) {}

TEST_F(NetworkContextTest, PreconnectDifferentCredentialsMode) {}

TEST_F(NetworkContextTest, PreconnectHSTS) {}

TEST_F(NetworkContextTest, PreconnectZero) {}

TEST_F(NetworkContextTest, PreconnectTwo) {}

TEST_F(NetworkContextTest, PreconnectFour) {}

TEST_F(NetworkContextTest, PreconnectMax) {}

// Make sure preconnects for the same URL but with different network isolation
// keys are not merged.
TEST_F(NetworkContextTest, PreconnectNetworkIsolationKey) {}

// This tests both ClostAllConnetions and CloseIdleConnections.
TEST_F(NetworkContextTest, CloseConnections) {}

// Test that only trusted URLLoaderFactories accept
// ResourceRequest::trusted_params.
TEST_F(NetworkContextTest, TrustedParams) {}

// Test that the disable_secure_dns trusted param is passed through to the
// host resolver.
TEST_F(NetworkContextTest, TrustedParams_DisableSecureDns) {}

// Test that the disable_secure_dns factory param is passed through to the
// host resolver.
TEST_F(NetworkContextTest, FactoryParams_DisableSecureDns) {}

TEST_F(NetworkContextTest, QueryHSTS) {}

TEST_F(NetworkContextTest, GetHSTSState) {}

TEST_F(NetworkContextTest, ForceReloadProxyConfig) {}

TEST_F(NetworkContextTest, ClearBadProxiesCache) {}

// This is a test ProxyErrorClient that records the sequence of calls made to
// OnPACScriptError() and OnRequestMaybeFailedDueToProxySettings().
class TestProxyErrorClient final : public mojom::ProxyErrorClient {};

// While in scope, all host resolutions will fail with ERR_NAME_NOT_RESOLVED,
// including localhost (so this precludes the use of embedded test server).
class ScopedFailAllHostResolutions {};

// Tests that when a ProxyErrorClient is provided to NetworkContextParams, this
// client's OnRequestMaybeFailedDueToProxySettings() method is called exactly
// once when a request fails due to a proxy server connectivity failure.
TEST_F(NetworkContextTest, ProxyErrorClientNotifiedOfProxyConnection) {}

// Tests that when a ProxyErrorClient is provided to NetworkContextParams, this
// client's OnRequestMaybeFailedDueToProxySettings() method is
// NOT called when a request fails due to a non-proxy related error (in this
// case the target host is unreachable).
TEST_F(NetworkContextTest, ProxyErrorClientNotNotifiedOfUnreachableError) {}

// Tests that when a ProxyErrorClient is provided to NetworkContextParams, this
// client's OnPACScriptError() method is called whenever the PAC script throws
// an error.
TEST_F(NetworkContextTest, ProxyErrorClientNotifiedOfPacError) {}

// Test ensures that ProxyChain data is populated correctly across Mojo calls.
// Basically it performs a set of URLLoader network requests, whose requests
// configure proxies. Then it checks whether the expected proxy chain is
// propagated.
TEST_F(NetworkContextTest, EnsureProperProxyChainIsUsed) {}

class TestURLLoaderHeaderClient : public mojom::TrustedURLLoaderHeaderClient {};

TEST_F(NetworkContextTest, HeaderClientModifiesHeaders) {}

TEST_F(NetworkContextTest, HeaderClientFailsRequest) {}

class HangingTestURLLoaderHeaderClient
    : public mojom::TrustedURLLoaderHeaderClient {};

// Test waiting on the OnHeadersReceived event, then proceeding to call the
// OnHeadersReceivedCallback asynchronously. This mostly just verifies that
// HangingTestURLLoaderHeaderClient works.
TEST_F(NetworkContextTest, HangingHeaderClientModifiesHeadersAsynchronously) {}

// Test destroying the mojom::URLLoader after the OnBeforeSendHeaders event and
// then calling the OnBeforeSendHeadersCallback.
TEST_F(NetworkContextTest, HangingHeaderClientAbortDuringOnBeforeSendHeaders) {}

// Test destroying the mojom::URLLoader after the OnHeadersReceived event and
// then calling the OnHeadersReceivedCallback.
TEST_F(NetworkContextTest, HangingHeaderClientAbortDuringOnHeadersReceived) {}

::testing::AssertionResult HasCookie(
    const net::cookie_util::ParsedRequestCookies& cookies,
    std::string_view name) {}

::testing::AssertionResult HasCookie(
    const net::cookie_util::ParsedRequestCookies& cookies,
    std::string_view name,
    std::string_view value) {}

TEST_F(NetworkContextTest,
       IncludeRequestCookiesWithResponse_FailWhenUntrusted) {}

TEST_F(NetworkContextTest,
       IncludeRequestCookiesWithResponse_NoCookiesByDefault) {}

TEST_F(NetworkContextTest, IncludeRequestCookiesWithResponse_Cookie) {}

TEST_F(NetworkContextTest,
       IncludeRequestCookiesWithResponse_CookieWithRedirect) {}

TEST_F(NetworkContextTest,
       IncludeRequestCookiesWithResponse_CookiesFromBrowser) {}

TEST_F(NetworkContextTest, IncludeRequestCookiesWithResponse_HeaderClient) {}

TEST_F(NetworkContextTest,
       IncludeRequestCookiesWithResponse_HSTSRedirectClearsCookie) {}

// Custom proxy does not apply to localhost, so resolve kMockHost to localhost,
// and use that instead.
class NetworkContextMockHostTest : public NetworkContextTest {};

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// Flaky crashes on Linux: https://crbug.com/1115201
#define MAYBE_CustomProxyUsesSpecifiedProxyList
#else
#define MAYBE_CustomProxyUsesSpecifiedProxyList
#endif
TEST_F(NetworkContextMockHostTest, MAYBE_CustomProxyUsesSpecifiedProxyList) {}

TEST_F(NetworkContextTest, MaximumCount) {}

TEST_F(NetworkContextTest, AllowAllCookies) {}

TEST_F(NetworkContextTest, BlockThirdPartyCookies) {}

TEST_F(NetworkContextTest, BlockAllCookies) {}

TEST_F(NetworkContextTest, AddHttpAuthCacheEntry) {}

TEST_F(NetworkContextTest, AddHttpAuthCacheEntryWithNetworkIsolationKey) {}

TEST_F(NetworkContextTest, CopyHttpAuthCacheProxyEntries) {}

TEST_F(NetworkContextTest, SplitAuthCacheByNetworkIsolationKey) {}

TEST_F(NetworkContextTest, HSTSPolicyBypassList) {}

TEST_F(NetworkContextTest, FactoriesDeletedWhenBindingsCleared) {}

static ResourceRequest CreateResourceRequest(const char* method,
                                             const GURL& url) {}

enum class SplitCacheTestCase {};

const struct {} kTestCaseToFeatureMapping[] =;

class NetworkContextSplitCacheTest
    : public NetworkContextTest,
      public testing::WithParamInterface<SplitCacheTestCase> {};

INSTANTIATE_TEST_SUITE_P();

TEST_P(NetworkContextSplitCacheTest, CachedUsingNetworkIsolationKey) {}

TEST_P(NetworkContextSplitCacheTest,
       NavigationResourceCachedUsingNetworkIsolationKey) {}

TEST_P(NetworkContextSplitCacheTest,
       CachedUsingNetworkIsolationKeyWithFrameOrigin) {}

TEST_P(NetworkContextSplitCacheTest,
       NavigationResourceRedirectNetworkIsolationKey) {}

TEST_P(NetworkContextSplitCacheTest, AutomaticallyAssignIsolationInfo) {}

TEST_F(NetworkContextTest, EnableTrustTokens) {}

// NotifyExternalCacheHit currently assumes that the cache hits are for
// resources, so ensure that entries corresponding to subframe navigations don't
// get updated unexpectedly.
TEST_P(NetworkContextSplitCacheTest,
       NotifyExternalCacheHitIsSubframeDocumentResource) {}

TEST_F(NetworkContextTest, EnableTrustTokensForFledge) {}

TEST_F(NetworkContextTestWithMockTime, EnableTrustTokensWithStoreOnDisk) {}

TEST_F(NetworkContextTest, DisableTrustTokens) {}

class NetworkContextExpectBadMessageTest : public NetworkContextTest {};

TEST_F(NetworkContextExpectBadMessageTest,
       FailsTrustTokenBearingRequestWhenTrustTokensIsDisabled) {}

TEST_F(NetworkContextExpectBadMessageTest,
       FailsTrustTokenRedemptionWhenForbidden) {}

TEST_F(NetworkContextExpectBadMessageTest,
       FailsTrustTokenSigningWhenForbidden) {}

TEST_F(NetworkContextExpectBadMessageTest,
       FailsTrustTokenIssuanceWhenForbidden) {}

TEST_F(NetworkContextTest,
       AttemptsTrustTokenBearingRequestWhenTrustTokensIsEnabled) {}

TEST_F(NetworkContextTest,
       RejectsTrustTokenBearingRequestWhenTrustTokensAreBlocked) {}

TEST_F(NetworkContextTest,
       RejectsTrustTokenBearingRequestWhenStorageIsBlocked) {}

TEST_F(NetworkContextTest,
       NoAvailableRedemptionRecordsWhenTrustTokensAreDisabled) {}

TEST_F(NetworkContextTestWithMockTime, GetPrivateStateTokenRedemptionRecords) {}

TEST_F(NetworkContextTest, NoAvailableTrustTokensWhenTrustTokensAreDisabled) {}

TEST_F(NetworkContextTest, GetStoredTrustTokens) {}

TEST_F(NetworkContextTest, GetStoredTrustTokensReentrant) {}

TEST_F(NetworkContextTest,
       DeleteStoredTrustTokensReportsErrorWhenFeatureIsDisabled) {}

TEST_F(NetworkContextTest,
       DeleteStoredTrustTokensReportsErrorWithInvalidOrigin) {}

TEST_F(NetworkContextTest, DeleteStoredTrustTokens) {}

TEST_F(NetworkContextTest, DeleteStoredTrustTokensReentrant) {}

// Verify authorizer fails for a specific top frame origin when it is blocked
// through content settings.
TEST_F(NetworkContextTest,
       RejectsTrustTokenBearingRequestWhenStorageForTopFrameOriginIsBlocked) {}

TEST_F(NetworkContextTest,
       RejectsTrustTokenBearingRequestWhenStorageForIssuerIsBlocked) {}

#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
TEST_F(NetworkContextTest, HttpAuthAllowGssApiLibraryLoad) {}
#endif  // BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)

TEST_F(NetworkContextTest, HttpAuthUrlFilter) {}

TEST_F(NetworkContextExpectBadMessageTest, DataUrl) {}

TEST_F(NetworkContextTest, RevokeNetworkForNoncesTest) {}

TEST_F(NetworkContextTest, RevokeNetworkForNoncesDisablesNewRequestsTest) {}

TEST_F(NetworkContextTest,
       RevokeNetworkForNoncesCancelsRequestsInProgressTest) {}

TEST_F(NetworkContextTest,
       RevokeNetworkForNoncesCancelsRequestsInProgressForSecondNonceTest) {}

TEST_F(NetworkContextTest,
       RevokeNetworkForNoncesAllowsExemptedRequestsInProgressTest) {}

TEST_F(NetworkContextTest,
       RevokeNetworkForNoncesAllowsUnrelatedNonceRequestsInProgressTest) {}

TEST_F(NetworkContextTest, RevokeNetworkForNoncesCancelsPreconnectRequests) {}

// ExemptUrlFromNetworkRevocationForNonce(exempted_url, nonce) exempts
// future requests that have the same "url without filename" as `exempted_url`
// under the nonce `nonce`.
TEST_F(NetworkContextTest, ExemptUrlFromNetworkRevocationForNonceTest) {}

TEST_F(NetworkContextTest, ExemptUrlFromNetworkRevocationForNonce_InvalidURLs) {}

TEST_F(NetworkContextTest, ClearNoncesTest) {}

// Verify that the Prefetch() method triggers a network request.
TEST_F(NetworkContextTest, Prefetch) {}

class NetworkContextBrowserCookieTest
    : public NetworkContextTest,
      public testing::WithParamInterface</*should_add_browser_cookies=*/bool> {};

TEST_P(NetworkContextBrowserCookieTest, Request) {}

TEST_P(NetworkContextBrowserCookieTest, RequestWithBody) {}

// Request cookies should still be stored even when a header client is present.
TEST_P(NetworkContextBrowserCookieTest, HeaderClient) {}

// Test that browser cookies are added to the request after a redirect.
TEST_P(NetworkContextBrowserCookieTest, Redirect) {}

// Test that browser cookies are cleared after a redirect.
TEST_P(NetworkContextBrowserCookieTest, RedirectClear) {}

// Test that browser cookies are added to the request after a CORS redirect.
TEST_P(NetworkContextBrowserCookieTest, CorsRedirect) {}

// Test that browser cookies are cleared after a CORS redirect.
TEST_P(NetworkContextBrowserCookieTest, CorsRedirectClear) {}

INSTANTIATE_TEST_SUITE_P();

class StorageAccessHeaderNetworkContextTest : public NetworkContextTest {};

// This test fetches `kStorageAccessRetryPath`, but the browser does not retry
// the request since there is no matching content setting (and therefore
// retrying the request would be a waste of time).
TEST_F(StorageAccessHeaderNetworkContextTest,
       StorageAccessHeader_Retry_WithoutContentSetting) {}

// This test fetches `kStorageAccessRetryPath`, but the browser does not retry
// the request since cookies are not blocked (and therefore retrying the request
// would be a waste of time).
TEST_F(StorageAccessHeaderNetworkContextTest,
       StorageAccessHeader_Retry_WithoutBlockingCookies) {}

// This test case makes a request to `kStorageAccessRetryPath`, which responds
// with the "Activate-Storage-Access: retry" header. The browser then retries
// the request (including unpartitioned cookies, if applicable). The second
// response still includes the header, but the browser ignores it the second
// time, since retrying would not make any difference.
TEST_F(StorageAccessHeaderNetworkContextTest, StorageAccessHeader_Retry) {}

// Regression test for https://crbug.com/352722603.
TEST_F(StorageAccessHeaderNetworkContextTest,
       StorageAccessHeader_Retry_ABA_WithStorageAccess) {}

TEST_F(StorageAccessHeaderNetworkContextTest, StorageAccessHeader_Load) {}

// Only the final response in a redirect chain has any say on the
// `load_with_storage_access` field of the response.
TEST_F(StorageAccessHeaderNetworkContextTest,
       StorageAccessHeader_RedirectWithLoad) {}

TEST_F(StorageAccessHeaderNetworkContextTest,
       SecFetchStorageAccessRequestHeaderFirstPartyRequest) {}

TEST_F(StorageAccessHeaderNetworkContextTest,
       SecFetchStorageAccessRequestHeaderCookiesBlocked) {}

TEST_F(StorageAccessHeaderNetworkContextTest,
       SecFetchStorageAccessRequestHeaderNone) {}

TEST_F(StorageAccessHeaderNetworkContextTest,
       SecFetchStorageAccessRequestHeaderInactive) {}

TEST_F(StorageAccessHeaderNetworkContextTest,
       SecFetchStorageAccessRequestHeaderActive) {}

// This test recreates the case of StorageAccessHeaderRetry, with the
// additional logic of demonstrating an initial call that receives an inactive
// response.
TEST_F(StorageAccessHeaderNetworkContextTest,
       StorageAccessHeaderRetryAfterInactive) {}

}  // namespace

}  // namespace network