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;
204 std::string base64_new;
205 base::Base64Encode(old_text, &base64_old);
206 base::Base64Encode(new_text, &base64_new);
207 if (first_query_parameter) {
208 new_file_path += "?";
209 first_query_parameter = false;
210 } else {
211 new_file_path += "&";
212 }
213 new_file_path += "replace_text=";
214 new_file_path += base64_old;
215 new_file_path += ":";
216 new_file_path += base64_new;
217 }
218
219 *replacement_path = new_file_path;
220 return true;
221 }
222
RegisterTestCerts()223 ScopedTestRoot BaseTestServer::RegisterTestCerts() {
224 auto root = ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
225 if (!root)
226 return ScopedTestRoot();
227 return ScopedTestRoot(CertificateList{root});
228 }
229
LoadTestRootCert()230 bool BaseTestServer::LoadTestRootCert() {
231 scoped_test_root_ = RegisterTestCerts();
232 return !scoped_test_root_.IsEmpty();
233 }
234
GetCertificate() const235 scoped_refptr<X509Certificate> BaseTestServer::GetCertificate() const {
236 base::FilePath certificate_path;
237 if (!GetLocalCertificatesDir(certificates_dir_, &certificate_path))
238 return nullptr;
239
240 base::FilePath certificate_file(ssl_options_.GetCertificateFile());
241 if (certificate_file.value().empty())
242 return nullptr;
243
244 certificate_path = certificate_path.Append(certificate_file);
245
246 std::string cert_data;
247 if (!base::ReadFileToString(certificate_path, &cert_data))
248 return nullptr;
249
250 CertificateList certs_in_file =
251 X509Certificate::CreateCertificateListFromBytes(
252 base::as_bytes(base::make_span(cert_data)),
253 X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
254 if (certs_in_file.empty())
255 return nullptr;
256 return certs_in_file[0];
257 }
258
Init(const std::string & host)259 void BaseTestServer::Init(const std::string& host) {
260 host_port_pair_ = HostPortPair(host, 0);
261
262 // TODO(battre) Remove this after figuring out why the TestServer is flaky.
263 // http://crbug.com/96594
264 log_to_console_ = true;
265 }
266
SetResourcePath(const base::FilePath & document_root,const base::FilePath & certificates_dir)267 void BaseTestServer::SetResourcePath(const base::FilePath& document_root,
268 const base::FilePath& certificates_dir) {
269 // This method shouldn't get called twice.
270 DCHECK(certificates_dir_.empty());
271 document_root_ = document_root;
272 certificates_dir_ = certificates_dir;
273 DCHECK(!certificates_dir_.empty());
274 }
275
SetAndParseServerData(const std::string & server_data,int * port)276 bool BaseTestServer::SetAndParseServerData(const std::string& server_data,
277 int* port) {
278 VLOG(1) << "Server data: " << server_data;
279 auto parsed_json = base::JSONReader::ReadAndReturnValueWithError(server_data);
280 if (!parsed_json.has_value()) {
281 LOG(ERROR) << "Could not parse server data: "
282 << parsed_json.error().message;
283 return false;
284 } else if (!parsed_json->is_dict()) {
285 LOG(ERROR) << "Could not parse server data: expecting a dictionary";
286 return false;
287 }
288
289 absl::optional<int> port_value = parsed_json->GetDict().FindInt("port");
290 if (!port_value) {
291 LOG(ERROR) << "Could not find port value";
292 return false;
293 }
294
295 *port = *port_value;
296 if ((*port <= 0) || (*port > std::numeric_limits<uint16_t>::max())) {
297 LOG(ERROR) << "Invalid port value: " << port;
298 return false;
299 }
300
301 return true;
302 }
303
SetupWhenServerStarted()304 bool BaseTestServer::SetupWhenServerStarted() {
305 DCHECK(host_port_pair_.port());
306 DCHECK(!started_);
307
308 if (UsingSSL(type_) && !LoadTestRootCert()) {
309 LOG(ERROR) << "Could not load test root certificate.";
310 return false;
311 }
312
313 started_ = true;
314 allowed_port_ = std::make_unique<ScopedPortException>(host_port_pair_.port());
315 return true;
316 }
317
CleanUpWhenStoppingServer()318 void BaseTestServer::CleanUpWhenStoppingServer() {
319 scoped_test_root_.Reset({});
320 host_port_pair_.set_port(0);
321 allowed_port_.reset();
322 started_ = false;
323 }
324
GenerateArguments() const325 absl::optional<base::Value::Dict> BaseTestServer::GenerateArguments() const {
326 base::Value::Dict arguments;
327 arguments.Set("host", host_port_pair_.host());
328 arguments.Set("port", host_port_pair_.port());
329 arguments.Set("data-dir", document_root_.AsUTF8Unsafe());
330
331 if (VLOG_IS_ON(1) || log_to_console_)
332 arguments.Set("log-to-console", base::Value());
333
334 if (ws_basic_auth_) {
335 DCHECK(type_ == TYPE_WS || type_ == TYPE_WSS);
336 arguments.Set("ws-basic-auth", base::Value());
337 }
338
339 if (redirect_connect_to_localhost_) {
340 DCHECK(type_ == TYPE_BASIC_AUTH_PROXY || type_ == TYPE_PROXY);
341 arguments.Set("redirect-connect-to-localhost", base::Value());
342 }
343
344 if (UsingSSL(type_)) {
345 // Check the certificate arguments of the HTTPS server.
346 base::FilePath certificate_path(certificates_dir_);
347 base::FilePath certificate_file(ssl_options_.GetCertificateFile());
348 if (!certificate_file.value().empty()) {
349 certificate_path = certificate_path.Append(certificate_file);
350 if (certificate_path.IsAbsolute() &&
351 !base::PathExists(certificate_path)) {
352 LOG(ERROR) << "Certificate path " << certificate_path.value()
353 << " doesn't exist. Can't launch https server.";
354 return absl::nullopt;
355 }
356 arguments.Set("cert-and-key-file", certificate_path.AsUTF8Unsafe());
357 }
358
359 // Check the client certificate related arguments.
360 if (ssl_options_.request_client_certificate)
361 arguments.Set("ssl-client-auth", base::Value());
362
363 base::Value::List ssl_client_certs;
364
365 std::vector<base::FilePath>::const_iterator it;
366 for (it = ssl_options_.client_authorities.begin();
367 it != ssl_options_.client_authorities.end(); ++it) {
368 if (it->IsAbsolute() && !base::PathExists(*it)) {
369 LOG(ERROR) << "Client authority path " << it->value()
370 << " doesn't exist. Can't launch https server.";
371 return absl::nullopt;
372 }
373 ssl_client_certs.Append(it->AsUTF8Unsafe());
374 }
375
376 if (ssl_client_certs.size()) {
377 arguments.Set("ssl-client-ca", std::move(ssl_client_certs));
378 }
379 }
380
381 return absl::make_optional(std::move(arguments));
382 }
383
384 } // namespace net
385