Debian Codegraph @

keymanager/workload_service/server.go

raw
1 // Package workloadservice implements the Key Orchestration Layer (KOL) for the
2 // Workload Service Daemon (WSD). It provides an HTTP server on a unix socket
3 // exposing key management endpoints.
4 package workloadservice
5
6 import (
7 "context"
8 "encoding/base64"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "log"
13 "math"
14 "net"
15 "net/http"
16 "os"
17 "sync"
18 "time"
19
20 "github.com/google/uuid"
21 "google.golang.org/protobuf/types/known/durationpb"
22
23 kpscc "github.com/google/go-tpm-tools/keymanager/key_protection_service/key_custody_core"
24 keymanager "github.com/google/go-tpm-tools/keymanager/km_common/proto"
25 wskcc "github.com/google/go-tpm-tools/keymanager/workload_service/key_custody_core"
26 )
27
28 // WorkloadService defines the interface for generating and managing binding keypairs.
29 // These keypairs are used by workloads to securely bind shared secrets to their identity.
30 type WorkloadService interface {
31 // GenerateBindingKeypair generates a new binding keypair for a workload.
32 // This keypair ensures that only the workload possessing the private key
33 // can open (decrypt) sealed secrets intended for it.
34 //
35 // Parameters:
36 // - algo: The HPKE algorithm suite to use for the binding keypair.
37 // - lifespanSecs: The duration (in seconds) for which the generated keypair remains valid.
38 //
39 // Returns:
40 // - uuid.UUID: A unique identifier representing the stored binding keypair.
41 // - []byte: The public binding key bytes to be shared with the Key Protection Service.
42 // - error: An error if generation or storage fails.
43 GenerateBindingKeypair(algo *keymanager.HpkeAlgorithm, lifespanSecs uint64) (uuid.UUID, []byte, error)
44
45 // DestroyBindingKey removes the specified binding keypair from the active key registry.
46 // It ensures that the keypair can no longer be used to decrypt (open) sealed secrets.
47 //
48 // Parameters:
49 // - bindingUUID: The unique identifier of the stored binding keypair to destroy.
50 //
51 // Returns:
52 // - error: An error if the key is not found or deletion fails.
53 DestroyBindingKey(bindingUUID uuid.UUID) error
54
55 // GetBindingKey retrieves metadata and public keys associated with a stored binding keypair.
56 //
57 // Parameters:
58 // - id: The unique identifier of the stored binding keypair.
59 //
60 // Returns:
61 // - []byte: The public binding key bytes.
62 // - *keymanager.HpkeAlgorithm: The HPKE algorithm suite of the binding key.
63 // - error: An error if the key is not found or has expired.
64 GetBindingKey(id uuid.UUID) ([]byte, *keymanager.HpkeAlgorithm, error)
65
66 // Open decrypts a sealed ciphertext using the specified binding private key.
67 // It is used by the workload to access shared secrets that have been resealed
68 // for its specific binding key.
69 //
70 // Parameters:
71 // - bindingUUID: The unique identifier of the stored binding keypair.
72 // - enc: The encapsulated key for the resealed shared secret (seal_enc).
73 // - ciphertext: The authenticated ciphertext of the resealed shared secret (sealed_ct).
74 // - aad: Additional Authenticated Data used during the sealing process.
75 //
76 // Returns:
77 // - []byte: The original plaintext (the shared secret).
78 // - error: An error if the binding key is not found, expired, or decryption fails.
79 Open(bindingUUID uuid.UUID, enc, ciphertext, aad []byte) ([]byte, error)
80 }
81 type keyProtectionService struct{}
82
83 // KeyProtectionService defines the interface for generating KEM keypairs.
84 type KeyProtectionService interface {
85 GenerateKEMKeypair(algo *keymanager.HpkeAlgorithm, bindingPubKey []byte, lifespanSecs uint64) (uuid.UUID, []byte, error)
86 EnumerateKEMKeys(limit, offset int) ([]kpscc.KEMKeyInfo, bool, error)
87 DestroyKEMKey(kemUUID uuid.UUID) error
88 GetKEMKey(id uuid.UUID) (kemPubKey []byte, bindingPubKey []byte, algo *keymanager.HpkeAlgorithm, deleteAfter uint64, err error)
89 DecapAndSeal(kemUUID uuid.UUID, encapsulatedKey, aad []byte) (sealEnc []byte, sealedCT []byte, err error)
90 }
91
92 // workloadService implements WorkloadService by delegating to the WSD KCC FFI.
93 type workloadService struct{}
94
95 // GenerateBindingKeypair generates a new binding keypair for the workload by
96 // delegating to the underlying WorkloadService backend (WSD KCC FFI).
97 func (r *workloadService) GenerateBindingKeypair(algo *keymanager.HpkeAlgorithm, lifespanSecs uint64) (uuid.UUID, []byte, error) {
98 return wskcc.GenerateBindingKeypair(algo, lifespanSecs)
99 }
100
101 // DestroyBindingKey removes the specified binding keypair from the active key registry
102 // by delegating to the underlying WorkloadService backend (WSD KCC FFI).
103 func (r *workloadService) DestroyBindingKey(bindingUUID uuid.UUID) error {
104 return wskcc.DestroyBindingKey(bindingUUID)
105 }
106
107 // Open decrypts a sealed ciphertext securely using the specified binding private key
108 // by delegating to the underlying WorkloadService backend (WSD KCC FFI).
109 func (r *workloadService) Open(bindingUUID uuid.UUID, enc, ciphertext, aad []byte) ([]byte, error) {
110 return wskcc.Open(bindingUUID, enc, ciphertext, aad)
111 }
112
113 // GetBindingKey retrieves the public binding key and HPKE algorithm of a stored
114 // binding keypair by delegating to the underlying WorkloadService backend (WSD KCC FFI).
115 func (r *workloadService) GetBindingKey(id uuid.UUID) ([]byte, *keymanager.HpkeAlgorithm, error) {
116 return wskcc.GetBindingKey(id)
117 }
118
119 func (r *keyProtectionService) GenerateKEMKeypair(algo *keymanager.HpkeAlgorithm, bindingPubKey []byte, lifespanSecs uint64) (uuid.UUID, []byte, error) {
120 return kpscc.GenerateKEMKeypair(algo, bindingPubKey, lifespanSecs)
121 }
122
123 func (r *keyProtectionService) EnumerateKEMKeys(limit, offset int) ([]kpscc.KEMKeyInfo, bool, error) {
124 return kpscc.EnumerateKEMKeys(limit, offset)
125 }
126
127 func (r *keyProtectionService) DestroyKEMKey(kemUUID uuid.UUID) error {
128 return kpscc.DestroyKEMKey(kemUUID)
129 }
130
131 func (r *keyProtectionService) DecapAndSeal(kemUUID uuid.UUID, encapsulatedKey, aad []byte) (sealEnc []byte, sealedCT []byte, err error) {
132 return kpscc.DecapAndSeal(kemUUID, encapsulatedKey, aad)
133 }
134
135 func (r *keyProtectionService) GetKEMKey(id uuid.UUID) ([]byte, []byte, *keymanager.HpkeAlgorithm, uint64, error) {
136 return kpscc.GetKEMKey(id)
137 }
138
139 // KeyClaimsProvider defines the interface for retrieving key claims.
140 // This abstraction allows the underlying implementation to be a local channel
141 // or a remote RPC call in future.
142 type KeyClaimsProvider interface {
143 GetKeyClaims(ctx context.Context, keyHandle string, keyType keymanager.KeyType) (*keymanager.KeyClaims, error)
144 }
145
146 // ClaimsCall acts as the internal "envelope" for the channel.
147 type ClaimsCall struct {
148 Request *keymanager.GetKeyClaimsRequest
149 RespChan chan *ClaimsResult
150 }
151
152 // ClaimsResult wraps the protobuf response with an error.
153 type ClaimsResult struct {
154 Reply *keymanager.KeyClaims
155 Err error
156 }
157
158 // KeyHandle represents a key handle returned from the API.
159 type KeyHandle struct {
160 Handle string `json:"handle"`
161 }
162
163 // GenerateKeyRequest is the JSON body for POST /v1/keys:generate_key.
164 type GenerateKeyRequest struct {
165 Algorithm AlgorithmDetails `json:"algorithm"`
166 Lifespan uint64 `json:"lifespan"`
167 }
168
169 // DestroyRequest is the JSON body for POST /v1/keys:destroy.
170 type DestroyRequest struct {
171 KeyHandle KeyHandle `json:"key_handle"`
172 }
173
174 // GenerateKeyResponse is returned by POST /v1/keys:generate_key.
175 type GenerateKeyResponse struct {
176 KeyHandle KeyHandle `json:"key_handle"`
177 PubKey PubKeyInfo `json:"pub_key"`
178 KeyProtectionMechanism string `json:"key_protection_mechanism"`
179 ExpirationTime int64 `json:"expiration_time"`
180 }
181
182 // AlgorithmParams represents the parameters for a specific algorithm type.
183 type AlgorithmParams struct {
184 KemID KemAlgorithm `json:"kem_id"`
185 }
186
187 // AlgorithmDetails captures type and specific params.
188 type AlgorithmDetails struct {
189 Type string `json:"type"`
190 Params AlgorithmParams `json:"params"`
191 }
192
193 // SupportedAlgorithm represents a single algorithm capability.
194 type SupportedAlgorithm struct {
195 Algorithm AlgorithmDetails `json:"algorithm"`
196 }
197
198 // GetCapabilitiesResponse represents the JSON body for GET /v1/capabilities.
199 type GetCapabilitiesResponse struct {
200 SupportedAlgorithms []SupportedAlgorithm `json:"supported_algorithms"`
201 }
202
203 // EnumerateKeysResponse represents the response for GET /v1/keys.
204 type EnumerateKeysResponse struct {
205 KeyInfos []KeyInfo `json:"key_infos"`
206 }
207
208 // KeyInfo contains information about a single key.
209 type KeyInfo struct {
210 KeyHandle KeyHandle `json:"key_handle"`
211 PubKey PubKeyInfo `json:"pub_key"`
212 KeyProtectionMechanism string `json:"key_protection_mechanism"`
213 ExpirationTime int64 `json:"expiration_time"`
214 }
215
216 // PubKeyInfo contains the public key and its algorithm.
217 type PubKeyInfo struct {
218 Algorithm AlgorithmDetails `json:"algorithm"`
219 PublicKey string `json:"public_key"` // Base64 encoded public key
220 }
221
222 // KemCiphertext carries raw encapsulated key bytes and the KEM algorithm.
223 type KemCiphertext struct {
224 Algorithm KemAlgorithm `json:"algorithm"`
225 Ciphertext string `json:"ciphertext"` // base64-encoded raw bytes
226 }
227
228 // DecapsRequest is the JSON body for POST /keys:decap.
229 type DecapsRequest struct {
230 KeyHandle KeyHandle `json:"key_handle"`
231 Ciphertext KemCiphertext `json:"ciphertext"`
232 }
233
234 // KemSharedSecret is the Decaps result payload.
235 type KemSharedSecret struct {
236 Algorithm KemAlgorithm `json:"algorithm"`
237 Secret string `json:"secret"` // base64-encoded raw bytes
238 }
239
240 // DecapsResponse is returned by POST /v1/keys:decap.
241 type DecapsResponse struct {
242 SharedSecret KemSharedSecret `json:"shared_secret"`
243 }
244
245 // Server is the WSD HTTP server.
246 type Server struct {
247 keyProtectionService KeyProtectionService
248 workloadService WorkloadService
249 mu sync.RWMutex
250 kemToBindingMap map[uuid.UUID]uuid.UUID
251
252 claimsChan chan *ClaimsCall
253
254 httpServer *http.Server
255 listener net.Listener
256 // todo: add logging mechanism here
257 }
258
259 var (
260 // ClaimsResponseTimeout is the maximum time to wait for the caller to receive
261 // the result of a GetKeyClaims request before timing out.
262 ClaimsResponseTimeout = 5 * time.Second
263 // ClaimsRequestTimeout is the maximum time to wait for enqueuing the request to
264 // claims channel for getting the key claims.
265 ClaimsRequestTimeout = 5 * time.Second
266 )
267
268 // New creates a new WSD Server listening on the given unix socket path.
269 func New(_ context.Context, socketPath string) (*Server, error) {
270 return NewServer(&keyProtectionService{}, &workloadService{}, socketPath)
271 }
272
273 // NewServer creates a new WSD server with the given dependencies.
274 func NewServer(keyProtectionService KeyProtectionService, workloadService WorkloadService, socketPath string) (*Server, error) {
275 s := &Server{
276 keyProtectionService: keyProtectionService,
277 workloadService: workloadService,
278 kemToBindingMap: make(map[uuid.UUID]uuid.UUID),
279 mu: sync.RWMutex{},
280 claimsChan: make(chan *ClaimsCall, 4),
281 }
282
283 mux := http.NewServeMux()
284 mux.HandleFunc("POST /v1/keys:generate_key", s.handleGenerateKey)
285 mux.HandleFunc("POST /v1/keys:decap", s.handleDecaps)
286 mux.HandleFunc("GET /v1/capabilities", s.handleGetCapabilities)
287 mux.HandleFunc("GET /v1/keys", s.handleEnumerateKeys)
288 mux.HandleFunc("POST /v1/keys:destroy", s.handleDestroy)
289 s.httpServer = &http.Server{Handler: mux}
290
291 _ = os.Remove(socketPath)
292 ln, err := net.Listen("unix", socketPath)
293 if err != nil {
294 return nil, fmt.Errorf("failed to listen on unix socket %s: %w", socketPath, err)
295 }
296 s.listener = ln
297
298 go s.processClaims()
299
300 return s, nil
301 }
302
303 // Serve starts the HTTP server listening on the given unix socket path.
304 func (s *Server) Serve() error {
305 return s.httpServer.Serve(s.listener)
306 }
307
308 // Shutdown gracefully shuts down the server.
309 func (s *Server) Shutdown(ctx context.Context) error {
310 return s.httpServer.Shutdown(ctx)
311 }
312
313 // Handler returns the HTTP handler for testing purposes.
314 func (s *Server) Handler() http.Handler {
315 return s.httpServer.Handler
316 }
317
318 // LookupBindingUUID returns the binding UUID associated with the given KEM UUID.
319 func (s *Server) LookupBindingUUID(kemUUID uuid.UUID) (uuid.UUID, bool) {
320 s.mu.RLock()
321 defer s.mu.RUnlock()
322 id, ok := s.kemToBindingMap[kemUUID]
323 return id, ok
324 }
325
326 func decapsAADContext(kemUUID uuid.UUID, algorithm KemAlgorithm) []byte {
327 // Bind the KPS->WSD transport ciphertext to this decapsulation context.
328 // Note: The AAD context string retains `decaps` as it is part of the internal binding protocol
329 // and changing it might affect backward compatibility if keys were already persisted (though lifespan is short).
330 // For API alignment, we only change the external endpoint and JSON.
331 return []byte(fmt.Sprintf("wsd:keys:decaps:v1:%d:%s", algorithm, kemUUID))
332 }
333
334 func (s *Server) handleDecaps(w http.ResponseWriter, r *http.Request) {
335
336 var req DecapsRequest
337 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
338 http.Error(w, fmt.Sprintf("invalid request body: %v", err), http.StatusBadRequest)
339 return
340 }
341
342 if !req.Ciphertext.Algorithm.IsSupported() {
343 http.Error(w, fmt.Sprintf("unsupported ciphertext algorithm: %d. Supported algorithms: %s", req.Ciphertext.Algorithm, SupportedKemAlgorithmsString()), http.StatusBadRequest)
344 return
345 }
346
347 kemUUID, err := uuid.Parse(req.KeyHandle.Handle)
348 if err != nil {
349 http.Error(w, fmt.Sprintf("invalid key_handle.handle: %v", err), http.StatusBadRequest)
350 return
351 }
352
353 encapsulatedKey, err := base64.StdEncoding.DecodeString(req.Ciphertext.Ciphertext)
354 if err != nil {
355 http.Error(w, fmt.Sprintf("invalid ciphertext.ciphertext base64: %v", err), http.StatusBadRequest)
356 return
357 }
358 if len(encapsulatedKey) == 0 {
359 http.Error(w, "ciphertext.ciphertext must not be empty", http.StatusBadRequest)
360 return
361 }
362 aad := decapsAADContext(kemUUID, req.Ciphertext.Algorithm)
363
364 // Look up the binding UUID for this KEM key.
365 bindingUUID, ok := s.LookupBindingUUID(kemUUID)
366 if !ok {
367 http.Error(w, fmt.Sprintf("KEM key handle not found: %s", kemUUID), http.StatusNotFound)
368 return
369 }
370
371 // Decapsulate and reseal via KPS.
372 sealEnc, sealedCT, err := s.keyProtectionService.DecapAndSeal(kemUUID, encapsulatedKey, aad)
373 if err != nil {
374 http.Error(w, fmt.Sprintf("failed to decap and seal: %v", err), http.StatusInternalServerError)
375 return
376 }
377
378 // Open the sealed secret using the binding key via WSD KCC.
379 plaintext, err := s.workloadService.Open(bindingUUID, sealEnc, sealedCT, aad)
380 if err != nil {
381 http.Error(w, fmt.Sprintf("failed to open sealed secret: %v", err), http.StatusInternalServerError)
382 return
383 }
384
385 // Return the shared secret.
386 resp := DecapsResponse{
387 SharedSecret: KemSharedSecret{
388 Algorithm: req.Ciphertext.Algorithm,
389 Secret: base64.StdEncoding.EncodeToString(plaintext),
390 },
391 }
392 w.Header().Set("Content-Type", "application/json")
393 _ = json.NewEncoder(w).Encode(resp)
394 }
395
396 func (s *Server) handleGenerateKey(w http.ResponseWriter, r *http.Request) {
397 var req GenerateKeyRequest
398 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
399 writeError(w, fmt.Sprintf("invalid request body: %v", err), http.StatusBadRequest)
400 return
401 }
402
403 // Validate lifespan is positive and does not cause int64 overflow.
404 if req.Lifespan == 0 {
405 writeError(w, "lifespan must be greater than 0s", http.StatusBadRequest)
406 return
407 }
408 if req.Lifespan > math.MaxInt64 {
409 writeError(w, "lifespan exceeds maximum allowed value", http.StatusBadRequest)
410 return
411 }
412
413 switch req.Algorithm.Type {
414 case "kem":
415 s.generateKEMKey(w, req)
416 default:
417 writeError(w, fmt.Sprintf("unsupported algorithm type: %q. Only 'kem' is supported.", req.Algorithm.Type), http.StatusBadRequest)
418 }
419 }
420
421 func (s *Server) generateKEMKey(w http.ResponseWriter, req GenerateKeyRequest) {
422 // Validate algorithm.
423 if !req.Algorithm.Params.KemID.IsSupported() {
424 writeError(w, fmt.Sprintf("unsupported algorithm: %s. Supported algorithms: %s", req.Algorithm.Params.KemID, SupportedKemAlgorithmsString()), http.StatusBadRequest)
425 return
426 }
427
428 // Construct the full HPKE algorithm suite based on the requested KEM.
429 // We currently only support one suite.
430 algo, err := req.Algorithm.Params.KemID.ToHpkeAlgorithm()
431 if err != nil {
432 writeError(w, err.Error(), http.StatusBadRequest)
433 return
434 }
435
436 // Generate binding keypair via WSD KCC FFI.
437 bindingUUID, bindingPubKey, err := s.workloadService.GenerateBindingKeypair(algo, req.Lifespan)
438 if err != nil {
439 writeError(w, fmt.Sprintf("failed to generate binding keypair: %v", err), http.StatusInternalServerError)
440 return
441 }
442
443 // Generate KEM keypair via KPS KOL, passing the binding public key.
444 kemUUID, kemPubKey, err := s.keyProtectionService.GenerateKEMKeypair(algo, bindingPubKey, req.Lifespan)
445 if err != nil {
446 writeError(w, fmt.Sprintf("failed to generate KEM keypair: %v", err), http.StatusInternalServerError)
447 return
448 }
449
450 // Store the KEM UUID → Binding UUID mapping.
451 s.mu.Lock()
452 s.kemToBindingMap[kemUUID] = bindingUUID
453 s.mu.Unlock()
454
455 // Return KEM UUID to workload.
456 resp := GenerateKeyResponse{
457 KeyHandle: KeyHandle{Handle: kemUUID.String()},
458 PubKey: PubKeyInfo{
459 Algorithm: AlgorithmDetails{
460 Type: "kem",
461 Params: AlgorithmParams{
462 KemID: req.Algorithm.Params.KemID,
463 },
464 },
465 PublicKey: base64.StdEncoding.EncodeToString(kemPubKey),
466 },
467 KeyProtectionMechanism: keymanager.KeyProtectionMechanism_KEY_PROTECTION_VM_EMULATED.String(),
468 ExpirationTime: time.Now().Unix() + int64(req.Lifespan),
469 }
470 writeJSON(w, resp, http.StatusOK)
471 }
472
473 func (s *Server) handleGetCapabilities(w http.ResponseWriter, _ *http.Request) {
474
475 var supportedAlgos []SupportedAlgorithm
476 for _, algo := range SupportedKemAlgorithms {
477 supportedAlgos = append(supportedAlgos, SupportedAlgorithm{
478 Algorithm: AlgorithmDetails{
479 Type: "kem",
480 Params: AlgorithmParams{
481 KemID: algo,
482 },
483 },
484 })
485 }
486
487 resp := GetCapabilitiesResponse{
488 SupportedAlgorithms: supportedAlgos,
489 }
490
491 writeJSON(w, resp, http.StatusOK)
492 }
493
494 func (s *Server) handleEnumerateKeys(w http.ResponseWriter, _ *http.Request) {
495 keys, _, err := s.keyProtectionService.EnumerateKEMKeys(100, 0)
496 if err != nil {
497 writeError(w, fmt.Sprintf("failed to enumerate keys: %v", err), http.StatusInternalServerError)
498 return
499 }
500
501 keyInfos := make([]KeyInfo, 0, len(keys))
502 for _, key := range keys {
503 kemAlgo := KemAlgorithmUnspecified
504 if key.Algorithm != nil {
505 switch key.Algorithm.Kem {
506 case keymanager.KemAlgorithm_KEM_ALGORITHM_DHKEM_X25519_HKDF_SHA256:
507 kemAlgo = KemAlgorithmDHKEMX25519HKDFSHA256
508 }
509 }
510
511 keyInfos = append(keyInfos, KeyInfo{
512 KeyHandle: KeyHandle{Handle: key.ID.String()},
513 PubKey: PubKeyInfo{
514 Algorithm: AlgorithmDetails{
515 Type: "kem",
516 Params: AlgorithmParams{
517 KemID: kemAlgo,
518 },
519 },
520 PublicKey: base64.StdEncoding.EncodeToString(key.KEMPubKey),
521 },
522 KeyProtectionMechanism: keymanager.KeyProtectionMechanism_KEY_PROTECTION_VM_EMULATED.String(),
523 ExpirationTime: time.Now().Unix() + int64(key.RemainingLifespanSecs),
524 })
525 }
526
527 resp := EnumerateKeysResponse{
528 KeyInfos: keyInfos,
529 }
530
531 writeJSON(w, resp, http.StatusOK)
532 }
533
534 // writeJSON writes a JSON response with the given status code.
535 func writeJSON(w http.ResponseWriter, v any, code int) {
536 w.Header().Set("Content-Type", "application/json")
537 w.Header().Set("X-Content-Type-Options", "nosniff")
538 w.WriteHeader(code)
539 if err := json.NewEncoder(w).Encode(v); err != nil {
540 log.Printf("failed to write JSON response: %v", err)
541 }
542 }
543
544 // writeError writes a JSON error response.
545 func writeError(w http.ResponseWriter, message string, code int) {
546 writeJSON(w, map[string]string{"error": message}, code)
547 }
548
549 func (s *Server) handleDestroy(w http.ResponseWriter, r *http.Request) {
550 var req DestroyRequest
551 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
552 writeError(w, fmt.Sprintf("invalid request body: %v", err), http.StatusBadRequest)
553 return
554 }
555
556 kemUUID, err := uuid.Parse(req.KeyHandle.Handle)
557 if err != nil {
558 writeError(w, fmt.Sprintf("invalid key handle: %v", err), http.StatusBadRequest)
559 return
560 }
561
562 // Look up the binding UUID for this KEM key.
563 bindingUUID, ok := s.LookupBindingUUID(kemUUID)
564 if !ok {
565 writeError(w, fmt.Sprintf("KEM key handle not found: %s", kemUUID), http.StatusNotFound)
566 return
567 }
568
569 errKps := s.keyProtectionService.DestroyKEMKey(kemUUID)
570 errWs := s.workloadService.DestroyBindingKey(bindingUUID)
571
572 // Remove the mapping.
573 s.mu.Lock()
574 delete(s.kemToBindingMap, kemUUID)
575 s.mu.Unlock()
576
577 if err := errors.Join(errKps, errWs); err != nil {
578 writeError(w, fmt.Sprintf("failed to destroy keys: %v", err), http.StatusInternalServerError)
579 return
580 }
581
582 w.WriteHeader(http.StatusNoContent)
583 }
584
585 // handleGetBindingKeyClaims returns the claims for a binding key identified by its KEM UUID.
586 func (s *Server) handleGetBindingKeyClaims(id uuid.UUID) (*keymanager.KeyClaims, error) {
587 // Key ID Lookup. The orchestration layer will look-up the key_handle
588 // in its ActiveKeyRegistry to find the Binding Key ID.
589 bindingID, ok := s.LookupBindingUUID(id)
590 if !ok {
591 return nil, fmt.Errorf("binding key ID not found for key handle: %s", id)
592 }
593
594 // Key Metadata Lookup.
595 pubKey, algo, err := s.workloadService.GetBindingKey(bindingID)
596 if err != nil {
597 return nil, fmt.Errorf("failed to get binding key: %w", err)
598 }
599
600 // Create KeyClaims
601 claims := &keymanager.KeyClaims{
602 Claims: &keymanager.KeyClaims_VmBindingClaims{
603 VmBindingClaims: &keymanager.KeyClaims_VmProtectionBindingClaims{
604 BindingPubKey: &keymanager.HpkePublicKey{
605 Algorithm: algo,
606 PublicKey: pubKey,
607 },
608 },
609 },
610 }
611 return claims, nil
612 }
613
614 // handleGetKEMKeyClaims returns the claims for a KEM key identified by its UUID.
615 func (s *Server) handleGetKEMKeyClaims(id uuid.UUID) (*keymanager.KeyClaims, error) {
616 // Key Metadata Lookup.
617 kemPubKey, bindingPubKey, algo, remainingLifespanSecs, err := s.keyProtectionService.GetKEMKey(id)
618 if err != nil {
619 return nil, fmt.Errorf("failed to get KEM key: %w", err)
620 }
621
622 // Calculate remaining time.
623 remaining := time.Duration(remainingLifespanSecs) * time.Second
624
625 // Create KeyClaims
626 claims := &keymanager.KeyClaims{
627 Claims: &keymanager.KeyClaims_VmKeyClaims{
628 VmKeyClaims: &keymanager.KeyClaims_VmProtectionKeyClaims{
629 KemPubKey: &keymanager.KemPublicKey{
630 Algorithm: algo.GetKem(),
631 PublicKey: kemPubKey,
632 },
633 BindingPubKey: &keymanager.HpkePublicKey{
634 Algorithm: algo,
635 PublicKey: bindingPubKey,
636 },
637 RemainingLifespan: durationpb.New(remaining),
638 },
639 },
640 }
641 return claims, nil
642 }
643
644 // processClaims is a background worker that processes key claims requests from claimsChan.
645 func (s *Server) processClaims() {
646 for call := range s.claimsChan {
647 result := s.handleGetClaims(call.Request)
648
649 select {
650 case call.RespChan <- result:
651 case <-time.After(ClaimsResponseTimeout):
652 log.Printf("processClaims: timed out sending response for key %s", call.Request.GetKeyHandle().GetHandle())
653 }
654 }
655 }
656
657 // handleGetClaims processes a single GetKeyClaimsRequest and returns the result.
658 func (s *Server) handleGetClaims(req *keymanager.GetKeyClaimsRequest) *ClaimsResult {
659 keyHandle := req.GetKeyHandle().GetHandle()
660 keyType := req.GetKeyType()
661
662 id, err := uuid.Parse(keyHandle)
663 if err != nil {
664 return &ClaimsResult{Err: fmt.Errorf("failed to retrieve key claims: %w", err)}
665 }
666
667 var claims *keymanager.KeyClaims
668 switch keyType {
669 case keymanager.KeyType_KEY_TYPE_VM_PROTECTION_BINDING:
670 claims, err = s.handleGetBindingKeyClaims(id)
671 if err != nil {
672 return &ClaimsResult{Err: fmt.Errorf("failed to retrieve binding key claims: %w", err)}
673 }
674
675 case keymanager.KeyType_KEY_TYPE_VM_PROTECTION_KEY:
676 claims, err = s.handleGetKEMKeyClaims(id)
677 if err != nil {
678 return &ClaimsResult{Err: fmt.Errorf("failed to retrieve VM protection key claims: %w", err)}
679 }
680 default:
681 return &ClaimsResult{Err: fmt.Errorf("unsupported key type: %v", keyType)}
682 }
683
684 return &ClaimsResult{Reply: claims}
685 }
686
687 // GetKeyClaims enqueues request for getting key claims to claims channel.
688 func (s *Server) GetKeyClaims(ctx context.Context, keyHandle string, keyType keymanager.KeyType) (*keymanager.KeyClaims, error) {
689 respChan := make(chan *ClaimsResult, 1)
690 req := &keymanager.GetKeyClaimsRequest{
691 KeyHandle: &keymanager.KeyHandle{Handle: keyHandle},
692 KeyType: keyType,
693 }
694 select {
695 case s.claimsChan <- &ClaimsCall{Request: req, RespChan: respChan}:
696 case <-ctx.Done():
697 return nil, ctx.Err()
698 case <-time.After(ClaimsRequestTimeout):
699 return nil, fmt.Errorf("failed to send request: claims channel is full or worker is stuck")
700 }
701 select {
702 case result := <-respChan:
703 if result.Err != nil {
704 return nil, fmt.Errorf("worker error: %w", result.Err)
705 }
706 return result.Reply, nil
707 case <-ctx.Done():
708 return nil, ctx.Err()
709 case <-time.After(ClaimsResponseTimeout):
710 return nil, fmt.Errorf("timed out waiting for processClaims to respond for key: %s", keyHandle)
711 }
712 }