github.com/myhau/pulumi/pkg/v3@v3.70.2-0.20221116134521-f2775972e587/backend/filestate/crypto.go (about)

     1  // Copyright 2016-2022, Pulumi Corporation.
     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  //     http://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 filestate
    16  
    17  import (
    18  	"github.com/pulumi/pulumi/pkg/v3/secrets"
    19  	"github.com/pulumi/pulumi/pkg/v3/secrets/passphrase"
    20  	"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
    21  	"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
    22  	"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
    23  )
    24  
    25  func NewPassphraseSecretsManager(stackName tokens.Name, configFile string,
    26  	rotatePassphraseSecretsProvider bool) (secrets.Manager, error) {
    27  	contract.Assertf(stackName != "", "stackName %s", "!= \"\"")
    28  
    29  	project, _, err := workspace.DetectProjectStackPath(stackName.Q())
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  
    34  	info, err := workspace.LoadProjectStack(project, configFile)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	if rotatePassphraseSecretsProvider {
    40  		info.EncryptionSalt = ""
    41  	}
    42  
    43  	// If there are any other secrets providers set in the config, remove them, as the passphrase
    44  	// provider deals only with EncryptionSalt, not EncryptedKey or SecretsProvider.
    45  	if info.EncryptedKey != "" || info.SecretsProvider != "" {
    46  		info.EncryptedKey = ""
    47  		info.SecretsProvider = ""
    48  	}
    49  
    50  	// If we have a salt, we can just use it.
    51  	if info.EncryptionSalt != "" {
    52  		return passphrase.NewPromptingPassphraseSecretsManager(info.EncryptionSalt)
    53  	}
    54  
    55  	// Otherwise, prompt the user for a new passphrase.
    56  	salt, sm, err := passphrase.PromptForNewPassphrase(rotatePassphraseSecretsProvider)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	// Store the salt and save it.
    62  	info.EncryptionSalt = salt
    63  	if err = info.Save(configFile); err != nil {
    64  		return nil, err
    65  	}
    66  
    67  	// Return the passphrase secrets manager.
    68  	return sm, nil
    69  }