7dbbbe7a00afef8a71f5f78e4d3e902e0cfcb53c
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2controller / util / certificate_update_util_test.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (C) 2021 Nokia. All rights reserved.
6  * ================================================================================
7  * This source code was copied from the following git repository:
8  * https://github.com/smallstep/step-issuer
9  * The source code was modified for usage in the ONAP project.
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24
25 package util
26
27 import (
28         "encoding/base64"
29         "fmt"
30         "testing"
31
32         cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
33         "github.com/stretchr/testify/assert"
34         v1 "k8s.io/api/core/v1"
35         metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
36         "onap.org/oom-certservice/k8s-external-provider/src/testdata"
37         "sigs.k8s.io/controller-runtime/pkg/client/fake"
38 )
39
40 const (
41         oldCertificateConfig = "{\"apiVersion\":\"cert-manager.io/v1\",\"kind\":\"Certificate\",\"metadata\":{\"annotations\":{},\"name\":\"cert-test\",\"namespace\":\"onap\"},\"spec\":{\"commonName\":\"certissuer.onap.org\",\"dnsNames\":[\"localhost\",\"certissuer.onap.org\"],\"emailAddresses\":[\"onap@onap.org\"],\"ipAddresses\":[\"127.0.0.1\"],\"issuerRef\":{\"group\":\"certmanager.onap.org\",\"kind\":\"CMPv2Issuer\",\"name\":\"cmpv2-issuer-onap\"},\"secretName\":\"cert-test-secret-name\",\"subject\":{\"countries\":[\"US\"],\"localities\":[\"San-Francisco\"],\"organizationalUnits\":[\"ONAP\"],\"organizations\":[\"Linux-Foundation\"],\"provinces\":[\"California\"]},\"uris\":[\"onap://cluster.local/\"]}}\n"
42         testPrivateKeyData   = "test-private-key"
43         testCertificateData  = "test-certificate"
44 )
45
46 func Test_CheckIfCertificateUpdateAndRetrieveOldCertificateAndPk_revisionOne(t *testing.T) {
47         request := new(cmapi.CertificateRequest)
48         request.ObjectMeta.Annotations = map[string]string{
49                 revisionAnnotation: "2",
50         }
51         isUpdate, certificate, privateKey := CheckIfCertificateUpdateAndRetrieveOldCertificateAndPk(nil, request, nil)
52         assert.False(t, isUpdate)
53         assert.Equal(t, "", certificate)
54         assert.Equal(t, "", privateKey)
55 }
56
57 func Test_CheckIfCertificateUpdateAndRetrieveOldCertificateAndPk_revisionTwoSecretPresent(t *testing.T) {
58         request := new(cmapi.CertificateRequest)
59         request.ObjectMeta.Annotations = map[string]string{
60                 revisionAnnotation:                 "2",
61                 certificateConfigurationAnnotation: oldCertificateConfig,
62         }
63         fakeClient := fake.NewFakeClientWithScheme(testdata.GetScheme(), getValidCertificateSecret())
64         isUpdate, certificate, privateKey := CheckIfCertificateUpdateAndRetrieveOldCertificateAndPk(fakeClient, request, nil)
65         assert.True(t, isUpdate)
66         assert.Equal(t, base64.StdEncoding.EncodeToString([]byte(testCertificateData)), certificate)
67         assert.Equal(t, base64.StdEncoding.EncodeToString([]byte(testPrivateKeyData)), privateKey)
68 }
69
70 func Test_CheckIfCertificateUpdateAndRetrieveOldCertificateAndPk_revisionTwoSecretNotPresent(t *testing.T) {
71         request := new(cmapi.CertificateRequest)
72         request.ObjectMeta.Annotations = map[string]string{
73                 revisionAnnotation:                 "2",
74                 certificateConfigurationAnnotation: oldCertificateConfig,
75         }
76         fakeClient := fake.NewFakeClientWithScheme(testdata.GetScheme())
77         isUpdate, certificate, privateKey := CheckIfCertificateUpdateAndRetrieveOldCertificateAndPk(fakeClient, request, nil)
78         assert.False(t, isUpdate)
79         assert.Equal(t, "", certificate)
80         assert.Equal(t, "", privateKey)
81 }
82
83 func Test_IsUpdateCertificateRevision(t *testing.T) {
84         parameters := []struct {
85                 revision string
86                 expected bool
87         }{
88                 {"1", false},
89                 {"2", true},
90                 {"invalid", false},
91         }
92
93         for _, parameter := range parameters {
94                 testName := fmt.Sprintf("Expected:%v for revision=%v", parameter.expected, parameter.revision)
95                 t.Run(testName, func(t *testing.T) {
96                         testIsUpdateCertificateRevision(t, parameter.revision, parameter.expected)
97                 })
98         }
99 }
100
101 func testIsUpdateCertificateRevision(t *testing.T, revision string, expected bool) {
102         request := new(cmapi.CertificateRequest)
103         request.ObjectMeta.Annotations = map[string]string{
104                 revisionAnnotation: revision,
105         }
106         assert.Equal(t, expected, IsUpdateCertificateRevision(request))
107 }
108
109 func Test_RetrieveOldCertificateAndPk_shouldSucceedWhenSecretPresent(t *testing.T) {
110         request := new(cmapi.CertificateRequest)
111         request.ObjectMeta.Annotations = map[string]string{
112                 certificateConfigurationAnnotation: oldCertificateConfig,
113         }
114         fakeClient := fake.NewFakeClientWithScheme(testdata.GetScheme(), getValidCertificateSecret())
115         certificate, privateKey := RetrieveOldCertificateAndPk(fakeClient, request, nil)
116         assert.Equal(t, base64.StdEncoding.EncodeToString([]byte(testCertificateData)), certificate)
117         assert.Equal(t, base64.StdEncoding.EncodeToString([]byte(testPrivateKeyData)), privateKey)
118 }
119
120 func Test_RetrieveOldCertificateAndPk_shouldReturnEmptyStringsWhenSecretNotPresent(t *testing.T) {
121         request := new(cmapi.CertificateRequest)
122         request.ObjectMeta.Annotations = map[string]string{
123                 certificateConfigurationAnnotation: oldCertificateConfig,
124         }
125         fakeClient := fake.NewFakeClientWithScheme(testdata.GetScheme())
126         certificate, privateKey := RetrieveOldCertificateAndPk(fakeClient, request, nil)
127         assert.Equal(t, "", certificate)
128         assert.Equal(t, "", privateKey)
129 }
130
131 func Test_RetrieveOldCertificateAndPk_shouldReturnEmptyStringsWhenOldCertificateCannotBeUnmarshalled(t *testing.T) {
132         request := new(cmapi.CertificateRequest)
133         fakeClient := fake.NewFakeClientWithScheme(testdata.GetScheme())
134         certificate, privateKey := RetrieveOldCertificateAndPk(fakeClient, request, nil)
135         assert.Equal(t, "", certificate)
136         assert.Equal(t, "", privateKey)
137 }
138
139 func getValidCertificateSecret() *v1.Secret {
140         const privateKeySecretKey = "tls.key"
141         const certificateSecretKey = "tls.crt"
142
143         return &v1.Secret{
144                 Data: map[string][]byte{
145                         privateKeySecretKey:  []byte("test-private-key"),
146                         certificateSecretKey: []byte("test-certificate"),
147                 },
148                 ObjectMeta: metav1.ObjectMeta{
149                         Name:      "cert-test-secret-name",
150                         Namespace: "onap",
151                 },
152         }
153 }