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_SOURCE_ROOT, &src_dir))
65 return false;
66
67 *local_certificates_dir = src_dir.Append(certificates_dir);
68 return true;
69 }
70
71 } // namespace
72
73 BaseTestServer::SSLOptions::SSLOptions() = default;
SSLOptions(ServerCertificate cert)74 BaseTestServer::SSLOptions::SSLOptions(ServerCertificate cert)
75 : server_certificate(cert) {}
SSLOptions(base::FilePath cert)76 BaseTestServer::SSLOptions::SSLOptions(base::FilePath cert)
77 : custom_certificate(std::move(cert)) {}
78 BaseTestServer::SSLOptions::SSLOptions(const SSLOptions& other) = default;
79
80 BaseTestServer::SSLOptions::~SSLOptions() = default;
81
GetCertificateFile() const82 base::FilePath BaseTestServer::SSLOptions::GetCertificateFile() const {
83 if (!custom_certificate.empty())
84 return custom_certificate;
85
86 switch (server_certificate) {
87 case CERT_OK:
88 case CERT_MISMATCHED_NAME:
89 return base::FilePath(FILE_PATH_LITERAL("ok_cert.pem"));
90 case CERT_COMMON_NAME_IS_DOMAIN:
91 return base::FilePath(FILE_PATH_LITERAL("localhost_cert.pem"));
92 case CERT_EXPIRED:
93 return base::FilePath(FILE_PATH_LITERAL("expired_cert.pem"));
94 case CERT_CHAIN_WRONG_ROOT:
95 // This chain uses its own dedicated test root certificate to avoid
96 // side-effects that may affect testing.
97 return base::FilePath(FILE_PATH_LITERAL("redundant-server-chain.pem"));
98 case CERT_BAD_VALIDITY:
99 return base::FilePath(FILE_PATH_LITERAL("bad_validity.pem"));
100 case CERT_KEY_USAGE_RSA_ENCIPHERMENT:
101 return base::FilePath(
102 FILE_PATH_LITERAL("key_usage_rsa_keyencipherment.pem"));
103 case CERT_KEY_USAGE_RSA_DIGITAL_SIGNATURE:
104 return base::FilePath(
105 FILE_PATH_LITERAL("key_usage_rsa_digitalsignature.pem"));
106 case CERT_TEST_NAMES:
107 return base::FilePath(FILE_PATH_LITERAL("test_names.pem"));
108 default:
109 NOTREACHED();
110 }
111 return base::FilePath();
112 }
113
BaseTestServer(Type type)114 BaseTestServer::BaseTestServer(Type type) : type_(type) {
115 Init(GetHostname(type, ssl_options_));
116 }
117
BaseTestServer(Type type,const SSLOptions & ssl_options)118 BaseTestServer::BaseTestServer(Type type, const SSLOptions& ssl_options)
119 : ssl_options_(ssl_options), type_(type) {
120 DCHECK(UsingSSL(type));
121 Init(GetHostname(type, ssl_options));
122 }
123
124 BaseTestServer::~BaseTestServer() = default;
125
Start()126 bool BaseTestServer::Start() {
127 return StartInBackground() && BlockUntilStarted();
128 }
129
host_port_pair() const130 const HostPortPair& BaseTestServer::host_port_pair() const {
131 DCHECK(started_);
132 return host_port_pair_;
133 }
134
GetScheme() const135 std::string BaseTestServer::GetScheme() const {
136 switch (type_) {
137 case TYPE_WS:
138 return "ws";
139 case TYPE_WSS:
140 return "wss";
141 default:
142 NOTREACHED();
143 }
144 return std::string();
145 }
146
GetAddressList(AddressList * address_list) const147 bool BaseTestServer::GetAddressList(AddressList* address_list) const {
148 // Historically, this function did a DNS lookup because `host_port_pair_`
149 // could specify something other than localhost. Now it is always localhost.
150 DCHECK(host_port_pair_.host() == "127.0.0.1" ||
151 host_port_pair_.host() == "localhost");
152 DCHECK(address_list);
153 *address_list = AddressList(
154 IPEndPoint(IPAddress::IPv4Localhost(), host_port_pair_.port()));
155 return true;
156 }
157
GetPort()158 uint16_t BaseTestServer::GetPort() {
159 return host_port_pair_.port();
160 }
161
SetPort(uint16_t port)162 void BaseTestServer::SetPort(uint16_t port) {
163 host_port_pair_.set_port(port);
164 }
165
GetURL(const std::string & path) const166 GURL BaseTestServer::GetURL(const std::string& path) const {
167 return GURL(GetScheme() + "://" + host_port_pair_.ToString() + "/" + path);
168 }
169
GetURL(const std::string & hostname,const std::string & relative_url) const170 GURL BaseTestServer::GetURL(const std::string& hostname,
171 const std::string& relative_url) const {
172 GURL local_url = GetURL(relative_url);
173 GURL::Replacements replace_host;
174 replace_host.SetHostStr(hostname);
175 return local_url.ReplaceComponents(replace_host);
176 }
177
GetURLWithUser(const std::string & path,const std::string & user) const178 GURL BaseTestServer::GetURLWithUser(const std::string& path,
179 const std::string& user) const {
180 return GURL(GetScheme() + "://" + user + "@" + host_port_pair_.ToString() +
181 "/" + path);
182 }
183
GetURLWithUserAndPassword(const std::string & path,const std::string & user,const std::string & password) const184 GURL BaseTestServer::GetURLWithUserAndPassword(const std::string& path,
185 const std::string& user,
186 const std::string& password) const {
187 return GURL(GetScheme() + "://" + user + ":" + password + "@" +
188 host_port_pair_.ToString() + "/" + path);
189 }
190
191 // static
GetFilePathWithReplacements(const std::string & original_file_path,const std::vector<StringPair> & text_to_replace,std::string * replacement_path)192 bool BaseTestServer::GetFilePathWithReplacements(
193 const std::string& original_file_path,
194 const std::vector<StringPair>& text_to_replace,
195 std::string* replacement_path) {
196 std::string new_file_path = original_file_path;
197 bool first_query_parameter = true;
198 const std::vector<StringPair>::const_iterator end = text_to_replace.end();
199 for (auto it = text_to_replace.begin(); it != end; ++it) {
200 const std::string& old_text = it->first;
201 const std::string& new_text = it->second;
202 std::string base64_old;
203 std::string base64_new;
204 base::Base64Encode(old_text, &base64_old);
205 base::Base64Encode(new_text, &base64_new);
206 if (first_query_parameter) {
207 new_file_path += "?";
208 first_query_parameter = false;
209 } else {
210 new_file_path += "&";
211 }
212 new_file_path += "replace_text=";
213 new_file_path += base64_old;
214 new_file_path += ":";
215 new_file_path += base64_new;
216 }
217
218 *replacement_path = new_file_path;
219 return true;
220 }
221
RegisterTestCerts()222 ScopedTestRoot BaseTestServer::RegisterTestCerts() {
223 auto root = ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
224 if (!root)
225 return ScopedTestRoot();
226 return ScopedTestRoot(CertificateList{root});
227 }
228
LoadTestRootCert()229 bool BaseTestServer::LoadTestRootCert() {
230 scoped_test_root_ = RegisterTestCerts();
231 return !scoped_test_root_.IsEmpty();
232 }
233
GetCertificate() const234 scoped_refptr<X509Certificate> BaseTestServer::GetCertificate() const {
235 base::FilePath certificate_path;
236 if (!GetLocalCertificatesDir(certificates_dir_, &certificate_path))
237 return nullptr;
238
239 base::FilePath certificate_file(ssl_options_.GetCertificateFile());
240 if (certificate_file.value().empty())
241 return nullptr;
242
243 certificate_path = certificate_path.Append(certificate_file);
244
245 std::string cert_data;
246 if (!base::ReadFileToString(certificate_path, &cert_data))
247 return nullptr;
248
249 CertificateList certs_in_file =
250 X509Certificate::CreateCertificateListFromBytes(
251 base::as_bytes(base::make_span(cert_data)),
252 X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
253 if (certs_in_file.empty())
254 return nullptr;
255 return certs_in_file[0];
256 }
257
Init(const std::string & host)258 void BaseTestServer::Init(const std::string& host) {
259 host_port_pair_ = HostPortPair(host, 0);
260
261 // TODO(battre) Remove this after figuring out why the TestServer is flaky.
262 // http://crbug.com/96594
263 log_to_console_ = true;
264 }
265
SetResourcePath(const base::FilePath & document_root,const base::FilePath & certificates_dir)266 void BaseTestServer::SetResourcePath(const base::FilePath& document_root,
267 const base::FilePath& certificates_dir) {
268 // This method shouldn't get called twice.
269 DCHECK(certificates_dir_.empty());
270 document_root_ = document_root;
271 certificates_dir_ = certificates_dir;
272 DCHECK(!certificates_dir_.empty());
273 }
274
SetAndParseServerData(const std::string & server_data,int * port)275 bool BaseTestServer::SetAndParseServerData(const std::string& server_data,
276 int* port) {
277 VLOG(1) << "Server data: " << server_data;
278 auto parsed_json = base::JSONReader::ReadAndReturnValueWithError(server_data);
279 if (!parsed_json.has_value()) {
280 LOG(ERROR) << "Could not parse server data: "
281 << parsed_json.error().message;
282 return false;
283 } else if (!parsed_json->is_dict()) {
284 LOG(ERROR) << "Could not parse server data: expecting a dictionary";
285 return false;
286 }
287
288 absl::optional<int> port_value = parsed_json->GetDict().FindInt("port");
289 if (!port_value) {
290 LOG(ERROR) << "Could not find port value";
291 return false;
292 }
293
294 *port = *port_value;
295 if ((*port <= 0) || (*port > std::numeric_limits<uint16_t>::max())) {
296 LOG(ERROR) << "Invalid port value: " << port;
297 return false;
298 }
299
300 return true;
301 }
302
SetupWhenServerStarted()303 bool BaseTestServer::SetupWhenServerStarted() {
304 DCHECK(host_port_pair_.port());
305 DCHECK(!started_);
306
307 if (UsingSSL(type_) && !LoadTestRootCert()) {
308 LOG(ERROR) << "Could not load test root certificate.";
309 return false;
310 }
311
312 started_ = true;
313 allowed_port_ = std::make_unique<ScopedPortException>(host_port_pair_.port());
314 return true;
315 }
316
CleanUpWhenStoppingServer()317 void BaseTestServer::CleanUpWhenStoppingServer() {
318 scoped_test_root_.Reset({});
319 host_port_pair_.set_port(0);
320 allowed_port_.reset();
321 started_ = false;
322 }
323
GenerateArguments() const324 absl::optional<base::Value::Dict> BaseTestServer::GenerateArguments() const {
325 base::Value::Dict arguments;
326 arguments.Set("host", host_port_pair_.host());
327 arguments.Set("port", host_port_pair_.port());
328 arguments.Set("data-dir", document_root_.AsUTF8Unsafe());
329
330 if (VLOG_IS_ON(1) || log_to_console_)
331 arguments.Set("log-to-console", base::Value());
332
333 if (ws_basic_auth_) {
334 DCHECK(type_ == TYPE_WS || type_ == TYPE_WSS);
335 arguments.Set("ws-basic-auth", base::Value());
336 }
337
338 if (redirect_connect_to_localhost_) {
339 DCHECK(type_ == TYPE_BASIC_AUTH_PROXY || type_ == TYPE_PROXY);
340 arguments.Set("redirect-connect-to-localhost", base::Value());
341 }
342
343 if (UsingSSL(type_)) {
344 // Check the certificate arguments of the HTTPS server.
345 base::FilePath certificate_path(certificates_dir_);
346 base::FilePath certificate_file(ssl_options_.GetCertificateFile());
347 if (!certificate_file.value().empty()) {
348 certificate_path = certificate_path.Append(certificate_file);
349 if (certificate_path.IsAbsolute() &&
350 !base::PathExists(certificate_path)) {
351 LOG(ERROR) << "Certificate path " << certificate_path.value()
352 << " doesn't exist. Can't launch https server.";
353 return absl::nullopt;
354 }
355 arguments.Set("cert-and-key-file", certificate_path.AsUTF8Unsafe());
356 }
357
358 // Check the client certificate related arguments.
359 if (ssl_options_.request_client_certificate)
360 arguments.Set("ssl-client-auth", base::Value());
361
362 base::Value::List ssl_client_certs;
363
364 std::vector<base::FilePath>::const_iterator it;
365 for (it = ssl_options_.client_authorities.begin();
366 it != ssl_options_.client_authorities.end(); ++it) {
367 if (it->IsAbsolute() && !base::PathExists(*it)) {
368 LOG(ERROR) << "Client authority path " << it->value()
369 << " doesn't exist. Can't launch https server.";
370 return absl::nullopt;
371 }
372 ssl_client_certs.Append(it->AsUTF8Unsafe());
373 }
374
375 if (ssl_client_certs.size()) {
376 arguments.Set("ssl-client-ca", std::move(ssl_client_certs));
377 }
378 }
379
380 return absl::make_optional(std::move(arguments));
381 }
382
383 } // namespace net
384