250fab8b2574507f3aa1605d983387f02e04a3cb
[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 'ipAddresses'",
44         "- property 'isCA'",
45         "- property 'subject.streetAddress'",
46         "- property 'subject.postalCodes'",
47         "- property 'subject.serialNumber'"}
48
49 var supportedProperties = []string{
50         "+ property 'common name'",
51         "+ property 'organization'",
52         "+ property 'organization unit'",
53         "+ property 'country'",
54         "+ property 'state'",
55         "+ property 'location'",
56         "+ property 'dns names'"}
57
58 const RESULT_LOG = "testdata/test_result.log"
59
60 func TestMain(m *testing.M) {
61         leveledlogger.SetConfigFileName("testdata/test_logger_config.json")
62         os.Exit(m.Run())
63 }
64
65 func TestLogShouldNotProvideInformationAboutSkippedPropertiesIfNotExistInCSR(t *testing.T) {
66         //given
67         logger := leveledlogger.GetLoggerWithName("test")
68         request := getCertificateRequestWithoutSkippedProperties()
69
70         csr, err := x509utils.DecodeCSR(request.Spec.Request)
71         if err != nil {
72                 assert.FailNow(t, "Could not parse Certificate Sign Request")
73         }
74
75         //when
76         LogCertRequestProperties(logger, request, csr)
77         logsArray := convertLogFileToStringArray(RESULT_LOG)
78
79         //then
80         for _, logMsg := range unsupportedProperties {
81                 assert.False(t, logsContainExpectedMessage(logsArray, logMsg), "Logs should not contain: ["+logMsg+"]")
82         }
83         removeTemporaryFile(RESULT_LOG)
84 }
85
86 func TestLogShouldProvideInformationAboutSkippedPropertiesIfExistInCSR(t *testing.T) {
87         //given
88         logger := leveledlogger.GetLoggerWithName("test")
89         request := getCertificateRequestWithSkippedProperties()
90
91         csr, err := x509utils.DecodeCSR(request.Spec.Request)
92         if err != nil {
93                 assert.FailNow(t, "Could not parse Certificate Sign Request")
94         }
95
96         //when
97         LogCertRequestProperties(logger, request, csr)
98         logsArray := convertLogFileToStringArray(RESULT_LOG)
99
100         //then
101         for _, logMsg := range unsupportedProperties {
102                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs should contain: ["+logMsg+"]")
103         }
104         removeTemporaryFile(RESULT_LOG)
105 }
106
107 func TestLogShouldListSupportedProperties(t *testing.T) {
108         //given
109         logger := leveledlogger.GetLoggerWithName("test")
110         request := getCertificateRequestWithoutSkippedProperties()
111
112         csr, err := x509utils.DecodeCSR(request.Spec.Request)
113         if err != nil {
114                 assert.FailNow(t, "Could not parse Certificate Sign Request")
115         }
116
117         //when
118         LogCertRequestProperties(logger, request, csr)
119         logsArray := convertLogFileToStringArray(RESULT_LOG)
120
121         //then
122         for _, logMsg := range supportedProperties {
123                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs should contain: ["+logMsg+"]")
124         }
125         removeTemporaryFile(RESULT_LOG)
126 }
127
128 func getCertificateRequestWithoutSkippedProperties() *cmapi.CertificateRequest {
129         request := new(cmapi.CertificateRequest)
130         request.Spec.Request = []byte(csrWithoutSkippedProperties)
131         return request
132 }
133
134 func getCertificateRequestWithSkippedProperties() *cmapi.CertificateRequest {
135         request := new(cmapi.CertificateRequest)
136         request.Spec.Request = []byte(csrWithSkippedProperties)
137         request.Spec.Duration = &metav1.Duration{Duration: time.Hour}
138         request.Spec.IsCA = true
139         request.Spec.Usages = cmapi.DefaultKeyUsages()
140         return request
141 }
142
143 func convertBufferToStringArray(buffer *bytes.Buffer) []string {
144         return strings.Split(buffer.String(), "\n")
145 }
146
147 func convertLogFileToStringArray(filename string) []string {
148         buffer := bytes.NewBuffer(make([]byte, 0))
149         buffer.Write(readFile(filename))
150         return convertBufferToStringArray(buffer)
151 }
152
153 func readFile(filename string) []byte {
154         certRequest, err := ioutil.ReadFile(filename)
155         if err != nil {
156                 log.Fatal(err)
157         }
158         return certRequest
159 }
160
161 func removeTemporaryFile(fileName string) {
162         if _, err := os.Stat(fileName); err == nil {
163                 e := os.Remove(fileName)
164                 if e != nil {
165                         log.Fatal(e)
166                 }
167         }
168 }
169
170 func logsContainExpectedMessage(array []string, expectedMsg string) bool {
171         for _, logMsg := range array {
172                 if strings.Contains(logMsg, expectedMsg) {
173                         return true
174                 }
175         }
176         return false
177 }