| 1 |
// Copyright 2019 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 awskms provides a secrets implementation backed by AWS KMS. |
| 16 |
// Use OpenKeeper to construct a *secrets.Keeper. |
| 17 |
// |
| 18 |
// # URLs |
| 19 |
// |
| 20 |
// For secrets.OpenKeeper, awskms registers for the scheme "awskms". |
| 21 |
// The default URL opener will use an AWS session with the default credentials |
| 22 |
// and configuration. |
| 23 |
// |
| 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 |
// awskms exposes the following type for As: |
| 31 |
// - Error: any error type returned by the service, notably smithy.APIError |
| 32 |
package awskms // import "gocloud.dev/secrets/awskms" |
| 33 |
|
| 34 |
import ( |
| 35 |
"context" |
| 36 |
"errors" |
| 37 |
"fmt" |
| 38 |
"net/url" |
| 39 |
"path" |
| 40 |
"strings" |
| 41 |
"sync" |
| 42 |
|
| 43 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 44 |
"github.com/aws/aws-sdk-go-v2/service/kms" |
| 45 |
"github.com/aws/aws-sdk-go-v2/service/kms/types" |
| 46 |
"github.com/aws/smithy-go" |
| 47 |
"github.com/google/wire" |
| 48 |
gcaws "gocloud.dev/aws" |
| 49 |
"gocloud.dev/gcerrors" |
| 50 |
"gocloud.dev/internal/gcerr" |
| 51 |
"gocloud.dev/secrets" |
| 52 |
) |
| 53 |
|
| 54 |
func init() { |
| 55 |
secrets.DefaultURLMux().RegisterKeeper(Scheme, new(lazySessionOpener)) |
| 56 |
} |
| 57 |
|
| 58 |
// Set holds Wire providers for this package. |
| 59 |
var Set = wire.NewSet( |
| 60 |
Dial, |
| 61 |
) |
| 62 |
|
| 63 |
// Dial gets an AWS KMS service client using the AWS SDK V2. |
| 64 |
func Dial(cfg aws.Config) (*kms.Client, error) { |
| 65 |
return kms.NewFromConfig(cfg), nil |
| 66 |
} |
| 67 |
|
| 68 |
var DialV2 = Dial |
| 69 |
|
| 70 |
// lazySessionOpener obtains the AWS session from the environment on the first |
| 71 |
// call to OpenKeeperURL. |
| 72 |
type lazySessionOpener struct { |
| 73 |
init sync.Once |
| 74 |
opener *URLOpener |
| 75 |
err error |
| 76 |
} |
| 77 |
|
| 78 |
func (o *lazySessionOpener) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { |
| 79 |
opener := &URLOpener{} |
| 80 |
return opener.OpenKeeperURL(ctx, u) |
| 81 |
} |
| 82 |
|
| 83 |
// Scheme is the URL scheme awskms registers its URLOpener under on secrets.DefaultMux. |
| 84 |
const Scheme = "awskms" |
| 85 |
|
| 86 |
// URLOpener opens AWS KMS URLs like "awskms://keyID" or "awskms:///keyID". |
| 87 |
// |
| 88 |
// The URL Host + Path are used as the key ID, which can be in the form of an |
| 89 |
// Amazon Resource Name (ARN), alias name, or alias ARN. See |
| 90 |
// https://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html#find-cmk-id-arn |
| 91 |
// for more details. Note that ARNs may contain ":" characters, which cannot be |
| 92 |
// escaped in the Host part of a URL, so the "awskms:///<ARN>" form should be used. |
| 93 |
// |
| 94 |
// See https://pkg.go.dev/gocloud.dev/aws#V2ConfigFromURLParams. |
| 95 |
// |
| 96 |
// EncryptionContext key/value pairs can be provided by providing URL parameters prefixed |
| 97 |
// with "context_"; e.g., "...&context_abc=foo&context_def=bar" would result in |
| 98 |
// an EncryptionContext of {abc=foo, def=bar}. |
| 99 |
// See https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context. |
| 100 |
type URLOpener struct { |
| 101 |
// Options specifies the options to pass to OpenKeeper. |
| 102 |
// EncryptionContext parameters from the URL are merged in. |
| 103 |
Options KeeperOptions |
| 104 |
} |
| 105 |
|
| 106 |
// addEncryptionContextFromURLParams merges any EncryptionContext URL parameters from |
| 107 |
// u into opts.EncryptionParameters. |
| 108 |
// It removes the processed URL parameters from u. |
| 109 |
func addEncryptionContextFromURLParams(opts *KeeperOptions, u url.Values) error { |
| 110 |
for k, vs := range u { |
| 111 |
if strings.HasPrefix(k, "context_") { |
| 112 |
if len(vs) != 1 { |
| 113 |
return fmt.Errorf("open keeper: EncryptionContext URL parameters %q must have exactly 1 value", k) |
| 114 |
} |
| 115 |
u.Del(k) |
| 116 |
if opts.EncryptionContext == nil { |
| 117 |
opts.EncryptionContext = map[string]string{} |
| 118 |
} |
| 119 |
opts.EncryptionContext[k[8:]] = vs[0] |
| 120 |
} |
| 121 |
} |
| 122 |
return nil |
| 123 |
} |
| 124 |
|
| 125 |
// OpenKeeperURL opens an AWS KMS Keeper based on u. |
| 126 |
func (o *URLOpener) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { |
| 127 |
// A leading "/" means the Host was empty; trim the slash. |
| 128 |
// This is so that awskms:///foo:bar results in "foo:bar" instead of |
| 129 |
// "/foo:bar". |
| 130 |
keyID := strings.TrimPrefix(path.Join(u.Host, u.Path), "/") |
| 131 |
|
| 132 |
queryParams := u.Query() |
| 133 |
opts := o.Options |
| 134 |
if err := addEncryptionContextFromURLParams(&opts, queryParams); err != nil { |
| 135 |
return nil, err |
| 136 |
} |
| 137 |
|
| 138 |
cfg, err := gcaws.V2ConfigFromURLParams(ctx, queryParams) |
| 139 |
if err != nil { |
| 140 |
return nil, fmt.Errorf("open keeper %v: %v", u, err) |
| 141 |
} |
| 142 |
client, err := Dial(cfg) |
| 143 |
if err != nil { |
| 144 |
return nil, err |
| 145 |
} |
| 146 |
return OpenKeeper(client, keyID, &opts), nil |
| 147 |
} |
| 148 |
|
| 149 |
// OpenKeeper returns a *secrets.Keeper that uses AWS KMS, using SDK v2. |
| 150 |
// The key ID can be in the form of an Amazon Resource Name (ARN), alias |
| 151 |
// name, or alias ARN. See |
| 152 |
// https://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html#find-cmk-id-arn |
| 153 |
// for more details. |
| 154 |
// See the package documentation for an example. |
| 155 |
func OpenKeeper(client *kms.Client, keyID string, opts *KeeperOptions) *secrets.Keeper { |
| 156 |
if opts == nil { |
| 157 |
opts = &KeeperOptions{} |
| 158 |
} |
| 159 |
return secrets.NewKeeper(&keeper{ |
| 160 |
keyID: keyID, |
| 161 |
client: client, |
| 162 |
opts: *opts, |
| 163 |
}) |
| 164 |
} |
| 165 |
|
| 166 |
var OpenKeeperV2 = OpenKeeper |
| 167 |
|
| 168 |
type keeper struct { |
| 169 |
keyID string |
| 170 |
opts KeeperOptions |
| 171 |
client *kms.Client |
| 172 |
} |
| 173 |
|
| 174 |
// Decrypt decrypts the ciphertext into a plaintext. |
| 175 |
func (k *keeper) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) { |
| 176 |
result, err := k.client.Decrypt(ctx, &kms.DecryptInput{ |
| 177 |
CiphertextBlob: ciphertext, |
| 178 |
EncryptionContext: k.opts.EncryptionContext, |
| 179 |
}) |
| 180 |
if err != nil { |
| 181 |
return nil, err |
| 182 |
} |
| 183 |
return result.Plaintext, nil |
| 184 |
} |
| 185 |
|
| 186 |
// Encrypt encrypts the plaintext into a ciphertext. |
| 187 |
func (k *keeper) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) { |
| 188 |
result, err := k.client.Encrypt(ctx, &kms.EncryptInput{ |
| 189 |
KeyId: aws.String(k.keyID), |
| 190 |
Plaintext: plaintext, |
| 191 |
EncryptionContext: k.opts.EncryptionContext, |
| 192 |
}) |
| 193 |
if err != nil { |
| 194 |
return nil, err |
| 195 |
} |
| 196 |
return result.CiphertextBlob, nil |
| 197 |
} |
| 198 |
|
| 199 |
// Close implements driver.Keeper.Close. |
| 200 |
func (k *keeper) Close() error { return nil } |
| 201 |
|
| 202 |
// ErrorAs implements driver.Keeper.ErrorAs. |
| 203 |
func (k *keeper) ErrorAs(err error, i any) bool { |
| 204 |
return errors.As(err, i) |
| 205 |
} |
| 206 |
|
| 207 |
// ErrorCode implements driver.ErrorCode. |
| 208 |
func (k *keeper) ErrorCode(err error) gcerrors.ErrorCode { |
| 209 |
var ae smithy.APIError |
| 210 |
if !errors.As(err, &ae) { |
| 211 |
return gcerr.Unknown |
| 212 |
} |
| 213 |
code := ae.ErrorCode() |
| 214 |
ec, ok := errorCodeMap[code] |
| 215 |
if !ok { |
| 216 |
return gcerr.Unknown |
| 217 |
} |
| 218 |
return ec |
| 219 |
} |
| 220 |
|
| 221 |
var errorCodeMap = map[string]gcerrors.ErrorCode{ |
| 222 |
(&types.NotFoundException{}).ErrorCode(): gcerrors.NotFound, |
| 223 |
(&types.InvalidCiphertextException{}).ErrorCode(): gcerrors.InvalidArgument, |
| 224 |
(&types.InvalidKeyUsageException{}).ErrorCode(): gcerrors.InvalidArgument, |
| 225 |
(&types.KMSInternalException{}).ErrorCode(): gcerrors.Internal, |
| 226 |
(&types.KMSInvalidStateException{}).ErrorCode(): gcerrors.FailedPrecondition, |
| 227 |
(&types.DisabledException{}).ErrorCode(): gcerrors.PermissionDenied, |
| 228 |
(&types.InvalidGrantTokenException{}).ErrorCode(): gcerrors.PermissionDenied, |
| 229 |
(&types.KeyUnavailableException{}).ErrorCode(): gcerrors.ResourceExhausted, |
| 230 |
(&types.DependencyTimeoutException{}).ErrorCode(): gcerrors.DeadlineExceeded, |
| 231 |
} |
| 232 |
|
| 233 |
// KeeperOptions controls Keeper behaviors. |
| 234 |
// It is provided for future extensibility. |
| 235 |
type KeeperOptions struct { |
| 236 |
// EncryptionContext parameters. |
| 237 |
// See https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context. |
| 238 |
EncryptionContext map[string]string |
| 239 |
} |