pulumi/pkg/secrets/cloud/manager.go

197 lines
6.3 KiB
Go
Raw Permalink Normal View History

// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package cloud implements support for a generic cloud secret manager.
package cloud
import (
"context"
"crypto/rand"
2023-01-12 14:37:21 +00:00
"encoding/base64"
"encoding/json"
"fmt"
netUrl "net/url"
2023-01-12 14:37:21 +00:00
"os"
gosecrets "gocloud.dev/secrets"
_ "gocloud.dev/secrets/awskms" // support for awskms://
_ "gocloud.dev/secrets/azurekeyvault" // support for azurekeyvault://
"gocloud.dev/secrets/gcpkms" // support for gcpkms://
_ "gocloud.dev/secrets/hashivault" // support for hashivault://
"google.golang.org/api/cloudkms/v1"
"github.com/pulumi/pulumi/pkg/v3/authhelpers"
"github.com/pulumi/pulumi/pkg/v3/secrets"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/config"
2023-01-12 14:37:21 +00:00
"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
)
// Type is the type of secrets managed by this secrets provider
const Type = "cloud"
type cloudSecretsManagerState struct {
URL string `json:"url"`
EncryptedKey []byte `json:"encryptedkey"`
}
// openKeeper opens the keeper, handling pulumi-specifc cases in the URL.
func openKeeper(ctx context.Context, url string) (*gosecrets.Keeper, error) {
u, err := netUrl.Parse(url)
if err != nil {
return nil, fmt.Errorf("unable to parse the secrets provider URL: %w", err)
}
switch u.Scheme {
case gcpkms.Scheme:
credentials, err := authhelpers.ResolveGoogleCredentials(ctx, cloudkms.CloudkmsScope)
if err != nil {
return nil, fmt.Errorf("missing google credentials: %w", err)
}
kmsClient, _, err := gcpkms.Dial(ctx, credentials.TokenSource)
if err != nil {
return nil, fmt.Errorf("failed to connect to gcpkms: %w", err)
}
opener := gcpkms.URLOpener{
Client: kmsClient,
}
return opener.OpenKeeperURL(ctx, u)
default:
return gosecrets.OpenKeeper(ctx, url)
}
}
2023-01-12 14:37:21 +00:00
// generateNewDataKey generates a new DataKey seeded by a fresh random 32-byte key and encrypted
// using the target cloud key management service.
2023-01-12 14:37:21 +00:00
func generateNewDataKey(url string) ([]byte, error) {
plaintextDataKey := make([]byte, 32)
_, err := rand.Read(plaintextDataKey)
if err != nil {
return nil, err
}
keeper, err := openKeeper(context.Background(), url)
if err != nil {
return nil, err
}
return keeper.Encrypt(context.Background(), plaintextDataKey)
}
2023-01-12 14:37:21 +00:00
// newCloudSecretsManager returns a secrets manager that uses the target cloud key management
// service to encrypt/decrypt a data key used for envelope encryption of secrets values.
2023-01-12 14:37:21 +00:00
func newCloudSecretsManager(url string, encryptedDataKey []byte) (*Manager, error) {
keeper, err := openKeeper(context.Background(), url)
if err != nil {
return nil, err
}
plaintextDataKey, err := keeper.Decrypt(context.Background(), encryptedDataKey)
if err != nil {
return nil, err
}
state, err := json.Marshal(cloudSecretsManagerState{
URL: url,
EncryptedKey: encryptedDataKey,
})
if err != nil {
return nil, fmt.Errorf("marshalling state: %w", err)
}
crypter := config.NewSymmetricCrypter(plaintextDataKey)
return &Manager{
crypter: crypter,
state: state,
}, nil
}
// Manager is the secrets.Manager implementation for cloud key management services
type Manager struct {
state json.RawMessage
crypter config.Crypter
}
func (m *Manager) Type() string { return Type }
func (m *Manager) State() json.RawMessage { return m.state }
func (m *Manager) Encrypter() (config.Encrypter, error) { return m.crypter, nil }
func (m *Manager) Decrypter() (config.Decrypter, error) { return m.crypter, nil }
2023-01-12 14:37:21 +00:00
Restore secrets provider in config refresh (#13900) <!--- Thanks so much for your contribution! If this is your first time contributing, please ensure that you have read the [CONTRIBUTING](https://github.com/pulumi/pulumi/blob/master/CONTRIBUTING.md) documentation. --> # Description <!--- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. --> Fixes https://github.com/pulumi/pulumi/issues/7282 This is fairly simple, just grab the last deployment from the stack (we should have one otherwise we wouldn't have any config to fetch either) and pull the SecretsProviders data out the deployment data and translate and insert it into the stack config. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works - I've manually checked this with a passphrase deployment. Need to do the command split for "config refresh" to write up some unit tests to cover this. <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2023-11-13 12:27:46 +00:00
func EditProjectStack(info *workspace.ProjectStack, state json.RawMessage) error {
info.EncryptionSalt = ""
var s cloudSecretsManagerState
err := json.Unmarshal(state, &s)
if err != nil {
return fmt.Errorf("unmarshalling cloud state: %w", err)
}
info.SecretsProvider = s.URL
info.EncryptedKey = base64.StdEncoding.EncodeToString(s.EncryptedKey)
return nil
}
2023-01-12 14:37:21 +00:00
// NewCloudSecretsManagerFromState deserialize configuration from state and returns a secrets
// manager that uses the target cloud key management service to encrypt/decrypt a data key used for
// envelope encryption of secrets values.
func NewCloudSecretsManagerFromState(state json.RawMessage) (secrets.Manager, error) {
var s cloudSecretsManagerState
if err := json.Unmarshal(state, &s); err != nil {
return nil, fmt.Errorf("unmarshalling state: %w", err)
}
return newCloudSecretsManager(s.URL, s.EncryptedKey)
}
func NewCloudSecretsManager(info *workspace.ProjectStack,
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
secretsProvider string, rotateSecretsProvider bool,
) (secrets.Manager, error) {
2023-01-12 14:37:21 +00:00
// Only a passphrase provider has an encryption salt. So changing a secrets provider
// from passphrase to a cloud secrets provider should ensure that we remove the enryptionsalt
// as it's a legacy artifact and needs to be removed
info.EncryptionSalt = ""
var secretsManager *Manager
// Allow per-execution override of the secrets provider via an environment
// variable. This allows a temporary replacement without updating the stack
// config, such a during CI.
if override := os.Getenv("PULUMI_CLOUD_SECRET_OVERRIDE"); override != "" {
secretsProvider = override
}
// If we're rotating then just clear the key so we create a fresh one below
if rotateSecretsProvider {
info.EncryptedKey = ""
}
// if there is no key OR the secrets provider is changing
// then we need to generate the new key based on the new secrets provider
if info.EncryptedKey == "" || info.SecretsProvider != secretsProvider {
dataKey, err := generateNewDataKey(secretsProvider)
if err != nil {
return nil, err
}
info.EncryptedKey = base64.StdEncoding.EncodeToString(dataKey)
}
info.SecretsProvider = secretsProvider
dataKey, err := base64.StdEncoding.DecodeString(info.EncryptedKey)
if err != nil {
return nil, err
}
secretsManager, err = newCloudSecretsManager(secretsProvider, dataKey)
if err != nil {
return nil, err
}
return secretsManager, nil
}