Debian Codegraph @

secrets/gcpkms/kms.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package gcpkms provides a secrets implementation backed by Google Cloud KMS.
16 // Use OpenKeeper to construct a *secrets.Keeper.
17 //
18 // # URLs
19 //
20 // For secrets.OpenKeeper, gcpkms registers for the scheme "gcpkms".
21 // The default URL opener will create a connection using use default
22 // credentials from the environment, as described in
23 // https://cloud.google.com/docs/authentication/production.
24 // To customize the URL opener, or for more details on the URL format,
25 // see URLOpener.
26 // See https://gocloud.dev/concepts/urls/ for background information.
27 //
28 // # As
29 //
30 // gcpkms exposes the following type for As:
31 // - Error: *google.golang.org/grpc/status.Status
32 package gcpkms // import "gocloud.dev/secrets/gcpkms"
33
34 import (
35 "context"
36 "encoding/base64"
37 "fmt"
38 "net/url"
39 "path"
40 "sync"
41
42 cloudkms "cloud.google.com/go/kms/apiv1"
43 "cloud.google.com/go/kms/apiv1/kmspb"
44 "github.com/google/wire"
45 "gocloud.dev/gcerrors"
46 "gocloud.dev/gcp"
47 "gocloud.dev/internal/gcerr"
48 "gocloud.dev/internal/useragent"
49 "gocloud.dev/secrets"
50 "google.golang.org/api/option"
51 "google.golang.org/grpc/status"
52 )
53
54 // endPoint is the address to access Google Cloud KMS API.
55 const endPoint = "cloudkms.googleapis.com:443"
56
57 // Dial returns a client to use with Cloud KMS and a clean-up function to close
58 // the client after used.
59 func Dial(ctx context.Context, ts gcp.TokenSource) (*cloudkms.KeyManagementClient, func(), error) {
60 c, err := cloudkms.NewKeyManagementClient(ctx, option.WithTokenSource(ts), useragent.ClientOption("secrets"))
61 return c, func() { c.Close() }, err
62 }
63
64 func init() {
65 secrets.DefaultURLMux().RegisterKeeper(Scheme, new(lazyCredsOpener))
66 }
67
68 // Set holds Wire providers for this package.
69 var Set = wire.NewSet(
70 Dial,
71 wire.Struct(new(URLOpener), "Client"),
72 )
73
74 // lazyCredsOpener obtains Application Default Credentials on the first call
75 // lazyCredsOpener obtains Application Default Credentials on the first call
76 // to OpenKeeperURL.
77 type lazyCredsOpener struct {
78 init sync.Once
79 opener *URLOpener
80 err error
81 }
82
83 func (o *lazyCredsOpener) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) {
84 o.init.Do(func() {
85 creds, err := gcp.DefaultCredentials(ctx)
86 if err != nil {
87 o.err = err
88 return
89 }
90 client, _, err := Dial(ctx, creds.TokenSource)
91 if err != nil {
92 o.err = err
93 return
94 }
95 o.opener = &URLOpener{Client: client}
96 })
97 if o.err != nil {
98 return nil, fmt.Errorf("open keeper %v: %v", u, o.err)
99 }
100 return o.opener.OpenKeeperURL(ctx, u)
101 }
102
103 // Scheme is the URL scheme gcpkms registers its URLOpener under on secrets.DefaultMux.
104 const Scheme = "gcpkms"
105
106 // URLOpener opens GCP KMS URLs like
107 // "gcpkms://projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEY_RING]/cryptoKeys/[KEY]".
108 //
109 // The URL host+path are used as the key resource ID; see
110 // https://cloud.google.com/kms/docs/object-hierarchy#key for more details.
111 //
112 // The following query parameters are supported:
113 //
114 // - additional_authenticated_data: a base64 URL encoded string of AAD provided to encrypt and
115 // decrypt calls.
116 type URLOpener struct {
117 // Client must be non-nil and be authenticated with "cloudkms" scope or equivalent.
118 Client *cloudkms.KeyManagementClient
119
120 // Options specifies the default options to pass to OpenKeeper.
121 Options KeeperOptions
122 }
123
124 // OpenKeeperURL opens GCP KMS URLs.
125 func (o *URLOpener) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) {
126 q := u.Query()
127 for param := range q {
128 if param != "additional_authenticated_data" {
129 return nil, fmt.Errorf("open keeper %v: invalid query parameter %q", u, param)
130 }
131 }
132 opts := o.Options
133 if aad := q.Get("additional_authenticated_data"); aad != "" {
134 dec, err := base64.URLEncoding.DecodeString(aad)
135 if err != nil {
136 return nil, fmt.Errorf("failed to base64-decode \"additional_authenticated_data\": %w", err)
137 }
138
139 opts.AdditionalAuthenticatedData = dec
140 }
141 return OpenKeeper(o.Client, path.Join(u.Host, u.Path), &opts), nil
142 }
143
144 // OpenKeeper returns a *secrets.Keeper that uses Google Cloud KMS.
145 // You can use KeyResourceID to construct keyResourceID from its parts,
146 // or provide the whole string if you have it (e.g., from the GCP console).
147 // See https://cloud.google.com/kms/docs/object-hierarchy#key for more details.
148 // See the package documentation for an example.
149 func OpenKeeper(client *cloudkms.KeyManagementClient, keyResourceID string, opts *KeeperOptions) *secrets.Keeper {
150 if opts == nil {
151 opts = &KeeperOptions{}
152 }
153 return secrets.NewKeeper(&keeper{
154 keyResourceID: keyResourceID,
155 client: client,
156 opts: *opts,
157 })
158 }
159
160 // KeyResourceID constructs a key resourceID for GCP KMS.
161 // See https://cloud.google.com/kms/docs/object-hierarchy#key for more details.
162 func KeyResourceID(projectID, location, keyRing, key string) string {
163 return fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
164 projectID, location, keyRing, key)
165 }
166
167 // keeper implements driver.Keeper.
168 type keeper struct {
169 keyResourceID string
170 client *cloudkms.KeyManagementClient
171 opts KeeperOptions
172 }
173
174 // Decrypt decrypts the ciphertext using the key constructed from ki.
175 func (k *keeper) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) {
176 req := &kmspb.DecryptRequest{
177 Name: k.keyResourceID,
178 Ciphertext: ciphertext,
179 AdditionalAuthenticatedData: k.opts.AdditionalAuthenticatedData,
180 }
181 resp, err := k.client.Decrypt(ctx, req)
182 if err != nil {
183 return nil, err
184 }
185 return resp.GetPlaintext(), nil
186 }
187
188 // Encrypt encrypts the plaintext into a ciphertext.
189 func (k *keeper) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) {
190 req := &kmspb.EncryptRequest{
191 Name: k.keyResourceID,
192 Plaintext: plaintext,
193 AdditionalAuthenticatedData: k.opts.AdditionalAuthenticatedData,
194 }
195 resp, err := k.client.Encrypt(ctx, req)
196 if err != nil {
197 return nil, err
198 }
199 return resp.GetCiphertext(), nil
200 }
201
202 // Close implements driver.Keeper.Close.
203 func (k *keeper) Close() error { return nil }
204
205 // ErrorAs implements driver.Keeper.ErrorAs.
206 func (k *keeper) ErrorAs(err error, i any) bool {
207 s, ok := status.FromError(err)
208 if !ok {
209 return false
210 }
211 p, ok := i.(**status.Status)
212 if !ok {
213 return false
214 }
215 *p = s
216 return true
217 }
218
219 // ErrorCode implements driver.ErrorCode.
220 func (k *keeper) ErrorCode(err error) gcerrors.ErrorCode {
221 return gcerr.GRPCCode(err)
222 }
223
224 // KeeperOptions controls Keeper behaviors.
225 type KeeperOptions struct {
226 // AdditionalAuthenticatedData is non-secret data used as an optional integrity check which must
227 // match between encrypt and decrypt operations. This prevents confused deputy attacks by
228 // binding context to encrypted data without being stored in the ciphertext.
229 // See here for more info: https://docs.cloud.google.com/kms/docs/additional-authenticated-data.
230 AdditionalAuthenticatedData []byte
231 }