mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-14 22:51:53 +00:00
keyring swap, better error messages/warnings, delay upgrade notif
This commit is contained in:
@@ -11,6 +11,7 @@ import (
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/rs/zerolog/log"
|
||||
@@ -20,13 +21,16 @@ func CheckForUpdate() {
|
||||
if checkEnv := os.Getenv("INFISICAL_DISABLE_UPDATE_CHECK"); checkEnv != "" {
|
||||
return
|
||||
}
|
||||
latestVersion, err := getLatestTag("Infisical", "infisical")
|
||||
latestVersion, publishedDate, err := getLatestTag("Infisical", "infisical")
|
||||
if err != nil {
|
||||
log.Debug().Err(err)
|
||||
// do nothing and continue
|
||||
return
|
||||
}
|
||||
if latestVersion != CLI_VERSION {
|
||||
|
||||
daysSinceRelease, _ := daysSinceDate(publishedDate)
|
||||
|
||||
if latestVersion != CLI_VERSION && daysSinceRelease > 5 {
|
||||
yellow := color.New(color.FgYellow).SprintFunc()
|
||||
blue := color.New(color.FgCyan).SprintFunc()
|
||||
black := color.New(color.FgBlack).SprintFunc()
|
||||
@@ -43,44 +47,45 @@ func CheckForUpdate() {
|
||||
updateInstructions := GetUpdateInstructions()
|
||||
|
||||
if updateInstructions != "" {
|
||||
msg = fmt.Sprintf("\n%s\n", GetUpdateInstructions())
|
||||
msg = fmt.Sprintf("%s\n", GetUpdateInstructions())
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func getLatestTag(repoOwner string, repoName string) (string, error) {
|
||||
func getLatestTag(repoOwner string, repoName string) (string, string, error) {
|
||||
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", repoOwner, repoName)
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", "", err
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
return "", errors.New(fmt.Sprintf("gitHub API returned status code %d", resp.StatusCode))
|
||||
return "", "", errors.New(fmt.Sprintf("gitHub API returned status code %d", resp.StatusCode))
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
var releaseTag struct {
|
||||
TagName string `json:"tag_name"`
|
||||
var releaseDetails struct {
|
||||
TagName string `json:"tag_name"`
|
||||
PublishedAt string `json:"published_at"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &releaseTag); err != nil {
|
||||
return "", fmt.Errorf("failed to unmarshal github response: %w", err)
|
||||
if err := json.Unmarshal(body, &releaseDetails); err != nil {
|
||||
return "", "", fmt.Errorf("failed to unmarshal github response: %w", err)
|
||||
}
|
||||
|
||||
tag_prefix := "infisical-cli/v"
|
||||
|
||||
// Extract the version from the first valid tag
|
||||
version := strings.TrimPrefix(releaseTag.TagName, tag_prefix)
|
||||
version := strings.TrimPrefix(releaseDetails.TagName, tag_prefix)
|
||||
|
||||
return version, nil
|
||||
return version, releaseDetails.PublishedAt, nil
|
||||
}
|
||||
|
||||
func GetUpdateInstructions() string {
|
||||
@@ -145,3 +150,16 @@ func IsRunningInDocker() bool {
|
||||
|
||||
return strings.Contains(string(cgroup), "docker")
|
||||
}
|
||||
|
||||
func daysSinceDate(dateString string) (int, error) {
|
||||
layout := "2006-01-02T15:04:05Z"
|
||||
parsedDate, err := time.Parse(layout, dateString)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
currentTime := time.Now()
|
||||
difference := currentTime.Sub(parsedDate)
|
||||
days := int(difference.Hours() / 24)
|
||||
return days, nil
|
||||
}
|
||||
|
||||
@@ -52,7 +52,6 @@ func WriteInitalConfig(userCredentials *models.UserCredentials) error {
|
||||
configFile := models.ConfigFile{
|
||||
LoggedInUserEmail: userCredentials.Email,
|
||||
LoggedInUserDomain: config.INFISICAL_URL,
|
||||
VaultBackendType: existingConfigFile.VaultBackendType,
|
||||
LoggedInUsers: existingConfigFile.LoggedInUsers,
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/99designs/keyring"
|
||||
keyring "github.com/Infisical/infisical-merge/internal"
|
||||
|
||||
"github.com/Infisical/infisical-merge/packages/api"
|
||||
"github.com/Infisical/infisical-merge/packages/config"
|
||||
"github.com/Infisical/infisical-merge/packages/models"
|
||||
@@ -24,17 +25,7 @@ func StoreUserCredsInKeyRing(userCred *models.UserCredentials) error {
|
||||
return fmt.Errorf("StoreUserCredsInKeyRing: something went wrong when marshalling user creds [err=%s]", err)
|
||||
}
|
||||
|
||||
// Get keyring
|
||||
configuredKeyring, err := GetKeyRing()
|
||||
if err != nil {
|
||||
return fmt.Errorf("StoreUserCredsInKeyRing: unable to get keyring instance with [err=%s]", err)
|
||||
}
|
||||
|
||||
err = configuredKeyring.Set(keyring.Item{
|
||||
Key: userCred.Email,
|
||||
Data: []byte(string(userCredMarshalled)),
|
||||
})
|
||||
|
||||
err = keyring.Set(userCred.Email, string(userCredMarshalled))
|
||||
if err != nil {
|
||||
return fmt.Errorf("StoreUserCredsInKeyRing: unable to store user credentials because [err=%s]", err)
|
||||
}
|
||||
@@ -43,20 +34,14 @@ func StoreUserCredsInKeyRing(userCred *models.UserCredentials) error {
|
||||
}
|
||||
|
||||
func GetUserCredsFromKeyRing(userEmail string) (credentials models.UserCredentials, err error) {
|
||||
// Get keyring
|
||||
configuredKeyring, err := GetKeyRing()
|
||||
credentialsValue, err := keyring.Get(userEmail)
|
||||
if err != nil {
|
||||
return models.UserCredentials{}, fmt.Errorf("GetUserCredsFromKeyRing: unable to get keyring instance with [err=%s]", err)
|
||||
}
|
||||
|
||||
credentialsValue, err := configuredKeyring.Get(userEmail)
|
||||
if err != nil {
|
||||
return models.UserCredentials{}, fmt.Errorf("GetUserCredsFromKeyRing: unable to get key from Keyring. could not find login credentials in your Keyring. This is common if you have switched vault backend recently. If so, please login in again and retry [err=%s]", err)
|
||||
return models.UserCredentials{}, fmt.Errorf("GetUserCredsFromKeyRing: Unable to get key from Keyring. Could not find login credentials in your Keyring [err=%v]", err)
|
||||
}
|
||||
|
||||
var userCredentials models.UserCredentials
|
||||
|
||||
err = json.Unmarshal([]byte(credentialsValue.Data), &userCredentials)
|
||||
err = json.Unmarshal([]byte(credentialsValue), &userCredentials)
|
||||
if err != nil {
|
||||
return models.UserCredentials{}, fmt.Errorf("getUserCredsFromKeyRing: Something went wrong when unmarshalling user creds [err=%s]", err)
|
||||
}
|
||||
@@ -98,9 +83,11 @@ func GetCurrentLoggedInUserDetails() (LoggedInUserDetails, error) {
|
||||
|
||||
isAuthenticated := api.CallIsAuthenticated(httpClient)
|
||||
|
||||
// TODO
|
||||
// No cookie is set when user logins via browser
|
||||
if !isAuthenticated {
|
||||
accessTokenResponse, _ := api.CallGetNewAccessTokenWithRefreshToken(httpClient, userCreds.RefreshToken)
|
||||
if accessTokenResponse.Token != "" {
|
||||
accessTokenResponse, err := api.CallGetNewAccessTokenWithRefreshToken(httpClient, userCreds.RefreshToken)
|
||||
if err == nil && accessTokenResponse.Token != "" {
|
||||
isAuthenticated = true
|
||||
userCreds.JTWToken = accessTokenResponse.Token
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func HandleError(err error, messages ...string) {
|
||||
@@ -16,12 +17,11 @@ func PrintErrorAndExit(exitCode int, err error, messages ...string) {
|
||||
|
||||
if len(messages) > 0 {
|
||||
for _, message := range messages {
|
||||
fmt.Println(message)
|
||||
log.Info().Msg(message)
|
||||
}
|
||||
}
|
||||
|
||||
supportMsg := fmt.Sprintf("\n\nIf this issue continues, get support at https://infisical.com/slack")
|
||||
fmt.Fprintln(os.Stderr, supportMsg)
|
||||
log.Info().Msg("If this issue continues, get support at https://infisical.com/slack")
|
||||
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
@@ -45,5 +45,5 @@ func PrintErrorMessageAndExit(messages ...string) {
|
||||
}
|
||||
|
||||
func printError(e error) {
|
||||
color.New(color.FgRed).Fprintf(os.Stderr, "Hmm, we ran into an error: %v\n", e)
|
||||
log.Error().Msg(e.Error())
|
||||
}
|
||||
|
||||
@@ -17,6 +17,18 @@ import (
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func containsGlobPatterns(secretPath string) bool {
|
||||
globChars := []string{"*", "?", "[", "]", "{", "}", "**"}
|
||||
normalizedPath := path.Clean(secretPath)
|
||||
for _, char := range globChars {
|
||||
if strings.Contains(normalizedPath, char) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func GetPlainTextSecretsViaServiceToken(fullServiceToken string, environment string, secretPath string, includeImports bool) ([]models.SingleEnvironmentVariable, api.GetServiceTokenDetailsResponse, error) {
|
||||
serviceTokenParts := strings.SplitN(fullServiceToken, ".", 4)
|
||||
if len(serviceTokenParts) < 4 {
|
||||
@@ -26,7 +38,6 @@ func GetPlainTextSecretsViaServiceToken(fullServiceToken string, environment str
|
||||
serviceToken := fmt.Sprintf("%v.%v.%v", serviceTokenParts[0], serviceTokenParts[1], serviceTokenParts[2])
|
||||
|
||||
httpClient := resty.New()
|
||||
|
||||
httpClient.SetAuthToken(serviceToken).
|
||||
SetHeader("Accept", "application/json")
|
||||
|
||||
@@ -198,15 +209,21 @@ func GetAllEnvironmentVariables(params models.GetAllSecretsParameters) ([]models
|
||||
log.Debug().Msg("GetAllEnvironmentVariables: Connected to internet, checking logged in creds")
|
||||
RequireLocalWorkspaceFile()
|
||||
RequireLogin()
|
||||
} else {
|
||||
PrintErrorMessageAndExit("It looks like you are not connected to the internet, please reconnect and try again")
|
||||
}
|
||||
|
||||
log.Debug().Msg("GetAllEnvironmentVariables: Trying to fetch secrets using logged in details")
|
||||
log.Trace().Msg("GetAllEnvironmentVariables: Trying to fetch secrets using logged in details")
|
||||
|
||||
loggedInUserDetails, err := GetCurrentLoggedInUserDetails()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if loggedInUserDetails.LoginExpired {
|
||||
PrintErrorMessageAndExit("Your login session has expired, please run [infisical login] and try again")
|
||||
}
|
||||
|
||||
workspaceFile, err := GetWorkSpaceFromFile()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -242,7 +259,7 @@ func GetAllEnvironmentVariables(params models.GetAllSecretsParameters) ([]models
|
||||
}
|
||||
|
||||
} else {
|
||||
log.Debug().Msg("Trying to fetch secrets using service token")
|
||||
log.Trace().Msg("Trying to fetch secrets using service token")
|
||||
secretsToReturn, _, errorToReturn = GetPlainTextSecretsViaServiceToken(infisicalToken, params.Environment, params.SecretsPath, params.IncludeImport)
|
||||
}
|
||||
|
||||
@@ -412,7 +429,11 @@ func ExpandSecrets(secrets []models.SingleEnvironmentVariable, infisicalToken st
|
||||
// if not in cross reference cache, fetch it from server
|
||||
refSecs, err := GetAllEnvironmentVariables(models.GetAllSecretsParameters{Environment: env, InfisicalToken: infisicalToken, SecretsPath: secPath})
|
||||
if err != nil {
|
||||
HandleError(err, fmt.Sprintf("Could not fetch secrets in environment: %s secret-path: %s", env, secPath), "If you are using a service token to fetch secrets, please ensure it is valid")
|
||||
if infisicalToken != "" {
|
||||
HandleError(err, fmt.Sprintf("Could not fetch secrets in environment: %s secret-path: %s", env, secPath), "Please ensure your service token has access to the required environments and paths to fetch the requested secrets")
|
||||
} else {
|
||||
HandleError(err, fmt.Sprintf("Could not fetch secrets in environment: %s secret-path: %s", env, secPath))
|
||||
}
|
||||
}
|
||||
refSecsByKey := getSecretsByKeys(refSecs)
|
||||
// save it to avoid calling api again for same environment and folder path
|
||||
@@ -676,7 +697,6 @@ func GetEnvelopmentBasedOnGitBranch(workspaceFile models.WorkspaceConfigFile) st
|
||||
if err == nil && ok {
|
||||
return envBasedOnGitBranch
|
||||
} else {
|
||||
log.Debug().Msgf("getEnvelopmentBasedOnGitBranch: [err=%s]", err)
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,258 +0,0 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/Infisical/infisical-merge/packages/models"
|
||||
)
|
||||
|
||||
// References to self should return the value unaltered
|
||||
func Test_SubstituteSecrets_When_ReferenceToSelf(t *testing.T) {
|
||||
|
||||
var tests = []struct {
|
||||
Key string
|
||||
Value string
|
||||
ExpectedValue string
|
||||
}{
|
||||
{Key: "A", Value: "${A}", ExpectedValue: "${A}"},
|
||||
{Key: "A", Value: "${A} ${A}", ExpectedValue: "${A} ${A}"},
|
||||
{Key: "A", Value: "${A}${A}", ExpectedValue: "${A}${A}"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
secret := models.SingleEnvironmentVariable{
|
||||
Key: test.Key,
|
||||
Value: test.Value,
|
||||
}
|
||||
|
||||
secrets := []models.SingleEnvironmentVariable{secret}
|
||||
result := SubstituteSecrets(secrets)
|
||||
|
||||
if result[0].Value != test.ExpectedValue {
|
||||
t.Errorf("Test_SubstituteSecrets_When_ReferenceToSelf: expected %s but got %s for input %s", test.ExpectedValue, result[0].Value, test.Value)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func Test_SubstituteSecrets_When_ReferenceDoesNotExist(t *testing.T) {
|
||||
|
||||
var tests = []struct {
|
||||
Key string
|
||||
Value string
|
||||
ExpectedValue string
|
||||
}{
|
||||
{Key: "A", Value: "${X}", ExpectedValue: "${X}"},
|
||||
{Key: "A", Value: "${H}HELLO", ExpectedValue: "${H}HELLO"},
|
||||
{Key: "A", Value: "${L}${S}", ExpectedValue: "${L}${S}"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
secret := models.SingleEnvironmentVariable{
|
||||
Key: test.Key,
|
||||
Value: test.Value,
|
||||
}
|
||||
|
||||
secrets := []models.SingleEnvironmentVariable{secret}
|
||||
result := SubstituteSecrets(secrets)
|
||||
|
||||
if result[0].Value != test.ExpectedValue {
|
||||
t.Errorf("Test_SubstituteSecrets_When_ReferenceToSelf: expected %s but got %s for input %s", test.ExpectedValue, result[0].Value, test.Value)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func Test_SubstituteSecrets_When_ReferenceDoesNotExist_And_Self_Referencing(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
Key string
|
||||
Value string
|
||||
ExpectedValue string
|
||||
}{
|
||||
{
|
||||
Key: "O",
|
||||
Value: "${P} ==$$ ${X} ${UNKNOWN} ${A}",
|
||||
ExpectedValue: "DOMAIN === ${A} DOMAIN >>> ==$$ DOMAIN ${UNKNOWN} ${A}",
|
||||
},
|
||||
{
|
||||
Key: "X",
|
||||
Value: "DOMAIN",
|
||||
ExpectedValue: "DOMAIN",
|
||||
},
|
||||
{
|
||||
Key: "A",
|
||||
Value: "*${A}* ${X}",
|
||||
ExpectedValue: "*${A}* DOMAIN",
|
||||
},
|
||||
{
|
||||
Key: "H",
|
||||
Value: "${X} >>>",
|
||||
ExpectedValue: "DOMAIN >>>",
|
||||
},
|
||||
{
|
||||
Key: "P",
|
||||
Value: "DOMAIN === ${A} ${H}",
|
||||
ExpectedValue: "DOMAIN === ${A} DOMAIN >>>",
|
||||
},
|
||||
{
|
||||
Key: "T",
|
||||
Value: "${P} ==$$ ${X} ${UNKNOWN} ${A} ${P} ==$$ ${X} ${UNKNOWN} ${A}",
|
||||
ExpectedValue: "DOMAIN === ${A} DOMAIN >>> ==$$ DOMAIN ${UNKNOWN} ${A} DOMAIN === ${A} DOMAIN >>> ==$$ DOMAIN ${UNKNOWN} ${A}",
|
||||
},
|
||||
{
|
||||
Key: "S",
|
||||
Value: "${ SSS$$ ${HEY}",
|
||||
ExpectedValue: "${ SSS$$ ${HEY}",
|
||||
},
|
||||
}
|
||||
|
||||
secrets := []models.SingleEnvironmentVariable{}
|
||||
for _, test := range tests {
|
||||
secrets = append(secrets, models.SingleEnvironmentVariable{Key: test.Key, Value: test.Value})
|
||||
}
|
||||
|
||||
results := SubstituteSecrets(secrets)
|
||||
|
||||
for index, expanded := range results {
|
||||
if expanded.Value != tests[index].ExpectedValue {
|
||||
t.Errorf("Test_SubstituteSecrets_When_ReferenceToSelf: expected [%s] but got [%s] for input [%s]", tests[index].ExpectedValue, expanded.Value, tests[index].Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Test_SubstituteSecrets_When_No_SubstituteNeeded(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
Key string
|
||||
Value string
|
||||
ExpectedValue string
|
||||
}{
|
||||
{
|
||||
Key: "DOMAIN",
|
||||
Value: "infisical.com",
|
||||
ExpectedValue: "infisical.com",
|
||||
},
|
||||
{
|
||||
Key: "API_KEY",
|
||||
Value: "hdgsvjshcgkdckhevdkd",
|
||||
ExpectedValue: "hdgsvjshcgkdckhevdkd",
|
||||
},
|
||||
{
|
||||
Key: "ENV",
|
||||
Value: "PROD",
|
||||
ExpectedValue: "PROD",
|
||||
},
|
||||
}
|
||||
|
||||
secrets := []models.SingleEnvironmentVariable{}
|
||||
for _, test := range tests {
|
||||
secrets = append(secrets, models.SingleEnvironmentVariable{Key: test.Key, Value: test.Value})
|
||||
}
|
||||
|
||||
results := SubstituteSecrets(secrets)
|
||||
|
||||
for index, expanded := range results {
|
||||
if expanded.Value != tests[index].ExpectedValue {
|
||||
t.Errorf("Test_SubstituteSecrets_When_ReferenceToSelf: expected [%s] but got [%s] for input [%s]", tests[index].ExpectedValue, expanded.Value, tests[index].Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Read_Env_From_File(t *testing.T) {
|
||||
type testCase struct {
|
||||
TestFile string
|
||||
ExpectedEnv string
|
||||
}
|
||||
|
||||
var cases = []testCase{
|
||||
{
|
||||
TestFile: "testdata/infisical-default-env.json",
|
||||
ExpectedEnv: "myDefaultEnv",
|
||||
},
|
||||
{
|
||||
TestFile: "testdata/infisical-branch-env.json",
|
||||
ExpectedEnv: "myMainEnv",
|
||||
},
|
||||
{
|
||||
TestFile: "testdata/infisical-no-matching-branch-env.json",
|
||||
ExpectedEnv: "myDefaultEnv",
|
||||
},
|
||||
}
|
||||
|
||||
// create a tmp directory for testing
|
||||
testDir, err := os.MkdirTemp(os.TempDir(), "infisical-test")
|
||||
if err != nil {
|
||||
t.Errorf("Test_Read_DefaultEnv_From_File: Failed to create temp directory: %s", err)
|
||||
}
|
||||
|
||||
// safe the current working directory
|
||||
originalDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Errorf("Test_Read_DefaultEnv_From_File: Failed to get current working directory: %s", err)
|
||||
}
|
||||
|
||||
// backup the original git command
|
||||
originalGitCmd := getCurrentBranchCmd
|
||||
|
||||
// make sure to clean up after the test
|
||||
t.Cleanup(func() {
|
||||
os.Chdir(originalDir)
|
||||
os.RemoveAll(testDir)
|
||||
getCurrentBranchCmd = originalGitCmd
|
||||
})
|
||||
|
||||
// mock the git command to return "main" as the current branch
|
||||
getCurrentBranchCmd = execCmd{cmd: "echo", args: []string{"main"}}
|
||||
|
||||
for _, c := range cases {
|
||||
// make sure we start in the original directory
|
||||
err = os.Chdir(originalDir)
|
||||
if err != nil {
|
||||
t.Errorf("Test_Read_DefaultEnv_From_File: Failed to change working directory: %s", err)
|
||||
}
|
||||
|
||||
// remove old test file if it exists
|
||||
err = os.Remove(path.Join(testDir, INFISICAL_WORKSPACE_CONFIG_FILE_NAME))
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Errorf("Test_Read_DefaultEnv_From_File: Failed to remove old test file: %s", err)
|
||||
}
|
||||
|
||||
// deploy the test file
|
||||
copyTestFile(t, c.TestFile, path.Join(testDir, INFISICAL_WORKSPACE_CONFIG_FILE_NAME))
|
||||
|
||||
// change the working directory to the tmp directory
|
||||
err = os.Chdir(testDir)
|
||||
if err != nil {
|
||||
t.Errorf("Test_Read_DefaultEnv_From_File: Failed to change working directory: %s", err)
|
||||
}
|
||||
|
||||
// get env from file
|
||||
env := GetEnvFromWorkspaceFile()
|
||||
if env != c.ExpectedEnv {
|
||||
t.Errorf("Test_Read_DefaultEnv_From_File: Expected env to be %s but got %s", c.ExpectedEnv, env)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func copyTestFile(t *testing.T, src, dst string) {
|
||||
srcFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
t.Errorf("Test_Read_Env_From_File_By_Branch: Failed to open source file: %s", err)
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
dstFile, err := os.Create(dst)
|
||||
if err != nil {
|
||||
t.Errorf("Test_Read_Env_From_File_By_Branch: Failed to create destination file: %s", err)
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
if err != nil {
|
||||
t.Errorf("Test_Read_Env_From_File_By_Branch: Failed to copy file: %s", err)
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/99designs/keyring"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func GetCurrentVaultBackend() (keyring.BackendType, error) {
|
||||
configFile, err := GetConfigFile()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("getCurrentVaultBackend: unable to get config file [err=%s]", err)
|
||||
}
|
||||
|
||||
if configFile.VaultBackendType == "" {
|
||||
return keyring.AvailableBackends()[0], nil
|
||||
}
|
||||
|
||||
return configFile.VaultBackendType, nil
|
||||
}
|
||||
|
||||
func GetKeyRing() (keyring.Keyring, error) {
|
||||
currentVaultBackend, err := GetCurrentVaultBackend()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetKeyRing: unable to get the current vault backend, [err=%s]", err)
|
||||
}
|
||||
|
||||
keyringInstanceConfig := keyring.Config{
|
||||
FilePasswordFunc: fileKeyringPassphrasePrompt,
|
||||
ServiceName: KEYRING_SERVICE_NAME,
|
||||
LibSecretCollectionName: KEYRING_SERVICE_NAME,
|
||||
KWalletAppID: KEYRING_SERVICE_NAME,
|
||||
KWalletFolder: KEYRING_SERVICE_NAME,
|
||||
KeychainName: "login", // default so user will not be prompted
|
||||
KeychainTrustApplication: true,
|
||||
WinCredPrefix: KEYRING_SERVICE_NAME,
|
||||
FileDir: fmt.Sprintf("~/%s-file-vault", KEYRING_SERVICE_NAME),
|
||||
KeychainAccessibleWhenUnlocked: true,
|
||||
}
|
||||
|
||||
// if the user explicitly sets a vault backend, then only use that
|
||||
if currentVaultBackend != "" {
|
||||
keyringInstanceConfig.AllowedBackends = []keyring.BackendType{keyring.BackendType(currentVaultBackend)}
|
||||
}
|
||||
|
||||
keyringInstance, err := keyring.Open(keyringInstanceConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetKeyRing: Unable to create instance of Keyring because of [err=%s]", err)
|
||||
}
|
||||
|
||||
return keyringInstance, nil
|
||||
}
|
||||
|
||||
func fileKeyringPassphrasePrompt(prompt string) (string, error) {
|
||||
if password, ok := os.LookupEnv("VAULT_PASS"); ok {
|
||||
return password, nil
|
||||
} else if password, ok := os.LookupEnv("INFISICAL_VAULT_FILE_PASSPHRASE"); ok {
|
||||
return password, nil
|
||||
} else {
|
||||
fmt.Println("To avoid repeatedly typing your password, set the environment variable `VAULT_PASS` to your password")
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "%s:", prompt)
|
||||
b, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
fmt.Println("")
|
||||
return string(b), nil
|
||||
}
|
||||
Reference in New Issue
Block a user