Debian Codegraph @

pkg/signature/kms/azure/client_test.go

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