2022-05-23 05:36:54 -04:00
|
|
|
package kms
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
2022-06-28 10:51:30 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/logger"
|
2022-05-23 05:36:54 -04:00
|
|
|
"github.com/edgelesssys/constellation/kms/server/kmsapi/kmsproto"
|
2022-06-28 10:51:30 -04:00
|
|
|
"go.uber.org/zap"
|
2022-05-23 05:36:54 -04:00
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Client interacts with Constellation's key management service.
|
|
|
|
type Client struct {
|
2022-06-28 10:51:30 -04:00
|
|
|
log *logger.Logger
|
2022-05-23 05:36:54 -04:00
|
|
|
endpoint string
|
|
|
|
grpc grpcClient
|
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a new KMS.
|
2022-06-28 10:51:30 -04:00
|
|
|
func New(log *logger.Logger, endpoint string) Client {
|
2022-05-23 05:36:54 -04:00
|
|
|
return Client{
|
2022-06-28 10:51:30 -04:00
|
|
|
log: log,
|
2022-05-23 05:36:54 -04:00
|
|
|
endpoint: endpoint,
|
|
|
|
grpc: client{},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetDEK returns a data encryption key for the given UUID.
|
|
|
|
func (c Client) GetDataKey(ctx context.Context, uuid string, length int) ([]byte, error) {
|
2022-06-28 10:51:30 -04:00
|
|
|
log := c.log.With(zap.String("diskUUID", uuid), zap.String("endpoint", c.endpoint))
|
2022-05-23 05:36:54 -04:00
|
|
|
// TODO: update credentials if we enable aTLS on the KMS
|
|
|
|
// For now this is fine since traffic is only routed through the Constellation cluster
|
2022-06-28 10:51:30 -04:00
|
|
|
log.Infof("Connecting to KMS at %s", c.endpoint)
|
2022-05-23 05:36:54 -04:00
|
|
|
conn, err := grpc.DialContext(ctx, c.endpoint, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
|
2022-06-28 10:51:30 -04:00
|
|
|
log.Infof("Requesting data key")
|
2022-05-23 05:36:54 -04:00
|
|
|
res, err := c.grpc.GetDataKey(
|
|
|
|
ctx,
|
|
|
|
&kmsproto.GetDataKeyRequest{
|
|
|
|
DataKeyId: uuid,
|
|
|
|
Length: uint32(length),
|
|
|
|
},
|
|
|
|
conn,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("fetching data encryption key from Constellation KMS: %w", err)
|
|
|
|
}
|
|
|
|
|
2022-06-28 10:51:30 -04:00
|
|
|
log.Infof("Data key request successful")
|
2022-05-23 05:36:54 -04:00
|
|
|
return res.DataKey, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type grpcClient interface {
|
|
|
|
GetDataKey(context.Context, *kmsproto.GetDataKeyRequest, *grpc.ClientConn) (*kmsproto.GetDataKeyResponse, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type client struct{}
|
|
|
|
|
|
|
|
func (c client) GetDataKey(ctx context.Context, req *kmsproto.GetDataKeyRequest, conn *grpc.ClientConn) (*kmsproto.GetDataKeyResponse, error) {
|
|
|
|
return kmsproto.NewAPIClient(conn).GetDataKey(ctx, req)
|
|
|
|
}
|