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 #ifndef NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 6 #define NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 7 8 #include <stdint.h> 9 10 #include <map> 11 #include <memory> 12 #include <optional> 13 #include <string> 14 #include <string_view> 15 #include <vector> 16 17 #include "base/files/file_path.h" 18 #include "base/functional/callback.h" 19 #include "base/memory/raw_ptr.h" 20 #include "base/memory/scoped_refptr.h" 21 #include "base/memory/weak_ptr.h" 22 #include "base/threading/thread.h" 23 #include "base/threading/thread_checker.h" 24 #include "net/base/address_list.h" 25 #include "net/base/host_port_pair.h" 26 #include "net/base/ip_endpoint.h" 27 #include "net/cert/test_root_certs.h" 28 #include "net/cert/x509_certificate.h" 29 #include "net/socket/ssl_server_socket.h" 30 #include "net/socket/stream_socket.h" 31 #include "net/socket/tcp_server_socket.h" 32 #include "net/ssl/ssl_server_config.h" 33 #include "net/test/cert_builder.h" 34 #include "net/test/embedded_test_server/http_connection.h" 35 #include "third_party/boringssl/src/pki/ocsp_revocation_status.h" 36 #include "third_party/boringssl/src/pki/parse_certificate.h" 37 #include "url/gurl.h" 38 #include "url/origin.h" 39 40 namespace net { 41 42 class StreamSocket; 43 class TCPServerSocket; 44 45 namespace test_server { 46 47 class EmbeddedTestServerConnectionListener; 48 class HttpConnection; 49 class HttpResponse; 50 class HttpResponseDelegate; 51 struct HttpRequest; 52 53 class EmbeddedTestServer; 54 55 // Returned by the Start[AcceptingConnections]WithHandle() APIs, to simplify 56 // correct shutdown ordering of the EmbeddedTestServer. Shutdown() is invoked 57 // on the associated test server when the handle goes out of scope. The handle 58 // must therefore be destroyed before the test server. 59 class EmbeddedTestServerHandle { 60 public: 61 EmbeddedTestServerHandle() = default; 62 EmbeddedTestServerHandle(EmbeddedTestServerHandle&& other); 63 EmbeddedTestServerHandle& operator=(EmbeddedTestServerHandle&& other); 64 ~EmbeddedTestServerHandle(); 65 is_valid()66 bool is_valid() const { return test_server_; } 67 explicit operator bool() const { return test_server_; } 68 69 private: 70 friend class EmbeddedTestServer; 71 72 explicit EmbeddedTestServerHandle(EmbeddedTestServer* test_server); 73 raw_ptr<EmbeddedTestServer> test_server_ = nullptr; 74 }; 75 76 // Class providing an HTTP server for testing purpose. This is a basic server 77 // providing only an essential subset of HTTP/1.1 protocol. Especially, 78 // it assumes that the request syntax is correct. It *does not* support 79 // a Chunked Transfer Encoding. 80 // 81 // The common use case for unit tests is below: 82 // 83 // void SetUp() { 84 // test_server_ = std::make_unique<EmbeddedTestServer>(); 85 // test_server_->RegisterRequestHandler( 86 // base::BindRepeating(&FooTest::HandleRequest, base::Unretained(this))); 87 // ASSERT_TRUE((test_server_handle_ = test_server_.StartAndReturnHandle())); 88 // } 89 // 90 // std::unique_ptr<HttpResponse> HandleRequest(const HttpRequest& request) { 91 // GURL absolute_url = test_server_->GetURL(request.relative_url); 92 // if (absolute_url.path() != "/test") 93 // return nullptr; 94 // 95 // auto http_response = std::make_unique<BasicHttpResponse>(); 96 // http_response->set_code(net::HTTP_OK); 97 // http_response->set_content("hello"); 98 // http_response->set_content_type("text/plain"); 99 // return http_response; 100 // } 101 // 102 // For a test that spawns another process such as browser_tests, it is 103 // suggested to call Start in SetUpOnMainThread after the process is spawned. 104 // If you have to do it before the process spawns, you need to first setup the 105 // listen socket so that there is no no other threads running while spawning 106 // the process. To do so, please follow the following example: 107 // 108 // void SetUp() { 109 // ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); 110 // ... 111 // InProcessBrowserTest::SetUp(); 112 // } 113 // 114 // void SetUpOnMainThread() { 115 // // Starts the accept IO thread. 116 // embedded_test_server()->StartAcceptingConnections(); 117 // } 118 // 119 class EmbeddedTestServer { 120 public: 121 enum Type { 122 TYPE_HTTP, 123 TYPE_HTTPS, 124 }; 125 126 // A Java counterpart will be generated for this enum. 127 // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.net.test 128 enum ServerCertificate { 129 CERT_OK, 130 131 CERT_MISMATCHED_NAME, 132 CERT_EXPIRED, 133 134 // Cross-signed certificate to test PKIX path building. Contains an 135 // intermediate cross-signed by an unknown root, while the client (via 136 // TestRootStore) is expected to have a self-signed version of the 137 // intermediate. 138 CERT_CHAIN_WRONG_ROOT, 139 140 // Causes the testserver to use a hostname that is a domain 141 // instead of an IP. 142 CERT_COMMON_NAME_IS_DOMAIN, 143 144 // A certificate that only contains a commonName, rather than also 145 // including a subjectAltName extension. 146 CERT_COMMON_NAME_ONLY, 147 148 // A certificate that is a leaf certificate signed with SHA-1. 149 CERT_SHA1_LEAF, 150 151 // A certificate that is signed by an intermediate certificate. 152 CERT_OK_BY_INTERMEDIATE, 153 154 // A certificate with invalid notBefore and notAfter times. Windows' 155 // certificate library will not parse this certificate. 156 CERT_BAD_VALIDITY, 157 158 // A certificate that covers a number of test names. See [test_names] in 159 // net/data/ssl/scripts/ee.cnf. More may be added by editing this list and 160 // and rerunning net/data/ssl/scripts/generate-test-certs.sh. 161 CERT_TEST_NAMES, 162 163 // An RSA certificate with the keyUsage extension specifying that the key 164 // is only for encipherment. 165 CERT_KEY_USAGE_RSA_ENCIPHERMENT, 166 167 // An RSA certificate with the keyUsage extension specifying that the key 168 // is only for digital signatures. 169 CERT_KEY_USAGE_RSA_DIGITAL_SIGNATURE, 170 171 // A certificate will be generated at runtime. A ServerCertificateConfig 172 // passed to SetSSLConfig may be used to configure the details of the 173 // generated certificate. 174 CERT_AUTO, 175 }; 176 177 enum class IntermediateType { 178 // Generated cert is issued directly by the CA. 179 kNone, 180 // Generated cert is issued by a generated intermediate cert, which is 181 // included in the TLS handshake. 182 kInHandshake, 183 // Generated cert is issued by a generated intermediate, which is NOT 184 // included in the TLS handshake, but is available through the leaf's 185 // AIA caIssuers URL. 186 kByAIA, 187 // Generated cert is issued by a generated intermediate, which is NOT 188 // included in the TLS handshake and not served by an AIA server. 189 kMissing, 190 }; 191 192 struct OCSPConfig { 193 // Enumerates the types of OCSP response that the testserver can produce. 194 enum class ResponseType { 195 // OCSP will not be enabled for the corresponding config. 196 kOff, 197 // These correspond to the OCSPResponseStatus enumeration in RFC 198 // 6960. 199 kSuccessful, 200 kMalformedRequest, 201 kInternalError, 202 kTryLater, 203 kSigRequired, 204 kUnauthorized, 205 // The response will not be valid bssl::OCSPResponse DER. 206 kInvalidResponse, 207 // bssl::OCSPResponse will be valid DER but the contained ResponseData 208 // will not. 209 kInvalidResponseData, 210 }; 211 212 // OCSPProduced describes the time of the producedAt field in the 213 // OCSP response relative to the certificate the response is for. 214 enum class Produced { 215 // producedAt is between certificate's notBefore and notAfter dates. 216 kValid, 217 // producedAt is before certificate's notBefore date. 218 kBeforeCert, 219 // producedAt is after certificate's notAfter date. 220 kAfterCert, 221 }; 222 223 struct SingleResponse { 224 // Date describes the thisUpdate..nextUpdate ranges for OCSP 225 // singleResponses, relative to the current time. 226 enum class Date { 227 // The singleResponse is valid for 7 days, and includes the current 228 // time. 229 kValid, 230 // The singleResponse is valid for 7 days, but nextUpdate is before the 231 // current time. 232 kOld, 233 // The singleResponse is valid for 7 days, but thisUpdate is after the 234 // current time. 235 kEarly, 236 // The singleResponse is valid for 366 days, and includes the current 237 // time. 238 kLong, 239 // The singleResponse is valid for 368 days, and includes the current 240 // time. 241 kLonger, 242 }; 243 244 // Configures whether a generated OCSP singleResponse's serial field 245 // matches the serial number of the target certificate. 246 enum class Serial { 247 kMatch, 248 kMismatch, 249 }; 250 251 bssl::OCSPRevocationStatus cert_status = bssl::OCSPRevocationStatus::GOOD; 252 Date ocsp_date = Date::kValid; 253 Serial serial = Serial::kMatch; 254 }; 255 256 OCSPConfig(); 257 // Configure OCSP response with |response_type|. 258 explicit OCSPConfig(ResponseType response_type); 259 // Configure a successful OCSP response with |single_responses|. |produced| 260 // specifies the response's producedAt value, relative to the validity 261 // period of the certificate the OCSPConfig is for. 262 explicit OCSPConfig(std::vector<SingleResponse> single_responses, 263 Produced produced = Produced::kValid); 264 OCSPConfig(const OCSPConfig&); 265 OCSPConfig(OCSPConfig&&); 266 ~OCSPConfig(); 267 OCSPConfig& operator=(const OCSPConfig&); 268 OCSPConfig& operator=(OCSPConfig&&); 269 270 ResponseType response_type = ResponseType::kOff; 271 Produced produced = Produced::kValid; 272 std::vector<SingleResponse> single_responses; 273 }; 274 275 // Configuration for generated server certificate. 276 struct ServerCertificateConfig { 277 ServerCertificateConfig(); 278 ServerCertificateConfig(const ServerCertificateConfig&); 279 ServerCertificateConfig(ServerCertificateConfig&&); 280 ~ServerCertificateConfig(); 281 ServerCertificateConfig& operator=(const ServerCertificateConfig&); 282 ServerCertificateConfig& operator=(ServerCertificateConfig&&); 283 284 // Configure whether the generated certificate chain should include an 285 // intermediate, and if so, how it is delivered to the client. 286 IntermediateType intermediate = IntermediateType::kNone; 287 288 // Configure OCSP handling. 289 // Note: In the current implementation the AIA request handler does not 290 // actually parse the OCSP request (a different OCSP URL is used for each 291 // cert). So this is useful for testing the client's handling of the OCSP 292 // response, but not for testing that the client is sending a proper OCSP 293 // request. 294 // 295 // AIA OCSP for the leaf cert. If |kOff|, no AIA OCSP URL will be included 296 // in the leaf cert. 297 OCSPConfig ocsp_config; 298 // Stapled OCSP for the leaf cert. If |kOff|, OCSP Stapling will not be 299 // used. 300 OCSPConfig stapled_ocsp_config; 301 // AIA OCSP for the intermediate cert. If |kOff|, no AIA OCSP URL will be 302 // included in the intermediate cert. It is invalid to supply a 303 // configuration other than |kOff| if |intermediate| is |kNone|. 304 OCSPConfig intermediate_ocsp_config; 305 306 // Certificate policy OIDs, in text notation (e.g. "1.2.3.4"). If 307 // non-empty, the policies will be added to the leaf cert and the 308 // intermediate cert (if an intermediate is configured). 309 std::vector<std::string> policy_oids; 310 311 // A list of DNS names to include in the leaf subjectAltName extension. 312 std::vector<std::string> dns_names; 313 314 // A list of IP addresses to include in the leaf subjectAltName extension. 315 std::vector<net::IPAddress> ip_addresses; 316 317 // A list of key usages to include in the leaf keyUsage extension. 318 std::vector<bssl::KeyUsageBit> key_usages; 319 320 // Generate embedded SCTList in the certificate for the specified logs. 321 std::vector<CertBuilder::SctConfig> embedded_scts; 322 }; 323 324 typedef base::RepeatingCallback<std::unique_ptr<HttpResponse>( 325 const HttpRequest& request)> 326 HandleRequestCallback; 327 typedef base::RepeatingCallback<void(const HttpRequest& request)> 328 MonitorRequestCallback; 329 330 // Creates a http test server. StartAndReturnHandle() must be called to start 331 // the server. 332 // |type| indicates the protocol type of the server (HTTP/HTTPS). 333 // 334 // When a TYPE_HTTPS server is created, EmbeddedTestServer will call 335 // EmbeddedTestServer::RegisterTestCerts(), so that when the default 336 // CertVerifiers are run in-process, they will recognize the test server's 337 // certs. However, if the test server is running in a different process from 338 // the CertVerifiers, EmbeddedTestServer::RegisterTestCerts() must be called 339 // in any process where CertVerifiers are expected to accept the 340 // EmbeddedTestServer's certs. 341 EmbeddedTestServer(); 342 explicit EmbeddedTestServer( 343 Type type, 344 HttpConnection::Protocol protocol = HttpConnection::Protocol::kHttp1); 345 ~EmbeddedTestServer(); 346 347 // Send a request to the server to be handled. If a response is created, 348 // SendResponseBytes() should be called on the provided HttpConnection. 349 void HandleRequest(base::WeakPtr<HttpResponseDelegate> connection, 350 std::unique_ptr<HttpRequest> request); 351 352 // Notify the server that a connection is no longer usable and is safe to 353 // destroy. For H/1 connections, this means a single request/response 354 // interaction, as keep-alive connections are not supported. If the 355 // connection listener is present and the socket is still connected, the 356 // listener will be notified. 357 void RemoveConnection( 358 HttpConnection* connection, 359 EmbeddedTestServerConnectionListener* listener = nullptr); 360 361 // Registers the EmbeddedTestServer's certs for the current process. See 362 // constructor documentation for more information. 363 [[nodiscard]] static ScopedTestRoot RegisterTestCerts(); 364 365 // Sets a connection listener, that would be notified when various connection 366 // events happen. May only be called before the server is started. Caller 367 // maintains ownership of the listener. 368 void SetConnectionListener(EmbeddedTestServerConnectionListener* listener); 369 370 // Initializes and waits until the server is ready to accept requests. 371 // This is the equivalent of calling InitializeAndListen() followed by 372 // StartAcceptingConnectionsAndReturnHandle(). 373 // Returns a "handle" which will ShutdownAndWaitUntilComplete() when 374 // destroyed, or null if the listening socket could not be created. 375 [[nodiscard]] EmbeddedTestServerHandle StartAndReturnHandle(int port = 0); 376 377 // Equivalent of StartAndReturnHandle(), but requires manual Shutdown() by 378 // the caller. 379 [[nodiscard]] bool Start(int port = 0, 380 std::string_view address = "127.0.0.1"); 381 382 // Starts listening for incoming connections but will not yet accept them. 383 // Returns whether a listening socket has been successfully created. 384 [[nodiscard]] bool InitializeAndListen( 385 int port = 0, 386 std::string_view address = "127.0.0.1"); 387 388 // Starts the Accept IO Thread and begins accepting connections. 389 [[nodiscard]] EmbeddedTestServerHandle 390 StartAcceptingConnectionsAndReturnHandle(); 391 392 // Equivalent of StartAcceptingConnectionsAndReturnHandle(), but requires 393 // manual Shutdown() by the caller. 394 void StartAcceptingConnections(); 395 396 // Shuts down the http server and waits until the shutdown is complete. 397 // Prefer to use the Start*AndReturnHandle() APIs to manage shutdown, if 398 // possible. 399 [[nodiscard]] bool ShutdownAndWaitUntilComplete(); 400 401 // Checks if the server has started listening for incoming connections. Started()402 bool Started() const { return listen_socket_.get() != nullptr; } 403 404 static base::FilePath GetRootCertPemPath(); 405 host_port_pair()406 HostPortPair host_port_pair() const { 407 return HostPortPair::FromURL(base_url_); 408 } 409 410 // Returns the base URL to the server, which looks like 411 // http://127.0.0.1:<port>/, where <port> is the actual port number used by 412 // the server. base_url()413 const GURL& base_url() const { return base_url_; } 414 415 // Returns a URL to the server based on the given relative URL, which 416 // should start with '/'. For example: GetURL("/path?query=foo") => 417 // http://127.0.0.1:<port>/path?query=foo. 418 GURL GetURL(std::string_view relative_url) const; 419 420 // Similar to the above method with the difference that it uses the supplied 421 // |hostname| for the URL instead of 127.0.0.1. The hostname should be 422 // resolved to 127.0.0.1. 423 GURL GetURL(std::string_view hostname, std::string_view relative_url) const; 424 425 // Convenience function equivalent to calling url::Origin::Create(base_url()). 426 // Will use the GetURL() variant that takes a hostname as the base URL, if 427 // `hostname` is non-null. 428 url::Origin GetOrigin( 429 const std::optional<std::string>& hostname = std::nullopt) const; 430 431 // Returns the address list needed to connect to the server. 432 [[nodiscard]] bool GetAddressList(AddressList* address_list) const; 433 434 // Returns the IP Address to connect to the server as a string. 435 std::string GetIPLiteralString() const; 436 437 // Returns the port number used by the server. port()438 uint16_t port() const { return port_; } 439 440 // SetSSLConfig sets the SSL configuration for the server. It is invalid to 441 // call after the server is started. If called multiple times, the last call 442 // will have effect. 443 void SetSSLConfig(ServerCertificate cert, const SSLServerConfig& ssl_config); 444 void SetSSLConfig(ServerCertificate cert); 445 void SetSSLConfig(const ServerCertificateConfig& cert_config, 446 const SSLServerConfig& ssl_config); 447 void SetSSLConfig(const ServerCertificateConfig& cert_config); 448 449 // TODO(mattm): make this [[nodiscard]] 450 bool ResetSSLConfig(ServerCertificate cert, 451 const SSLServerConfig& ssl_config); 452 453 // Configures the test server to generate a certificate that covers the 454 // specified hostnames. This implicitly also includes 127.0.0.1 in the 455 // certificate. It is invalid to call after the server is started. If called 456 // multiple times, the last call will have effect. 457 // Convenience method for configuring an HTTPS test server when a test needs 458 // to support a set of hostnames over HTTPS, rather than explicitly setting 459 /// up a full config using SetSSLConfig(). 460 void SetCertHostnames(std::vector<std::string> hostnames); 461 462 // Returns the certificate that the server is using. 463 // If using a generated ServerCertificate type, this must not be called before 464 // InitializeAndListen() has been called. 465 scoped_refptr<X509Certificate> GetCertificate(); 466 467 // Returns any generated intermediates that the server may be using. May 468 // return null if no intermediate is generated. Must not be called before 469 // InitializeAndListen(). 470 scoped_refptr<X509Certificate> GetGeneratedIntermediate(); 471 472 // Registers request handler which serves files from |directory|. 473 // For instance, a request to "/foo.html" is served by "foo.html" under 474 // |directory|. Files under sub directories are also handled in the same way 475 // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|). 476 // TODO(svaldez): Merge ServeFilesFromDirectory and 477 // ServeFilesFromSourceDirectory. 478 void ServeFilesFromDirectory(const base::FilePath& directory); 479 480 // Serves files relative to DIR_SRC_TEST_DATA_ROOT. 481 void ServeFilesFromSourceDirectory(std::string_view relative); 482 void ServeFilesFromSourceDirectory(const base::FilePath& relative); 483 484 // Registers the default handlers and serve additional files from the 485 // |directory| directory, relative to DIR_SRC_TEST_DATA_ROOT. 486 void AddDefaultHandlers(const base::FilePath& directory); 487 488 // Returns the directory that files will be served from if |relative| is 489 // passed to ServeFilesFromSourceDirectory(). 490 static base::FilePath GetFullPathFromSourceDirectory( 491 const base::FilePath& relative); 492 493 // Adds all default handlers except, without serving additional files from any 494 // directory. 495 void AddDefaultHandlers(); 496 497 // Adds a request handler that can perform any general-purpose processing. 498 // |callback| will be invoked on the server's IO thread. Note that: 499 // 1. All handlers must be registered before the server is Start()ed. 500 // 2. The server should be Shutdown() before any variables referred to by 501 // |callback| (e.g. via base::Unretained(&local)) are deleted. Using the 502 // Start*WithHandle() API variants is recommended for this reason. 503 void RegisterRequestHandler(const HandleRequestCallback& callback); 504 505 // Adds a request monitor that will be called before any handlers. Monitors 506 // can be used to observe requests, but not to respond to them. 507 // See RegisterRequestHandler() for notes on usage. 508 void RegisterRequestMonitor(const MonitorRequestCallback& callback); 509 510 // Adds a default request handler, to be called if no user-specified handler 511 // handles the request. 512 // See RegisterRequestHandler() for notes on usage. 513 void RegisterDefaultHandler(const HandleRequestCallback& callback); 514 515 bool FlushAllSocketsAndConnectionsOnUIThread(); 516 void FlushAllSocketsAndConnections(); 517 518 // Adds an origin/accept_ch pair to add to an ACCEPT_CH HTTP/2 frame. If any 519 // pairs have been added, the ALPS TLS extension will be populated, which 520 // will act as though an ACCEPT_CH frame was sent by the server before the 521 // first frame is sent by a client. For more information, see 522 // draft-vvv-tls-alps-01 and section 4.1 (HTTP/2 ACCEPT_CH Frame) of 523 // draft-davidben-http-client-hint-reliability 524 // 525 // Only valid before Start() or ResetSSLServerConfig(). Only valid when 526 // constructed with PROTOCOL_HTTP2. For the default host, use an empty 527 // string. 528 void SetAlpsAcceptCH(std::string hostname, std::string accept_ch); 529 530 private: 531 // Returns the file name of the certificate the server is using. The test 532 // certificates can be found in net/data/ssl/certificates/. 533 std::string GetCertificateName() const; 534 535 // Shuts down the server. 536 void ShutdownOnIOThread(); 537 538 // Sets the SSL configuration for the server. It is invalid for |cert_config| 539 // to be non-null if |cert| is not CERT_AUTO. 540 void SetSSLConfigInternal(ServerCertificate cert, 541 const ServerCertificateConfig* cert_config, 542 const SSLServerConfig& ssl_config); 543 544 // Resets the SSLServerConfig on the IO thread. 545 bool ResetSSLConfigOnIOThread(ServerCertificate cert, 546 const SSLServerConfig& ssl_config); 547 548 // Upgrade the TCP connection to one over SSL. 549 std::unique_ptr<SSLServerSocket> DoSSLUpgrade( 550 std::unique_ptr<StreamSocket> connection); 551 // Handles async callback when the SSL handshake has been completed. 552 void OnHandshakeDone(HttpConnection* http_connection, int rv); 553 // Begins new connection if handshake resulted in a connection 554 void HandleHandshakeResults(); 555 556 // Begins accepting new client connections. 557 void DoAcceptLoop(); 558 // Handles async callback when there is a new client socket. |rv| is the 559 // return value of the socket Accept. 560 void OnAcceptCompleted(int rv); 561 // Adds the new |socket| to the list of clients and begins the reading 562 // data. 563 void HandleAcceptResult(std::unique_ptr<StreamSocket> socket_ptr); 564 565 // Create a connection with a socket, add it to the map, and return pointers 566 // to both. 567 HttpConnection* AddConnection(std::unique_ptr<StreamSocket> socket_ptr); 568 569 // Handles async callback when new data has been read from the |connection|. 570 void OnReadCompleted(HttpConnection* connection, int rv); 571 572 // Returns true if the current |cert_| configuration uses a static 573 // pre-generated cert loaded from the filesystem. 574 bool UsingStaticCert() const; 575 576 // Reads server certificate and private key from file. May only be called if 577 // |cert_| refers to a file-based cert & key. 578 [[nodiscard]] bool InitializeCertAndKeyFromFile(); 579 580 // Generate server certificate and private key. May only be called if |cert_| 581 // refers to a generated cert & key. 582 [[nodiscard]] bool GenerateCertAndKey(); 583 584 // Initializes the SSLServerContext so that SSLServerSocket connections may 585 // share the same cache 586 [[nodiscard]] bool InitializeSSLServerContext(); 587 588 // Posts a task to the |io_thread_| and waits for a reply. 589 [[nodiscard]] bool PostTaskToIOThreadAndWait(base::OnceClosure closure); 590 591 // Posts a task that returns a true/false success/fail value to the 592 // |io_thread_| and waits for a reply. 593 [[nodiscard]] bool PostTaskToIOThreadAndWaitWithResult( 594 base::OnceCallback<bool()> task); 595 596 const bool is_using_ssl_; 597 const HttpConnection::Protocol protocol_; 598 599 std::unique_ptr<base::Thread> io_thread_; 600 601 std::unique_ptr<TCPServerSocket> listen_socket_; 602 std::unique_ptr<StreamSocket> accepted_socket_; 603 604 raw_ptr<EmbeddedTestServerConnectionListener, DanglingUntriaged> 605 connection_listener_ = nullptr; 606 uint16_t port_ = 0; 607 GURL base_url_; 608 IPEndPoint local_endpoint_; 609 610 std::map<const StreamSocket*, std::unique_ptr<HttpConnection>> connections_; 611 612 // Vector of registered and default request handlers and monitors. 613 std::vector<HandleRequestCallback> request_handlers_; 614 std::vector<MonitorRequestCallback> request_monitors_; 615 std::vector<HandleRequestCallback> default_request_handlers_; 616 617 base::ThreadChecker thread_checker_; 618 619 ScopedTestRoot scoped_test_root_; 620 net::SSLServerConfig ssl_config_; 621 ServerCertificate cert_ = CERT_OK; 622 ServerCertificateConfig cert_config_; 623 scoped_refptr<X509Certificate> x509_cert_; 624 // May be null if no intermediate is generated. 625 scoped_refptr<X509Certificate> intermediate_; 626 bssl::UniquePtr<EVP_PKEY> private_key_; 627 base::flat_map<std::string, std::string> alps_accept_ch_; 628 std::unique_ptr<SSLServerContext> context_; 629 630 // HTTP server that handles AIA URLs that are embedded in this test server's 631 // certificate when the server certificate is one of the CERT_AUTO variants. 632 std::unique_ptr<EmbeddedTestServer> aia_http_server_; 633 634 base::WeakPtrFactory<EmbeddedTestServer> weak_factory_{this}; 635 }; 636 637 } // namespace test_server 638 639 // TODO(svaldez): Refactor EmbeddedTestServer to be in the net namespace. 640 using test_server::EmbeddedTestServer; 641 642 } // namespace net 643 644 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 645