istio

Форк
0
122 строки · 3.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 mock
16

17
import (
18
	"encoding/pem"
19
	"fmt"
20
	"path"
21
	"sync/atomic"
22
	"time"
23

24
	"istio.io/istio/pkg/security"
25
	"istio.io/istio/security/pkg/pki/util"
26
)
27

28
var (
29
	sampleKeyCertsPath = "../../../../samples/certs/"
30
	caCertPath         = path.Join(sampleKeyCertsPath, "ca-cert.pem")
31
	caKeyPath          = path.Join(sampleKeyCertsPath, "ca-key.pem")
32
	certChainPath      = []string{path.Join(sampleKeyCertsPath, "cert-chain.pem")}
33
	rootCertPath       = path.Join(sampleKeyCertsPath, "root-cert.pem")
34
)
35

36
// CAClient is the mocked CAClient for testing.
37
type CAClient struct {
38
	SignInvokeCount uint64
39
	bundle          *util.KeyCertBundle
40
	certLifetime    time.Duration
41
	GeneratedCerts  [][]string // Cache the generated certificates for verification purpose.
42
	mockTrustAnchor bool
43
}
44

45
// NewMockCAClient creates an instance of CAClient. errors is used to specify the number of errors
46
// before CSRSign returns a valid response. certLifetime specifies the TTL for the newly issued workload cert.
47
func NewMockCAClient(certLifetime time.Duration, mockTrustAnchor bool) (*CAClient, error) {
48
	cl := CAClient{
49
		SignInvokeCount: 0,
50
		certLifetime:    certLifetime,
51
		mockTrustAnchor: mockTrustAnchor,
52
	}
53
	bundle, err := util.NewVerifiedKeyCertBundleFromFile(caCertPath, caKeyPath, certChainPath, rootCertPath)
54
	if err != nil {
55
		return nil, fmt.Errorf("mock ca client creation error: %v", err)
56
	}
57
	cl.bundle = bundle
58

59
	atomic.StoreUint64(&cl.SignInvokeCount, 0)
60
	return &cl, nil
61
}
62

63
func (c *CAClient) Close() {}
64

65
// CSRSign returns the certificate or errors depending on the settings.
66
func (c *CAClient) CSRSign(csrPEM []byte, certValidTTLInSec int64) ([]string, error) {
67
	atomic.AddUint64(&c.SignInvokeCount, 1)
68
	signingCert, signingKey, certChain, rootCert := c.bundle.GetAll()
69
	csr, err := util.ParsePemEncodedCSR(csrPEM)
70
	if err != nil {
71
		return nil, fmt.Errorf("csr sign error: %v", err)
72
	}
73
	subjectIDs := []string{"test"}
74
	certBytes, err := util.GenCertFromCSR(csr, signingCert, csr.PublicKey, *signingKey, subjectIDs, c.certLifetime, false)
75
	if err != nil {
76
		return nil, fmt.Errorf("csr sign error: %v", err)
77
	}
78

79
	block := &pem.Block{
80
		Type:  "CERTIFICATE",
81
		Bytes: certBytes,
82
	}
83
	cert := pem.EncodeToMemory(block)
84

85
	ret := []string{string(cert), string(certChain), string(rootCert)}
86
	c.GeneratedCerts = append(c.GeneratedCerts, ret)
87
	return ret, nil
88
}
89

90
func (c *CAClient) GetRootCertBundle() ([]string, error) {
91
	if c.mockTrustAnchor {
92
		rootCertBytes := c.bundle.GetRootCertPem()
93
		return []string{string(rootCertBytes)}, nil
94
	}
95

96
	return []string{}, nil
97
}
98

99
// TokenExchangeServer is the mocked token exchange server for testing.
100
type TokenExchangeServer struct {
101
	exchangeMap map[string]string
102
}
103

104
// NewMockTokenExchangeServer creates an instance of TokenExchangeServer. errors is used to
105
// specify the number of errors before ExchangeToken returns a dumb token.
106
func NewMockTokenExchangeServer(exchangeMap map[string]string) *TokenExchangeServer {
107
	return &TokenExchangeServer{exchangeMap}
108
}
109

110
var _ security.TokenExchanger = &TokenExchangeServer{}
111

112
// ExchangeToken returns a dumb token or errors depending on the settings.
113
func (s *TokenExchangeServer) ExchangeToken(token string) (string, error) {
114
	if len(s.exchangeMap) == 0 {
115
		return "some-token", nil
116
	}
117
	ex, f := s.exchangeMap[token]
118
	if !f {
119
		return "", fmt.Errorf("token %v not found", token)
120
	}
121
	return ex, nil
122
}
123

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

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

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

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