[OOM-K8S-CERT-EXTERNAL-PROVIDER] Add logging of supported CSR properties
[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         "flag"
26         "os"
27         "strings"
28         "testing"
29         "time"
30
31         cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
32         "github.com/stretchr/testify/assert"
33         metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
34         "k8s.io/klog/v2"
35         "k8s.io/klog/v2/klogr"
36
37         x509utils "onap.org/oom-certservice/k8s-external-provider/src/x509"
38 )
39
40 var checkedLogMessages = [7]string{"Property 'duration'", "Property 'usages'", "Property 'ipAddresses'",
41         "Property 'isCA'", "Property 'subject.streetAddress'", "Property 'subject.postalCodes'",
42         "Property 'subject.serialNumber'"}
43
44 var supportedProperties = [7]string{"Property 'organization'", "Property 'organization unit'", "Property 'country'",
45         "Property 'state'", "Property 'location'", "Property 'dns names'"}
46
47
48 func TestMain(m *testing.M) {
49         klog.InitFlags(nil)
50         flag.CommandLine.Set("v", "10")
51         flag.CommandLine.Set("skip_headers", "true")
52         flag.CommandLine.Set("logtostderr", "false")
53         flag.CommandLine.Set("alsologtostderr", "false")
54         flag.Parse()
55         os.Exit(m.Run())
56 }
57
58 func TestLogShouldNotProvideInformationAboutSkippedPropertiesIfNotExistInCSR(t *testing.T) {
59         //given
60         logger := klogr.New()
61         request := getCertificateRequestWithoutSkippedProperties()
62         tmpWriteBuffer := getLogBuffer()
63
64         csr, err := x509utils.DecodeCSR(request.Spec.Request)
65         if err != nil {
66                 assert.FailNow(t, "Could not parse Certificate Sign Request")
67         }
68
69         //when
70         LogCertRequestProperties(logger, request, csr)
71         closeLogBuffer()
72         logsArray := convertBufferToStringArray(tmpWriteBuffer)
73         //then
74         for _, logMsg := range checkedLogMessages {
75                 assert.False(t, logsContainExpectedMessage(logsArray, logMsg), "Logs contain: "+logMsg+", but should not")
76         }
77 }
78
79 func TestLogShouldProvideInformationAboutSkippedPropertiesIfExistInCSR(t *testing.T) {
80         //given
81         logger := klogr.New()
82         request := getCertificateRequestWithSkippedProperties()
83         tmpWriteBuffer := getLogBuffer()
84
85         csr, err := x509utils.DecodeCSR(request.Spec.Request)
86         if err != nil {
87                 assert.FailNow(t, "Could not parse Certificate Sign Request")
88         }
89
90         //when
91         LogCertRequestProperties(logger, request, csr)
92         closeLogBuffer()
93         logsArray := convertBufferToStringArray(tmpWriteBuffer)
94
95         //then
96         for _, logMsg := range checkedLogMessages {
97                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs not contain: "+logMsg)
98         }
99 }
100
101 func TestLogShouldListSupportedProperties(t *testing.T) {
102         //given
103         logger := klogr.New()
104         request := getCertificateRequestWithoutSkippedProperties()
105         tmpWriteBuffer := getLogBuffer()
106
107         csr, err := x509utils.DecodeCSR(request.Spec.Request)
108         if err != nil {
109                 assert.FailNow(t, "Could not parse Certificate Sign Request")
110         }
111
112         //when
113         LogCertRequestProperties(logger, request, csr)
114         closeLogBuffer()
115         logsArray := convertBufferToStringArray(tmpWriteBuffer)
116
117         //then
118         for _, logMsg := range supportedProperties {
119                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs not contain: "+logMsg)
120         }
121 }
122
123 func getCertificateRequestWithoutSkippedProperties() *cmapi.CertificateRequest {
124         request := new(cmapi.CertificateRequest)
125         request.Spec.Request = []byte(csrWithoutSkippedProperties)
126         return request
127 }
128
129 func getCertificateRequestWithSkippedProperties() *cmapi.CertificateRequest {
130         request := new(cmapi.CertificateRequest)
131         request.Spec.Request = []byte(csrWithSkippedProperties)
132         request.Spec.Duration = &metav1.Duration{Duration: time.Hour}
133         request.Spec.IsCA = true
134         request.Spec.Usages = cmapi.DefaultKeyUsages()
135         return request
136 }
137
138 func getLogBuffer() *bytes.Buffer {
139         tmpWriteBuffer := bytes.NewBuffer(nil)
140         klog.SetOutput(tmpWriteBuffer)
141         return tmpWriteBuffer
142 }
143
144 func closeLogBuffer() {
145         klog.Flush()
146 }
147
148 func convertBufferToStringArray(buffer *bytes.Buffer) []string {
149         return strings.Split(buffer.String(), "\n")
150 }
151
152 func logsContainExpectedMessage(array []string, expectedMsg string) bool {
153         for _, logMsg := range array {
154                 if strings.Contains(logMsg, expectedMsg) {
155                         return true
156                 }
157         }
158         return false
159 }