[OOM-K8S-CERT-EXTERNAL-PROVIDER] Extend SANs support
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2controller / logger / certificate_request_logger_test.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (C) 2020 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package logger
22
23 import (
24         "bytes"
25         "io/ioutil"
26         "log"
27         "os"
28         "strings"
29         "testing"
30         "time"
31
32         cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
33         "github.com/stretchr/testify/assert"
34         metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
35
36         "onap.org/oom-certservice/k8s-external-provider/src/leveledlogger"
37         x509utils "onap.org/oom-certservice/k8s-external-provider/src/x509"
38 )
39
40 var unsupportedProperties = []string{
41         "* property 'duration'",
42         "* property 'usages'",
43         "- property 'isCA'",
44         "- property 'subject.streetAddress'",
45         "- property 'subject.postalCodes'",
46         "- property 'subject.serialNumber'"}
47
48 var supportedProperties = []string{
49         "+ property 'common name'",
50         "+ property 'organization'",
51         "+ property 'organization unit'",
52         "+ property 'country'",
53         "+ property 'state'",
54         "+ property 'location'",
55         "+ property 'dns names'",
56         "+ property 'ipAddresses'",
57         "+ property 'uris'",
58         "+ property 'email addresses'",
59         }
60
61 const RESULT_LOG = "testdata/test_result.log"
62
63 func TestMain(m *testing.M) {
64         leveledlogger.SetConfigFileName("testdata/test_logger_config.json")
65         os.Exit(m.Run())
66 }
67
68 func TestLogShouldNotProvideInformationAboutSkippedPropertiesIfNotExistInCSR(t *testing.T) {
69         //given
70         logger := leveledlogger.GetLoggerWithName("test")
71         request := getCertificateRequestWithoutSkippedProperties()
72
73         csr, err := x509utils.DecodeCSR(request.Spec.Request)
74         if err != nil {
75                 assert.FailNow(t, "Could not parse Certificate Sign Request")
76         }
77
78         //when
79         LogCertRequestProperties(logger, request, csr)
80         logsArray := convertLogFileToStringArray(RESULT_LOG)
81
82         //then
83         for _, logMsg := range unsupportedProperties {
84                 assert.False(t, logsContainExpectedMessage(logsArray, logMsg), "Logs should not contain: ["+logMsg+"]")
85         }
86         removeTemporaryFile(RESULT_LOG)
87 }
88
89 func TestLogShouldProvideInformationAboutSkippedPropertiesIfExistInCSR(t *testing.T) {
90         //given
91         logger := leveledlogger.GetLoggerWithName("test")
92         request := getCertificateRequestWithSkippedProperties()
93
94         csr, err := x509utils.DecodeCSR(request.Spec.Request)
95         if err != nil {
96                 assert.FailNow(t, "Could not parse Certificate Sign Request")
97         }
98
99         //when
100         LogCertRequestProperties(logger, request, csr)
101         logsArray := convertLogFileToStringArray(RESULT_LOG)
102
103         //then
104         for _, logMsg := range unsupportedProperties {
105                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs should contain: ["+logMsg+"]")
106         }
107         removeTemporaryFile(RESULT_LOG)
108 }
109
110 func TestLogShouldListSupportedProperties(t *testing.T) {
111         //given
112         logger := leveledlogger.GetLoggerWithName("test")
113         request := getCertificateRequestWithoutSkippedProperties()
114
115         csr, err := x509utils.DecodeCSR(request.Spec.Request)
116         if err != nil {
117                 assert.FailNow(t, "Could not parse Certificate Sign Request")
118         }
119
120         //when
121         LogCertRequestProperties(logger, request, csr)
122         logsArray := convertLogFileToStringArray(RESULT_LOG)
123
124         //then
125         for _, logMsg := range supportedProperties {
126                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs should contain: ["+logMsg+"]")
127         }
128         removeTemporaryFile(RESULT_LOG)
129 }
130
131 func getCertificateRequestWithoutSkippedProperties() *cmapi.CertificateRequest {
132         request := new(cmapi.CertificateRequest)
133         request.Spec.Request = []byte(csrWithoutSkippedProperties)
134         return request
135 }
136
137 func getCertificateRequestWithSkippedProperties() *cmapi.CertificateRequest {
138         request := new(cmapi.CertificateRequest)
139         request.Spec.Request = []byte(csrWithSkippedProperties)
140         request.Spec.Duration = &metav1.Duration{Duration: time.Hour}
141         request.Spec.IsCA = true
142         request.Spec.Usages = cmapi.DefaultKeyUsages()
143         return request
144 }
145
146 func convertBufferToStringArray(buffer *bytes.Buffer) []string {
147         return strings.Split(buffer.String(), "\n")
148 }
149
150 func convertLogFileToStringArray(filename string) []string {
151         buffer := bytes.NewBuffer(make([]byte, 0))
152         buffer.Write(readFile(filename))
153         return convertBufferToStringArray(buffer)
154 }
155
156 func readFile(filename string) []byte {
157         certRequest, err := ioutil.ReadFile(filename)
158         if err != nil {
159                 log.Fatal(err)
160         }
161         return certRequest
162 }
163
164 func removeTemporaryFile(fileName string) {
165         if _, err := os.Stat(fileName); err == nil {
166                 e := os.Remove(fileName)
167                 if e != nil {
168                         log.Fatal(e)
169                 }
170         }
171 }
172
173 func logsContainExpectedMessage(array []string, expectedMsg string) bool {
174         for _, logMsg := range array {
175                 if strings.Contains(logMsg, expectedMsg) {
176                         return true
177                 }
178         }
179         return false
180 }