| 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 |
// limtations under the License. |
| 14 |
|
| 15 |
// Package hashivault provides a secrets implementation using the Transit |
| 16 |
// Secrets Engine of Vault by Hashicorp. |
| 17 |
// Use OpenKeeper to construct a *secrets.Keeper. |
| 18 |
// |
| 19 |
// # URLs |
| 20 |
// |
| 21 |
// For secrets.OpenKeeper, hashivault registers for the scheme "hashivault". |
| 22 |
// The default URL opener will dial a Vault server using the environment variables |
| 23 |
// "VAULT_SERVER_URL" (or "VAULT_ADDR") and "VAULT_SERVER_TOKEN" (or "VAULT_TOKEN"). |
| 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 |
// hashivault does not support any types for As. |
| 31 |
package hashivault |
| 32 |
|
| 33 |
import ( |
| 34 |
"context" |
| 35 |
"encoding/base64" |
| 36 |
"errors" |
| 37 |
"fmt" |
| 38 |
"net/url" |
| 39 |
"os" |
| 40 |
"path" |
| 41 |
"sync" |
| 42 |
|
| 43 |
"github.com/hashicorp/vault/api" |
| 44 |
"gocloud.dev/gcerrors" |
| 45 |
"gocloud.dev/secrets" |
| 46 |
) |
| 47 |
|
| 48 |
// Config is the authentication configurations of the Vault server. |
| 49 |
type Config struct { |
| 50 |
// Token is the access token the Vault client uses to talk to the server. |
| 51 |
// See https://www.vaultproject.io/docs/concepts/tokens.html for more |
| 52 |
// information. |
| 53 |
Token string |
| 54 |
// APIConfig is used to configure the creation of the client. |
| 55 |
APIConfig api.Config |
| 56 |
} |
| 57 |
|
| 58 |
// Dial gets a Vault client. |
| 59 |
func Dial(ctx context.Context, cfg *Config) (*api.Client, error) { |
| 60 |
if cfg == nil { |
| 61 |
return nil, errors.New("no auth Config provided") |
| 62 |
} |
| 63 |
c, err := api.NewClient(&cfg.APIConfig) |
| 64 |
if err != nil { |
| 65 |
return nil, err |
| 66 |
} |
| 67 |
if cfg.Token != "" { |
| 68 |
c.SetToken(cfg.Token) |
| 69 |
} |
| 70 |
return c, nil |
| 71 |
} |
| 72 |
|
| 73 |
func init() { |
| 74 |
secrets.DefaultURLMux().RegisterKeeper(Scheme, new(defaultDialer)) |
| 75 |
} |
| 76 |
|
| 77 |
// getVaultURL ensures that we check both VAULT_SERVER_URL and VAULT_ADDR environment |
| 78 |
// variables for the API address for vault. VAULT_SERVER_URL takes precedence over VAULT_ADDR. |
| 79 |
func getVaultURL() (string, error) { |
| 80 |
serverURL := os.Getenv("VAULT_SERVER_URL") |
| 81 |
if serverURL != "" { |
| 82 |
return serverURL, nil |
| 83 |
} |
| 84 |
|
| 85 |
vaultAddr := os.Getenv("VAULT_ADDR") |
| 86 |
if vaultAddr != "" { |
| 87 |
return vaultAddr, nil |
| 88 |
} |
| 89 |
|
| 90 |
return "", errors.New("neither VAULT_SERVER_URL nor VAULT_ADDR environment variables are set") |
| 91 |
} |
| 92 |
|
| 93 |
// getVaultToken ensures that we check both VAULT_SERVER_TOKEN and VAULT_TOKEN environment |
| 94 |
// variables for the API token for vault. VAULT_SERVER_TOKEN takes precedence over VAULT_TOKEN. |
| 95 |
// If neither environment variables are found, then we return an empty string as token is not required. |
| 96 |
func getVaultToken() string { |
| 97 |
serverToken := os.Getenv("VAULT_SERVER_TOKEN") |
| 98 |
if serverToken != "" { |
| 99 |
return serverToken |
| 100 |
} |
| 101 |
|
| 102 |
vaultToken := os.Getenv("VAULT_TOKEN") |
| 103 |
if vaultToken != "" { |
| 104 |
return vaultToken |
| 105 |
} |
| 106 |
|
| 107 |
return "" |
| 108 |
} |
| 109 |
|
| 110 |
// defaultDialer dials a default Vault server based on the environment variables |
| 111 |
// VAULT_SERVER_URL / VAULT_ADDR and VAULT_SERVER_TOKEN / VAULT_TOKEN |
| 112 |
type defaultDialer struct { |
| 113 |
init sync.Once |
| 114 |
opener *URLOpener |
| 115 |
err error |
| 116 |
} |
| 117 |
|
| 118 |
func (o *defaultDialer) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { |
| 119 |
o.init.Do(func() { |
| 120 |
serverURL, err := getVaultURL() |
| 121 |
if err != nil { |
| 122 |
o.err = err |
| 123 |
return |
| 124 |
} |
| 125 |
token := getVaultToken() |
| 126 |
cfg := Config{Token: token, APIConfig: api.Config{Address: serverURL}} |
| 127 |
client, err := Dial(ctx, &cfg) |
| 128 |
if err != nil { |
| 129 |
o.err = fmt.Errorf("failed to Dial default Vault server at %q: %v", serverURL, err) |
| 130 |
return |
| 131 |
} |
| 132 |
o.opener = &URLOpener{Client: client} |
| 133 |
}) |
| 134 |
if o.err != nil { |
| 135 |
return nil, fmt.Errorf("open keeper %v: %v", u, o.err) |
| 136 |
} |
| 137 |
return o.opener.OpenKeeperURL(ctx, u) |
| 138 |
} |
| 139 |
|
| 140 |
// Scheme is the URL scheme hashivault registers its URLOpener under on secrets.DefaultMux. |
| 141 |
const Scheme = "hashivault" |
| 142 |
|
| 143 |
// URLOpener opens Vault URLs like "hashivault://mykey". |
| 144 |
// |
| 145 |
// The URL Host + Path are used as the keyID. |
| 146 |
// |
| 147 |
// The following query parameters are supported: |
| 148 |
// - engine: The secrets engine to use; defaults to "transit". |
| 149 |
type URLOpener struct { |
| 150 |
// Client must be non-nil. |
| 151 |
Client *api.Client |
| 152 |
|
| 153 |
// Options specifies the options to pass to OpenKeeper. |
| 154 |
Options KeeperOptions |
| 155 |
} |
| 156 |
|
| 157 |
// OpenKeeperURL opens the Keeper URL. |
| 158 |
func (o *URLOpener) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { |
| 159 |
for param, vals := range u.Query() { |
| 160 |
switch param { |
| 161 |
case "engine": |
| 162 |
o.Options.Engine = vals[0] |
| 163 |
default: |
| 164 |
return nil, fmt.Errorf("open keeper %v: invalid query parameter %q", u, param) |
| 165 |
} |
| 166 |
} |
| 167 |
return OpenKeeper(o.Client, path.Join(u.Host, u.Path), &o.Options), nil |
| 168 |
} |
| 169 |
|
| 170 |
func newKeeper(client *api.Client, keyID string, opts *KeeperOptions) *keeper { |
| 171 |
if opts == nil { |
| 172 |
opts = &KeeperOptions{} |
| 173 |
} |
| 174 |
if opts.Engine == "" { |
| 175 |
opts.Engine = "transit" |
| 176 |
} |
| 177 |
return &keeper{ |
| 178 |
keyID: keyID, |
| 179 |
client: client, |
| 180 |
opts: *opts, |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
// OpenKeeper returns a *secrets.Keeper that uses the Transit Secrets Engine of |
| 185 |
// Vault by Hashicorp. |
| 186 |
// See the package documentation for an example. |
| 187 |
func OpenKeeper(client *api.Client, keyID string, opts *KeeperOptions) *secrets.Keeper { |
| 188 |
return secrets.NewKeeper(newKeeper(client, keyID, opts)) |
| 189 |
} |
| 190 |
|
| 191 |
type keeper struct { |
| 192 |
// keyID is an encryption key ring name used by the Vault's transit API. |
| 193 |
keyID string |
| 194 |
client *api.Client |
| 195 |
opts KeeperOptions |
| 196 |
} |
| 197 |
|
| 198 |
// Decrypt decrypts the ciphertext into a plaintext. |
| 199 |
func (k *keeper) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) { |
| 200 |
out, err := k.client.Logical().Write( |
| 201 |
path.Join(k.opts.Engine+"/decrypt", k.keyID), |
| 202 |
map[string]any{ |
| 203 |
"ciphertext": string(ciphertext), |
| 204 |
}, |
| 205 |
) |
| 206 |
if err != nil { |
| 207 |
return nil, err |
| 208 |
} |
| 209 |
return base64.StdEncoding.DecodeString(out.Data["plaintext"].(string)) |
| 210 |
} |
| 211 |
|
| 212 |
// Encrypt encrypts a plaintext into a ciphertext. |
| 213 |
func (k *keeper) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) { |
| 214 |
secret, err := k.client.Logical().Write( |
| 215 |
path.Join(k.opts.Engine+"/encrypt", k.keyID), |
| 216 |
map[string]any{ |
| 217 |
"plaintext": plaintext, |
| 218 |
}, |
| 219 |
) |
| 220 |
if err != nil { |
| 221 |
return nil, err |
| 222 |
} |
| 223 |
return []byte(secret.Data["ciphertext"].(string)), nil |
| 224 |
} |
| 225 |
|
| 226 |
// Close implements driver.Keeper.Close. |
| 227 |
func (k *keeper) Close() error { return nil } |
| 228 |
|
| 229 |
// ErrorAs implements driver.Keeper.ErrorAs. |
| 230 |
func (k *keeper) ErrorAs(err error, i any) bool { |
| 231 |
return false |
| 232 |
} |
| 233 |
|
| 234 |
// ErrorCode implements driver.ErrorCode. |
| 235 |
func (k *keeper) ErrorCode(error) gcerrors.ErrorCode { |
| 236 |
// TODO(shantuo): try to classify vault error codes |
| 237 |
return gcerrors.Unknown |
| 238 |
} |
| 239 |
|
| 240 |
// KeeperOptions controls Keeper behaviors. |
| 241 |
// It is provided for future extensibility. |
| 242 |
type KeeperOptions struct { |
| 243 |
// Engine is the name of the secrets engine to use. |
| 244 |
// It defaults to "transit". |
| 245 |
Engine string |
| 246 |
} |