cloudcas_test.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. package cloudcas
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/ecdsa"
  7. "crypto/ed25519"
  8. "crypto/rand"
  9. "crypto/x509"
  10. "encoding/asn1"
  11. "encoding/pem"
  12. "fmt"
  13. "io"
  14. "log"
  15. "net"
  16. "os"
  17. "reflect"
  18. "testing"
  19. "time"
  20. lroauto "cloud.google.com/go/longrunning/autogen"
  21. privateca "cloud.google.com/go/security/privateca/apiv1beta1"
  22. gomock "github.com/golang/mock/gomock"
  23. "github.com/google/uuid"
  24. gax "github.com/googleapis/gax-go/v2"
  25. "github.com/pkg/errors"
  26. "github.com/smallstep/certificates/cas/apiv1"
  27. kmsapi "github.com/smallstep/certificates/kms/apiv1"
  28. "google.golang.org/api/option"
  29. pb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1"
  30. longrunningpb "google.golang.org/genproto/googleapis/longrunning"
  31. "google.golang.org/grpc"
  32. "google.golang.org/grpc/test/bufconn"
  33. "google.golang.org/protobuf/types/known/anypb"
  34. )
  35. var (
  36. errTest = errors.New("test error")
  37. testAuthorityName = "projects/test-project/locations/us-west1/certificateAuthorities/test-ca"
  38. testCertificateName = "projects/test-project/locations/us-west1/certificateAuthorities/test-ca/certificates/test-certificate"
  39. testProject = "test-project"
  40. testLocation = "us-west1"
  41. testRootCertificate = `-----BEGIN CERTIFICATE-----
  42. MIIBeDCCAR+gAwIBAgIQcXWWjtSZ/PAyH8D1Ou4L9jAKBggqhkjOPQQDAjAbMRkw
  43. FwYDVQQDExBDbG91ZENBUyBSb290IENBMB4XDTIwMTAyNzIyNTM1NFoXDTMwMTAy
  44. NzIyNTM1NFowGzEZMBcGA1UEAxMQQ2xvdWRDQVMgUm9vdCBDQTBZMBMGByqGSM49
  45. AgEGCCqGSM49AwEHA0IABIySHA4b78Yu4LuGhZIlv/PhNwXz4ZoV1OUZQ0LrK3vj
  46. B13O12DLZC5uj1z3kxdQzXUttSbtRv49clMpBiTpsZKjRTBDMA4GA1UdDwEB/wQE
  47. AwIBBjASBgNVHRMBAf8ECDAGAQH/AgEBMB0GA1UdDgQWBBSZ+t9RMHbFTl5BatM3
  48. 5bJlHPOu3DAKBggqhkjOPQQDAgNHADBEAiASah6gg0tVM3WI0meCQ4SEKk7Mjhbv
  49. +SmhuZHWV1QlXQIgRXNyWcpVUrAoG6Uy1KQg07LDpF5dFeK9InrDxSJAkVo=
  50. -----END CERTIFICATE-----`
  51. testIntermediateCertificate = `-----BEGIN CERTIFICATE-----
  52. MIIBpDCCAUmgAwIBAgIRALLKxnxyl0GBeKevIcbx02wwCgYIKoZIzj0EAwIwGzEZ
  53. MBcGA1UEAxMQQ2xvdWRDQVMgUm9vdCBDQTAeFw0yMDEwMjcyMjUzNTRaFw0zMDEw
  54. MjcyMjUzNTRaMCMxITAfBgNVBAMTGENsb3VkQ0FTIEludGVybWVkaWF0ZSBDQTBZ
  55. MBMGByqGSM49AgEGCCqGSM49AwEHA0IABPLuqxgBY+QmaXc8zKIC8FMgjJ6dF/cL
  56. b+Dig0XKc5GH/T1ORrhgOkRayrQcjPMu+jkjg25qn6vvp43LRtUKPXOjZjBkMA4G
  57. A1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBQ8RVQI
  58. VgXAmRNDX8qItalVpSBEGjAfBgNVHSMEGDAWgBSZ+t9RMHbFTl5BatM35bJlHPOu
  59. 3DAKBggqhkjOPQQDAgNJADBGAiEA70MVYVqjm8SBHJf5cOlWfiXXOfHUsctTJ+/F
  60. pLsKBogCIQDJJkoQqYl9B59Dq3zydl8bpJevQxsoaa4Wqg+ZBMkvbQ==
  61. -----END CERTIFICATE-----`
  62. testLeafCertificate = `-----BEGIN CERTIFICATE-----
  63. MIIB1jCCAX2gAwIBAgIQQfOn+COMeuD8VYF1TiDkEzAKBggqhkjOPQQDAjAqMSgw
  64. JgYDVQQDEx9Hb29nbGUgQ0FTIFRlc3QgSW50ZXJtZWRpYXRlIENBMB4XDTIwMDkx
  65. NDIyNTE1NVoXDTMwMDkxMjIyNTE1MlowHTEbMBkGA1UEAxMSdGVzdC5zbWFsbHN0
  66. ZXAuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAdUSRBrpgHFilN4eaGlN
  67. nX2+xfjXa1Iwk2/+AensjFTXJi1UAIB0e+4pqi7Sen5E2QVBhntEHCrA3xOf7czg
  68. P6OBkTCBjjAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsG
  69. AQUFBwMCMB0GA1UdDgQWBBSYPbu4Tmm7Zze/hCePeZH1Avoj+jAfBgNVHSMEGDAW
  70. gBRIOVqyLDSlErJLuWWEvRm5UU1r1TAdBgNVHREEFjAUghJ0ZXN0LnNtYWxsc3Rl
  71. cC5jb20wCgYIKoZIzj0EAwIDRwAwRAIgY+nTc+RHn31/BOhht4JpxCmJPHxqFT3S
  72. ojnictBudV0CIB87ipY5HV3c8FLVEzTA0wFwdDZvQraQYsthwbg2kQFb
  73. -----END CERTIFICATE-----`
  74. testSignedCertificate = `-----BEGIN CERTIFICATE-----
  75. MIIB/DCCAaKgAwIBAgIQHHFuGMz0cClfde5kqP5prTAKBggqhkjOPQQDAjAqMSgw
  76. JgYDVQQDEx9Hb29nbGUgQ0FTIFRlc3QgSW50ZXJtZWRpYXRlIENBMB4XDTIwMDkx
  77. NTAwMDQ0M1oXDTMwMDkxMzAwMDQ0MFowHTEbMBkGA1UEAxMSdGVzdC5zbWFsbHN0
  78. ZXAuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMqNCiXMvbn74LsHzRv+8
  79. 17m9vEzH6RHrg3m82e0uEc36+fZWV/zJ9SKuONmnl5VP79LsjL5SVH0RDj73U2XO
  80. DKOBtjCBszAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsG
  81. AQUFBwMCMB0GA1UdDgQWBBRTA2cTs7PCNjnps/+T0dS8diqv0DAfBgNVHSMEGDAW
  82. gBRIOVqyLDSlErJLuWWEvRm5UU1r1TBCBgwrBgEEAYKkZMYoQAIEMjAwEwhjbG91
  83. ZGNhcxMkZDhkMThhNjgtNTI5Ni00YWYzLWFlNGItMmY4NzdkYTNmYmQ5MAoGCCqG
  84. SM49BAMCA0gAMEUCIGxl+pqJ50WYWUqK2l4V1FHoXSi0Nht5kwTxFxnWZu1xAiEA
  85. zemu3bhWLFaGg3s8i+HTEhw4RqkHP74vF7AVYp88bAw=
  86. -----END CERTIFICATE-----`
  87. testIntermediateCsr = `-----BEGIN CERTIFICATE REQUEST-----
  88. MIHeMIGFAgEAMCMxITAfBgNVBAMTGENsb3VkQ0FTIEludGVybWVkaWF0ZSBDQTBZ
  89. MBMGByqGSM49AgEGCCqGSM49AwEHA0IABPLuqxgBY+QmaXc8zKIC8FMgjJ6dF/cL
  90. b+Dig0XKc5GH/T1ORrhgOkRayrQcjPMu+jkjg25qn6vvp43LRtUKPXOgADAKBggq
  91. hkjOPQQDAgNIADBFAiEAn3pkYXb2OzoQZ+AExFqd7qZ7pg2nyP2kBZZ01Pl8KfcC
  92. IHKplBXDR79/i7kjOtv1iWfgf5S/XQHrz178gXA0YQe7
  93. -----END CERTIFICATE REQUEST-----`
  94. testRootKey = `-----BEGIN EC PRIVATE KEY-----
  95. MHcCAQEEIN51Rgg6YcQVLeCRzumdw4pjM3VWqFIdCbnsV3Up1e/goAoGCCqGSM49
  96. AwEHoUQDQgAEjJIcDhvvxi7gu4aFkiW/8+E3BfPhmhXU5RlDQusre+MHXc7XYMtk
  97. Lm6PXPeTF1DNdS21Ju1G/j1yUykGJOmxkg==
  98. -----END EC PRIVATE KEY-----`
  99. // nolint:unused,deadcode
  100. testIntermediateKey = `-----BEGIN EC PRIVATE KEY-----
  101. MHcCAQEEIMMX/XkXGnRDD4fYu7Z4rHACdJn/iyOy2UTwsv+oZ0C+oAoGCCqGSM49
  102. AwEHoUQDQgAE8u6rGAFj5CZpdzzMogLwUyCMnp0X9wtv4OKDRcpzkYf9PU5GuGA6
  103. RFrKtByM8y76OSODbmqfq++njctG1Qo9cw==
  104. -----END EC PRIVATE KEY-----`
  105. )
  106. type testClient struct {
  107. credentialsFile string
  108. certificate *pb.Certificate
  109. certificateAuthority *pb.CertificateAuthority
  110. err error
  111. }
  112. func newTestClient(credentialsFile string) (CertificateAuthorityClient, error) {
  113. if credentialsFile == "testdata/error.json" {
  114. return nil, errTest
  115. }
  116. return &testClient{
  117. credentialsFile: credentialsFile,
  118. }, nil
  119. }
  120. func okTestClient() *testClient {
  121. return &testClient{
  122. credentialsFile: "testdata/credentials.json",
  123. certificate: &pb.Certificate{
  124. Name: testCertificateName,
  125. PemCertificate: testSignedCertificate,
  126. PemCertificateChain: []string{testIntermediateCertificate, testRootCertificate},
  127. },
  128. certificateAuthority: &pb.CertificateAuthority{
  129. PemCaCertificates: []string{testIntermediateCertificate, testRootCertificate},
  130. },
  131. }
  132. }
  133. func failTestClient() *testClient {
  134. return &testClient{
  135. credentialsFile: "testdata/credentials.json",
  136. err: errTest,
  137. }
  138. }
  139. func badTestClient() *testClient {
  140. return &testClient{
  141. credentialsFile: "testdata/credentials.json",
  142. certificate: &pb.Certificate{
  143. Name: testCertificateName,
  144. PemCertificate: "not a pem cert",
  145. PemCertificateChain: []string{testIntermediateCertificate, testRootCertificate},
  146. },
  147. certificateAuthority: &pb.CertificateAuthority{
  148. PemCaCertificates: []string{testIntermediateCertificate, "not a pem cert"},
  149. },
  150. }
  151. }
  152. func setTeeReader(t *testing.T, w *bytes.Buffer) {
  153. t.Helper()
  154. reader := rand.Reader
  155. t.Cleanup(func() {
  156. rand.Reader = reader
  157. })
  158. rand.Reader = io.TeeReader(reader, w)
  159. }
  160. type badSigner struct {
  161. pub crypto.PublicKey
  162. }
  163. func createBadSigner(t *testing.T) *badSigner {
  164. t.Helper()
  165. pub, _, err := ed25519.GenerateKey(rand.Reader)
  166. if err != nil {
  167. t.Fatal(err)
  168. }
  169. return &badSigner{
  170. pub: pub,
  171. }
  172. }
  173. func (b *badSigner) Public() crypto.PublicKey {
  174. return b.pub
  175. }
  176. func (b *badSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
  177. return nil, fmt.Errorf("💥")
  178. }
  179. func (c *testClient) CreateCertificate(ctx context.Context, req *pb.CreateCertificateRequest, opts ...gax.CallOption) (*pb.Certificate, error) {
  180. return c.certificate, c.err
  181. }
  182. func (c *testClient) RevokeCertificate(ctx context.Context, req *pb.RevokeCertificateRequest, opts ...gax.CallOption) (*pb.Certificate, error) {
  183. return c.certificate, c.err
  184. }
  185. func (c *testClient) GetCertificateAuthority(ctx context.Context, req *pb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*pb.CertificateAuthority, error) {
  186. return c.certificateAuthority, c.err
  187. }
  188. func (c *testClient) CreateCertificateAuthority(ctx context.Context, req *pb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*privateca.CreateCertificateAuthorityOperation, error) {
  189. return nil, errors.New("use NewMockCertificateAuthorityClient")
  190. }
  191. func (c *testClient) FetchCertificateAuthorityCsr(ctx context.Context, req *pb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*pb.FetchCertificateAuthorityCsrResponse, error) {
  192. return nil, errors.New("use NewMockCertificateAuthorityClient")
  193. }
  194. func (c *testClient) ActivateCertificateAuthority(ctx context.Context, req *pb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*privateca.ActivateCertificateAuthorityOperation, error) {
  195. return nil, errors.New("use NewMockCertificateAuthorityClient")
  196. }
  197. func mustParseCertificate(t *testing.T, pemCert string) *x509.Certificate {
  198. t.Helper()
  199. crt, err := parseCertificate(pemCert)
  200. if err != nil {
  201. t.Fatal(err)
  202. }
  203. return crt
  204. }
  205. func mustParseECKey(t *testing.T, pemKey string) *ecdsa.PrivateKey {
  206. t.Helper()
  207. block, _ := pem.Decode([]byte(pemKey))
  208. if block == nil {
  209. t.Fatal("failed to parse key")
  210. }
  211. key, err := x509.ParseECPrivateKey(block.Bytes)
  212. if err != nil {
  213. t.Fatal(err)
  214. }
  215. return key
  216. }
  217. func TestNew(t *testing.T) {
  218. tmp := newCertificateAuthorityClient
  219. newCertificateAuthorityClient = func(ctx context.Context, credentialsFile string) (CertificateAuthorityClient, error) {
  220. return newTestClient(credentialsFile)
  221. }
  222. t.Cleanup(func() {
  223. newCertificateAuthorityClient = tmp
  224. })
  225. type args struct {
  226. ctx context.Context
  227. opts apiv1.Options
  228. }
  229. tests := []struct {
  230. name string
  231. args args
  232. want *CloudCAS
  233. wantErr bool
  234. }{
  235. {"ok", args{context.Background(), apiv1.Options{
  236. CertificateAuthority: testAuthorityName,
  237. }}, &CloudCAS{
  238. client: &testClient{},
  239. certificateAuthority: testAuthorityName,
  240. project: testProject,
  241. location: testLocation,
  242. }, false},
  243. {"ok with credentials", args{context.Background(), apiv1.Options{
  244. CertificateAuthority: testAuthorityName, CredentialsFile: "testdata/credentials.json",
  245. }}, &CloudCAS{
  246. client: &testClient{credentialsFile: "testdata/credentials.json"},
  247. certificateAuthority: testAuthorityName,
  248. project: testProject,
  249. location: testLocation,
  250. }, false},
  251. {"ok creator", args{context.Background(), apiv1.Options{
  252. IsCreator: true, Project: testProject, Location: testLocation,
  253. }}, &CloudCAS{
  254. client: &testClient{},
  255. project: testProject,
  256. location: testLocation,
  257. }, false},
  258. {"fail certificate authority", args{context.Background(), apiv1.Options{
  259. CertificateAuthority: "projects/ok1234/locations/ok1234/certificateAuthorities/ok1234/bad",
  260. }}, nil, true},
  261. {"fail certificate authority regex", args{context.Background(), apiv1.Options{}}, nil, true},
  262. {"fail with credentials", args{context.Background(), apiv1.Options{
  263. CertificateAuthority: testAuthorityName, CredentialsFile: "testdata/error.json",
  264. }}, nil, true},
  265. {"fail creator project", args{context.Background(), apiv1.Options{
  266. IsCreator: true, Project: "", Location: testLocation,
  267. }}, nil, true},
  268. {"fail creator location", args{context.Background(), apiv1.Options{
  269. IsCreator: true, Project: testProject, Location: "",
  270. }}, nil, true},
  271. }
  272. for _, tt := range tests {
  273. t.Run(tt.name, func(t *testing.T) {
  274. got, err := New(tt.args.ctx, tt.args.opts)
  275. if (err != nil) != tt.wantErr {
  276. t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr)
  277. return
  278. }
  279. if !reflect.DeepEqual(got, tt.want) {
  280. t.Errorf("New() = %v, want %v", got, tt.want)
  281. }
  282. })
  283. }
  284. }
  285. func TestNew_register(t *testing.T) {
  286. tmp := newCertificateAuthorityClient
  287. newCertificateAuthorityClient = func(ctx context.Context, credentialsFile string) (CertificateAuthorityClient, error) {
  288. return newTestClient(credentialsFile)
  289. }
  290. t.Cleanup(func() {
  291. newCertificateAuthorityClient = tmp
  292. })
  293. want := &CloudCAS{
  294. client: &testClient{credentialsFile: "testdata/credentials.json"},
  295. certificateAuthority: testAuthorityName,
  296. project: testProject,
  297. location: testLocation,
  298. }
  299. newFn, ok := apiv1.LoadCertificateAuthorityServiceNewFunc(apiv1.CloudCAS)
  300. if !ok {
  301. t.Error("apiv1.LoadCertificateAuthorityServiceNewFunc(apiv1.CloudCAS) was not found")
  302. return
  303. }
  304. got, err := newFn(context.Background(), apiv1.Options{
  305. CertificateAuthority: testAuthorityName, CredentialsFile: "testdata/credentials.json",
  306. })
  307. if err != nil {
  308. t.Errorf("New() error = %v", err)
  309. return
  310. }
  311. if !reflect.DeepEqual(got, want) {
  312. t.Errorf("New() = %v, want %v", got, want)
  313. }
  314. }
  315. func TestNew_real(t *testing.T) {
  316. if v, ok := os.LookupEnv("GOOGLE_APPLICATION_CREDENTIALS"); ok {
  317. os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS")
  318. t.Cleanup(func() {
  319. os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", v)
  320. })
  321. }
  322. type args struct {
  323. ctx context.Context
  324. opts apiv1.Options
  325. }
  326. tests := []struct {
  327. name string
  328. skipOnCI bool
  329. args args
  330. wantErr bool
  331. }{
  332. {"fail default credentials", true, args{context.Background(), apiv1.Options{CertificateAuthority: testAuthorityName}}, true},
  333. {"fail certificate authority", false, args{context.Background(), apiv1.Options{}}, true},
  334. {"fail with credentials", false, args{context.Background(), apiv1.Options{
  335. CertificateAuthority: testAuthorityName, CredentialsFile: "testdata/missing.json",
  336. }}, true},
  337. }
  338. for _, tt := range tests {
  339. t.Run(tt.name, func(t *testing.T) {
  340. if tt.skipOnCI && os.Getenv("CI") == "true" {
  341. t.SkipNow()
  342. }
  343. _, err := New(tt.args.ctx, tt.args.opts)
  344. if (err != nil) != tt.wantErr {
  345. t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr)
  346. }
  347. })
  348. }
  349. }
  350. func TestCloudCAS_GetCertificateAuthority(t *testing.T) {
  351. root := mustParseCertificate(t, testRootCertificate)
  352. type fields struct {
  353. client CertificateAuthorityClient
  354. certificateAuthority string
  355. }
  356. type args struct {
  357. req *apiv1.GetCertificateAuthorityRequest
  358. }
  359. tests := []struct {
  360. name string
  361. fields fields
  362. args args
  363. want *apiv1.GetCertificateAuthorityResponse
  364. wantErr bool
  365. }{
  366. {"ok", fields{okTestClient(), testCertificateName}, args{&apiv1.GetCertificateAuthorityRequest{}}, &apiv1.GetCertificateAuthorityResponse{
  367. RootCertificate: root,
  368. }, false},
  369. {"ok with name", fields{okTestClient(), testCertificateName}, args{&apiv1.GetCertificateAuthorityRequest{
  370. Name: testCertificateName,
  371. }}, &apiv1.GetCertificateAuthorityResponse{
  372. RootCertificate: root,
  373. }, false},
  374. {"fail GetCertificateAuthority", fields{failTestClient(), testCertificateName}, args{&apiv1.GetCertificateAuthorityRequest{}}, nil, true},
  375. {"fail bad root", fields{badTestClient(), testCertificateName}, args{&apiv1.GetCertificateAuthorityRequest{}}, nil, true},
  376. {"fail no pems", fields{&testClient{certificateAuthority: &pb.CertificateAuthority{}}, testCertificateName}, args{&apiv1.GetCertificateAuthorityRequest{}}, nil, true},
  377. }
  378. for _, tt := range tests {
  379. t.Run(tt.name, func(t *testing.T) {
  380. c := &CloudCAS{
  381. client: tt.fields.client,
  382. certificateAuthority: tt.fields.certificateAuthority,
  383. }
  384. got, err := c.GetCertificateAuthority(tt.args.req)
  385. if (err != nil) != tt.wantErr {
  386. t.Errorf("CloudCAS.GetCertificateAuthority() error = %v, wantErr %v", err, tt.wantErr)
  387. return
  388. }
  389. if !reflect.DeepEqual(got, tt.want) {
  390. t.Errorf("CloudCAS.GetCertificateAuthority() = %v, want %v", got, tt.want)
  391. }
  392. })
  393. }
  394. }
  395. func TestCloudCAS_CreateCertificate(t *testing.T) {
  396. type fields struct {
  397. client CertificateAuthorityClient
  398. certificateAuthority string
  399. }
  400. type args struct {
  401. req *apiv1.CreateCertificateRequest
  402. }
  403. tests := []struct {
  404. name string
  405. fields fields
  406. args args
  407. want *apiv1.CreateCertificateResponse
  408. wantErr bool
  409. }{
  410. {"ok", fields{okTestClient(), testCertificateName}, args{&apiv1.CreateCertificateRequest{
  411. Template: mustParseCertificate(t, testLeafCertificate),
  412. Lifetime: 24 * time.Hour,
  413. }}, &apiv1.CreateCertificateResponse{
  414. Certificate: mustParseCertificate(t, testSignedCertificate),
  415. CertificateChain: []*x509.Certificate{mustParseCertificate(t, testIntermediateCertificate)},
  416. }, false},
  417. {"fail Template", fields{okTestClient(), testCertificateName}, args{&apiv1.CreateCertificateRequest{
  418. Lifetime: 24 * time.Hour,
  419. }}, nil, true},
  420. {"fail Lifetime", fields{okTestClient(), testCertificateName}, args{&apiv1.CreateCertificateRequest{
  421. Template: mustParseCertificate(t, testLeafCertificate),
  422. }}, nil, true},
  423. {"fail CreateCertificate", fields{failTestClient(), testCertificateName}, args{&apiv1.CreateCertificateRequest{
  424. Template: mustParseCertificate(t, testLeafCertificate),
  425. Lifetime: 24 * time.Hour,
  426. }}, nil, true},
  427. {"fail Certificate", fields{badTestClient(), testCertificateName}, args{&apiv1.CreateCertificateRequest{
  428. Template: mustParseCertificate(t, testLeafCertificate),
  429. Lifetime: 24 * time.Hour,
  430. }}, nil, true},
  431. }
  432. for _, tt := range tests {
  433. t.Run(tt.name, func(t *testing.T) {
  434. c := &CloudCAS{
  435. client: tt.fields.client,
  436. certificateAuthority: tt.fields.certificateAuthority,
  437. }
  438. got, err := c.CreateCertificate(tt.args.req)
  439. if (err != nil) != tt.wantErr {
  440. t.Errorf("CloudCAS.CreateCertificate() error = %v, wantErr %v", err, tt.wantErr)
  441. return
  442. }
  443. if !reflect.DeepEqual(got, tt.want) {
  444. t.Errorf("CloudCAS.CreateCertificate() = %v, want %v", got, tt.want)
  445. }
  446. })
  447. }
  448. }
  449. func TestCloudCAS_createCertificate(t *testing.T) {
  450. leaf := mustParseCertificate(t, testLeafCertificate)
  451. signed := mustParseCertificate(t, testSignedCertificate)
  452. chain := []*x509.Certificate{mustParseCertificate(t, testIntermediateCertificate)}
  453. type fields struct {
  454. client CertificateAuthorityClient
  455. certificateAuthority string
  456. }
  457. type args struct {
  458. tpl *x509.Certificate
  459. lifetime time.Duration
  460. requestID string
  461. }
  462. tests := []struct {
  463. name string
  464. fields fields
  465. args args
  466. want *x509.Certificate
  467. want1 []*x509.Certificate
  468. wantErr bool
  469. }{
  470. {"ok", fields{okTestClient(), testAuthorityName}, args{leaf, 24 * time.Hour, "request-id"}, signed, chain, false},
  471. {"fail CertificateConfig", fields{okTestClient(), testAuthorityName}, args{&x509.Certificate{}, 24 * time.Hour, "request-id"}, nil, nil, true},
  472. {"fail CreateCertificate", fields{failTestClient(), testAuthorityName}, args{leaf, 24 * time.Hour, "request-id"}, nil, nil, true},
  473. {"fail ParseCertificates", fields{badTestClient(), testAuthorityName}, args{leaf, 24 * time.Hour, "request-id"}, nil, nil, true},
  474. {"fail create id", fields{okTestClient(), testAuthorityName}, args{leaf, 24 * time.Hour, "request-id"}, nil, nil, true},
  475. }
  476. // Pre-calculate rand.Random
  477. buf := new(bytes.Buffer)
  478. setTeeReader(t, buf)
  479. for i := 0; i < len(tests)-1; i++ {
  480. _, err := uuid.NewRandomFromReader(rand.Reader)
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. }
  485. rand.Reader = buf
  486. for _, tt := range tests {
  487. t.Run(tt.name, func(t *testing.T) {
  488. c := &CloudCAS{
  489. client: tt.fields.client,
  490. certificateAuthority: tt.fields.certificateAuthority,
  491. }
  492. got, got1, err := c.createCertificate(tt.args.tpl, tt.args.lifetime, tt.args.requestID)
  493. if (err != nil) != tt.wantErr {
  494. t.Errorf("CloudCAS.createCertificate() error = %v, wantErr %v", err, tt.wantErr)
  495. return
  496. }
  497. if !reflect.DeepEqual(got, tt.want) {
  498. t.Errorf("CloudCAS.createCertificate() got = %v, want %v", got, tt.want)
  499. }
  500. if !reflect.DeepEqual(got1, tt.want1) {
  501. t.Errorf("CloudCAS.createCertificate() got1 = %v, want %v", got1, tt.want1)
  502. }
  503. })
  504. }
  505. }
  506. func TestCloudCAS_RenewCertificate(t *testing.T) {
  507. type fields struct {
  508. client CertificateAuthorityClient
  509. certificateAuthority string
  510. }
  511. type args struct {
  512. req *apiv1.RenewCertificateRequest
  513. }
  514. tests := []struct {
  515. name string
  516. fields fields
  517. args args
  518. want *apiv1.RenewCertificateResponse
  519. wantErr bool
  520. }{
  521. {"ok", fields{okTestClient(), testCertificateName}, args{&apiv1.RenewCertificateRequest{
  522. Template: mustParseCertificate(t, testLeafCertificate),
  523. Lifetime: 24 * time.Hour,
  524. }}, &apiv1.RenewCertificateResponse{
  525. Certificate: mustParseCertificate(t, testSignedCertificate),
  526. CertificateChain: []*x509.Certificate{mustParseCertificate(t, testIntermediateCertificate)},
  527. }, false},
  528. {"fail Template", fields{okTestClient(), testCertificateName}, args{&apiv1.RenewCertificateRequest{
  529. Lifetime: 24 * time.Hour,
  530. }}, nil, true},
  531. {"fail Lifetime", fields{okTestClient(), testCertificateName}, args{&apiv1.RenewCertificateRequest{
  532. Template: mustParseCertificate(t, testLeafCertificate),
  533. }}, nil, true},
  534. {"fail CreateCertificate", fields{failTestClient(), testCertificateName}, args{&apiv1.RenewCertificateRequest{
  535. Template: mustParseCertificate(t, testLeafCertificate),
  536. Lifetime: 24 * time.Hour,
  537. }}, nil, true},
  538. {"fail Certificate", fields{badTestClient(), testCertificateName}, args{&apiv1.RenewCertificateRequest{
  539. Template: mustParseCertificate(t, testLeafCertificate),
  540. Lifetime: 24 * time.Hour,
  541. }}, nil, true},
  542. }
  543. for _, tt := range tests {
  544. t.Run(tt.name, func(t *testing.T) {
  545. c := &CloudCAS{
  546. client: tt.fields.client,
  547. certificateAuthority: tt.fields.certificateAuthority,
  548. }
  549. got, err := c.RenewCertificate(tt.args.req)
  550. if (err != nil) != tt.wantErr {
  551. t.Errorf("CloudCAS.RenewCertificate() error = %v, wantErr %v", err, tt.wantErr)
  552. return
  553. }
  554. if !reflect.DeepEqual(got, tt.want) {
  555. t.Errorf("CloudCAS.RenewCertificate() = %v, want %v", got, tt.want)
  556. }
  557. })
  558. }
  559. }
  560. func TestCloudCAS_RevokeCertificate(t *testing.T) {
  561. badExtensionCert := mustParseCertificate(t, testSignedCertificate)
  562. for i, ext := range badExtensionCert.Extensions {
  563. if ext.Id.Equal(asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 2}) {
  564. badExtensionCert.Extensions[i].Value = []byte("bad-data")
  565. }
  566. }
  567. type fields struct {
  568. client CertificateAuthorityClient
  569. certificateAuthority string
  570. }
  571. type args struct {
  572. req *apiv1.RevokeCertificateRequest
  573. }
  574. tests := []struct {
  575. name string
  576. fields fields
  577. args args
  578. want *apiv1.RevokeCertificateResponse
  579. wantErr bool
  580. }{
  581. {"ok", fields{okTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  582. Certificate: mustParseCertificate(t, testSignedCertificate),
  583. ReasonCode: 1,
  584. }}, &apiv1.RevokeCertificateResponse{
  585. Certificate: mustParseCertificate(t, testSignedCertificate),
  586. CertificateChain: []*x509.Certificate{mustParseCertificate(t, testIntermediateCertificate)},
  587. }, false},
  588. {"fail Extension", fields{okTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  589. Certificate: mustParseCertificate(t, testLeafCertificate),
  590. ReasonCode: 1,
  591. }}, nil, true},
  592. {"fail Extension Value", fields{okTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  593. Certificate: badExtensionCert,
  594. ReasonCode: 1,
  595. }}, nil, true},
  596. {"fail Certificate", fields{okTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  597. ReasonCode: 2,
  598. }}, nil, true},
  599. {"fail ReasonCode", fields{okTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  600. Certificate: mustParseCertificate(t, testSignedCertificate),
  601. ReasonCode: 100,
  602. }}, nil, true},
  603. {"fail ReasonCode 7", fields{okTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  604. Certificate: mustParseCertificate(t, testSignedCertificate),
  605. ReasonCode: 7,
  606. }}, nil, true},
  607. {"fail ReasonCode 8", fields{okTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  608. Certificate: mustParseCertificate(t, testSignedCertificate),
  609. ReasonCode: 8,
  610. }}, nil, true},
  611. {"fail RevokeCertificate", fields{failTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  612. Certificate: mustParseCertificate(t, testSignedCertificate),
  613. ReasonCode: 1,
  614. }}, nil, true},
  615. {"fail ParseCertificate", fields{badTestClient(), testCertificateName}, args{&apiv1.RevokeCertificateRequest{
  616. Certificate: mustParseCertificate(t, testSignedCertificate),
  617. ReasonCode: 1,
  618. }}, nil, true},
  619. }
  620. for _, tt := range tests {
  621. t.Run(tt.name, func(t *testing.T) {
  622. c := &CloudCAS{
  623. client: tt.fields.client,
  624. certificateAuthority: tt.fields.certificateAuthority,
  625. }
  626. got, err := c.RevokeCertificate(tt.args.req)
  627. if (err != nil) != tt.wantErr {
  628. t.Errorf("CloudCAS.RevokeCertificate() error = %v, wantErr %v", err, tt.wantErr)
  629. return
  630. }
  631. if !reflect.DeepEqual(got, tt.want) {
  632. t.Errorf("CloudCAS.RevokeCertificate() = %v, want %v", got, tt.want)
  633. }
  634. })
  635. }
  636. }
  637. func Test_createCertificateID(t *testing.T) {
  638. buf := new(bytes.Buffer)
  639. setTeeReader(t, buf)
  640. uuid, err := uuid.NewRandomFromReader(rand.Reader)
  641. if err != nil {
  642. t.Fatal(err)
  643. }
  644. rand.Reader = buf
  645. tests := []struct {
  646. name string
  647. want string
  648. wantErr bool
  649. }{
  650. {"ok", uuid.String(), false},
  651. {"fail", "", true},
  652. }
  653. for _, tt := range tests {
  654. t.Run(tt.name, func(t *testing.T) {
  655. got, err := createCertificateID()
  656. if (err != nil) != tt.wantErr {
  657. t.Errorf("createCertificateID() error = %v, wantErr %v", err, tt.wantErr)
  658. return
  659. }
  660. if got != tt.want {
  661. t.Errorf("createCertificateID() = %v, want %v", got, tt.want)
  662. }
  663. })
  664. }
  665. }
  666. func Test_parseCertificate(t *testing.T) {
  667. type args struct {
  668. pemCert string
  669. }
  670. tests := []struct {
  671. name string
  672. args args
  673. want *x509.Certificate
  674. wantErr bool
  675. }{
  676. {"ok", args{testLeafCertificate}, mustParseCertificate(t, testLeafCertificate), false},
  677. {"ok intermediate", args{testIntermediateCertificate}, mustParseCertificate(t, testIntermediateCertificate), false},
  678. {"fail pem", args{"not pem"}, nil, true},
  679. {"fail parseCertificate", args{"-----BEGIN CERTIFICATE-----\nZm9vYmFyCg==\n-----END CERTIFICATE-----\n"}, nil, true},
  680. }
  681. for _, tt := range tests {
  682. t.Run(tt.name, func(t *testing.T) {
  683. got, err := parseCertificate(tt.args.pemCert)
  684. if (err != nil) != tt.wantErr {
  685. t.Errorf("parseCertificate() error = %v, wantErr %v", err, tt.wantErr)
  686. return
  687. }
  688. if !reflect.DeepEqual(got, tt.want) {
  689. t.Errorf("parseCertificate() = %v, want %v", got, tt.want)
  690. }
  691. })
  692. }
  693. }
  694. func Test_getCertificateAndChain(t *testing.T) {
  695. type args struct {
  696. certpb *pb.Certificate
  697. }
  698. tests := []struct {
  699. name string
  700. args args
  701. want *x509.Certificate
  702. want1 []*x509.Certificate
  703. wantErr bool
  704. }{
  705. {"ok", args{&pb.Certificate{
  706. Name: testCertificateName,
  707. PemCertificate: testSignedCertificate,
  708. PemCertificateChain: []string{testIntermediateCertificate, testRootCertificate},
  709. }}, mustParseCertificate(t, testSignedCertificate), []*x509.Certificate{mustParseCertificate(t, testIntermediateCertificate)}, false},
  710. {"fail PemCertificate", args{&pb.Certificate{
  711. Name: testCertificateName,
  712. PemCertificate: "foobar",
  713. PemCertificateChain: []string{testIntermediateCertificate, testRootCertificate},
  714. }}, nil, nil, true},
  715. {"fail PemCertificateChain", args{&pb.Certificate{
  716. Name: testCertificateName,
  717. PemCertificate: testSignedCertificate,
  718. PemCertificateChain: []string{"foobar", testRootCertificate},
  719. }}, nil, nil, true},
  720. }
  721. for _, tt := range tests {
  722. t.Run(tt.name, func(t *testing.T) {
  723. got, got1, err := getCertificateAndChain(tt.args.certpb)
  724. if (err != nil) != tt.wantErr {
  725. t.Errorf("getCertificateAndChain() error = %v, wantErr %v", err, tt.wantErr)
  726. return
  727. }
  728. if !reflect.DeepEqual(got, tt.want) {
  729. t.Errorf("getCertificateAndChain() got = %v, want %v", got, tt.want)
  730. }
  731. if !reflect.DeepEqual(got1, tt.want1) {
  732. t.Errorf("getCertificateAndChain() got1 = %v, want %v", got1, tt.want1)
  733. }
  734. })
  735. }
  736. }
  737. func TestCloudCAS_CreateCertificateAuthority(t *testing.T) {
  738. must := func(a, b interface{}) interface{} {
  739. return a
  740. }
  741. ctrl := gomock.NewController(t)
  742. defer ctrl.Finish()
  743. mosCtrl := gomock.NewController(t)
  744. defer mosCtrl.Finish()
  745. m := NewMockCertificateAuthorityClient(ctrl)
  746. mos := NewMockOperationsServer(mosCtrl)
  747. // Create operation server
  748. srv := grpc.NewServer()
  749. longrunningpb.RegisterOperationsServer(srv, mos)
  750. lis := bufconn.Listen(2)
  751. go srv.Serve(lis)
  752. defer srv.Stop()
  753. // Create fake privateca client
  754. conn, err := grpc.DialContext(context.Background(), "", grpc.WithInsecure(),
  755. grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {
  756. return lis.Dial()
  757. }))
  758. if err != nil {
  759. log.Fatal(err)
  760. }
  761. client, err := lroauto.NewOperationsClient(context.Background(), option.WithGRPCConn(conn))
  762. if err != nil {
  763. t.Fatal(err)
  764. }
  765. fake := &privateca.CertificateAuthorityClient{
  766. LROClient: client,
  767. }
  768. // Configure mocks
  769. any := gomock.Any()
  770. // ok root
  771. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  772. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  773. Name: "CreateCertificateAuthority",
  774. Done: true,
  775. Result: &longrunningpb.Operation_Response{
  776. Response: must(anypb.New(&pb.CertificateAuthority{
  777. Name: testAuthorityName,
  778. PemCaCertificates: []string{testRootCertificate},
  779. })).(*anypb.Any),
  780. },
  781. }, nil)
  782. // ok intermediate
  783. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  784. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  785. Name: "CreateCertificateAuthority",
  786. Done: true,
  787. Result: &longrunningpb.Operation_Response{
  788. Response: must(anypb.New(&pb.CertificateAuthority{
  789. Name: testAuthorityName,
  790. })).(*anypb.Any),
  791. },
  792. }, nil)
  793. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{
  794. PemCsr: testIntermediateCsr,
  795. }, nil)
  796. m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil)
  797. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  798. Name: "ActivateCertificateAuthority",
  799. Done: true,
  800. Result: &longrunningpb.Operation_Response{
  801. Response: must(anypb.New(&pb.CertificateAuthority{
  802. Name: testAuthorityName,
  803. PemCaCertificates: []string{testIntermediateCertificate, testRootCertificate},
  804. })).(*anypb.Any),
  805. },
  806. }, nil)
  807. // ok intermediate local signer
  808. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  809. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  810. Name: "CreateCertificateAuthority",
  811. Done: true,
  812. Result: &longrunningpb.Operation_Response{
  813. Response: must(anypb.New(&pb.CertificateAuthority{
  814. Name: testAuthorityName,
  815. })).(*anypb.Any),
  816. },
  817. }, nil)
  818. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{
  819. PemCsr: testIntermediateCsr,
  820. }, nil)
  821. m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{
  822. PemCertificate: testIntermediateCertificate,
  823. PemCertificateChain: []string{testRootCertificate},
  824. }, nil)
  825. m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil)
  826. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  827. Name: "ActivateCertificateAuthority",
  828. Done: true,
  829. Result: &longrunningpb.Operation_Response{
  830. Response: must(anypb.New(&pb.CertificateAuthority{
  831. Name: testAuthorityName,
  832. PemCaCertificates: []string{testIntermediateCertificate, testRootCertificate},
  833. })).(*anypb.Any),
  834. },
  835. }, nil)
  836. // ok create key
  837. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  838. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  839. Name: "CreateCertificateAuthority",
  840. Done: true,
  841. Result: &longrunningpb.Operation_Response{
  842. Response: must(anypb.New(&pb.CertificateAuthority{
  843. Name: testAuthorityName,
  844. PemCaCertificates: []string{testRootCertificate},
  845. })).(*anypb.Any),
  846. },
  847. }, nil)
  848. // fail CreateCertificateAuthority
  849. m.EXPECT().CreateCertificateAuthority(any, any).Return(nil, errTest)
  850. // fail CreateCertificateAuthority.Wait
  851. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  852. mos.EXPECT().GetOperation(any, any).Return(nil, errTest)
  853. // fail FetchCertificateAuthorityCsr
  854. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  855. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  856. Name: "CreateCertificateAuthority",
  857. Done: true,
  858. Result: &longrunningpb.Operation_Response{
  859. Response: must(anypb.New(&pb.CertificateAuthority{
  860. Name: testAuthorityName,
  861. })).(*anypb.Any),
  862. },
  863. }, nil)
  864. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(nil, errTest)
  865. // fail CreateCertificate
  866. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  867. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  868. Name: "CreateCertificateAuthority",
  869. Done: true,
  870. Result: &longrunningpb.Operation_Response{
  871. Response: must(anypb.New(&pb.CertificateAuthority{
  872. Name: testAuthorityName,
  873. })).(*anypb.Any),
  874. },
  875. }, nil)
  876. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{
  877. PemCsr: testIntermediateCsr,
  878. }, nil)
  879. m.EXPECT().CreateCertificate(any, any).Return(nil, errTest)
  880. // fail ActivateCertificateAuthority
  881. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  882. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  883. Name: "CreateCertificateAuthority",
  884. Done: true,
  885. Result: &longrunningpb.Operation_Response{
  886. Response: must(anypb.New(&pb.CertificateAuthority{
  887. Name: testAuthorityName,
  888. })).(*anypb.Any),
  889. },
  890. }, nil)
  891. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{
  892. PemCsr: testIntermediateCsr,
  893. }, nil)
  894. m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{
  895. PemCertificate: testIntermediateCertificate,
  896. PemCertificateChain: []string{testRootCertificate},
  897. }, nil)
  898. m.EXPECT().ActivateCertificateAuthority(any, any).Return(nil, errTest)
  899. // fail ActivateCertificateAuthority.Wait
  900. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  901. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  902. Name: "CreateCertificateAuthority",
  903. Done: true,
  904. Result: &longrunningpb.Operation_Response{
  905. Response: must(anypb.New(&pb.CertificateAuthority{
  906. Name: testAuthorityName,
  907. })).(*anypb.Any),
  908. },
  909. }, nil)
  910. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{
  911. PemCsr: testIntermediateCsr,
  912. }, nil)
  913. m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{
  914. PemCertificate: testIntermediateCertificate,
  915. PemCertificateChain: []string{testRootCertificate},
  916. }, nil)
  917. m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil)
  918. mos.EXPECT().GetOperation(any, any).Return(nil, errTest)
  919. // fail x509util.CreateCertificate
  920. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  921. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  922. Name: "CreateCertificateAuthority",
  923. Done: true,
  924. Result: &longrunningpb.Operation_Response{
  925. Response: must(anypb.New(&pb.CertificateAuthority{
  926. Name: testAuthorityName,
  927. })).(*anypb.Any),
  928. },
  929. }, nil)
  930. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{
  931. PemCsr: testIntermediateCsr,
  932. }, nil)
  933. // fail parseCertificateRequest
  934. m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil)
  935. mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{
  936. Name: "CreateCertificateAuthority",
  937. Done: true,
  938. Result: &longrunningpb.Operation_Response{
  939. Response: must(anypb.New(&pb.CertificateAuthority{
  940. Name: testAuthorityName,
  941. })).(*anypb.Any),
  942. },
  943. }, nil)
  944. m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{
  945. PemCsr: "Not a CSR",
  946. }, nil)
  947. rootCrt := mustParseCertificate(t, testRootCertificate)
  948. intCrt := mustParseCertificate(t, testIntermediateCertificate)
  949. type fields struct {
  950. client CertificateAuthorityClient
  951. certificateAuthority string
  952. project string
  953. location string
  954. }
  955. type args struct {
  956. req *apiv1.CreateCertificateAuthorityRequest
  957. }
  958. tests := []struct {
  959. name string
  960. fields fields
  961. args args
  962. want *apiv1.CreateCertificateAuthorityResponse
  963. wantErr bool
  964. }{
  965. {"ok root", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  966. Type: apiv1.RootCA,
  967. Template: mustParseCertificate(t, testRootCertificate),
  968. Lifetime: 24 * time.Hour,
  969. }}, &apiv1.CreateCertificateAuthorityResponse{
  970. Name: testAuthorityName,
  971. Certificate: rootCrt,
  972. }, false},
  973. {"ok intermediate", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  974. Type: apiv1.IntermediateCA,
  975. Template: mustParseCertificate(t, testIntermediateCertificate),
  976. Lifetime: 24 * time.Hour,
  977. Parent: &apiv1.CreateCertificateAuthorityResponse{
  978. Name: testAuthorityName,
  979. Certificate: rootCrt,
  980. },
  981. }}, &apiv1.CreateCertificateAuthorityResponse{
  982. Name: testAuthorityName,
  983. Certificate: intCrt,
  984. CertificateChain: []*x509.Certificate{rootCrt},
  985. }, false},
  986. {"ok intermediate local signer", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  987. Type: apiv1.IntermediateCA,
  988. Template: mustParseCertificate(t, testIntermediateCertificate),
  989. Lifetime: 24 * time.Hour,
  990. Parent: &apiv1.CreateCertificateAuthorityResponse{
  991. Certificate: rootCrt,
  992. Signer: mustParseECKey(t, testRootKey),
  993. },
  994. }}, &apiv1.CreateCertificateAuthorityResponse{
  995. Name: testAuthorityName,
  996. Certificate: intCrt,
  997. CertificateChain: []*x509.Certificate{rootCrt},
  998. }, false},
  999. {"ok create key", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1000. Type: apiv1.RootCA,
  1001. Template: mustParseCertificate(t, testRootCertificate),
  1002. Lifetime: 24 * time.Hour,
  1003. CreateKey: &kmsapi.CreateKeyRequest{
  1004. SignatureAlgorithm: kmsapi.ECDSAWithSHA256,
  1005. },
  1006. }}, &apiv1.CreateCertificateAuthorityResponse{
  1007. Name: testAuthorityName,
  1008. Certificate: rootCrt,
  1009. }, false},
  1010. {"fail project", fields{m, "", "", testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1011. Type: apiv1.RootCA,
  1012. Template: mustParseCertificate(t, testRootCertificate),
  1013. Lifetime: 24 * time.Hour,
  1014. }}, nil, true},
  1015. {"fail location", fields{m, "", testProject, ""}, args{&apiv1.CreateCertificateAuthorityRequest{
  1016. Type: apiv1.RootCA,
  1017. Template: mustParseCertificate(t, testRootCertificate),
  1018. Lifetime: 24 * time.Hour,
  1019. }}, nil, true},
  1020. {"fail template", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1021. Type: apiv1.RootCA,
  1022. Lifetime: 24 * time.Hour,
  1023. }}, nil, true},
  1024. {"fail lifetime", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1025. Type: apiv1.RootCA,
  1026. Template: mustParseCertificate(t, testRootCertificate),
  1027. }}, nil, true},
  1028. {"fail parent", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1029. Type: apiv1.IntermediateCA,
  1030. Template: mustParseCertificate(t, testRootCertificate),
  1031. Lifetime: 24 * time.Hour,
  1032. }}, nil, true},
  1033. {"fail parent name", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1034. Type: apiv1.IntermediateCA,
  1035. Template: mustParseCertificate(t, testRootCertificate),
  1036. Lifetime: 24 * time.Hour,
  1037. Parent: &apiv1.CreateCertificateAuthorityResponse{},
  1038. }}, nil, true},
  1039. {"fail type", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1040. Type: 0,
  1041. Template: mustParseCertificate(t, testRootCertificate),
  1042. Lifetime: 24 * time.Hour,
  1043. }}, nil, true},
  1044. {"fail create key", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1045. Type: apiv1.RootCA,
  1046. Template: mustParseCertificate(t, testRootCertificate),
  1047. Lifetime: 24 * time.Hour,
  1048. CreateKey: &kmsapi.CreateKeyRequest{
  1049. SignatureAlgorithm: kmsapi.PureEd25519,
  1050. },
  1051. }}, nil, true},
  1052. {"fail CreateCertificateAuthority", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1053. Type: apiv1.RootCA,
  1054. Template: mustParseCertificate(t, testRootCertificate),
  1055. Lifetime: 24 * time.Hour,
  1056. }}, nil, true},
  1057. {"fail CreateCertificateAuthority.Wait", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1058. Type: apiv1.RootCA,
  1059. Template: mustParseCertificate(t, testRootCertificate),
  1060. Lifetime: 24 * time.Hour,
  1061. }}, nil, true},
  1062. {"fail FetchCertificateAuthorityCsr", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1063. Type: apiv1.IntermediateCA,
  1064. Template: mustParseCertificate(t, testIntermediateCertificate),
  1065. Lifetime: 24 * time.Hour,
  1066. Parent: &apiv1.CreateCertificateAuthorityResponse{
  1067. Name: testAuthorityName,
  1068. Certificate: rootCrt,
  1069. },
  1070. }}, nil, true},
  1071. {"fail CreateCertificate", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1072. Type: apiv1.IntermediateCA,
  1073. Template: mustParseCertificate(t, testIntermediateCertificate),
  1074. Lifetime: 24 * time.Hour,
  1075. Parent: &apiv1.CreateCertificateAuthorityResponse{
  1076. Name: testAuthorityName,
  1077. Certificate: rootCrt,
  1078. },
  1079. }}, nil, true},
  1080. {"fail ActivateCertificateAuthority", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1081. Type: apiv1.IntermediateCA,
  1082. Template: mustParseCertificate(t, testIntermediateCertificate),
  1083. Lifetime: 24 * time.Hour,
  1084. Parent: &apiv1.CreateCertificateAuthorityResponse{
  1085. Name: testAuthorityName,
  1086. Certificate: rootCrt,
  1087. },
  1088. }}, nil, true},
  1089. {"fail ActivateCertificateAuthority.Wait", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1090. Type: apiv1.IntermediateCA,
  1091. Template: mustParseCertificate(t, testIntermediateCertificate),
  1092. Lifetime: 24 * time.Hour,
  1093. Parent: &apiv1.CreateCertificateAuthorityResponse{
  1094. Name: testAuthorityName,
  1095. Certificate: rootCrt,
  1096. },
  1097. }}, nil, true},
  1098. {"fail x509util.CreateCertificate", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1099. Type: apiv1.IntermediateCA,
  1100. Template: mustParseCertificate(t, testIntermediateCertificate),
  1101. Lifetime: 24 * time.Hour,
  1102. Parent: &apiv1.CreateCertificateAuthorityResponse{
  1103. Certificate: rootCrt,
  1104. Signer: createBadSigner(t),
  1105. },
  1106. }}, nil, true},
  1107. {"fail parseCertificateRequest", fields{m, "", testProject, testLocation}, args{&apiv1.CreateCertificateAuthorityRequest{
  1108. Type: apiv1.IntermediateCA,
  1109. Template: mustParseCertificate(t, testIntermediateCertificate),
  1110. Lifetime: 24 * time.Hour,
  1111. Parent: &apiv1.CreateCertificateAuthorityResponse{
  1112. Certificate: rootCrt,
  1113. Signer: createBadSigner(t),
  1114. },
  1115. }}, nil, true},
  1116. }
  1117. for _, tt := range tests {
  1118. t.Run(tt.name, func(t *testing.T) {
  1119. c := &CloudCAS{
  1120. client: tt.fields.client,
  1121. certificateAuthority: tt.fields.certificateAuthority,
  1122. project: tt.fields.project,
  1123. location: tt.fields.location,
  1124. }
  1125. got, err := c.CreateCertificateAuthority(tt.args.req)
  1126. if (err != nil) != tt.wantErr {
  1127. t.Errorf("CloudCAS.CreateCertificateAuthority() error = %+v, wantErr %v", err, tt.wantErr)
  1128. return
  1129. }
  1130. if !reflect.DeepEqual(got, tt.want) {
  1131. t.Errorf("CloudCAS.CreateCertificateAuthority() = %v, want %v", got, tt.want)
  1132. }
  1133. })
  1134. }
  1135. }
  1136. func Test_normalizeCertificateAuthorityName(t *testing.T) {
  1137. type args struct {
  1138. name string
  1139. }
  1140. tests := []struct {
  1141. name string
  1142. args args
  1143. want string
  1144. }{
  1145. {"ok", args{"Test-CA-Name_1234"}, "Test-CA-Name_1234"},
  1146. {"change", args{"💥 CA"}, "--CA"},
  1147. }
  1148. for _, tt := range tests {
  1149. t.Run(tt.name, func(t *testing.T) {
  1150. if got := normalizeCertificateAuthorityName(tt.args.name); got != tt.want {
  1151. t.Errorf("normalizeCertificateAuthorityName() = %v, want %v", got, tt.want)
  1152. }
  1153. })
  1154. }
  1155. }