istio

Форк
0
111 строк · 4.0 Кб
1
// Copyright Istio Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package caclient
16

17
import (
18
	"reflect"
19
	"testing"
20

21
	"google.golang.org/api/option"
22
	"google.golang.org/grpc"
23
	"google.golang.org/grpc/codes"
24
	"google.golang.org/grpc/credentials/insecure"
25
	"google.golang.org/grpc/status"
26

27
	"istio.io/istio/security/pkg/nodeagent/caclient/providers/google-cas/mock"
28
)
29

30
var (
31
	fakeCert                 = "foo"
32
	fakeCertChain            = []string{"baz", "bar"}
33
	fakeCaBundle             = [][]string{{"bar"}, {"baz", "bar"}}
34
	fakeExpectedRootCaBundle = []string{"bar"}
35
	fakePoolLocator          = "projects/test-project/locations/test-location/caPools/test-pool"
36
	badPoolLocator           = "bad-pool"
37
)
38

39
func TestGoogleCASClient(t *testing.T) {
40
	fakeCombinedCert := append([]string{}, fakeCert)
41
	fakeCombinedCert = append(fakeCombinedCert, fakeCertChain...)
42

43
	testCases := map[string]struct {
44
		poolLocator        string
45
		service            mock.CASService
46
		expectedCert       []string
47
		expectedCertBundle []string
48
		expectedErr        error
49
	}{
50
		"Valid certs": {
51
			// Check RootCertBundle is correctly extracted from CAS response
52
			// Check Certchain is correctly build from CAS response
53
			poolLocator:        fakePoolLocator,
54
			service:            mock.CASService{CertPEM: fakeCert, CertChainPEM: fakeCertChain, CaCertBundle: fakeCaBundle},
55
			expectedCert:       fakeCombinedCert,
56
			expectedCertBundle: fakeExpectedRootCaBundle,
57
			expectedErr:        nil,
58
		},
59
		"Invalid Pool": {
60
			// Destination is invalid pool
61
			poolLocator:        badPoolLocator,
62
			service:            mock.CASService{CertPEM: fakeCert, CertChainPEM: fakeCertChain, CaCertBundle: fakeCaBundle},
63
			expectedCert:       fakeCombinedCert,
64
			expectedCertBundle: fakeExpectedRootCaBundle,
65
			expectedErr:        status.Error(codes.InvalidArgument, "malformed ca path"),
66
		},
67
	}
68

69
	for id, tc := range testCases {
70
		// create a local grpc server
71
		s, lis, err := mock.CreateServer(&tc.service)
72
		if err != nil {
73
			t.Fatalf("Test case [%s] Mock CAS Server Init: failed to create server: %v", id, err)
74
		}
75
		defer s.Stop()
76

77
		cli, err := NewGoogleCASClient(tc.poolLocator,
78
			option.WithoutAuthentication(),
79
			option.WithGRPCDialOption(grpc.WithContextDialer(mock.ContextDialerCreate(lis))),
80
			option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())))
81
		if err != nil {
82
			t.Errorf("Test case [%s] Client Init: failed to create ca client: %v", id, err)
83
		}
84

85
		resp, err := cli.CSRSign([]byte{0o1}, 1)
86
		if err != nil {
87
			if err.Error() != tc.expectedErr.Error() {
88
				t.Errorf("Test case [%s] Cert Check: error (%s) does not match expected error (%s)", id, err.Error(), tc.expectedErr.Error())
89
			}
90
		} else {
91
			if tc.expectedErr != nil {
92
				t.Errorf("Test case [%s] Cert Check: expect error: %s but got no error", id, tc.expectedErr.Error())
93
			} else if !reflect.DeepEqual(resp, tc.expectedCert) {
94
				t.Errorf("Test case [%s] Cert Check: resp: got %+v, expected %v", id, resp, tc.expectedCert)
95
			}
96
		}
97

98
		resp, err = cli.GetRootCertBundle()
99
		if err != nil {
100
			if err.Error() != tc.expectedErr.Error() {
101
				t.Errorf("Test case [%s] RootCaBundle check: error (%s) does not match expected error (%s)", id, err.Error(), tc.expectedErr.Error())
102
			}
103
		} else {
104
			if tc.expectedErr != nil {
105
				t.Errorf("Test case [%s] RootCaBundle check: expect error: %s but got no error", id, tc.expectedErr.Error())
106
			} else if !reflect.DeepEqual(resp, tc.expectedCertBundle) {
107
				t.Errorf("Test case [%s] RootCaBundle check: resp: got %+v, expected %v", id, resp, tc.expectedCertBundle)
108
			}
109
		}
110
	}
111
}
112

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.