xref: /aosp_15_r20/external/cronet/net/test/spawned_test_server/base_test_server.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/test/spawned_test_server/base_test_server.h"
6 
7 #include <stdint.h>
8 #include <limits>
9 #include <memory>
10 #include <string>
11 #include <utility>
12 #include <vector>
13 
14 #include "base/base64.h"
15 #include "base/files/file_util.h"
16 #include "base/json/json_reader.h"
17 #include "base/logging.h"
18 #include "base/notreached.h"
19 #include "base/path_service.h"
20 #include "base/strings/string_util.h"
21 #include "base/values.h"
22 #include "net/base/address_list.h"
23 #include "net/base/host_port_pair.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/network_isolation_key.h"
26 #include "net/base/port_util.h"
27 #include "net/cert/x509_certificate.h"
28 #include "net/dns/public/dns_query_type.h"
29 #include "net/log/net_log_with_source.h"
30 #include "net/test/cert_test_util.h"
31 #include "net/test/test_data_directory.h"
32 #include "url/gurl.h"
33 
34 namespace net {
35 
36 namespace {
37 
GetHostname(BaseTestServer::Type type,const BaseTestServer::SSLOptions & options)38 std::string GetHostname(BaseTestServer::Type type,
39                         const BaseTestServer::SSLOptions& options) {
40   if (BaseTestServer::UsingSSL(type)) {
41     if (options.server_certificate ==
42             BaseTestServer::SSLOptions::CERT_MISMATCHED_NAME ||
43         options.server_certificate ==
44             BaseTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN) {
45       // For |CERT_MISMATCHED_NAME|, return a different hostname string
46       // that resolves to the same hostname. For
47       // |CERT_COMMON_NAME_IS_DOMAIN|, the certificate is issued for
48       // "localhost" instead of "127.0.0.1".
49       return "localhost";
50     }
51   }
52 
53   return "127.0.0.1";
54 }
55 
GetLocalCertificatesDir(const base::FilePath & certificates_dir,base::FilePath * local_certificates_dir)56 bool GetLocalCertificatesDir(const base::FilePath& certificates_dir,
57                              base::FilePath* local_certificates_dir) {
58   if (certificates_dir.IsAbsolute()) {
59     *local_certificates_dir = certificates_dir;
60     return true;
61   }
62 
63   base::FilePath src_dir;
64   if (!base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_dir)) {
65     return false;
66   }
67 
68   *local_certificates_dir = src_dir.Append(certificates_dir);
69   return true;
70 }
71 
72 }  // namespace
73 
74 BaseTestServer::SSLOptions::SSLOptions() = default;
SSLOptions(ServerCertificate cert)75 BaseTestServer::SSLOptions::SSLOptions(ServerCertificate cert)
76     : server_certificate(cert) {}
SSLOptions(base::FilePath cert)77 BaseTestServer::SSLOptions::SSLOptions(base::FilePath cert)
78     : custom_certificate(std::move(cert)) {}
79 BaseTestServer::SSLOptions::SSLOptions(const SSLOptions& other) = default;
80 
81 BaseTestServer::SSLOptions::~SSLOptions() = default;
82 
GetCertificateFile() const83 base::FilePath BaseTestServer::SSLOptions::GetCertificateFile() const {
84   if (!custom_certificate.empty())
85     return custom_certificate;
86 
87   switch (server_certificate) {
88     case CERT_OK:
89     case CERT_MISMATCHED_NAME:
90       return base::FilePath(FILE_PATH_LITERAL("ok_cert.pem"));
91     case CERT_COMMON_NAME_IS_DOMAIN:
92       return base::FilePath(FILE_PATH_LITERAL("localhost_cert.pem"));
93     case CERT_EXPIRED:
94       return base::FilePath(FILE_PATH_LITERAL("expired_cert.pem"));
95     case CERT_CHAIN_WRONG_ROOT:
96       // This chain uses its own dedicated test root certificate to avoid
97       // side-effects that may affect testing.
98       return base::FilePath(FILE_PATH_LITERAL("redundant-server-chain.pem"));
99     case CERT_BAD_VALIDITY:
100       return base::FilePath(FILE_PATH_LITERAL("bad_validity.pem"));
101     case CERT_KEY_USAGE_RSA_ENCIPHERMENT:
102       return base::FilePath(
103           FILE_PATH_LITERAL("key_usage_rsa_keyencipherment.pem"));
104     case CERT_KEY_USAGE_RSA_DIGITAL_SIGNATURE:
105       return base::FilePath(
106           FILE_PATH_LITERAL("key_usage_rsa_digitalsignature.pem"));
107     case CERT_TEST_NAMES:
108       return base::FilePath(FILE_PATH_LITERAL("test_names.pem"));
109     default:
110       NOTREACHED();
111   }
112   return base::FilePath();
113 }
114 
BaseTestServer(Type type)115 BaseTestServer::BaseTestServer(Type type) : type_(type) {
116   Init(GetHostname(type, ssl_options_));
117 }
118 
BaseTestServer(Type type,const SSLOptions & ssl_options)119 BaseTestServer::BaseTestServer(Type type, const SSLOptions& ssl_options)
120     : ssl_options_(ssl_options), type_(type) {
121   DCHECK(UsingSSL(type));
122   Init(GetHostname(type, ssl_options));
123 }
124 
125 BaseTestServer::~BaseTestServer() = default;
126 
Start()127 bool BaseTestServer::Start() {
128   return StartInBackground() && BlockUntilStarted();
129 }
130 
host_port_pair() const131 const HostPortPair& BaseTestServer::host_port_pair() const {
132   DCHECK(started_);
133   return host_port_pair_;
134 }
135 
GetScheme() const136 std::string BaseTestServer::GetScheme() const {
137   switch (type_) {
138     case TYPE_WS:
139       return "ws";
140     case TYPE_WSS:
141       return "wss";
142     default:
143       NOTREACHED();
144   }
145   return std::string();
146 }
147 
GetAddressList(AddressList * address_list) const148 bool BaseTestServer::GetAddressList(AddressList* address_list) const {
149   // Historically, this function did a DNS lookup because `host_port_pair_`
150   // could specify something other than localhost. Now it is always localhost.
151   DCHECK(host_port_pair_.host() == "127.0.0.1" ||
152          host_port_pair_.host() == "localhost");
153   DCHECK(address_list);
154   *address_list = AddressList(
155       IPEndPoint(IPAddress::IPv4Localhost(), host_port_pair_.port()));
156   return true;
157 }
158 
GetPort()159 uint16_t BaseTestServer::GetPort() {
160   return host_port_pair_.port();
161 }
162 
SetPort(uint16_t port)163 void BaseTestServer::SetPort(uint16_t port) {
164   host_port_pair_.set_port(port);
165 }
166 
GetURL(const std::string & path) const167 GURL BaseTestServer::GetURL(const std::string& path) const {
168   return GURL(GetScheme() + "://" + host_port_pair_.ToString() + "/" + path);
169 }
170 
GetURL(const std::string & hostname,const std::string & relative_url) const171 GURL BaseTestServer::GetURL(const std::string& hostname,
172                             const std::string& relative_url) const {
173   GURL local_url = GetURL(relative_url);
174   GURL::Replacements replace_host;
175   replace_host.SetHostStr(hostname);
176   return local_url.ReplaceComponents(replace_host);
177 }
178 
GetURLWithUser(const std::string & path,const std::string & user) const179 GURL BaseTestServer::GetURLWithUser(const std::string& path,
180                                 const std::string& user) const {
181   return GURL(GetScheme() + "://" + user + "@" + host_port_pair_.ToString() +
182               "/" + path);
183 }
184 
GetURLWithUserAndPassword(const std::string & path,const std::string & user,const std::string & password) const185 GURL BaseTestServer::GetURLWithUserAndPassword(const std::string& path,
186                                            const std::string& user,
187                                            const std::string& password) const {
188   return GURL(GetScheme() + "://" + user + ":" + password + "@" +
189               host_port_pair_.ToString() + "/" + path);
190 }
191 
192 // static
GetFilePathWithReplacements(const std::string & original_file_path,const std::vector<StringPair> & text_to_replace,std::string * replacement_path)193 bool BaseTestServer::GetFilePathWithReplacements(
194     const std::string& original_file_path,
195     const std::vector<StringPair>& text_to_replace,
196     std::string* replacement_path) {
197   std::string new_file_path = original_file_path;
198   bool first_query_parameter = true;
199   const std::vector<StringPair>::const_iterator end = text_to_replace.end();
200   for (auto it = text_to_replace.begin(); it != end; ++it) {
201     const std::string& old_text = it->first;
202     const std::string& new_text = it->second;
203     std::string base64_old = base::Base64Encode(old_text);
204     std::string base64_new = base::Base64Encode(new_text);
205     if (first_query_parameter) {
206       new_file_path += "?";
207       first_query_parameter = false;
208     } else {
209       new_file_path += "&";
210     }
211     new_file_path += "replace_text=";
212     new_file_path += base64_old;
213     new_file_path += ":";
214     new_file_path += base64_new;
215   }
216 
217   *replacement_path = new_file_path;
218   return true;
219 }
220 
RegisterTestCerts()221 ScopedTestRoot BaseTestServer::RegisterTestCerts() {
222   auto root = ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
223   if (!root)
224     return ScopedTestRoot();
225   return ScopedTestRoot(CertificateList{root});
226 }
227 
LoadTestRootCert()228 bool BaseTestServer::LoadTestRootCert() {
229   scoped_test_root_ = RegisterTestCerts();
230   return !scoped_test_root_.IsEmpty();
231 }
232 
GetCertificate() const233 scoped_refptr<X509Certificate> BaseTestServer::GetCertificate() const {
234   base::FilePath certificate_path;
235   if (!GetLocalCertificatesDir(certificates_dir_, &certificate_path))
236     return nullptr;
237 
238   base::FilePath certificate_file(ssl_options_.GetCertificateFile());
239   if (certificate_file.value().empty())
240     return nullptr;
241 
242   certificate_path = certificate_path.Append(certificate_file);
243 
244   std::string cert_data;
245   if (!base::ReadFileToString(certificate_path, &cert_data))
246     return nullptr;
247 
248   CertificateList certs_in_file =
249       X509Certificate::CreateCertificateListFromBytes(
250           base::as_byte_span(cert_data),
251           X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
252   if (certs_in_file.empty())
253     return nullptr;
254   return certs_in_file[0];
255 }
256 
Init(const std::string & host)257 void BaseTestServer::Init(const std::string& host) {
258   host_port_pair_ = HostPortPair(host, 0);
259 
260   // TODO(battre) Remove this after figuring out why the TestServer is flaky.
261   // http://crbug.com/96594
262   log_to_console_ = true;
263 }
264 
SetResourcePath(const base::FilePath & document_root,const base::FilePath & certificates_dir)265 void BaseTestServer::SetResourcePath(const base::FilePath& document_root,
266                                      const base::FilePath& certificates_dir) {
267   // This method shouldn't get called twice.
268   DCHECK(certificates_dir_.empty());
269   document_root_ = document_root;
270   certificates_dir_ = certificates_dir;
271   DCHECK(!certificates_dir_.empty());
272 }
273 
SetAndParseServerData(const std::string & server_data,int * port)274 bool BaseTestServer::SetAndParseServerData(const std::string& server_data,
275                                            int* port) {
276   VLOG(1) << "Server data: " << server_data;
277   auto parsed_json = base::JSONReader::ReadAndReturnValueWithError(server_data);
278   if (!parsed_json.has_value()) {
279     LOG(ERROR) << "Could not parse server data: "
280                << parsed_json.error().message;
281     return false;
282   } else if (!parsed_json->is_dict()) {
283     LOG(ERROR) << "Could not parse server data: expecting a dictionary";
284     return false;
285   }
286 
287   std::optional<int> port_value = parsed_json->GetDict().FindInt("port");
288   if (!port_value) {
289     LOG(ERROR) << "Could not find port value";
290     return false;
291   }
292 
293   *port = *port_value;
294   if ((*port <= 0) || (*port > std::numeric_limits<uint16_t>::max())) {
295     LOG(ERROR) << "Invalid port value: " << port;
296     return false;
297   }
298 
299   return true;
300 }
301 
SetupWhenServerStarted()302 bool BaseTestServer::SetupWhenServerStarted() {
303   DCHECK(host_port_pair_.port());
304   DCHECK(!started_);
305 
306   if (UsingSSL(type_) && !LoadTestRootCert()) {
307     LOG(ERROR) << "Could not load test root certificate.";
308     return false;
309   }
310 
311   started_ = true;
312   allowed_port_ = std::make_unique<ScopedPortException>(host_port_pair_.port());
313   return true;
314 }
315 
CleanUpWhenStoppingServer()316 void BaseTestServer::CleanUpWhenStoppingServer() {
317   scoped_test_root_.Reset({});
318   host_port_pair_.set_port(0);
319   allowed_port_.reset();
320   started_ = false;
321 }
322 
GenerateArguments() const323 std::optional<base::Value::Dict> BaseTestServer::GenerateArguments() const {
324   base::Value::Dict arguments;
325   arguments.Set("host", host_port_pair_.host());
326   arguments.Set("port", host_port_pair_.port());
327   arguments.Set("data-dir", document_root_.AsUTF8Unsafe());
328 
329   if (VLOG_IS_ON(1) || log_to_console_)
330     arguments.Set("log-to-console", base::Value());
331 
332   if (ws_basic_auth_) {
333     DCHECK(type_ == TYPE_WS || type_ == TYPE_WSS);
334     arguments.Set("ws-basic-auth", base::Value());
335   }
336 
337   if (redirect_connect_to_localhost_) {
338     DCHECK(type_ == TYPE_BASIC_AUTH_PROXY || type_ == TYPE_PROXY);
339     arguments.Set("redirect-connect-to-localhost", base::Value());
340   }
341 
342   if (UsingSSL(type_)) {
343     // Check the certificate arguments of the HTTPS server.
344     base::FilePath certificate_path(certificates_dir_);
345     base::FilePath certificate_file(ssl_options_.GetCertificateFile());
346     if (!certificate_file.value().empty()) {
347       certificate_path = certificate_path.Append(certificate_file);
348       if (certificate_path.IsAbsolute() &&
349           !base::PathExists(certificate_path)) {
350         LOG(ERROR) << "Certificate path " << certificate_path.value()
351                    << " doesn't exist. Can't launch https server.";
352         return std::nullopt;
353       }
354       arguments.Set("cert-and-key-file", certificate_path.AsUTF8Unsafe());
355     }
356 
357     // Check the client certificate related arguments.
358     if (ssl_options_.request_client_certificate)
359       arguments.Set("ssl-client-auth", base::Value());
360 
361     base::Value::List ssl_client_certs;
362 
363     std::vector<base::FilePath>::const_iterator it;
364     for (it = ssl_options_.client_authorities.begin();
365          it != ssl_options_.client_authorities.end(); ++it) {
366       if (it->IsAbsolute() && !base::PathExists(*it)) {
367         LOG(ERROR) << "Client authority path " << it->value()
368                    << " doesn't exist. Can't launch https server.";
369         return std::nullopt;
370       }
371       ssl_client_certs.Append(it->AsUTF8Unsafe());
372     }
373 
374     if (ssl_client_certs.size()) {
375       arguments.Set("ssl-client-ca", std::move(ssl_client_certs));
376     }
377   }
378 
379   return std::make_optional(std::move(arguments));
380 }
381 
382 }  // namespace net
383