1 // Copyright 2019 The Chromium Authors. All rights reserved.
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 "cast/receiver/channel/testing/device_auth_test_helpers.h"
6 
7 #include <string>
8 #include <utility>
9 
10 #include "cast/common/certificate/testing/test_helpers.h"
11 #include "gtest/gtest.h"
12 #include "util/crypto/pem_helpers.h"
13 
14 namespace openscreen {
15 namespace cast {
16 
InitStaticCredentialsFromFiles(StaticCredentialsProvider * creds,bssl::UniquePtr<X509> * parsed_cert,TrustStore * fake_trust_store,absl::string_view privkey_filename,absl::string_view chain_filename,absl::string_view tls_filename)17 void InitStaticCredentialsFromFiles(StaticCredentialsProvider* creds,
18                                     bssl::UniquePtr<X509>* parsed_cert,
19                                     TrustStore* fake_trust_store,
20                                     absl::string_view privkey_filename,
21                                     absl::string_view chain_filename,
22                                     absl::string_view tls_filename) {
23   auto private_key = ReadKeyFromPemFile(privkey_filename);
24   ASSERT_TRUE(private_key);
25   std::vector<std::string> certs = ReadCertificatesFromPemFile(chain_filename);
26   ASSERT_GT(certs.size(), 1u);
27 
28   // Use the root of the chain as the trust store for the test.
29   auto* data = reinterpret_cast<const uint8_t*>(certs.back().data());
30   auto fake_root =
31       bssl::UniquePtr<X509>(d2i_X509(nullptr, &data, certs.back().size()));
32   ASSERT_TRUE(fake_root);
33   certs.pop_back();
34   if (fake_trust_store) {
35     fake_trust_store->certs.emplace_back(fake_root.release());
36   }
37 
38   creds->device_creds = DeviceCredentials{
39       std::move(certs), std::move(private_key), std::string()};
40 
41   const std::vector<std::string> tls_cert =
42       ReadCertificatesFromPemFile(tls_filename);
43   ASSERT_EQ(tls_cert.size(), 1u);
44   data = reinterpret_cast<const uint8_t*>(tls_cert[0].data());
45   if (parsed_cert) {
46     *parsed_cert =
47         bssl::UniquePtr<X509>(d2i_X509(nullptr, &data, tls_cert[0].size()));
48     ASSERT_TRUE(*parsed_cert);
49   }
50   const auto* begin = reinterpret_cast<const uint8_t*>(tls_cert[0].data());
51   creds->tls_cert_der.assign(begin, begin + tls_cert[0].size());
52 }
53 
54 }  // namespace cast
55 }  // namespace openscreen
56