| 1 |
package workloadservice |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/base64" |
| 7 |
"encoding/json" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"net/http" |
| 11 |
"net/http/httptest" |
| 12 |
"path/filepath" |
| 13 |
"strings" |
| 14 |
"testing" |
| 15 |
"time" |
| 16 |
|
| 17 |
kpskcc "github.com/google/go-tpm-tools/keymanager/key_protection_service/key_custody_core" |
| 18 |
"github.com/google/uuid" |
| 19 |
|
| 20 |
kps "github.com/google/go-tpm-tools/keymanager/key_protection_service" |
| 21 |
keymanager "github.com/google/go-tpm-tools/keymanager/km_common/proto" |
| 22 |
) |
| 23 |
|
| 24 |
func newTestServer(t *testing.T, kemGen kps.KeyProtectionService, bindingGen WorkloadService) *Server { |
| 25 |
srv, err := NewServer(kemGen, bindingGen, filepath.Join(t.TempDir(), "test.sock")) |
| 26 |
if err != nil { |
| 27 |
t.Fatalf("failed to create test server: %v", err) |
| 28 |
} |
| 29 |
t.Cleanup(func() { |
| 30 |
srv.listener.Close() |
| 31 |
close(srv.claimsChan) |
| 32 |
}) |
| 33 |
return srv |
| 34 |
} |
| 35 |
|
| 36 |
// mockWorkloadService implements WorkloadService for testing. |
| 37 |
type mockWorkloadService struct { |
| 38 |
uuid uuid.UUID |
| 39 |
pubKey []byte |
| 40 |
algo *keymanager.HpkeAlgorithm |
| 41 |
err error |
| 42 |
destroyErr error |
| 43 |
destroyedUUID uuid.UUID |
| 44 |
plaintext []byte |
| 45 |
receivedUUID uuid.UUID |
| 46 |
receivedEnc []byte |
| 47 |
receivedCT []byte |
| 48 |
receivedAAD []byte |
| 49 |
} |
| 50 |
|
| 51 |
func (m *mockWorkloadService) GenerateBindingKeypair(_ *keymanager.HpkeAlgorithm, _ uint64) (uuid.UUID, []byte, error) { |
| 52 |
return m.uuid, m.pubKey, m.err |
| 53 |
} |
| 54 |
|
| 55 |
func (m *mockWorkloadService) DestroyBindingKey(bindingUUID uuid.UUID) error { |
| 56 |
m.destroyedUUID = bindingUUID |
| 57 |
return m.destroyErr |
| 58 |
} |
| 59 |
|
| 60 |
func (m *mockWorkloadService) Open(bindingUUID uuid.UUID, enc, ciphertext, aad []byte) ([]byte, error) { |
| 61 |
m.receivedUUID = bindingUUID |
| 62 |
m.receivedEnc = enc |
| 63 |
m.receivedCT = ciphertext |
| 64 |
m.receivedAAD = aad |
| 65 |
return m.plaintext, m.err |
| 66 |
} |
| 67 |
|
| 68 |
func (m *mockWorkloadService) GetBindingKey(_ uuid.UUID) ([]byte, *keymanager.HpkeAlgorithm, error) { |
| 69 |
return m.pubKey, m.algo, m.err |
| 70 |
} |
| 71 |
|
| 72 |
// mockKeyProtectionService implements KeyProtectionService for testing. |
| 73 |
type mockKeyProtectionService struct { |
| 74 |
uuid uuid.UUID |
| 75 |
pubKey []byte |
| 76 |
bindingPubKey []byte |
| 77 |
algo *keymanager.HpkeAlgorithm |
| 78 |
remainingLifespanSecs uint64 |
| 79 |
err error |
| 80 |
destroyErr error |
| 81 |
destroyedUUID uuid.UUID |
| 82 |
receivedPubKey []byte |
| 83 |
receivedLifespan uint64 |
| 84 |
sealEnc []byte |
| 85 |
sealedCT []byte |
| 86 |
receivedKEMUUID uuid.UUID |
| 87 |
receivedEncKey []byte |
| 88 |
receivedAAD []byte |
| 89 |
enumeratedKeys []kpskcc.KEMKeyInfo |
| 90 |
enumerateErr error |
| 91 |
} |
| 92 |
|
| 93 |
func (m *mockKeyProtectionService) GenerateKEMKeypair(_ *keymanager.HpkeAlgorithm, bindingPubKey []byte, lifespanSecs uint64) (uuid.UUID, []byte, error) { |
| 94 |
m.receivedPubKey = bindingPubKey |
| 95 |
m.receivedLifespan = lifespanSecs |
| 96 |
return m.uuid, m.pubKey, m.err |
| 97 |
} |
| 98 |
|
| 99 |
func (m *mockKeyProtectionService) EnumerateKEMKeys(_, _ int) ([]kpskcc.KEMKeyInfo, bool, error) { |
| 100 |
return m.enumeratedKeys, false, m.enumerateErr |
| 101 |
} |
| 102 |
|
| 103 |
func (m *mockKeyProtectionService) DestroyKEMKey(kemUUID uuid.UUID) error { |
| 104 |
m.destroyedUUID = kemUUID |
| 105 |
return m.destroyErr |
| 106 |
} |
| 107 |
|
| 108 |
func (m *mockKeyProtectionService) DecapAndSeal(kemUUID uuid.UUID, encapsulatedKey, aad []byte) ([]byte, []byte, error) { |
| 109 |
m.receivedKEMUUID = kemUUID |
| 110 |
m.receivedEncKey = encapsulatedKey |
| 111 |
m.receivedAAD = aad |
| 112 |
return m.sealEnc, m.sealedCT, m.err |
| 113 |
} |
| 114 |
|
| 115 |
func (m *mockKeyProtectionService) GetKEMKey(_ uuid.UUID) ([]byte, []byte, *keymanager.HpkeAlgorithm, uint64, error) { |
| 116 |
return m.pubKey, m.bindingPubKey, m.algo, m.remainingLifespanSecs, m.err |
| 117 |
} |
| 118 |
|
| 119 |
func validGenerateBody() []byte { |
| 120 |
body, _ := json.Marshal(GenerateKeyRequest{ |
| 121 |
Algorithm: AlgorithmDetails{ |
| 122 |
Type: "kem", |
| 123 |
Params: AlgorithmParams{ |
| 124 |
KemID: KemAlgorithmDHKEMX25519HKDFSHA256, |
| 125 |
}, |
| 126 |
}, |
| 127 |
Lifespan: 3600, |
| 128 |
}) |
| 129 |
return body |
| 130 |
} |
| 131 |
|
| 132 |
// --- /keys:generate_kem tests --- |
| 133 |
|
| 134 |
func TestHandleGenerateKeySuccess(t *testing.T) { |
| 135 |
bindingUUID := uuid.New() |
| 136 |
kemUUID := uuid.New() |
| 137 |
bindingPubKey := make([]byte, 32) |
| 138 |
for i := range bindingPubKey { |
| 139 |
bindingPubKey[i] = byte(i) |
| 140 |
} |
| 141 |
kemPubKey := make([]byte, 32) |
| 142 |
for i := range kemPubKey { |
| 143 |
kemPubKey[i] = byte(i + 100) |
| 144 |
} |
| 145 |
|
| 146 |
kemGen := &mockKeyProtectionService{uuid: kemUUID, pubKey: kemPubKey} |
| 147 |
srv := newTestServer(t, |
| 148 |
kemGen, |
| 149 |
&mockWorkloadService{uuid: bindingUUID, pubKey: bindingPubKey}, |
| 150 |
) |
| 151 |
|
| 152 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader(validGenerateBody())) |
| 153 |
req.Header.Set("Content-Type", "application/json") |
| 154 |
w := httptest.NewRecorder() |
| 155 |
srv.Handler().ServeHTTP(w, req) |
| 156 |
|
| 157 |
if w.Code != http.StatusOK { |
| 158 |
t.Fatalf("expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 159 |
} |
| 160 |
|
| 161 |
var resp GenerateKeyResponse |
| 162 |
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { |
| 163 |
t.Fatalf("failed to decode response: %v", err) |
| 164 |
} |
| 165 |
if resp.KeyHandle.Handle != kemUUID.String() { |
| 166 |
t.Fatalf("expected KEM UUID %s, got %s", kemUUID, resp.KeyHandle.Handle) |
| 167 |
} |
| 168 |
if resp.PubKey.PublicKey != base64.StdEncoding.EncodeToString(kemPubKey) { |
| 169 |
t.Fatalf("expected KEM pub key %s, got %s", base64.StdEncoding.EncodeToString(kemPubKey), resp.PubKey.PublicKey) |
| 170 |
} |
| 171 |
if resp.KeyProtectionMechanism != keymanager.KeyProtectionMechanism_KEY_PROTECTION_VM_EMULATED.String() { |
| 172 |
t.Fatalf("expected %s, got %s", keymanager.KeyProtectionMechanism_KEY_PROTECTION_VM_EMULATED.String(), resp.KeyProtectionMechanism) |
| 173 |
} |
| 174 |
if resp.ExpirationTime <= time.Now().Unix() { |
| 175 |
t.Fatalf("expected expiration time in the future, got %d", resp.ExpirationTime) |
| 176 |
} |
| 177 |
|
| 178 |
// Verify the binding public key was passed to KEM generator. |
| 179 |
if len(kemGen.receivedPubKey) != 32 { |
| 180 |
t.Fatalf("expected 32-byte binding pub key passed to KEM gen, got %d", len(kemGen.receivedPubKey)) |
| 181 |
} |
| 182 |
for i, b := range kemGen.receivedPubKey { |
| 183 |
if b != byte(i) { |
| 184 |
t.Fatalf("binding pub key mismatch at index %d", i) |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
// Verify lifespanSecs was forwarded. |
| 189 |
if kemGen.receivedLifespan != 3600 { |
| 190 |
t.Fatalf("expected lifespanSecs 3600, got %d", kemGen.receivedLifespan) |
| 191 |
} |
| 192 |
|
| 193 |
// Verify the KEM → Binding mapping was stored. |
| 194 |
mappedBinding, ok := srv.LookupBindingUUID(kemUUID) |
| 195 |
if !ok { |
| 196 |
t.Fatal("expected KEM UUID to be in kemToBindingMap") |
| 197 |
} |
| 198 |
if mappedBinding != bindingUUID { |
| 199 |
t.Fatalf("expected mapped binding UUID %s, got %s", bindingUUID, mappedBinding) |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
func TestHandleGenerateKeyInvalidMethod(t *testing.T) { |
| 204 |
srv := newTestServer(t, |
| 205 |
&mockKeyProtectionService{pubKey: make([]byte, 32)}, |
| 206 |
&mockWorkloadService{pubKey: make([]byte, 32)}, |
| 207 |
) |
| 208 |
|
| 209 |
req := httptest.NewRequest(http.MethodGet, "/v1/keys:generate_key", nil) |
| 210 |
w := httptest.NewRecorder() |
| 211 |
srv.Handler().ServeHTTP(w, req) |
| 212 |
|
| 213 |
if w.Code != http.StatusMethodNotAllowed { |
| 214 |
t.Fatalf("expected status 405, got %d", w.Code) |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
func TestHandleGenerateKeyBadRequest(t *testing.T) { |
| 219 |
srv := newTestServer(t, |
| 220 |
&mockKeyProtectionService{uuid: uuid.New(), pubKey: make([]byte, 32)}, |
| 221 |
&mockWorkloadService{uuid: uuid.New(), pubKey: make([]byte, 32)}, |
| 222 |
) |
| 223 |
|
| 224 |
tests := []struct { |
| 225 |
name string |
| 226 |
body GenerateKeyRequest |
| 227 |
}{ |
| 228 |
{ |
| 229 |
name: "unsupported algorithm type", |
| 230 |
body: GenerateKeyRequest{Algorithm: AlgorithmDetails{Type: "mac", Params: AlgorithmParams{KemID: KemAlgorithmDHKEMX25519HKDFSHA256}}, Lifespan: 3600}, |
| 231 |
}, |
| 232 |
{ |
| 233 |
name: "unsupported algorithm", |
| 234 |
body: GenerateKeyRequest{Algorithm: AlgorithmDetails{Type: "kem", Params: AlgorithmParams{KemID: KemAlgorithmUnspecified}}, Lifespan: 3600}, |
| 235 |
}, |
| 236 |
{ |
| 237 |
name: "zero lifespan", |
| 238 |
body: GenerateKeyRequest{Algorithm: AlgorithmDetails{Type: "kem", Params: AlgorithmParams{KemID: KemAlgorithmDHKEMX25519HKDFSHA256}}, Lifespan: 0}, |
| 239 |
}, |
| 240 |
{ |
| 241 |
name: "missing algorithm (defaults to 0, type empty)", |
| 242 |
body: GenerateKeyRequest{Lifespan: 3600}, |
| 243 |
}, |
| 244 |
} |
| 245 |
|
| 246 |
for _, tc := range tests { |
| 247 |
t.Run(tc.name, func(t *testing.T) { |
| 248 |
body, _ := json.Marshal(tc.body) |
| 249 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader(body)) |
| 250 |
req.Header.Set("Content-Type", "application/json") |
| 251 |
w := httptest.NewRecorder() |
| 252 |
srv.Handler().ServeHTTP(w, req) |
| 253 |
|
| 254 |
if w.Code != http.StatusBadRequest { |
| 255 |
t.Fatalf("expected status 400, got %d: %s", w.Code, w.Body.String()) |
| 256 |
} |
| 257 |
|
| 258 |
if tc.name == "unsupported algorithm" { |
| 259 |
var resp map[string]string |
| 260 |
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { |
| 261 |
t.Fatalf("failed to decode response: %v", err) |
| 262 |
} |
| 263 |
expectedSubstr := "Supported algorithms: DHKEM_X25519_HKDF_SHA256" |
| 264 |
if errMsg, ok := resp["error"]; !ok || !strings.Contains(errMsg, expectedSubstr) { |
| 265 |
t.Errorf("expected error message to contain %q, got %q", expectedSubstr, errMsg) |
| 266 |
} |
| 267 |
} |
| 268 |
}) |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
func TestHandleGenerateKeyBadJSON(t *testing.T) { |
| 273 |
srv := newTestServer(t, |
| 274 |
&mockKeyProtectionService{pubKey: make([]byte, 32)}, |
| 275 |
&mockWorkloadService{pubKey: make([]byte, 32)}, |
| 276 |
) |
| 277 |
|
| 278 |
badBodies := []struct { |
| 279 |
name string |
| 280 |
body string |
| 281 |
}{ |
| 282 |
{"not json", "not json"}, |
| 283 |
{"lifespan as string", `{"algorithm":{"type":"kem","params":{"kem_id":"DHKEM_X25519_HKDF_SHA256"}},"lifespan":"3600"}`}, |
| 284 |
{"lifespan as string with suffix", `{"algorithm":{"type":"kem","params":{"kem_id":"DHKEM_X25519_HKDF_SHA256"}},"lifespan":"3600s"}`}, |
| 285 |
{"lifespan negative", `{"algorithm":{"type":"kem","params":{"kem_id":"DHKEM_X25519_HKDF_SHA256"}},"lifespan":-1}`}, |
| 286 |
{"lifespan too large", `{"algorithm":{"type":"kem","params":{"kem_id":"DHKEM_X25519_HKDF_SHA256"}},"lifespan":9223372036854775808}`}, |
| 287 |
} |
| 288 |
|
| 289 |
for _, tc := range badBodies { |
| 290 |
t.Run(tc.name, func(t *testing.T) { |
| 291 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader([]byte(tc.body))) |
| 292 |
req.Header.Set("Content-Type", "application/json") |
| 293 |
w := httptest.NewRecorder() |
| 294 |
srv.Handler().ServeHTTP(w, req) |
| 295 |
|
| 296 |
if w.Code != http.StatusBadRequest { |
| 297 |
t.Fatalf("expected status 400, got %d: %s", w.Code, w.Body.String()) |
| 298 |
} |
| 299 |
}) |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
func TestHandleGenerateKeyBindingGenError(t *testing.T) { |
| 304 |
srv := newTestServer(t, |
| 305 |
&mockKeyProtectionService{pubKey: make([]byte, 32)}, |
| 306 |
&mockWorkloadService{err: fmt.Errorf("binding FFI error")}, |
| 307 |
) |
| 308 |
|
| 309 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader(validGenerateBody())) |
| 310 |
req.Header.Set("Content-Type", "application/json") |
| 311 |
w := httptest.NewRecorder() |
| 312 |
srv.Handler().ServeHTTP(w, req) |
| 313 |
|
| 314 |
if w.Code != http.StatusInternalServerError { |
| 315 |
t.Fatalf("expected status 500, got %d", w.Code) |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
func TestHandleGenerateKeyFlexibleLifespan(t *testing.T) { |
| 320 |
srv := newTestServer(t, |
| 321 |
&mockKeyProtectionService{uuid: uuid.New(), pubKey: make([]byte, 32)}, |
| 322 |
&mockWorkloadService{uuid: uuid.New(), pubKey: make([]byte, 32)}, |
| 323 |
) |
| 324 |
|
| 325 |
tests := []struct { |
| 326 |
name string |
| 327 |
body string |
| 328 |
expected uint64 |
| 329 |
}{ |
| 330 |
{ |
| 331 |
name: "integer seconds", |
| 332 |
body: `{"algorithm":{"type":"kem","params":{"kem_id":"DHKEM_X25519_HKDF_SHA256"}},"lifespan":3600}`, |
| 333 |
expected: 3600, |
| 334 |
}, |
| 335 |
} |
| 336 |
|
| 337 |
for _, tc := range tests { |
| 338 |
t.Run(tc.name, func(t *testing.T) { |
| 339 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader([]byte(tc.body))) |
| 340 |
req.Header.Set("Content-Type", "application/json") |
| 341 |
w := httptest.NewRecorder() |
| 342 |
srv.Handler().ServeHTTP(w, req) |
| 343 |
|
| 344 |
if w.Code != http.StatusOK { |
| 345 |
t.Fatalf("expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 346 |
} |
| 347 |
}) |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
func TestHandleGenerateKeyKEMGenError(t *testing.T) { |
| 352 |
srv := newTestServer(t, |
| 353 |
&mockKeyProtectionService{err: fmt.Errorf("KEM FFI error")}, |
| 354 |
&mockWorkloadService{uuid: uuid.New(), pubKey: make([]byte, 32)}, |
| 355 |
) |
| 356 |
|
| 357 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader(validGenerateBody())) |
| 358 |
req.Header.Set("Content-Type", "application/json") |
| 359 |
w := httptest.NewRecorder() |
| 360 |
srv.Handler().ServeHTTP(w, req) |
| 361 |
|
| 362 |
if w.Code != http.StatusInternalServerError { |
| 363 |
t.Fatalf("expected status 500, got %d", w.Code) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
func TestHandleGenerateKeyMapUniqueness(t *testing.T) { |
| 368 |
bindingPubKey := make([]byte, 32) |
| 369 |
|
| 370 |
bindingUUID1 := uuid.New() |
| 371 |
bindingUUID2 := uuid.New() |
| 372 |
kemUUID1 := uuid.New() |
| 373 |
kemUUID2 := uuid.New() |
| 374 |
|
| 375 |
callCount := 0 |
| 376 |
bindingGen := &mockWorkloadService{} |
| 377 |
kemGen := &mockKeyProtectionService{} |
| 378 |
|
| 379 |
srv := newTestServer(t, kemGen, bindingGen) |
| 380 |
|
| 381 |
// First call. |
| 382 |
bindingGen.uuid = bindingUUID1 |
| 383 |
bindingGen.pubKey = bindingPubKey |
| 384 |
kemGen.uuid = kemUUID1 |
| 385 |
kemGen.pubKey = make([]byte, 32) |
| 386 |
|
| 387 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader(validGenerateBody())) |
| 388 |
req.Header.Set("Content-Type", "application/json") |
| 389 |
w := httptest.NewRecorder() |
| 390 |
srv.Handler().ServeHTTP(w, req) |
| 391 |
if w.Code != http.StatusOK { |
| 392 |
t.Fatalf("call 1: expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 393 |
} |
| 394 |
callCount++ |
| 395 |
|
| 396 |
// Second call. |
| 397 |
bindingGen.uuid = bindingUUID2 |
| 398 |
kemGen.uuid = kemUUID2 |
| 399 |
|
| 400 |
req = httptest.NewRequest(http.MethodPost, "/v1/keys:generate_key", bytes.NewReader(validGenerateBody())) |
| 401 |
req.Header.Set("Content-Type", "application/json") |
| 402 |
w = httptest.NewRecorder() |
| 403 |
srv.Handler().ServeHTTP(w, req) |
| 404 |
if w.Code != http.StatusOK { |
| 405 |
t.Fatalf("call 2: expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 406 |
} |
| 407 |
callCount++ |
| 408 |
|
| 409 |
// Verify both mappings exist. |
| 410 |
mapped1, ok := srv.LookupBindingUUID(kemUUID1) |
| 411 |
if !ok { |
| 412 |
t.Fatal("expected kemUUID1 in map") |
| 413 |
} |
| 414 |
if mapped1 != bindingUUID1 { |
| 415 |
t.Fatalf("expected binding UUID %s for kem UUID %s, got %s", bindingUUID1, kemUUID1, mapped1) |
| 416 |
} |
| 417 |
|
| 418 |
mapped2, ok := srv.LookupBindingUUID(kemUUID2) |
| 419 |
if !ok { |
| 420 |
t.Fatal("expected kemUUID2 in map") |
| 421 |
} |
| 422 |
if mapped2 != bindingUUID2 { |
| 423 |
t.Fatalf("expected binding UUID %s for kem UUID %s, got %s", bindingUUID2, kemUUID2, mapped2) |
| 424 |
} |
| 425 |
|
| 426 |
if callCount != 2 { |
| 427 |
t.Fatalf("expected 2 calls, got %d", callCount) |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
func TestHandleEnumerateKeysEmpty(t *testing.T) { |
| 432 |
srv := newTestServer(t, |
| 433 |
&mockKeyProtectionService{enumeratedKeys: []kpskcc.KEMKeyInfo{}}, |
| 434 |
&mockWorkloadService{}, |
| 435 |
) |
| 436 |
|
| 437 |
req := httptest.NewRequest(http.MethodGet, "/v1/keys", nil) |
| 438 |
w := httptest.NewRecorder() |
| 439 |
srv.Handler().ServeHTTP(w, req) |
| 440 |
|
| 441 |
if w.Code != http.StatusOK { |
| 442 |
t.Fatalf("expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 443 |
} |
| 444 |
|
| 445 |
var resp EnumerateKeysResponse |
| 446 |
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { |
| 447 |
t.Fatalf("failed to decode response: %v", err) |
| 448 |
} |
| 449 |
if len(resp.KeyInfos) != 0 { |
| 450 |
t.Fatalf("expected 0 key infos, got %d", len(resp.KeyInfos)) |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
func TestHandleEnumerateKeysWithKeys(t *testing.T) { |
| 455 |
kem1 := uuid.New() |
| 456 |
kem2 := uuid.New() |
| 457 |
kemPubKey1 := make([]byte, 32) |
| 458 |
kemPubKey2 := make([]byte, 32) |
| 459 |
// BindingPubKey no longer used in response |
| 460 |
for i := range kemPubKey1 { |
| 461 |
kemPubKey1[i] = byte(i) |
| 462 |
kemPubKey2[i] = byte(i + 50) |
| 463 |
} |
| 464 |
|
| 465 |
mockEnumKeys := []kpskcc.KEMKeyInfo{ |
| 466 |
{ |
| 467 |
ID: kem1, |
| 468 |
Algorithm: &keymanager.HpkeAlgorithm{ |
| 469 |
Kem: keymanager.KemAlgorithm_KEM_ALGORITHM_DHKEM_X25519_HKDF_SHA256, |
| 470 |
Kdf: keymanager.KdfAlgorithm_KDF_ALGORITHM_HKDF_SHA256, |
| 471 |
Aead: keymanager.AeadAlgorithm_AEAD_ALGORITHM_AES_256_GCM, |
| 472 |
}, |
| 473 |
KEMPubKey: kemPubKey1, |
| 474 |
RemainingLifespanSecs: 3500, |
| 475 |
}, |
| 476 |
{ |
| 477 |
ID: kem2, |
| 478 |
Algorithm: &keymanager.HpkeAlgorithm{ |
| 479 |
Kem: keymanager.KemAlgorithm_KEM_ALGORITHM_DHKEM_X25519_HKDF_SHA256, |
| 480 |
Kdf: keymanager.KdfAlgorithm_KDF_ALGORITHM_HKDF_SHA256, |
| 481 |
Aead: keymanager.AeadAlgorithm_AEAD_ALGORITHM_AES_256_GCM, |
| 482 |
}, |
| 483 |
KEMPubKey: kemPubKey2, |
| 484 |
RemainingLifespanSecs: 7100, |
| 485 |
}, |
| 486 |
} |
| 487 |
|
| 488 |
srv := newTestServer(t, |
| 489 |
&mockKeyProtectionService{enumeratedKeys: mockEnumKeys}, |
| 490 |
&mockWorkloadService{}, |
| 491 |
) |
| 492 |
|
| 493 |
req := httptest.NewRequest(http.MethodGet, "/v1/keys", nil) |
| 494 |
w := httptest.NewRecorder() |
| 495 |
srv.Handler().ServeHTTP(w, req) |
| 496 |
|
| 497 |
if w.Code != http.StatusOK { |
| 498 |
t.Fatalf("expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 499 |
} |
| 500 |
|
| 501 |
var resp EnumerateKeysResponse |
| 502 |
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { |
| 503 |
t.Fatalf("failed to decode response: %v", err) |
| 504 |
} |
| 505 |
if len(resp.KeyInfos) != 2 { |
| 506 |
t.Fatalf("expected 2 key infos, got %d", len(resp.KeyInfos)) |
| 507 |
} |
| 508 |
|
| 509 |
// Verify both keys appear (order-independent). |
| 510 |
found := make(map[string]*KeyInfo) |
| 511 |
for i := range resp.KeyInfos { |
| 512 |
ki := &resp.KeyInfos[i] |
| 513 |
found[ki.KeyHandle.Handle] = ki |
| 514 |
} |
| 515 |
|
| 516 |
// Verify key 1. |
| 517 |
info1, ok := found[kem1.String()] |
| 518 |
if !ok { |
| 519 |
t.Fatalf("expected kem1 %s in response", kem1) |
| 520 |
} |
| 521 |
if info1.PubKey.Algorithm.Params.KemID != KemAlgorithmDHKEMX25519HKDFSHA256 { |
| 522 |
t.Fatalf("expected algorithm %v, got %v", KemAlgorithmDHKEMX25519HKDFSHA256, info1.PubKey.Algorithm.Params.KemID) |
| 523 |
} |
| 524 |
if info1.PubKey.PublicKey != base64.StdEncoding.EncodeToString(kemPubKey1) { |
| 525 |
t.Fatalf("KEM pub key mismatch for kem1") |
| 526 |
} |
| 527 |
if info1.KeyProtectionMechanism != keymanager.KeyProtectionMechanism_KEY_PROTECTION_VM_EMULATED.String() { |
| 528 |
t.Fatalf("expected key protection mechanism %s, got %s", keymanager.KeyProtectionMechanism_KEY_PROTECTION_VM_EMULATED.String(), info1.KeyProtectionMechanism) |
| 529 |
} |
| 530 |
// Approximate check for expiration time |
| 531 |
if info1.ExpirationTime <= time.Now().Unix() { |
| 532 |
t.Fatalf("expected expiration time in the future, got %d", info1.ExpirationTime) |
| 533 |
} |
| 534 |
|
| 535 |
// Verify key 2. |
| 536 |
info2, ok := found[kem2.String()] |
| 537 |
if !ok { |
| 538 |
t.Fatalf("expected kem2 %s in response", kem2) |
| 539 |
} |
| 540 |
// Approximate check for expiration time |
| 541 |
if info2.ExpirationTime <= time.Now().Unix() { |
| 542 |
t.Fatalf("expected expiration time in the future, got %d", info2.ExpirationTime) |
| 543 |
} |
| 544 |
} |
| 545 |
|
| 546 |
func TestHandleEnumerateKeysMethodNotAllowed(t *testing.T) { |
| 547 |
srv := newTestServer(t, |
| 548 |
&mockKeyProtectionService{}, |
| 549 |
&mockWorkloadService{}, |
| 550 |
) |
| 551 |
|
| 552 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys", nil) |
| 553 |
w := httptest.NewRecorder() |
| 554 |
srv.Handler().ServeHTTP(w, req) |
| 555 |
|
| 556 |
if w.Code != http.StatusMethodNotAllowed { |
| 557 |
t.Fatalf("expected status 405, got %d", w.Code) |
| 558 |
} |
| 559 |
} |
| 560 |
|
| 561 |
func TestHandleEnumerateKeysError(t *testing.T) { |
| 562 |
srv := newTestServer(t, |
| 563 |
&mockKeyProtectionService{enumerateErr: fmt.Errorf("enumerate error")}, |
| 564 |
&mockWorkloadService{}, |
| 565 |
) |
| 566 |
|
| 567 |
req := httptest.NewRequest(http.MethodGet, "/v1/keys", nil) |
| 568 |
w := httptest.NewRecorder() |
| 569 |
srv.Handler().ServeHTTP(w, req) |
| 570 |
|
| 571 |
if w.Code != http.StatusInternalServerError { |
| 572 |
t.Fatalf("expected status 500, got %d: %s", w.Code, w.Body.String()) |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
func TestToHpkeAlgorithm(t *testing.T) { |
| 577 |
tests := []struct { |
| 578 |
input KemAlgorithm |
| 579 |
want *keymanager.HpkeAlgorithm |
| 580 |
wantErr bool |
| 581 |
}{ |
| 582 |
{ |
| 583 |
input: KemAlgorithmDHKEMX25519HKDFSHA256, |
| 584 |
want: &keymanager.HpkeAlgorithm{ |
| 585 |
Kem: keymanager.KemAlgorithm_KEM_ALGORITHM_DHKEM_X25519_HKDF_SHA256, |
| 586 |
Kdf: keymanager.KdfAlgorithm_KDF_ALGORITHM_HKDF_SHA256, |
| 587 |
Aead: keymanager.AeadAlgorithm_AEAD_ALGORITHM_AES_256_GCM, |
| 588 |
}, |
| 589 |
wantErr: false, |
| 590 |
}, |
| 591 |
{ |
| 592 |
input: KemAlgorithmUnspecified, |
| 593 |
want: nil, |
| 594 |
wantErr: true, |
| 595 |
}, |
| 596 |
{ |
| 597 |
input: KemAlgorithm(999), |
| 598 |
want: nil, |
| 599 |
wantErr: true, |
| 600 |
}, |
| 601 |
} |
| 602 |
|
| 603 |
for _, tc := range tests { |
| 604 |
t.Run(fmt.Sprintf("%v", tc.input), func(t *testing.T) { |
| 605 |
got, err := tc.input.ToHpkeAlgorithm() |
| 606 |
if (err != nil) != tc.wantErr { |
| 607 |
t.Errorf("ToHpkeAlgorithm() error = %v, wantErr %v", err, tc.wantErr) |
| 608 |
return |
| 609 |
} |
| 610 |
if !tc.wantErr { |
| 611 |
if got.Kem != tc.want.Kem || got.Kdf != tc.want.Kdf || got.Aead != tc.want.Aead { |
| 612 |
t.Errorf("ToHpkeAlgorithm() = %v, want %v", got, tc.want) |
| 613 |
} |
| 614 |
} |
| 615 |
}) |
| 616 |
} |
| 617 |
} |
| 618 |
|
| 619 |
func TestHandleGetCapabilities(t *testing.T) { |
| 620 |
bindingGen := &mockWorkloadService{} |
| 621 |
kemGen := &mockKeyProtectionService{} |
| 622 |
srv := newTestServer(t, |
| 623 |
kemGen, |
| 624 |
bindingGen, |
| 625 |
) |
| 626 |
|
| 627 |
req := httptest.NewRequest(http.MethodGet, "/v1/capabilities", nil) |
| 628 |
w := httptest.NewRecorder() |
| 629 |
srv.Handler().ServeHTTP(w, req) |
| 630 |
|
| 631 |
if w.Code != http.StatusOK { |
| 632 |
t.Fatalf("expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 633 |
} |
| 634 |
|
| 635 |
contentType := w.Header().Get("Content-Type") |
| 636 |
if contentType != "application/json" { |
| 637 |
t.Fatalf("expected Content-Type application/json, got %s", contentType) |
| 638 |
} |
| 639 |
|
| 640 |
var resp GetCapabilitiesResponse |
| 641 |
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { |
| 642 |
t.Fatalf("failed to decode response: %v", err) |
| 643 |
} |
| 644 |
|
| 645 |
if len(resp.SupportedAlgorithms) != 1 || |
| 646 |
resp.SupportedAlgorithms[0].Algorithm.Params.KemID != KemAlgorithmDHKEMX25519HKDFSHA256 || |
| 647 |
resp.SupportedAlgorithms[0].Algorithm.Type != "kem" { |
| 648 |
t.Errorf("unexpected supported algorithms: %v", resp.SupportedAlgorithms) |
| 649 |
} |
| 650 |
} |
| 651 |
|
| 652 |
func TestProcessClaims(t *testing.T) { |
| 653 |
bindingUUID := uuid.New() |
| 654 |
kemUUID := uuid.New() |
| 655 |
bindingPubKey := make([]byte, 32) |
| 656 |
for i := range bindingPubKey { |
| 657 |
bindingPubKey[i] = byte(i + 1) |
| 658 |
} |
| 659 |
kemPubKey := make([]byte, 32) |
| 660 |
for i := range kemPubKey { |
| 661 |
kemPubKey[i] = byte(i + 100) |
| 662 |
} |
| 663 |
|
| 664 |
expectedAlgo := &keymanager.HpkeAlgorithm{ |
| 665 |
Kem: keymanager.KemAlgorithm_KEM_ALGORITHM_DHKEM_X25519_HKDF_SHA256, |
| 666 |
Kdf: keymanager.KdfAlgorithm_KDF_ALGORITHM_HKDF_SHA256, |
| 667 |
Aead: keymanager.AeadAlgorithm_AEAD_ALGORITHM_AES_256_GCM, |
| 668 |
} |
| 669 |
|
| 670 |
ws := &mockWorkloadService{ |
| 671 |
uuid: bindingUUID, |
| 672 |
pubKey: bindingPubKey, |
| 673 |
algo: expectedAlgo, |
| 674 |
} |
| 675 |
kps := &mockKeyProtectionService{ |
| 676 |
uuid: kemUUID, |
| 677 |
pubKey: kemPubKey, |
| 678 |
bindingPubKey: bindingPubKey, |
| 679 |
algo: expectedAlgo, |
| 680 |
remainingLifespanSecs: 3600, |
| 681 |
} |
| 682 |
|
| 683 |
srv := newTestServer(t, kps, ws) |
| 684 |
// Populate kemToBindingMap for the claims test. |
| 685 |
srv.kemToBindingMap[kemUUID] = bindingUUID |
| 686 |
|
| 687 |
t.Run("BindingClaims", func(t *testing.T) { |
| 688 |
respChan := make(chan *ClaimsResult, 1) |
| 689 |
req := &keymanager.GetKeyClaimsRequest{ |
| 690 |
KeyHandle: &keymanager.KeyHandle{Handle: kemUUID.String()}, |
| 691 |
KeyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 692 |
} |
| 693 |
srv.claimsChan <- &ClaimsCall{Request: req, RespChan: respChan} |
| 694 |
|
| 695 |
select { |
| 696 |
case res := <-respChan: |
| 697 |
if res.Err != nil { |
| 698 |
t.Fatalf("unexpected error: %v", res.Err) |
| 699 |
} |
| 700 |
claims := res.Reply.GetVmBindingClaims() |
| 701 |
if claims == nil { |
| 702 |
t.Fatal("expected VmBindingClaims") |
| 703 |
} |
| 704 |
if !bytes.Equal(claims.BindingPubKey.PublicKey, bindingPubKey) { |
| 705 |
t.Errorf("expected binding pubkey %v, got %v", bindingPubKey, claims.BindingPubKey.PublicKey) |
| 706 |
} |
| 707 |
if claims.BindingPubKey.Algorithm.Kem != expectedAlgo.Kem || |
| 708 |
claims.BindingPubKey.Algorithm.Kdf != expectedAlgo.Kdf || |
| 709 |
claims.BindingPubKey.Algorithm.Aead != expectedAlgo.Aead { |
| 710 |
t.Errorf("expected binding algorithm %v, got %v", expectedAlgo, claims.BindingPubKey.Algorithm) |
| 711 |
} |
| 712 |
case <-time.After(2 * time.Second): |
| 713 |
t.Fatal("timed out waiting for response") |
| 714 |
} |
| 715 |
}) |
| 716 |
|
| 717 |
t.Run("KemClaims", func(t *testing.T) { |
| 718 |
respChan := make(chan *ClaimsResult, 1) |
| 719 |
req := &keymanager.GetKeyClaimsRequest{ |
| 720 |
KeyHandle: &keymanager.KeyHandle{Handle: kemUUID.String()}, |
| 721 |
KeyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_KEY, |
| 722 |
} |
| 723 |
srv.claimsChan <- &ClaimsCall{Request: req, RespChan: respChan} |
| 724 |
|
| 725 |
select { |
| 726 |
case res := <-respChan: |
| 727 |
if res.Err != nil { |
| 728 |
t.Fatalf("unexpected error: %v", res.Err) |
| 729 |
} |
| 730 |
claims := res.Reply.GetVmKeyClaims() |
| 731 |
if claims == nil { |
| 732 |
t.Fatal("expected VmKeyClaims") |
| 733 |
} |
| 734 |
if !bytes.Equal(claims.KemPubKey.PublicKey, kemPubKey) { |
| 735 |
t.Errorf("expected KEM pubkey %v, got %v", kemPubKey, claims.KemPubKey.PublicKey) |
| 736 |
} |
| 737 |
if claims.KemPubKey.Algorithm != expectedAlgo.Kem { |
| 738 |
t.Errorf("expected KEM algorithm %v, got %v", expectedAlgo.Kem, claims.KemPubKey.Algorithm) |
| 739 |
} |
| 740 |
if !bytes.Equal(claims.BindingPubKey.PublicKey, bindingPubKey) { |
| 741 |
t.Errorf("expected binding pubkey %v, got %v", bindingPubKey, claims.BindingPubKey.PublicKey) |
| 742 |
} |
| 743 |
if claims.BindingPubKey.Algorithm.Kem != expectedAlgo.Kem || |
| 744 |
claims.BindingPubKey.Algorithm.Kdf != expectedAlgo.Kdf || |
| 745 |
claims.BindingPubKey.Algorithm.Aead != expectedAlgo.Aead { |
| 746 |
t.Errorf("expected binding algorithm %v, got %v", expectedAlgo, claims.BindingPubKey.Algorithm) |
| 747 |
} |
| 748 |
if claims.RemainingLifespan.AsDuration() <= 0 { |
| 749 |
t.Errorf("expected positive remaining lifespan, got %v", claims.RemainingLifespan.AsDuration()) |
| 750 |
} |
| 751 |
case <-time.After(2 * time.Second): |
| 752 |
t.Fatal("timed out waiting for response") |
| 753 |
} |
| 754 |
}) |
| 755 |
|
| 756 |
t.Run("InvalidUUID", func(t *testing.T) { |
| 757 |
respChan := make(chan *ClaimsResult, 1) |
| 758 |
req := &keymanager.GetKeyClaimsRequest{ |
| 759 |
KeyHandle: &keymanager.KeyHandle{Handle: "invalid-uuid"}, |
| 760 |
KeyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 761 |
} |
| 762 |
srv.claimsChan <- &ClaimsCall{Request: req, RespChan: respChan} |
| 763 |
|
| 764 |
select { |
| 765 |
case res := <-respChan: |
| 766 |
if res.Err == nil { |
| 767 |
t.Fatal("expected error for invalid UUID") |
| 768 |
} |
| 769 |
case <-time.After(2 * time.Second): |
| 770 |
t.Fatal("timed out waiting for response") |
| 771 |
} |
| 772 |
}) |
| 773 |
|
| 774 |
t.Run("UnsupportedKeyType", func(t *testing.T) { |
| 775 |
respChan := make(chan *ClaimsResult, 1) |
| 776 |
req := &keymanager.GetKeyClaimsRequest{ |
| 777 |
KeyHandle: &keymanager.KeyHandle{Handle: bindingUUID.String()}, |
| 778 |
KeyType: keymanager.KeyType_KEY_TYPE_UNSPECIFIED, |
| 779 |
} |
| 780 |
srv.claimsChan <- &ClaimsCall{Request: req, RespChan: respChan} |
| 781 |
|
| 782 |
select { |
| 783 |
case res := <-respChan: |
| 784 |
if res.Err == nil { |
| 785 |
t.Fatal("expected error for unsupported key type") |
| 786 |
} |
| 787 |
if !strings.Contains(res.Err.Error(), "unsupported key type") { |
| 788 |
t.Errorf("expected error to contain 'unsupported key type', got %v", res.Err) |
| 789 |
} |
| 790 |
case <-time.After(2 * time.Second): |
| 791 |
t.Fatal("timed out waiting for response") |
| 792 |
} |
| 793 |
}) |
| 794 |
|
| 795 |
t.Run("BindingKeyNotFound", func(t *testing.T) { |
| 796 |
respChan := make(chan *ClaimsResult, 1) |
| 797 |
// Use a random UUID that isn't the mock's UUID |
| 798 |
notFoundUUID := uuid.New() |
| 799 |
req := &keymanager.GetKeyClaimsRequest{ |
| 800 |
KeyHandle: &keymanager.KeyHandle{Handle: notFoundUUID.String()}, |
| 801 |
KeyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 802 |
} |
| 803 |
|
| 804 |
// Update mock to return error for anything other than its set UUID |
| 805 |
// Actually, the current mock returns its fixed pubKey/err regardless of input ID. |
| 806 |
// Let's create a new server with a mock that returns error. |
| 807 |
wsErr := &mockWorkloadService{err: fmt.Errorf("not found")} |
| 808 |
srvErr := newTestServer(t, kps, wsErr) |
| 809 |
|
| 810 |
srvErr.claimsChan <- &ClaimsCall{Request: req, RespChan: respChan} |
| 811 |
|
| 812 |
select { |
| 813 |
case res := <-respChan: |
| 814 |
if res.Err == nil { |
| 815 |
t.Fatal("expected error for binding key not found") |
| 816 |
} |
| 817 |
if !strings.Contains(res.Err.Error(), "failed to retrieve binding key claims") { |
| 818 |
t.Errorf("expected error to contain 'failed to retrieve binding key claims', got %v", res.Err) |
| 819 |
} |
| 820 |
case <-time.After(2 * time.Second): |
| 821 |
t.Fatal("timed out waiting for response") |
| 822 |
} |
| 823 |
}) |
| 824 |
|
| 825 |
t.Run("KemKeyNotFound", func(t *testing.T) { |
| 826 |
respChan := make(chan *ClaimsResult, 1) |
| 827 |
req := &keymanager.GetKeyClaimsRequest{ |
| 828 |
KeyHandle: &keymanager.KeyHandle{Handle: kemUUID.String()}, |
| 829 |
KeyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_KEY, |
| 830 |
} |
| 831 |
|
| 832 |
kpsErr := &mockKeyProtectionService{err: fmt.Errorf("not found")} |
| 833 |
srvErr := newTestServer(t, kpsErr, ws) |
| 834 |
|
| 835 |
srvErr.claimsChan <- &ClaimsCall{Request: req, RespChan: respChan} |
| 836 |
|
| 837 |
select { |
| 838 |
case res := <-respChan: |
| 839 |
if res.Err == nil { |
| 840 |
t.Fatal("expected error for KEM key not found") |
| 841 |
} |
| 842 |
if !strings.Contains(res.Err.Error(), "failed to get KEM key") { |
| 843 |
t.Errorf("expected error to contain 'failed to get KEM key', got %v", res.Err) |
| 844 |
} |
| 845 |
case <-time.After(2 * time.Second): |
| 846 |
t.Fatal("timed out waiting for response") |
| 847 |
} |
| 848 |
}) |
| 849 |
} |
| 850 |
|
| 851 |
func TestHandleGetCapabilitiesInvalidMethod(t *testing.T) { |
| 852 |
bindingGen := &mockWorkloadService{} |
| 853 |
kemGen := &mockKeyProtectionService{} |
| 854 |
srv := newTestServer(t, |
| 855 |
kemGen, |
| 856 |
bindingGen, |
| 857 |
) |
| 858 |
|
| 859 |
req := httptest.NewRequest(http.MethodPost, "/v1/capabilities", nil) |
| 860 |
w := httptest.NewRecorder() |
| 861 |
srv.Handler().ServeHTTP(w, req) |
| 862 |
|
| 863 |
if w.Code != http.StatusMethodNotAllowed { |
| 864 |
t.Fatalf("expected status 405, got %d", w.Code) |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
func validDestroyBody(handle string) []byte { |
| 869 |
body, _ := json.Marshal(DestroyRequest{ |
| 870 |
KeyHandle: KeyHandle{Handle: handle}, |
| 871 |
}) |
| 872 |
return body |
| 873 |
} |
| 874 |
|
| 875 |
func TestHandleDestroy(t *testing.T) { |
| 876 |
validKEMUUID := uuid.New() |
| 877 |
validBindingUUID := uuid.New() |
| 878 |
|
| 879 |
tests := []struct { |
| 880 |
name string |
| 881 |
method string |
| 882 |
body []byte |
| 883 |
setupMap bool |
| 884 |
kemDestroyerErr error |
| 885 |
bindingDestroyerErr error |
| 886 |
expectedStatus int |
| 887 |
expectKEMDestroyed bool |
| 888 |
expectBindingDestroyed bool |
| 889 |
expectMapRemoved bool |
| 890 |
}{ |
| 891 |
{ |
| 892 |
name: "success", |
| 893 |
method: http.MethodPost, |
| 894 |
body: validDestroyBody(validKEMUUID.String()), |
| 895 |
setupMap: true, |
| 896 |
expectedStatus: http.StatusNoContent, |
| 897 |
expectKEMDestroyed: true, |
| 898 |
expectBindingDestroyed: true, |
| 899 |
expectMapRemoved: true, |
| 900 |
}, |
| 901 |
{ |
| 902 |
name: "invalid method", |
| 903 |
method: http.MethodGet, |
| 904 |
body: nil, |
| 905 |
expectedStatus: http.StatusMethodNotAllowed, |
| 906 |
}, |
| 907 |
{ |
| 908 |
name: "bad json", |
| 909 |
method: http.MethodPost, |
| 910 |
body: []byte("not json"), |
| 911 |
expectedStatus: http.StatusBadRequest, |
| 912 |
}, |
| 913 |
{ |
| 914 |
name: "invalid uuid", |
| 915 |
method: http.MethodPost, |
| 916 |
body: validDestroyBody("invalid-uuid"), |
| 917 |
expectedStatus: http.StatusBadRequest, |
| 918 |
}, |
| 919 |
{ |
| 920 |
name: "key not found", |
| 921 |
method: http.MethodPost, |
| 922 |
body: validDestroyBody(uuid.New().String()), |
| 923 |
setupMap: false, |
| 924 |
expectedStatus: http.StatusNotFound, |
| 925 |
}, |
| 926 |
{ |
| 927 |
name: "kps failure", |
| 928 |
method: http.MethodPost, |
| 929 |
body: validDestroyBody(validKEMUUID.String()), |
| 930 |
setupMap: true, |
| 931 |
kemDestroyerErr: fmt.Errorf("KPS error"), |
| 932 |
expectedStatus: http.StatusInternalServerError, |
| 933 |
expectBindingDestroyed: true, |
| 934 |
expectMapRemoved: true, |
| 935 |
}, |
| 936 |
{ |
| 937 |
name: "binding failure", |
| 938 |
method: http.MethodPost, |
| 939 |
body: validDestroyBody(validKEMUUID.String()), |
| 940 |
setupMap: true, |
| 941 |
bindingDestroyerErr: fmt.Errorf("Binding error"), |
| 942 |
expectedStatus: http.StatusInternalServerError, |
| 943 |
expectKEMDestroyed: true, |
| 944 |
expectMapRemoved: true, |
| 945 |
}, |
| 946 |
} |
| 947 |
|
| 948 |
for _, tc := range tests { |
| 949 |
t.Run(tc.name, func(t *testing.T) { |
| 950 |
kemDestroyer := &mockKeyProtectionService{destroyErr: tc.kemDestroyerErr} |
| 951 |
bindingDestroyer := &mockWorkloadService{destroyErr: tc.bindingDestroyerErr} |
| 952 |
|
| 953 |
srv := newTestServer(t, kemDestroyer, bindingDestroyer) |
| 954 |
|
| 955 |
if tc.setupMap { |
| 956 |
srv.mu.Lock() |
| 957 |
srv.kemToBindingMap[validKEMUUID] = validBindingUUID |
| 958 |
srv.mu.Unlock() |
| 959 |
} |
| 960 |
|
| 961 |
req := httptest.NewRequest(tc.method, "/v1/keys:destroy", bytes.NewReader(tc.body)) |
| 962 |
if tc.body != nil { |
| 963 |
req.Header.Set("Content-Type", "application/json") |
| 964 |
} |
| 965 |
w := httptest.NewRecorder() |
| 966 |
srv.Handler().ServeHTTP(w, req) |
| 967 |
|
| 968 |
if w.Code != tc.expectedStatus { |
| 969 |
t.Fatalf("expected status %d, got %d: %s", tc.expectedStatus, w.Code, w.Body.String()) |
| 970 |
} |
| 971 |
|
| 972 |
if tc.expectKEMDestroyed { |
| 973 |
if kemDestroyer.destroyedUUID != validKEMUUID { |
| 974 |
t.Fatalf("expected KEM destroy for %s, got %s", validKEMUUID, kemDestroyer.destroyedUUID) |
| 975 |
} |
| 976 |
} |
| 977 |
|
| 978 |
if tc.expectBindingDestroyed { |
| 979 |
if bindingDestroyer.destroyedUUID != validBindingUUID { |
| 980 |
t.Fatalf("expected Binding destroy for %s, got %s", validBindingUUID, bindingDestroyer.destroyedUUID) |
| 981 |
} |
| 982 |
} |
| 983 |
|
| 984 |
if tc.setupMap { |
| 985 |
_, ok := srv.LookupBindingUUID(validKEMUUID) |
| 986 |
if tc.expectMapRemoved && ok { |
| 987 |
t.Fatalf("expected KEM UUID to be removed from map") |
| 988 |
} else if !tc.expectMapRemoved && !ok { |
| 989 |
t.Fatalf("expected KEM UUID to persist in map on failure") |
| 990 |
} |
| 991 |
} |
| 992 |
}) |
| 993 |
} |
| 994 |
} |
| 995 |
|
| 996 |
// --- /keys:decap tests --- |
| 997 |
|
| 998 |
// newDecapsTestServer creates a server pre-populated with a KEM→Binding mapping. |
| 999 |
func newDecapsTestServer(t *testing.T, kemUUID, bindingUUID uuid.UUID, ds *mockKeyProtectionService, op *mockWorkloadService) *Server { |
| 1000 |
srv := newTestServer(t, ds, op) |
| 1001 |
srv.mu.Lock() |
| 1002 |
srv.kemToBindingMap[kemUUID] = bindingUUID |
| 1003 |
srv.mu.Unlock() |
| 1004 |
return srv |
| 1005 |
} |
| 1006 |
|
| 1007 |
func decapsRequestBody(kemUUID uuid.UUID, algo KemAlgorithm, encKey []byte) string { |
| 1008 |
return fmt.Sprintf( |
| 1009 |
`{"key_handle":{"handle":"%s"},"ciphertext":{"algorithm":"%s","ciphertext":"%s"}}`, |
| 1010 |
kemUUID.String(), |
| 1011 |
algo.String(), |
| 1012 |
base64.StdEncoding.EncodeToString(encKey), |
| 1013 |
) |
| 1014 |
} |
| 1015 |
|
| 1016 |
func TestHandleDecapsSuccess(t *testing.T) { |
| 1017 |
kemUUID := uuid.New() |
| 1018 |
bindingUUID := uuid.New() |
| 1019 |
encKey := []byte("test-encapsulated-key-32-bytes!!") |
| 1020 |
sealEnc := []byte("seal-encapsulated-key-32-bytes!!") |
| 1021 |
sealedCT := []byte("sealed-ciphertext-48-bytes-with-tag!!!!!!!!!!!!!!") |
| 1022 |
plaintext := []byte("shared-secret-32-bytes-value!!!!") // 32 bytes |
| 1023 |
expectedAAD := decapsAADContext(kemUUID, KemAlgorithmDHKEMX25519HKDFSHA256) |
| 1024 |
|
| 1025 |
ds := &mockKeyProtectionService{sealEnc: sealEnc, sealedCT: sealedCT} |
| 1026 |
op := &mockWorkloadService{plaintext: plaintext} |
| 1027 |
srv := newDecapsTestServer(t, kemUUID, bindingUUID, ds, op) |
| 1028 |
|
| 1029 |
body := decapsRequestBody(kemUUID, KemAlgorithmDHKEMX25519HKDFSHA256, encKey) |
| 1030 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:decap", strings.NewReader(body)) |
| 1031 |
w := httptest.NewRecorder() |
| 1032 |
srv.Handler().ServeHTTP(w, req) |
| 1033 |
|
| 1034 |
if w.Code != http.StatusOK { |
| 1035 |
t.Fatalf("expected status 200, got %d: %s", w.Code, w.Body.String()) |
| 1036 |
} |
| 1037 |
|
| 1038 |
var resp DecapsResponse |
| 1039 |
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { |
| 1040 |
t.Fatalf("failed to decode response: %v", err) |
| 1041 |
} |
| 1042 |
if resp.SharedSecret.Algorithm != KemAlgorithmDHKEMX25519HKDFSHA256 { |
| 1043 |
t.Fatalf("expected shared_secret.algorithm=%d, got %d", KemAlgorithmDHKEMX25519HKDFSHA256, resp.SharedSecret.Algorithm) |
| 1044 |
} |
| 1045 |
|
| 1046 |
decoded, err := base64.StdEncoding.DecodeString(resp.SharedSecret.Secret) |
| 1047 |
if err != nil { |
| 1048 |
t.Fatalf("failed to base64-decode shared secret: %v", err) |
| 1049 |
} |
| 1050 |
if string(decoded) != string(plaintext) { |
| 1051 |
t.Fatalf("expected plaintext %q, got %q", plaintext, decoded) |
| 1052 |
} |
| 1053 |
|
| 1054 |
// Verify KeyProtectionService received correct args. |
| 1055 |
if ds.receivedKEMUUID != kemUUID { |
| 1056 |
t.Fatalf("expected KeyProtectionService to receive KEM UUID %s, got %s", kemUUID, ds.receivedKEMUUID) |
| 1057 |
} |
| 1058 |
if string(ds.receivedEncKey) != string(encKey) { |
| 1059 |
t.Fatalf("expected KeyProtectionService to receive enc key %q, got %q", encKey, ds.receivedEncKey) |
| 1060 |
} |
| 1061 |
if string(ds.receivedAAD) != string(expectedAAD) { |
| 1062 |
t.Fatalf("expected KeyProtectionService to receive AAD %q, got %q", expectedAAD, ds.receivedAAD) |
| 1063 |
} |
| 1064 |
|
| 1065 |
// Verify WorkloadService received correct args. |
| 1066 |
if op.receivedUUID != bindingUUID { |
| 1067 |
t.Fatalf("expected WorkloadService to receive binding UUID %s, got %s", bindingUUID, op.receivedUUID) |
| 1068 |
} |
| 1069 |
if string(op.receivedEnc) != string(sealEnc) { |
| 1070 |
t.Fatalf("expected WorkloadService to receive enc %q, got %q", sealEnc, op.receivedEnc) |
| 1071 |
} |
| 1072 |
if string(op.receivedCT) != string(sealedCT) { |
| 1073 |
t.Fatalf("expected WorkloadService to receive CT %q, got %q", sealedCT, op.receivedCT) |
| 1074 |
} |
| 1075 |
if string(op.receivedAAD) != string(expectedAAD) { |
| 1076 |
t.Fatalf("expected WorkloadService to receive AAD %q, got %q", expectedAAD, op.receivedAAD) |
| 1077 |
} |
| 1078 |
} |
| 1079 |
|
| 1080 |
func TestHandleDecapsMethodNotAllowed(t *testing.T) { |
| 1081 |
srv := newTestServer(t, &mockKeyProtectionService{}, &mockWorkloadService{}) |
| 1082 |
|
| 1083 |
req := httptest.NewRequest(http.MethodGet, "/v1/keys:decap", nil) |
| 1084 |
w := httptest.NewRecorder() |
| 1085 |
srv.Handler().ServeHTTP(w, req) |
| 1086 |
|
| 1087 |
if w.Code != http.StatusMethodNotAllowed { |
| 1088 |
t.Fatalf("expected status 405, got %d", w.Code) |
| 1089 |
} |
| 1090 |
} |
| 1091 |
|
| 1092 |
func TestHandleDecapsBadRequestBody(t *testing.T) { |
| 1093 |
srv := newTestServer(t, &mockKeyProtectionService{}, &mockWorkloadService{}) |
| 1094 |
|
| 1095 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:decap", strings.NewReader("not-json")) |
| 1096 |
w := httptest.NewRecorder() |
| 1097 |
srv.Handler().ServeHTTP(w, req) |
| 1098 |
|
| 1099 |
if w.Code != http.StatusBadRequest { |
| 1100 |
t.Fatalf("expected status 400, got %d", w.Code) |
| 1101 |
} |
| 1102 |
} |
| 1103 |
|
| 1104 |
func TestHandleDecapsInvalidKEMUUID(t *testing.T) { |
| 1105 |
srv := newTestServer(t, &mockKeyProtectionService{}, &mockWorkloadService{}) |
| 1106 |
|
| 1107 |
body := `{"key_handle":{"handle":"not-a-uuid"},"ciphertext":{"algorithm":"DHKEM_X25519_HKDF_SHA256","ciphertext":"AAAA"}}` |
| 1108 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:decap", strings.NewReader(body)) |
| 1109 |
w := httptest.NewRecorder() |
| 1110 |
srv.Handler().ServeHTTP(w, req) |
| 1111 |
|
| 1112 |
if w.Code != http.StatusBadRequest { |
| 1113 |
t.Fatalf("expected status 400, got %d", w.Code) |
| 1114 |
} |
| 1115 |
} |
| 1116 |
|
| 1117 |
func TestHandleDecapsKEMKeyNotFound(t *testing.T) { |
| 1118 |
kemUUID := uuid.New() |
| 1119 |
srv := newTestServer(t, &mockKeyProtectionService{}, &mockWorkloadService{}) |
| 1120 |
// Don't populate kemToBindingMap. |
| 1121 |
|
| 1122 |
body := decapsRequestBody(kemUUID, KemAlgorithmDHKEMX25519HKDFSHA256, []byte("enc-key")) |
| 1123 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:decap", strings.NewReader(body)) |
| 1124 |
w := httptest.NewRecorder() |
| 1125 |
srv.Handler().ServeHTTP(w, req) |
| 1126 |
|
| 1127 |
if w.Code != http.StatusNotFound { |
| 1128 |
t.Fatalf("expected status 404, got %d: %s", w.Code, w.Body.String()) |
| 1129 |
} |
| 1130 |
} |
| 1131 |
|
| 1132 |
func TestHandleDecapsDecapSealError(t *testing.T) { |
| 1133 |
kemUUID := uuid.New() |
| 1134 |
bindingUUID := uuid.New() |
| 1135 |
|
| 1136 |
ds := &mockKeyProtectionService{err: fmt.Errorf("decap FFI error")} |
| 1137 |
srv := newDecapsTestServer(t, kemUUID, bindingUUID, ds, &mockWorkloadService{}) |
| 1138 |
|
| 1139 |
body := decapsRequestBody(kemUUID, KemAlgorithmDHKEMX25519HKDFSHA256, []byte("enc-key")) |
| 1140 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:decap", strings.NewReader(body)) |
| 1141 |
w := httptest.NewRecorder() |
| 1142 |
srv.Handler().ServeHTTP(w, req) |
| 1143 |
|
| 1144 |
if w.Code != http.StatusInternalServerError { |
| 1145 |
t.Fatalf("expected status 500, got %d", w.Code) |
| 1146 |
} |
| 1147 |
} |
| 1148 |
|
| 1149 |
func TestHandleDecapsOpenError(t *testing.T) { |
| 1150 |
kemUUID := uuid.New() |
| 1151 |
bindingUUID := uuid.New() |
| 1152 |
|
| 1153 |
ds := &mockKeyProtectionService{sealEnc: []byte("enc"), sealedCT: []byte("ct")} |
| 1154 |
op := &mockWorkloadService{err: fmt.Errorf("open FFI error")} |
| 1155 |
srv := newDecapsTestServer(t, kemUUID, bindingUUID, ds, op) |
| 1156 |
|
| 1157 |
body := decapsRequestBody(kemUUID, KemAlgorithmDHKEMX25519HKDFSHA256, []byte("enc-key")) |
| 1158 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:decap", strings.NewReader(body)) |
| 1159 |
w := httptest.NewRecorder() |
| 1160 |
srv.Handler().ServeHTTP(w, req) |
| 1161 |
|
| 1162 |
if w.Code != http.StatusInternalServerError { |
| 1163 |
t.Fatalf("expected status 500, got %d", w.Code) |
| 1164 |
} |
| 1165 |
} |
| 1166 |
|
| 1167 |
func TestHandleDecapsUnsupportedAlgorithm(t *testing.T) { |
| 1168 |
kemUUID := uuid.New() |
| 1169 |
bindingUUID := uuid.New() |
| 1170 |
srv := newDecapsTestServer(t, kemUUID, bindingUUID, &mockKeyProtectionService{}, &mockWorkloadService{}) |
| 1171 |
|
| 1172 |
body := decapsRequestBody(kemUUID, KemAlgorithm(999), []byte("enc-key")) |
| 1173 |
req := httptest.NewRequest(http.MethodPost, "/v1/keys:decap", strings.NewReader(body)) |
| 1174 |
w := httptest.NewRecorder() |
| 1175 |
srv.Handler().ServeHTTP(w, req) |
| 1176 |
|
| 1177 |
if w.Code != http.StatusBadRequest { |
| 1178 |
t.Fatalf("expected status 400, got %d", w.Code) |
| 1179 |
} |
| 1180 |
} |
| 1181 |
|
| 1182 |
func TestProcessClaimsTimeout(t *testing.T) { |
| 1183 |
oldTimeout := ClaimsResponseTimeout |
| 1184 |
ClaimsResponseTimeout = 10 * time.Millisecond |
| 1185 |
defer func() { ClaimsResponseTimeout = oldTimeout }() |
| 1186 |
|
| 1187 |
srv := newTestServer(t, &mockKeyProtectionService{}, &mockWorkloadService{}) |
| 1188 |
// processClaims is already started in newTestServer -> NewServer -> New |
| 1189 |
|
| 1190 |
respChan1 := make(chan *ClaimsResult) // Unbuffered |
| 1191 |
req1 := &keymanager.GetKeyClaimsRequest{ |
| 1192 |
KeyHandle: &keymanager.KeyHandle{Handle: uuid.New().String()}, |
| 1193 |
KeyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 1194 |
} |
| 1195 |
|
| 1196 |
// 1. Send first request and DO NOT read from it. |
| 1197 |
// This should timeout in 10ms. |
| 1198 |
srv.claimsChan <- &ClaimsCall{Request: req1, RespChan: respChan1} |
| 1199 |
|
| 1200 |
// 2. Send second request and read from it. |
| 1201 |
// We need a valid UUID in the map for this to succeed easily. |
| 1202 |
kemUUID := uuid.New() |
| 1203 |
bindingUUID := uuid.New() |
| 1204 |
srv.mu.Lock() |
| 1205 |
srv.kemToBindingMap[kemUUID] = bindingUUID |
| 1206 |
srv.mu.Unlock() |
| 1207 |
|
| 1208 |
respChan2 := make(chan *ClaimsResult, 1) |
| 1209 |
req2 := &keymanager.GetKeyClaimsRequest{ |
| 1210 |
KeyHandle: &keymanager.KeyHandle{Handle: kemUUID.String()}, |
| 1211 |
KeyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 1212 |
} |
| 1213 |
|
| 1214 |
// Give it a bit of time for the first one to timeout |
| 1215 |
time.Sleep(20 * time.Millisecond) |
| 1216 |
|
| 1217 |
srv.claimsChan <- &ClaimsCall{Request: req2, RespChan: respChan2} |
| 1218 |
|
| 1219 |
select { |
| 1220 |
case res := <-respChan2: |
| 1221 |
if res.Err != nil { |
| 1222 |
t.Errorf("expected no error for second request, got: %v", res.Err) |
| 1223 |
} |
| 1224 |
case <-time.After(1 * time.Second): |
| 1225 |
t.Fatal("timed out waiting for second request response - background worker might be blocked!") |
| 1226 |
} |
| 1227 |
} |
| 1228 |
|
| 1229 |
func TestGetClaimsFromChannel(t *testing.T) { |
| 1230 |
keyHandle := "test-uuid-123" |
| 1231 |
expectedReply := &keymanager.KeyClaims{ |
| 1232 |
Claims: &keymanager.KeyClaims_VmBindingClaims{}, |
| 1233 |
} |
| 1234 |
|
| 1235 |
tests := []struct { |
| 1236 |
name string |
| 1237 |
keyType keymanager.KeyType |
| 1238 |
workerBehavior func(call *ClaimsCall) |
| 1239 |
ctxTimeout time.Duration |
| 1240 |
wantErr string |
| 1241 |
}{ |
| 1242 |
{ |
| 1243 |
name: "success", |
| 1244 |
keyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 1245 |
workerBehavior: func(call *ClaimsCall) { |
| 1246 |
call.RespChan <- &ClaimsResult{Reply: expectedReply} |
| 1247 |
}, |
| 1248 |
ctxTimeout: 5 * time.Second, |
| 1249 |
wantErr: "", |
| 1250 |
}, |
| 1251 |
{ |
| 1252 |
name: "worker returns error", |
| 1253 |
keyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_KEY, |
| 1254 |
workerBehavior: func(call *ClaimsCall) { |
| 1255 |
call.RespChan <- &ClaimsResult{Err: errors.New("db connection failed")} |
| 1256 |
}, |
| 1257 |
ctxTimeout: 5 * time.Second, |
| 1258 |
wantErr: "worker error: db connection failed", |
| 1259 |
}, |
| 1260 |
{ |
| 1261 |
name: "context already cancelled", |
| 1262 |
keyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 1263 |
workerBehavior: func(_ *ClaimsCall) { |
| 1264 |
// Worker won't even be reached if ctx is canceled early |
| 1265 |
}, |
| 1266 |
ctxTimeout: -1, // Force immediate cancel |
| 1267 |
wantErr: context.Canceled.Error(), |
| 1268 |
}, |
| 1269 |
{ |
| 1270 |
name: "response timeout", |
| 1271 |
keyType: keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING, |
| 1272 |
workerBehavior: func(_ *ClaimsCall) { |
| 1273 |
// Simulate worker hanging by doing nothing |
| 1274 |
}, |
| 1275 |
ctxTimeout: 5 * time.Second, |
| 1276 |
wantErr: "timed out waiting for processClaims", |
| 1277 |
}, |
| 1278 |
} |
| 1279 |
|
| 1280 |
for _, tt := range tests { |
| 1281 |
t.Run(tt.name, func(t *testing.T) { |
| 1282 |
claimsChan := make(chan *ClaimsCall, 1) |
| 1283 |
s := &Server{claimsChan: claimsChan} |
| 1284 |
|
| 1285 |
var ctx context.Context |
| 1286 |
var cancel context.CancelFunc |
| 1287 |
if tt.ctxTimeout < 0 { |
| 1288 |
ctx, cancel = context.WithCancel(context.Background()) |
| 1289 |
cancel() // Pre-cancel |
| 1290 |
} else { |
| 1291 |
ctx, cancel = context.WithTimeout(context.Background(), tt.ctxTimeout) |
| 1292 |
defer cancel() |
| 1293 |
} |
| 1294 |
|
| 1295 |
go func() { |
| 1296 |
select { |
| 1297 |
case call := <-claimsChan: |
| 1298 |
tt.workerBehavior(call) |
| 1299 |
case <-ctx.Done(): |
| 1300 |
return |
| 1301 |
} |
| 1302 |
}() |
| 1303 |
|
| 1304 |
result, err := s.GetKeyClaims(ctx, keyHandle, tt.keyType) |
| 1305 |
|
| 1306 |
if tt.wantErr != "" { |
| 1307 |
if err == nil { |
| 1308 |
t.Fatalf("expected error containing %q, got nil", tt.wantErr) |
| 1309 |
} |
| 1310 |
if !strings.Contains(err.Error(), tt.wantErr) { |
| 1311 |
t.Errorf("expected error %q, got %q", tt.wantErr, err.Error()) |
| 1312 |
} |
| 1313 |
return |
| 1314 |
} |
| 1315 |
|
| 1316 |
if err != nil { |
| 1317 |
t.Fatalf("unexpected error: %v", err) |
| 1318 |
} |
| 1319 |
if result != expectedReply { |
| 1320 |
t.Errorf("result mismatch: expected %v, got %v", expectedReply, result) |
| 1321 |
} |
| 1322 |
}) |
| 1323 |
} |
| 1324 |
} |