istio

Форк
0
/
credentials_test.go 
150 строк · 4.9 Кб
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_test
16

17
import (
18
	"fmt"
19
	"os"
20
	"testing"
21
	"time"
22

23
	"istio.io/istio/pilot/cmd/pilot-agent/config"
24
	"istio.io/istio/pilot/cmd/pilot-agent/options"
25
	"istio.io/istio/pilot/pkg/model"
26
	"istio.io/istio/pkg/config/constants"
27
	"istio.io/istio/pkg/jwt"
28
	"istio.io/istio/pkg/security"
29
	"istio.io/istio/security/pkg/credentialfetcher"
30
	"istio.io/istio/security/pkg/credentialfetcher/plugin"
31
	"istio.io/istio/security/pkg/nodeagent/caclient"
32
	"istio.io/istio/security/pkg/stsservice"
33
	stsmock "istio.io/istio/security/pkg/stsservice/mock"
34
	"istio.io/istio/security/pkg/stsservice/tokenmanager/google"
35
	"istio.io/istio/security/pkg/stsservice/tokenmanager/google/mock"
36
)
37

38
// TestGetTokenForXDS tests getting token for XDS.
39
// Test case 1: xdsAuthProvider is google.GCPAuthProvider.
40
// Test case 2: xdsAuthProvider is empty.
41
func TestGetTokenForXDS(t *testing.T) {
42
	role := &model.Proxy{}
43
	role.Type = model.SidecarProxy
44
	meshConfigFile := ""
45
	serviceCluster := constants.ServiceClusterName
46
	proxyConfigEnv := ""
47
	concurrency := 0
48
	proxyConfig, err := config.ConstructProxyConfig(meshConfigFile, serviceCluster, proxyConfigEnv, concurrency)
49
	if err != nil {
50
		t.Fatalf("failed to construct proxy config: %v", err)
51
	}
52

53
	jwtPolicy := jwt.PolicyThirdParty
54
	credFetcherTypeEnv := ""
55
	credIdentityProvider := google.GCEProvider
56
	sop := &security.Options{
57
		CAEndpoint:                     "",
58
		CAProviderName:                 "Citadel",
59
		PilotCertProvider:              "istiod",
60
		OutputKeyCertToDir:             "",
61
		ProvCert:                       "",
62
		ClusterID:                      "",
63
		FileMountedCerts:               false,
64
		WorkloadNamespace:              "",
65
		ServiceAccount:                 "",
66
		TrustDomain:                    "cluster.local",
67
		Pkcs8Keys:                      false,
68
		ECCSigAlg:                      "",
69
		SecretTTL:                      24 * time.Hour,
70
		SecretRotationGracePeriodRatio: 0.5,
71
	}
72
	secOpts, err := options.SetupSecurityOptions(proxyConfig, sop, jwtPolicy,
73
		credFetcherTypeEnv, credIdentityProvider)
74
	if err != nil {
75
		t.Fatalf("failed to setup security options: %v", err)
76
	}
77
	jwtPath, err := writeToTempFile(mock.FakeSubjectToken, "jwt-token-*")
78
	if err != nil {
79
		t.Fatalf("failed to write the JWT token file: %v", err)
80
	}
81
	secOpts.CredFetcher = plugin.CreateTokenPlugin(jwtPath)
82
	defer os.Remove(jwtPath)
83

84
	mockCredFetcher, err := credentialfetcher.NewCredFetcher(security.Mock, "", "", "")
85
	if err != nil {
86
		t.Fatalf("failed to create mock credential fetcher: %v", err)
87
	}
88
	// Use a mock token manager because real token exchange requires a working k8s token,
89
	// permissions for token exchange, and connection to the token exchange server.
90
	tokenManager := stsmock.CreateFakeTokenManager()
91
	tokenManager.SetRespStsParam(stsservice.StsResponseParameters{
92
		AccessToken:     mock.FakeAccessToken,
93
		IssuedTokenType: "urn:ietf:params:oauth:token-type:access_token",
94
		TokenType:       "Bearer",
95
		ExpiresIn:       60,
96
		Scope:           "example.com",
97
	})
98
	secOpts.TokenManager = tokenManager
99

100
	tests := []struct {
101
		name        string
102
		provider    string
103
		credFetcher security.CredFetcher
104
		expectToken string
105
	}{
106
		{
107
			name:        "xdsAuthProvider is google.GCPAuthProvider",
108
			provider:    google.GCPAuthProvider,
109
			expectToken: mock.FakeAccessToken,
110
		},
111
		{
112
			name:        "xdsAuthProvider is empty",
113
			provider:    "",
114
			expectToken: mock.FakeSubjectToken,
115
		},
116
		{
117
			name:        "credential fetcher and google.GCPAuthProvider",
118
			provider:    google.GCPAuthProvider,
119
			credFetcher: mockCredFetcher,
120
			expectToken: mock.FakeAccessToken,
121
		},
122
	}
123

124
	for _, tt := range tests {
125
		t.Run(tt.name, func(t *testing.T) {
126
			secOpts.XdsAuthProvider = tt.provider
127
			provider := caclient.NewXDSTokenProvider(secOpts)
128
			token, err := provider.GetToken()
129
			if err != nil {
130
				t.Errorf("failed to get token: %v", err)
131
			}
132
			if token != tt.expectToken {
133
				t.Errorf("the token returned is unexpected, expect: %v, got: %v", tt.expectToken, token)
134
			}
135
		})
136
	}
137
}
138

139
func writeToTempFile(content, fileNamePrefix string) (string, error) {
140
	outFile, err := os.CreateTemp("", fileNamePrefix)
141
	if err != nil {
142
		return "", fmt.Errorf("failed creating a temp file: %v", err)
143
	}
144
	defer func() { _ = outFile.Close() }()
145

146
	if _, err := outFile.WriteString(content); err != nil {
147
		return "", fmt.Errorf("failed writing to the temp file: %v", err)
148
	}
149
	return outFile.Name(), nil
150
}
151

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

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

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

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