Debian Codegraph @

pkg/signature/kms/azure/client_test.go

raw ◀ ▶
1 Debian patch touch this file
•1 // +build debian_disabled
2
3 // disabled in debian as these tests require internet connectivity
4
5 //
6 // Copyright 2022 The Sigstore Authors.
7 //
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 //
12 // http://www.apache.org/licenses/LICENSE-2.0
13 //
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19
20 package azure
21
22 import (
23 "context"
24 "crypto"
25 "crypto/ecdsa"
26 "crypto/elliptic"
27 "crypto/rand"
28 "crypto/rsa"
29 "errors"
30 "fmt"
31 "net/http"
32 "testing"
33
34 "github.com/jellydator/ttlcache/v3"
35
36 "github.com/Azure/azure-sdk-for-go/sdk/azcore"
37 "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
38 "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys"
39 )
40
41 type testKVClient struct {
42 key azkeys.JSONWebKey
43 }
44
45 func (c *testKVClient) CreateKey(_ context.Context, _ string, _ azkeys.CreateKeyParameters, _ *azkeys.CreateKeyOptions) (azkeys.CreateKeyResponse, error) {
46 key, err := generatePublicKey("EC")
47 if err != nil {
48 return azkeys.CreateKeyResponse{}, err
49 }
50 c.key = key
51
52 return azkeys.CreateKeyResponse{
53 KeyBundle: azkeys.KeyBundle{
54 Key: &key,
55 },
56 }, nil
57 }
58
59 func (c *testKVClient) GetKey(_ context.Context, _, _ string, _ *azkeys.GetKeyOptions) (azkeys.GetKeyResponse, error) {
60 return azkeys.GetKeyResponse{
61 KeyBundle: azkeys.KeyBundle{
62 Key: &c.key,
63 },
64 }, nil
65 }
66
67 func (c *testKVClient) Sign(_ context.Context, _, _ string, _ azkeys.SignParameters, _ *azkeys.SignOptions) (result azkeys.SignResponse, err error) {
68 return result, nil
69 }
70
71 func (c *testKVClient) Verify(_ context.Context, _, _ string, _ azkeys.VerifyParameters, _ *azkeys.VerifyOptions) (result azkeys.VerifyResponse, err error) {
72 return result, nil
73 }
74
75 type keyNotFoundClient struct {
76 testKVClient
77 key azkeys.JSONWebKey
78 getKeyReturnsErr bool
79 getKeyCallThreshold int
80 getKeyCallCount int
81 }
82
83 func (c *keyNotFoundClient) GetKey(_ context.Context, _, _ string, _ *azkeys.GetKeyOptions) (azkeys.GetKeyResponse, error) {
84 if c.getKeyReturnsErr && c.getKeyCallCount < c.getKeyCallThreshold {
85 c.getKeyCallCount++
86 return azkeys.GetKeyResponse{}, &azcore.ResponseError{
87 StatusCode: http.StatusNotFound,
88 RawResponse: &http.Response{},
89 }
90 }
91
92 return azkeys.GetKeyResponse{
93 KeyBundle: azkeys.KeyBundle{
94 Key: &c.key,
95 },
96 }, nil
97 }
98
99 type nonResponseErrClient struct {
100 testKVClient
101 }
102
103 func (c *nonResponseErrClient) GetKey(_ context.Context, _, _ string, _ *azkeys.GetKeyOptions) (result azkeys.GetKeyResponse, err error) {
104 err = errors.New("unexpected error")
105 return result, err
106 }
107
108 type non404RespClient struct {
109 testKVClient
110 }
111
112 func (c *non404RespClient) GetKey(_ context.Context, _, _ string, _ *azkeys.GetKeyOptions) (result azkeys.GetKeyResponse, err error) {
113 err = &azcore.ResponseError{
114 StatusCode: http.StatusServiceUnavailable,
115 }
116
117 return result, err
118 }
119
120 func generatePublicKey(azureKeyType string) (azkeys.JSONWebKey, error) {
121 keyOps := []*azkeys.KeyOperation{to.Ptr(azkeys.KeyOperationSign), to.Ptr(azkeys.KeyOperationVerify)}
122 kid := "https://honk-vault.vault.azure.net/keys/honk-key/abc123"
123
124 key := azkeys.JSONWebKey{
125 KID: to.Ptr(azkeys.ID(kid)),
126 Kty: to.Ptr(azkeys.KeyType(azureKeyType)),
127 Crv: to.Ptr(azkeys.CurveName("P-256")),
128 KeyOps: keyOps,
129 }
130
131 keyType := azkeys.KeyType(azureKeyType)
132 switch keyType {
133 case azkeys.KeyTypeEC, azkeys.KeyTypeECHSM:
134 privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
135 if err != nil {
136 return azkeys.JSONWebKey{}, err
137 }
138
139 ecdsaPub, ok := privKey.Public().(*ecdsa.PublicKey)
140 if !ok {
141 return azkeys.JSONWebKey{}, fmt.Errorf("failed to cast public key to esdsa public key")
142 }
143
144 curveByteSize := 32 // this assumes P256 as coded above
145 key.X = make([]byte, curveByteSize)
146 key.Y = make([]byte, curveByteSize)
147 ecdsaPub.X.FillBytes(key.X)
148 ecdsaPub.Y.FillBytes(key.Y)
149
150 return key, nil
151 case azkeys.KeyTypeRSA, azkeys.KeyTypeRSAHSM:
152 privKey, err := rsa.GenerateKey(rand.Reader, 1024)
153 if err != nil {
154 return azkeys.JSONWebKey{}, err
155 }
156
157 rsaPub, ok := privKey.Public().(*rsa.PublicKey)
158 if !ok {
159 return azkeys.JSONWebKey{}, fmt.Errorf("failed to cast public key to rsa public key")
160 }
161
162 key.N = rsaPub.N.Bytes()
163 key.E = fmt.Append(nil, rsaPub.E)
164
165 return key, nil
166 default:
167 return azkeys.JSONWebKey{}, fmt.Errorf("invalid key type passed: %s", azureKeyType)
168 }
169 }
170
171 func TestAzureVaultClientFetchPublicKey(t *testing.T) {
172 keyTypes := []string{"EC", "EC-HSM", "RSA", "RSA-HSM"}
173
174 for _, keyType := range keyTypes {
175 key, err := generatePublicKey(keyType)
176 if err != nil {
177 t.Fatalf("unexpected error while generating public key for testing: %v", err)
178 }
179
180 kvClient := testKVClient{key: key}
181 client := azureVaultClient{
182 client: &kvClient,
183 }
184
185 _, err = client.fetchPublicKey(context.Background())
186 if err != nil {
187 t.Fatalf("expected error to be nil, actual value: %v", err)
188 }
189 }
190 }
191
192 func TestAzureVaultClientCreateKey(t *testing.T) {
193 type test struct {
194 name string
195 client kvClient
196 expectSuccess bool
197 }
198
199 key, err := generatePublicKey("EC")
200 if err != nil {
201 t.Fatalf("unexpected error while generating public key for testing: %v", err)
202 }
203
204 tests := []test{
205 {
206 name: "Successfully create key if it doesn't exist",
207 client: &keyNotFoundClient{
208 key: key,
209 getKeyReturnsErr: true,
210 getKeyCallThreshold: 1,
211 },
212 expectSuccess: true,
213 },
214 {
215 name: "Return public key if it already exists",
216 client: &testKVClient{
217 key: key,
218 },
219 expectSuccess: true,
220 },
221 {
222 name: "Fail to create key due to unknown error",
223 client: &nonResponseErrClient{},
224 expectSuccess: false,
225 },
226 {
227 name: "Fail to create key due to non-404 status code error",
228 client: &non404RespClient{},
229 expectSuccess: false,
230 },
231 }
232
233 for _, tc := range tests {
234 client := azureVaultClient{
235 client: tc.client,
236 keyCache: ttlcache.New[string, crypto.PublicKey](
237 ttlcache.WithDisableTouchOnHit[string, crypto.PublicKey](),
238 ),
239 }
240
241 _, err = client.createKey(context.Background())
242 if err != nil && tc.expectSuccess {
243 t.Fatalf("Test '%s' failed. Expected nil error, actual value: %v", tc.name, err)
244 }
245 if err == nil && !tc.expectSuccess {
246 t.Fatalf("Test '%s' failed. Expected non-nil error", tc.name)
247 }
248 }
249 }
250
251 func TestParseReference(t *testing.T) {
252 tests := []struct {
253 in string
254 wantVaultURL string
255 wantKeyName string
256 wantKeyVersion string
257 wantErr bool
258 }{
259 {
260 in: "azurekms://honk-vault.vault.azure.net/honk-key",
261 wantVaultURL: "https://honk-vault.vault.azure.net/",
262 wantKeyName: "honk-key",
263 wantKeyVersion: "",
264 wantErr: false,
265 },
266 {
267 in: "azurekms://honk-vault.vault.azure.net/honk-key/123abc",
268 wantVaultURL: "https://honk-vault.vault.azure.net/",
269 wantKeyName: "honk-key",
270 wantKeyVersion: "123abc",
271 wantErr: false,
272 },
273 {
274 in: "foo://bar",
275 wantErr: true,
276 },
277 {
278 in: "",
279 wantErr: true,
280 },
281 {
282 in: "azurekms://wrong-test/test/1/3",
283 wantErr: true,
284 },
285 }
286 for _, tt := range tests {
287 t.Run(tt.in, func(t *testing.T) {
288 gotVaultURL, gotKeyName, gotKeyVersion, err := parseReference(tt.in)
289 if (err != nil) != tt.wantErr {
290 t.Errorf("parseReference() error = %v, wantErr %v", err, tt.wantErr)
291 return
292 }
293 if gotVaultURL != tt.wantVaultURL {
294 t.Errorf("parseReference() gotVaultURL = %v, want %v", gotVaultURL, tt.wantVaultURL)
295 }
296 if gotKeyName != tt.wantKeyName {
297 t.Errorf("parseReference() gotKeyName = %v, want %v", gotKeyName, tt.wantKeyName)
298 }
299 if gotKeyVersion != tt.wantKeyVersion {
300 t.Errorf("parseReference() gotKeyVersion = %v, want %v", gotKeyVersion, tt.wantKeyVersion)
301 }
302 })
303 }
304 }