Debian Codegraph @

pkg/storage/value/encrypt/envelope/kmsv2/grpc_service.go

raw
1 /*
2 Copyright 2022 The Kubernetes 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
17 // Package kmsv2 transforms values for storage at rest using a Envelope provider
18 package kmsv2
19
20 import (
21 "context"
22 "fmt"
23 "net"
24 "time"
25
26 "google.golang.org/grpc"
27 "google.golang.org/grpc/credentials/insecure"
28
29 utilruntime "k8s.io/apimachinery/pkg/util/runtime"
30 "k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics"
31 "k8s.io/klog/v2"
32 kmsapi "k8s.io/kms/apis/v2"
33 kmsservice "k8s.io/kms/pkg/service"
34 "k8s.io/kms/pkg/util"
35 )
36
37 const (
38 // unixProtocol is the only supported protocol for remote KMS provider.
39 unixProtocol = "unix"
40 )
41
42 // The gRPC implementation for envelope.Service.
43 type gRPCService struct {
44 kmsClient kmsapi.KeyManagementServiceClient
45 connection *grpc.ClientConn
46 callTimeout time.Duration
47 }
48
49 // NewGRPCService returns an envelope.Service which use gRPC to communicate the remote KMS provider.
50 func NewGRPCService(ctx context.Context, endpoint, providerName string, callTimeout time.Duration) (kmsservice.Service, error) {
51 klog.V(4).InfoS("Configure KMS provider", "endpoint", endpoint)
52
53 addr, err := util.ParseEndpoint(endpoint)
54 if err != nil {
55 return nil, err
56 }
57
58 s := &gRPCService{callTimeout: callTimeout}
59 s.connection, err = grpc.Dial(
60 addr,
61 grpc.WithAuthority("localhost"),
62 grpc.WithTransportCredentials(insecure.NewCredentials()),
63 grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
64 grpc.WithContextDialer(
65 func(context.Context, string) (net.Conn, error) {
66 // Ignoring addr and timeout arguments:
67 // addr - comes from the closure
68 c, err := net.DialUnix(unixProtocol, nil, &net.UnixAddr{Name: addr})
69 if err != nil {
70 klog.ErrorS(err, "failed to create connection to unix socket", "addr", addr)
71 } else {
72 klog.V(4).InfoS("Successfully dialed Unix socket", "addr", addr)
73 }
74 return c, err
75 }),
76 grpc.WithChainUnaryInterceptor(recordMetricsInterceptor(providerName)),
77 )
78
79 if err != nil {
80 return nil, fmt.Errorf("failed to create connection to %s, error: %v", endpoint, err)
81 }
82
83 s.kmsClient = kmsapi.NewKeyManagementServiceClient(s.connection)
84
85 go func() {
86 defer utilruntime.HandleCrash()
87
88 <-ctx.Done()
89 _ = s.connection.Close()
90 }()
91
92 return s, nil
93 }
94
95 // Decrypt a given data string to obtain the original byte data.
96 func (g *gRPCService) Decrypt(ctx context.Context, uid string, req *kmsservice.DecryptRequest) ([]byte, error) {
97 ctx, cancel := context.WithTimeout(ctx, g.callTimeout)
98 defer cancel()
99
100 request := &kmsapi.DecryptRequest{
101 Ciphertext: req.Ciphertext,
102 Uid: uid,
103 KeyId: req.KeyID,
104 Annotations: req.Annotations,
105 }
106 response, err := g.kmsClient.Decrypt(ctx, request)
107 if err != nil {
108 return nil, err
109 }
110 return response.Plaintext, nil
111 }
112
113 // Encrypt bytes to a string ciphertext.
114 func (g *gRPCService) Encrypt(ctx context.Context, uid string, plaintext []byte) (*kmsservice.EncryptResponse, error) {
115 ctx, cancel := context.WithTimeout(ctx, g.callTimeout)
116 defer cancel()
117
118 request := &kmsapi.EncryptRequest{
119 Plaintext: plaintext,
120 Uid: uid,
121 }
122 response, err := g.kmsClient.Encrypt(ctx, request)
123 if err != nil {
124 return nil, err
125 }
126 return &kmsservice.EncryptResponse{
127 Ciphertext: response.Ciphertext,
128 KeyID: response.KeyId,
129 Annotations: response.Annotations,
130 }, nil
131 }
132
133 // Status returns the status of the KMSv2 provider.
134 func (g *gRPCService) Status(ctx context.Context) (*kmsservice.StatusResponse, error) {
135 ctx, cancel := context.WithTimeout(ctx, g.callTimeout)
136 defer cancel()
137
138 request := &kmsapi.StatusRequest{}
139 response, err := g.kmsClient.Status(ctx, request)
140 if err != nil {
141 return nil, err
142 }
143 return &kmsservice.StatusResponse{Version: response.Version, Healthz: response.Healthz, KeyID: response.KeyId}, nil
144 }
145
146 func recordMetricsInterceptor(providerName string) grpc.UnaryClientInterceptor {
147 return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
148 start := NowFunc()
149 respErr := invoker(ctx, method, req, reply, cc, opts...)
150 elapsed := NowFunc().Sub(start)
151 metrics.RecordKMSOperationLatency(providerName, method, elapsed, respErr)
152 return respErr
153 }
154 }