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