github.com/criteo/command-launcher@v0.0.0-20230407142452-fb616f546e98/internal/helper/sys-vault.go (about)

     1  package helper
     2  
     3  import (
     4  	"runtime"
     5  
     6  	"github.com/criteo/command-launcher/internal/context"
     7  	vault "github.com/criteo/command-launcher/internal/gvault"
     8  	log "github.com/sirupsen/logrus"
     9  	"github.com/zalando/go-keyring"
    10  )
    11  
    12  func SetSecret(key string, value string) error {
    13  	ctx, _ := context.AppContext()
    14  	if runtime.GOOS == "linux" || HasDebugFlag(USE_FILE_VAULT) {
    15  		return setSecretFromFileVault(key, value, ctx.AppName())
    16  	}
    17  	if err := keyring.Set(ctx.AppName(), key, value); err != nil {
    18  		// fallback to the file vault
    19  		log.Warnf("fail to write secret to system vault, fallback to file vault, %v\n", err)
    20  		return setSecretFromFileVault(key, value, ctx.AppName())
    21  	}
    22  	return nil
    23  }
    24  
    25  func GetSecret(key string) (string, error) {
    26  	ctx, _ := context.AppContext()
    27  	if runtime.GOOS == "linux" || HasDebugFlag(USE_FILE_VAULT) {
    28  		return getSecretFromFileVault(key, ctx.AppName())
    29  	}
    30  
    31  	secret, err := keyring.Get(ctx.AppName(), key)
    32  	if err != nil {
    33  		// fallback to the file vault
    34  		log.Warnf("fail to get secret from system vault, fallback to file vault, %v\n", err)
    35  		return getSecretFromFileVault(key, ctx.AppName())
    36  	}
    37  	return secret, nil
    38  }
    39  
    40  func setSecretFromFileVault(key string, value string, appName string) error {
    41  	fv, err := vault.CreateVault(appName)
    42  	if err != nil {
    43  		return err
    44  	}
    45  	return fv.Write(key, value)
    46  }
    47  
    48  func getSecretFromFileVault(key string, appName string) (string, error) {
    49  	fv, err := vault.CreateVault(appName)
    50  	if err != nil {
    51  		return "", err
    52  	}
    53  	return fv.Read(key)
    54  }