• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #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 <string>
13 #include <vector>
14 
15 #include "base/files/file_path.h"
16 #include "base/functional/callback.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/memory/scoped_refptr.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/strings/string_piece.h"
21 #include "base/threading/thread.h"
22 #include "base/threading/thread_checker.h"
23 #include "net/base/address_list.h"
24 #include "net/base/host_port_pair.h"
25 #include "net/base/ip_endpoint.h"
26 #include "net/cert/test_root_certs.h"
27 #include "net/cert/x509_certificate.h"
28 #include "net/socket/ssl_server_socket.h"
29 #include "net/socket/stream_socket.h"
30 #include "net/socket/tcp_server_socket.h"
31 #include "net/ssl/ssl_server_config.h"
32 #include "net/test/cert_builder.h"
33 #include "net/test/embedded_test_server/http_connection.h"
34 #include "third_party/abseil-cpp/absl/types/optional.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   };
188 
189   struct OCSPConfig {
190     // Enumerates the types of OCSP response that the testserver can produce.
191     enum class ResponseType {
192       // OCSP will not be enabled for the corresponding config.
193       kOff,
194       // These correspond to the OCSPResponseStatus enumeration in RFC
195       // 6960.
196       kSuccessful,
197       kMalformedRequest,
198       kInternalError,
199       kTryLater,
200       kSigRequired,
201       kUnauthorized,
202       // The response will not be valid bssl::OCSPResponse DER.
203       kInvalidResponse,
204       // bssl::OCSPResponse will be valid DER but the contained ResponseData
205       // will not.
206       kInvalidResponseData,
207     };
208 
209     // OCSPProduced describes the time of the producedAt field in the
210     // OCSP response relative to the certificate the response is for.
211     enum class Produced {
212       // producedAt is between certificate's notBefore and notAfter dates.
213       kValid,
214       // producedAt is before certificate's notBefore date.
215       kBeforeCert,
216       // producedAt is after certificate's notAfter date.
217       kAfterCert,
218     };
219 
220     struct SingleResponse {
221       // Date describes the thisUpdate..nextUpdate ranges for OCSP
222       // singleResponses, relative to the current time.
223       enum class Date {
224         // The singleResponse is valid for 7 days, and includes the current
225         // time.
226         kValid,
227         // The singleResponse is valid for 7 days, but nextUpdate is before the
228         // current time.
229         kOld,
230         // The singleResponse is valid for 7 days, but thisUpdate is after the
231         // current time.
232         kEarly,
233         // The singleResponse is valid for 366 days, and includes the current
234         // time.
235         kLong,
236         // The singleResponse is valid for 368 days, and includes the current
237         // time.
238         kLonger,
239       };
240 
241       // Configures whether a generated OCSP singleResponse's serial field
242       // matches the serial number of the target certificate.
243       enum class Serial {
244         kMatch,
245         kMismatch,
246       };
247 
248       bssl::OCSPRevocationStatus cert_status = bssl::OCSPRevocationStatus::GOOD;
249       Date ocsp_date = Date::kValid;
250       Serial serial = Serial::kMatch;
251     };
252 
253     OCSPConfig();
254     // Configure OCSP response with |response_type|.
255     explicit OCSPConfig(ResponseType response_type);
256     // Configure a successful OCSP response with |single_responses|. |produced|
257     // specifies the response's producedAt value, relative to the validity
258     // period of the certificate the OCSPConfig is for.
259     explicit OCSPConfig(std::vector<SingleResponse> single_responses,
260                         Produced produced = Produced::kValid);
261     OCSPConfig(const OCSPConfig&);
262     OCSPConfig(OCSPConfig&&);
263     ~OCSPConfig();
264     OCSPConfig& operator=(const OCSPConfig&);
265     OCSPConfig& operator=(OCSPConfig&&);
266 
267     ResponseType response_type = ResponseType::kOff;
268     Produced produced = Produced::kValid;
269     std::vector<SingleResponse> single_responses;
270   };
271 
272   // Configuration for generated server certificate.
273   struct ServerCertificateConfig {
274     ServerCertificateConfig();
275     ServerCertificateConfig(const ServerCertificateConfig&);
276     ServerCertificateConfig(ServerCertificateConfig&&);
277     ~ServerCertificateConfig();
278     ServerCertificateConfig& operator=(const ServerCertificateConfig&);
279     ServerCertificateConfig& operator=(ServerCertificateConfig&&);
280 
281     // Configure whether the generated certificate chain should include an
282     // intermediate, and if so, how it is delivered to the client.
283     IntermediateType intermediate = IntermediateType::kNone;
284 
285     // Configure OCSP handling.
286     // Note: In the current implementation the AIA request handler does not
287     // actually parse the OCSP request (a different OCSP URL is used for each
288     // cert). So this is useful for testing the client's handling of the OCSP
289     // response, but not for testing that the client is sending a proper OCSP
290     // request.
291     //
292     // AIA OCSP for the leaf cert. If |kOff|, no AIA OCSP URL will be included
293     // in the leaf cert.
294     OCSPConfig ocsp_config;
295     // Stapled OCSP for the leaf cert. If |kOff|, OCSP Stapling will not be
296     // used.
297     OCSPConfig stapled_ocsp_config;
298     // AIA OCSP for the intermediate cert. If |kOff|, no AIA OCSP URL will be
299     // included in the intermediate cert. It is invalid to supply a
300     // configuration other than |kOff| if |intermediate| is |kNone|.
301     OCSPConfig intermediate_ocsp_config;
302 
303     // Certificate policy OIDs, in text notation (e.g. "1.2.3.4"). If
304     // non-empty, the policies will be added to the leaf cert and the
305     // intermediate cert (if an intermediate is configured).
306     std::vector<std::string> policy_oids;
307 
308     // A list of DNS names to include in the leaf subjectAltName extension.
309     std::vector<std::string> dns_names;
310 
311     // A list of IP addresses to include in the leaf subjectAltName extension.
312     std::vector<net::IPAddress> ip_addresses;
313 
314     // A list of key usages to include in the leaf keyUsage extension.
315     std::vector<bssl::KeyUsageBit> key_usages;
316 
317     // Generate embedded SCTList in the certificate for the specified logs.
318     std::vector<CertBuilder::SctConfig> embedded_scts;
319   };
320 
321   typedef base::RepeatingCallback<std::unique_ptr<HttpResponse>(
322       const HttpRequest& request)>
323       HandleRequestCallback;
324   typedef base::RepeatingCallback<void(const HttpRequest& request)>
325       MonitorRequestCallback;
326 
327   // Creates a http test server. StartAndReturnHandle() must be called to start
328   // the server.
329   // |type| indicates the protocol type of the server (HTTP/HTTPS).
330   //
331   //  When a TYPE_HTTPS server is created, EmbeddedTestServer will call
332   // EmbeddedTestServer::RegisterTestCerts(), so that when the default
333   // CertVerifiers are run in-process, they will recognize the test server's
334   // certs. However, if the test server is running in a different process from
335   // the CertVerifiers, EmbeddedTestServer::RegisterTestCerts() must be called
336   // in any process where CertVerifiers are expected to accept the
337   // EmbeddedTestServer's certs.
338   EmbeddedTestServer();
339   explicit EmbeddedTestServer(
340       Type type,
341       HttpConnection::Protocol protocol = HttpConnection::Protocol::kHttp1);
342   ~EmbeddedTestServer();
343 
344   //  Send a request to the server to be handled. If a response is created,
345   //  SendResponseBytes() should be called on the provided HttpConnection.
346   void HandleRequest(base::WeakPtr<HttpResponseDelegate> connection,
347                      std::unique_ptr<HttpRequest> request);
348 
349   // Notify the server that a connection is no longer usable and is safe to
350   // destroy. For H/1 connections, this means a single request/response
351   // interaction, as keep-alive connections are not supported. If the
352   // connection listener is present and the socket is still connected, the
353   // listener will be notified.
354   void RemoveConnection(
355       HttpConnection* connection,
356       EmbeddedTestServerConnectionListener* listener = nullptr);
357 
358   // Registers the EmbeddedTestServer's certs for the current process. See
359   // constructor documentation for more information.
360   [[nodiscard]] static ScopedTestRoot RegisterTestCerts();
361 
362   // Sets a connection listener, that would be notified when various connection
363   // events happen. May only be called before the server is started. Caller
364   // maintains ownership of the listener.
365   void SetConnectionListener(EmbeddedTestServerConnectionListener* listener);
366 
367   // Initializes and waits until the server is ready to accept requests.
368   // This is the equivalent of calling InitializeAndListen() followed by
369   // StartAcceptingConnectionsAndReturnHandle().
370   // Returns a "handle" which will ShutdownAndWaitUntilComplete() when
371   // destroyed, or null if the listening socket could not be created.
372   [[nodiscard]] EmbeddedTestServerHandle StartAndReturnHandle(int port = 0);
373 
374   // Equivalent of StartAndReturnHandle(), but requires manual Shutdown() by
375   // the caller.
376   [[nodiscard]] bool Start(int port = 0,
377                            base::StringPiece address = "127.0.0.1");
378 
379   // Starts listening for incoming connections but will not yet accept them.
380   // Returns whether a listening socket has been successfully created.
381   [[nodiscard]] bool InitializeAndListen(
382       int port = 0,
383       base::StringPiece address = "127.0.0.1");
384 
385   // Starts the Accept IO Thread and begins accepting connections.
386   [[nodiscard]] EmbeddedTestServerHandle
387   StartAcceptingConnectionsAndReturnHandle();
388 
389   // Equivalent of StartAcceptingConnectionsAndReturnHandle(), but requires
390   // manual Shutdown() by the caller.
391   void StartAcceptingConnections();
392 
393   // Shuts down the http server and waits until the shutdown is complete.
394   // Prefer to use the Start*AndReturnHandle() APIs to manage shutdown, if
395   // possible.
396   [[nodiscard]] bool ShutdownAndWaitUntilComplete();
397 
398   // Checks if the server has started listening for incoming connections.
Started()399   bool Started() const { return listen_socket_.get() != nullptr; }
400 
401   static base::FilePath GetRootCertPemPath();
402 
host_port_pair()403   HostPortPair host_port_pair() const {
404     return HostPortPair::FromURL(base_url_);
405   }
406 
407   // Returns the base URL to the server, which looks like
408   // http://127.0.0.1:<port>/, where <port> is the actual port number used by
409   // the server.
base_url()410   const GURL& base_url() const { return base_url_; }
411 
412   // Returns a URL to the server based on the given relative URL, which
413   // should start with '/'. For example: GetURL("/path?query=foo") =>
414   // http://127.0.0.1:<port>/path?query=foo.
415   GURL GetURL(base::StringPiece relative_url) const;
416 
417   // Similar to the above method with the difference that it uses the supplied
418   // |hostname| for the URL instead of 127.0.0.1. The hostname should be
419   // resolved to 127.0.0.1.
420   GURL GetURL(base::StringPiece hostname, base::StringPiece relative_url) const;
421 
422   // Convenience function equivalent to calling url::Origin::Create(base_url()).
423   // Will use the GetURL() variant that takes a hostname as the base URL, if
424   // `hostname` is non-null.
425   url::Origin GetOrigin(
426       const absl::optional<std::string>& hostname = absl::nullopt) const;
427 
428   // Returns the address list needed to connect to the server.
429   [[nodiscard]] bool GetAddressList(AddressList* address_list) const;
430 
431   // Returns the IP Address to connect to the server as a string.
432   std::string GetIPLiteralString() const;
433 
434   // Returns the port number used by the server.
port()435   uint16_t port() const { return port_; }
436 
437   // SetSSLConfig sets the SSL configuration for the server. It is invalid to
438   // call after the server is started. If called multiple times, the last call
439   // will have effect.
440   void SetSSLConfig(ServerCertificate cert, const SSLServerConfig& ssl_config);
441   void SetSSLConfig(ServerCertificate cert);
442   void SetSSLConfig(const ServerCertificateConfig& cert_config,
443                     const SSLServerConfig& ssl_config);
444   void SetSSLConfig(const ServerCertificateConfig& cert_config);
445 
446   // TODO(mattm): make this [[nodiscard]]
447   bool ResetSSLConfig(ServerCertificate cert,
448                       const SSLServerConfig& ssl_config);
449 
450   // Returns the certificate that the server is using.
451   // If using a generated ServerCertificate type, this must not be called before
452   // InitializeAndListen() has been called.
453   scoped_refptr<X509Certificate> GetCertificate();
454 
455   // Registers request handler which serves files from |directory|.
456   // For instance, a request to "/foo.html" is served by "foo.html" under
457   // |directory|. Files under sub directories are also handled in the same way
458   // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|).
459   // TODO(svaldez): Merge ServeFilesFromDirectory and
460   // ServeFilesFromSourceDirectory.
461   void ServeFilesFromDirectory(const base::FilePath& directory);
462 
463   // Serves files relative to DIR_SRC_TEST_DATA_ROOT.
464   void ServeFilesFromSourceDirectory(base::StringPiece relative);
465   void ServeFilesFromSourceDirectory(const base::FilePath& relative);
466 
467   // Registers the default handlers and serve additional files from the
468   // |directory| directory, relative to DIR_SRC_TEST_DATA_ROOT.
469   void AddDefaultHandlers(const base::FilePath& directory);
470 
471   // Returns the directory that files will be served from if |relative| is
472   // passed to ServeFilesFromSourceDirectory().
473   static base::FilePath GetFullPathFromSourceDirectory(
474       const base::FilePath& relative);
475 
476   // Adds all default handlers except, without serving additional files from any
477   // directory.
478   void AddDefaultHandlers();
479 
480   // Adds a request handler that can perform any general-purpose processing.
481   // |callback| will be invoked on the server's IO thread. Note that:
482   // 1. All handlers must be registered before the server is Start()ed.
483   // 2. The server should be Shutdown() before any variables referred to by
484   //    |callback| (e.g. via base::Unretained(&local)) are deleted. Using the
485   //    Start*WithHandle() API variants is recommended for this reason.
486   void RegisterRequestHandler(const HandleRequestCallback& callback);
487 
488   // Adds a request monitor that will be called before any handlers. Monitors
489   // can be used to observe requests, but not to respond to them.
490   // See RegisterRequestHandler() for notes on usage.
491   void RegisterRequestMonitor(const MonitorRequestCallback& callback);
492 
493   // Adds a default request handler, to be called if no user-specified handler
494   // handles the request.
495   // See RegisterRequestHandler() for notes on usage.
496   void RegisterDefaultHandler(const HandleRequestCallback& callback);
497 
498   bool FlushAllSocketsAndConnectionsOnUIThread();
499   void FlushAllSocketsAndConnections();
500 
501   // Adds an origin/accept_ch pair to add to an ACCEPT_CH HTTP/2 frame. If any
502   // pairs have been added, the ALPS TLS extension will be populated, which
503   // will act as though an ACCEPT_CH frame was sent by the server before the
504   // first frame is sent by a client. For more information, see
505   // draft-vvv-tls-alps-01 and section 4.1 (HTTP/2 ACCEPT_CH Frame) of
506   // draft-davidben-http-client-hint-reliability
507   //
508   // Only valid before Start() or ResetSSLServerConfig(). Only valid when
509   // constructed with PROTOCOL_HTTP2. For the default host, use an empty
510   // string.
511   void SetAlpsAcceptCH(std::string hostname, std::string accept_ch);
512 
513  private:
514   // Returns the file name of the certificate the server is using. The test
515   // certificates can be found in net/data/ssl/certificates/.
516   std::string GetCertificateName() const;
517 
518   // Shuts down the server.
519   void ShutdownOnIOThread();
520 
521   // Sets the SSL configuration for the server. It is invalid for |cert_config|
522   // to be non-null if |cert| is not CERT_AUTO.
523   void SetSSLConfigInternal(ServerCertificate cert,
524                             const ServerCertificateConfig* cert_config,
525                             const SSLServerConfig& ssl_config);
526 
527   // Resets the SSLServerConfig on the IO thread.
528   bool ResetSSLConfigOnIOThread(ServerCertificate cert,
529                                 const SSLServerConfig& ssl_config);
530 
531   // Upgrade the TCP connection to one over SSL.
532   std::unique_ptr<SSLServerSocket> DoSSLUpgrade(
533       std::unique_ptr<StreamSocket> connection);
534   // Handles async callback when the SSL handshake has been completed.
535   void OnHandshakeDone(HttpConnection* http_connection, int rv);
536   // Begins new connection if handshake resulted in a connection
537   void HandleHandshakeResults();
538 
539   // Begins accepting new client connections.
540   void DoAcceptLoop();
541   // Handles async callback when there is a new client socket. |rv| is the
542   // return value of the socket Accept.
543   void OnAcceptCompleted(int rv);
544   // Adds the new |socket| to the list of clients and begins the reading
545   // data.
546   void HandleAcceptResult(std::unique_ptr<StreamSocket> socket_ptr);
547 
548   // Create a connection with a socket, add it to the map, and return pointers
549   // to both.
550   HttpConnection* AddConnection(std::unique_ptr<StreamSocket> socket_ptr);
551 
552   // Handles async callback when new data has been read from the |connection|.
553   void OnReadCompleted(HttpConnection* connection, int rv);
554 
555   // Returns true if the current |cert_| configuration uses a static
556   // pre-generated cert loaded from the filesystem.
557   bool UsingStaticCert() const;
558 
559   // Reads server certificate and private key from file. May only be called if
560   // |cert_| refers to a file-based cert & key.
561   [[nodiscard]] bool InitializeCertAndKeyFromFile();
562 
563   // Generate server certificate and private key. May only be called if |cert_|
564   // refers to a generated cert & key.
565   [[nodiscard]] bool GenerateCertAndKey();
566 
567   // Initializes the SSLServerContext so that SSLServerSocket connections may
568   // share the same cache
569   [[nodiscard]] bool InitializeSSLServerContext();
570 
571   // Posts a task to the |io_thread_| and waits for a reply.
572   [[nodiscard]] bool PostTaskToIOThreadAndWait(base::OnceClosure closure);
573 
574   // Posts a task that returns a true/false success/fail value to the
575   // |io_thread_| and waits for a reply.
576   [[nodiscard]] bool PostTaskToIOThreadAndWaitWithResult(
577       base::OnceCallback<bool()> task);
578 
579   const bool is_using_ssl_;
580   const HttpConnection::Protocol protocol_;
581 
582   std::unique_ptr<base::Thread> io_thread_;
583 
584   std::unique_ptr<TCPServerSocket> listen_socket_;
585   std::unique_ptr<StreamSocket> accepted_socket_;
586 
587   raw_ptr<EmbeddedTestServerConnectionListener, DanglingUntriaged>
588       connection_listener_ = nullptr;
589   uint16_t port_ = 0;
590   GURL base_url_;
591   IPEndPoint local_endpoint_;
592 
593   std::map<const StreamSocket*, std::unique_ptr<HttpConnection>> connections_;
594 
595   // Vector of registered and default request handlers and monitors.
596   std::vector<HandleRequestCallback> request_handlers_;
597   std::vector<MonitorRequestCallback> request_monitors_;
598   std::vector<HandleRequestCallback> default_request_handlers_;
599 
600   base::ThreadChecker thread_checker_;
601 
602   ScopedTestRoot scoped_test_root_;
603   net::SSLServerConfig ssl_config_;
604   ServerCertificate cert_ = CERT_OK;
605   ServerCertificateConfig cert_config_;
606   scoped_refptr<X509Certificate> x509_cert_;
607   bssl::UniquePtr<EVP_PKEY> private_key_;
608   base::flat_map<std::string, std::string> alps_accept_ch_;
609   std::unique_ptr<SSLServerContext> context_;
610 
611   // HTTP server that handles AIA URLs that are embedded in this test server's
612   // certificate when the server certificate is one of the CERT_AUTO variants.
613   std::unique_ptr<EmbeddedTestServer> aia_http_server_;
614 
615   base::WeakPtrFactory<EmbeddedTestServer> weak_factory_{this};
616 };
617 
618 }  // namespace test_server
619 
620 // TODO(svaldez): Refactor EmbeddedTestServer to be in the net namespace.
621 using test_server::EmbeddedTestServer;
622 
623 }  // namespace net
624 
625 #endif  // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_
626