| 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 azurekeyvault provides a secrets implementation backed by Azure KeyVault. |
| 16 |
// See https://docs.microsoft.com/en-us/azure/key-vault/key-vault-whatis for more information. |
| 17 |
// Use OpenKeeper to construct a *secrets.Keeper. |
| 18 |
// |
| 19 |
// # URLs |
| 20 |
// |
| 21 |
// For secrets.OpenKeeper, azurekeyvault registers for the scheme "azurekeyvault". |
| 22 |
// The default URL opener will use azidentity.DefaultAzureCredential to get credentials. |
| 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 |
// azurekeyvault exposes the following type for As: |
| 31 |
// - Error: *azcore.ResponseError. |
| 32 |
package azurekeyvault |
| 33 |
|
| 34 |
import ( |
| 35 |
"context" |
| 36 |
"errors" |
| 37 |
"fmt" |
| 38 |
"net/url" |
| 39 |
"path" |
| 40 |
"regexp" |
| 41 |
"strings" |
| 42 |
|
| 43 |
"github.com/Azure/azure-sdk-for-go/sdk/azcore" |
| 44 |
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" |
| 45 |
"github.com/Azure/azure-sdk-for-go/sdk/azidentity" |
| 46 |
"github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys" |
| 47 |
"github.com/google/wire" |
| 48 |
"gocloud.dev/gcerrors" |
| 49 |
"gocloud.dev/internal/gcerr" |
| 50 |
"gocloud.dev/internal/useragent" |
| 51 |
"gocloud.dev/secrets" |
| 52 |
) |
| 53 |
|
| 54 |
// Map of HTTP Status Code to go-cloud ErrorCode |
| 55 |
var errorCodeMap = map[int]gcerrors.ErrorCode{ |
| 56 |
200: gcerrors.OK, |
| 57 |
400: gcerrors.InvalidArgument, |
| 58 |
401: gcerrors.PermissionDenied, |
| 59 |
403: gcerrors.PermissionDenied, |
| 60 |
404: gcerrors.NotFound, |
| 61 |
408: gcerrors.DeadlineExceeded, |
| 62 |
429: gcerrors.ResourceExhausted, |
| 63 |
500: gcerrors.Internal, |
| 64 |
501: gcerrors.Unimplemented, |
| 65 |
} |
| 66 |
|
| 67 |
func init() { |
| 68 |
secrets.DefaultURLMux().RegisterKeeper(Scheme, new(defaultDialer)) |
| 69 |
} |
| 70 |
|
| 71 |
// Set holds Wire providers for this package. |
| 72 |
var Set = wire.NewSet( |
| 73 |
DefaultClientMaker, |
| 74 |
wire.Struct(new(URLOpener), "Client"), |
| 75 |
) |
| 76 |
|
| 77 |
// ClientMakerT is the type of a function used to generate a Client. |
| 78 |
type ClientMakerT func(keyVaultURI string) (*azkeys.Client, error) |
| 79 |
|
| 80 |
// defaultDialer dials Azure KeyVault using DefaultClientMaker. |
| 81 |
type defaultDialer struct{} |
| 82 |
|
| 83 |
func (o *defaultDialer) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { |
| 84 |
opener := &URLOpener{ClientMaker: DefaultClientMaker} |
| 85 |
return opener.OpenKeeperURL(ctx, u) |
| 86 |
} |
| 87 |
|
| 88 |
// Scheme is the URL scheme azurekeyvault registers its URLOpener under on secrets.DefaultMux. |
| 89 |
const Scheme = "azurekeyvault" |
| 90 |
|
| 91 |
// URLOpener opens Azure KeyVault URLs like |
| 92 |
// "azurekeyvault://{keyvault-name}.vault.azure.net/keys/{key-name}/{key-version}?algorithm=RSA-OAEP-256". |
| 93 |
// |
| 94 |
// The "azurekeyvault" URL scheme is replaced with "https" to construct an Azure |
| 95 |
// Key Vault keyID, as described in https://docs.microsoft.com/en-us/azure/key-vault/about-keys-secrets-and-certificates. |
| 96 |
// The "/{key-version}"" suffix is optional; it defaults to the latest version. |
| 97 |
// |
| 98 |
// The "algorithm" query parameter sets the algorithm to use; see |
| 99 |
// https://docs.microsoft.com/en-us/rest/api/keyvault/encrypt/encrypt#jsonwebkeyencryptionalgorithm |
| 100 |
// for supported algorithms. It defaults to "RSA-OAEP-256". |
| 101 |
// |
| 102 |
// No other query parameters are supported. |
| 103 |
type URLOpener struct { |
| 104 |
// ClientMaker defaults to DefaultClientMaker. |
| 105 |
ClientMaker ClientMakerT |
| 106 |
|
| 107 |
// Options specifies the options to pass to OpenKeeper. |
| 108 |
Options KeeperOptions |
| 109 |
} |
| 110 |
|
| 111 |
// OpenKeeperURL opens an Azure KeyVault Keeper based on u. |
| 112 |
func (o *URLOpener) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { |
| 113 |
q := u.Query() |
| 114 |
algorithm := q.Get("algorithm") |
| 115 |
if algorithm != "" { |
| 116 |
o.Options.Algorithm = azkeys.JSONWebKeyEncryptionAlgorithm(algorithm) |
| 117 |
q.Del("algorithm") |
| 118 |
} |
| 119 |
for param := range q { |
| 120 |
return nil, fmt.Errorf("open keeper %v: invalid query parameter %q", u, param) |
| 121 |
} |
| 122 |
keyID := "https://" + path.Join(u.Host, u.Path) |
| 123 |
return OpenKeeper(o.ClientMaker, keyID, &o.Options) |
| 124 |
} |
| 125 |
|
| 126 |
type keeper struct { |
| 127 |
client *azkeys.Client |
| 128 |
keyVaultURI string // unused, but for validation in tests |
| 129 |
keyName string |
| 130 |
keyVersion string |
| 131 |
options *KeeperOptions |
| 132 |
} |
| 133 |
|
| 134 |
// KeeperOptions provides configuration options for encryption/decryption operations. |
| 135 |
type KeeperOptions struct { |
| 136 |
// Algorithm sets the encryption algorithm used. |
| 137 |
// Defaults to "RSA-OAEP-256". |
| 138 |
// See https://docs.microsoft.com/en-us/rest/api/keyvault/encrypt/encrypt#jsonwebkeyencryptionalgorithm |
| 139 |
// for more details. |
| 140 |
Algorithm azkeys.JSONWebKeyEncryptionAlgorithm |
| 141 |
|
| 142 |
// EncryptOptions are passed through to Encrypt. |
| 143 |
EncryptOptions *azkeys.EncryptOptions |
| 144 |
|
| 145 |
// DecryptOptions are passed through to Decrypt. |
| 146 |
DecryptOptions *azkeys.DecryptOptions |
| 147 |
} |
| 148 |
|
| 149 |
// DefaultClientMaker returns a function that constructs a KeyVault Client. |
| 150 |
// By default it uses credentials from the environment; |
| 151 |
// See https://docs.microsoft.com/en-us/go/azure/azure-sdk-go-authorization#use-environment-based-authentication. |
| 152 |
// If the environment variable AZURE_KEYVAULT_AUTH_VIA_CLI is set to a truthy value, it |
| 153 |
// uses credentials from the Azure CLI instead. |
| 154 |
func DefaultClientMaker(keyVaultURI string) (*azkeys.Client, error) { |
| 155 |
creds, err := azidentity.NewDefaultAzureCredential(nil) |
| 156 |
if err != nil { |
| 157 |
return nil, err |
| 158 |
} |
| 159 |
return azkeys.NewClient(keyVaultURI, creds, &azkeys.ClientOptions{ |
| 160 |
ClientOptions: policy.ClientOptions{ |
| 161 |
Telemetry: policy.TelemetryOptions{ |
| 162 |
ApplicationID: useragent.AzureUserAgentPrefix("secrets"), |
| 163 |
}, |
| 164 |
}, |
| 165 |
}) |
| 166 |
} |
| 167 |
|
| 168 |
// Note that the last binding may be just a key, or key/version. |
| 169 |
var keyIDRE = regexp.MustCompile(`^(https://.+\.vault\.(?:[a-z\d-.]+)/)keys/(.+)$`) |
| 170 |
|
| 171 |
// OpenKeeper returns a *secrets.Keeper that uses Azure keyVault. |
| 172 |
// |
| 173 |
// clientMaker is used to construct an azkeys.Client. |
| 174 |
// |
| 175 |
// keyID is a Azure Key Vault key identifier like "https://{keyvault-name}.vault.azure.net/keys/{key-name}/{key-version}". |
| 176 |
// The "/{key-version}" suffix is optional; it defaults to the latest version. |
| 177 |
// See https://docs.microsoft.com/en-us/azure/key-vault/about-keys-secrets-and-certificates |
| 178 |
// for more details. |
| 179 |
func OpenKeeper(clientMaker ClientMakerT, keyID string, opts *KeeperOptions) (*secrets.Keeper, error) { |
| 180 |
drv, err := openKeeper(clientMaker, keyID, opts) |
| 181 |
if err != nil { |
| 182 |
return nil, err |
| 183 |
} |
| 184 |
return secrets.NewKeeper(drv), nil |
| 185 |
} |
| 186 |
|
| 187 |
func openKeeper(clientMaker ClientMakerT, keyID string, opts *KeeperOptions) (*keeper, error) { |
| 188 |
if opts == nil { |
| 189 |
opts = &KeeperOptions{} |
| 190 |
} |
| 191 |
if opts.Algorithm == "" { |
| 192 |
opts.Algorithm = azkeys.JSONWebKeyEncryptionAlgorithmRSAOAEP256 |
| 193 |
} |
| 194 |
matches := keyIDRE.FindStringSubmatch(keyID) |
| 195 |
if len(matches) != 3 { |
| 196 |
return nil, fmt.Errorf("invalid keyID %q; must match %v %v", keyID, keyIDRE, matches) |
| 197 |
} |
| 198 |
// matches[0] is the whole keyID, [1] is the keyVaultURI, and [2] is the key or the key/version. |
| 199 |
keyVaultURI := matches[1] |
| 200 |
parts := strings.SplitN(matches[2], "/", 2) |
| 201 |
keyName := parts[0] |
| 202 |
var keyVersion string |
| 203 |
if len(parts) > 1 { |
| 204 |
keyVersion = parts[1] |
| 205 |
} |
| 206 |
client, err := clientMaker(keyVaultURI) |
| 207 |
if err != nil { |
| 208 |
return nil, err |
| 209 |
} |
| 210 |
return &keeper{ |
| 211 |
client: client, |
| 212 |
keyVaultURI: keyVaultURI, |
| 213 |
keyName: keyName, |
| 214 |
keyVersion: keyVersion, |
| 215 |
options: opts, |
| 216 |
}, nil |
| 217 |
} |
| 218 |
|
| 219 |
// Encrypt encrypts the plaintext into a ciphertext. |
| 220 |
func (k *keeper) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) { |
| 221 |
keyOpsResult, err := k.client.Encrypt(ctx, k.keyName, k.keyVersion, azkeys.KeyOperationsParameters{ |
| 222 |
Algorithm: &k.options.Algorithm, |
| 223 |
Value: plaintext, |
| 224 |
}, k.options.EncryptOptions) |
| 225 |
if err != nil { |
| 226 |
return nil, err |
| 227 |
} |
| 228 |
return keyOpsResult.Result, nil |
| 229 |
} |
| 230 |
|
| 231 |
// Decrypt decrypts the ciphertext into a plaintext. |
| 232 |
func (k *keeper) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) { |
| 233 |
keyOpsResult, err := k.client.Decrypt(ctx, k.keyName, k.keyVersion, azkeys.KeyOperationsParameters{ |
| 234 |
Algorithm: &k.options.Algorithm, |
| 235 |
Value: ciphertext, |
| 236 |
}, k.options.DecryptOptions) |
| 237 |
if err != nil { |
| 238 |
return nil, err |
| 239 |
} |
| 240 |
return keyOpsResult.Result, nil |
| 241 |
} |
| 242 |
|
| 243 |
// Close implements driver.Keeper.Close. |
| 244 |
func (k *keeper) Close() error { return nil } |
| 245 |
|
| 246 |
// ErrorAs implements driver.Keeper.ErrorAs. |
| 247 |
func (k *keeper) ErrorAs(err error, i any) bool { |
| 248 |
return errors.As(err, i) |
| 249 |
} |
| 250 |
|
| 251 |
// ErrorCode implements driver.ErrorCode. |
| 252 |
func (k *keeper) ErrorCode(err error) gcerrors.ErrorCode { |
| 253 |
re, ok := err.(*azcore.ResponseError) |
| 254 |
if !ok { |
| 255 |
return gcerr.Unknown |
| 256 |
} |
| 257 |
ec, ok := errorCodeMap[re.StatusCode] |
| 258 |
if !ok { |
| 259 |
return gcerr.Unknown |
| 260 |
} |
| 261 |
return ec |
| 262 |
} |