Skip to content

Commit

Permalink
Squashed 'keyconjurer-v2/' changes from 68ff0dd..be45b54
Browse files Browse the repository at this point in the history
be45b54 Remove unused return value
b66a276 Run go test
6aa2105 Remove unnecessary refs that are breaking PR builds
10156de Conform to gorevives suggestions
ba36b5b Strip symbols

git-subtree-dir: keyconjurer-v2
git-subtree-split: be45b54
  • Loading branch information
punmechanic committed Sep 18, 2023
1 parent 0481f6e commit 8ce6fac
Show file tree
Hide file tree
Showing 21 changed files with 120 additions and 171 deletions.
24 changes: 2 additions & 22 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.head_ref }}
- uses: hashicorp/setup-terraform@v2
with:
terraform_version: "1.3.7"
Expand All @@ -30,33 +28,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.head_ref }}
- uses: actions/setup-node@v3
with:
node-version: "16.17.0"
# Tests just need the file to exist with the appropriate exports - the values do not matter.
- run: cd frontend && npm install && npm test
api-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.head_ref }}
- uses: actions/setup-go@v3
with:
go-version: "1.19"
- run: cd api && go test ./...
cli-test:
go-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.head_ref }}
- uses: actions/setup-go@v3
with:
go-version: "1.19"
# CLI test requires a dummy ~/.aws/credentials and config file exists.
- run: mkdir -p ~/.aws
- run: touch ~/.aws/{credentials,config}
- run: cd cli && go test ./...
- run: go test ./...
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ cli/keyconjurer:
cd cli && \
go build \
-ldflags "\
-s -w \
-X main.Version=$(shell git rev-parse --short HEAD)-$(RELEASE) \
-X main.ClientID=$(CLIENT_ID) \
-X main.OIDCDomain=$(OIDC_DOMAIN) \
Expand Down
4 changes: 2 additions & 2 deletions cli/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ var accountsCmd = &cobra.Command{
}

serverAddr, _ := cmd.Flags().GetString(FlagServerAddress)
serverAddrUri, err := url.Parse(serverAddr)
serverAddrURI, err := url.Parse(serverAddr)
if err != nil {
cmd.PrintErrf("--%s had an invalid value: %s\n", FlagServerAddress, err)
return nil
Expand All @@ -62,7 +62,7 @@ var accountsCmd = &cobra.Command{
TokenType: config.Tokens.TokenType,
}

accounts, err := refreshAccounts(cmd.Context(), serverAddrUri, &tok)
accounts, err := refreshAccounts(cmd.Context(), serverAddrURI, &tok)
if err != nil {
cmd.PrintErrf("Error refreshing accounts: %s\n", err)
cmd.PrintErrln("If you don't need to refresh your accounts, consider adding the --no-refresh flag")
Expand Down
8 changes: 4 additions & 4 deletions cli/awsconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
// Intentionally missing the `ini` notation sections,keys, and values are being handled by the ini library
type CloudCliEntry struct {
profileName string
keyId string
keyID string
key string
token string
}
Expand All @@ -25,7 +25,7 @@ func NewCloudCliEntry(c CloudCredentials, a *Account) CloudCliEntry {

return CloudCliEntry{
profileName: name,
keyId: c.AccessKeyID,
keyID: c.AccessKeyID,
key: c.SecretAccessKey,
token: c.SessionToken,
}
Expand Down Expand Up @@ -56,11 +56,11 @@ func ResolveAWSCredentialsPath(rootPath string) string {
func saveCredentialEntry(file *ini.File, entry CloudCliEntry, cloud string) error {
section := file.Section(entry.profileName)
if cloud == cloudAws {
section.Key("aws_access_key_id").SetValue(entry.keyId)
section.Key("aws_access_key_id").SetValue(entry.keyID)
section.Key("aws_secret_access_key").SetValue(entry.key)
section.Key("aws_session_token").SetValue(entry.token)
} else if cloud == cloudTencent {
section.Key("tencent_access_key_id").SetValue(entry.keyId)
section.Key("tencent_access_key_id").SetValue(entry.keyID)
section.Key("tencent_secret_access_key").SetValue(entry.key)
section.Key("tencent_session_token").SetValue(entry.token)
}
Expand Down
2 changes: 1 addition & 1 deletion cli/awsconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestAddAWSCliEntry(t *testing.T) {

entry := CloudCliEntry{
profileName: "test-profile",
keyId: "notanid",
keyID: "notanid",
key: "notakey",
token: "notatoken",
}
Expand Down
8 changes: 4 additions & 4 deletions cli/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,13 @@ func (a *accountSet) ReplaceWith(other []Account) {

m := map[string]struct{}{}
for _, acc := range other {
copy := acc
clone := acc
// Preserve the alias if the account ID is the same and it already exists
if entry, ok := a.accounts[acc.ID]; ok {
// The name is the only thing that might change.
entry.Name = acc.Name
} else {
a.accounts[acc.ID] = &copy
a.accounts[acc.ID] = &clone
}

m[acc.ID] = struct{}{}
Expand All @@ -169,10 +169,10 @@ func (a *accountSet) ReplaceWith(other []Account) {
}
}

func (s accountSet) WriteTable(w io.Writer) {
func (a accountSet) WriteTable(w io.Writer) {
tbl := csv.NewWriter(w)
tbl.Write([]string{"id,name,alias"})
s.ForEach(func(id string, acc Account, alias string) {
a.ForEach(func(id string, acc Account, alias string) {
tbl.Write([]string{id, acc.Name, alias})
})
tbl.Flush()
Expand Down
6 changes: 3 additions & 3 deletions cli/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ var (
ClientID string
OIDCDomain string
ServerAddress string
Version string = "TBD"
BuildTimestamp string = "BuildTimestamp is not set"
DownloadURL string = "URL not set yet"
Version = "TBD"
BuildTimestamp = "BuildTimestamp is not set"
DownloadURL = "URL not set yet"
)

const (
Expand Down
26 changes: 13 additions & 13 deletions cli/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func LoadAWSCredentialsFromEnvironment() CloudCredentials {
}
}

func (c *CloudCredentials) ValidUntil(account *Account, cloudFlag string, dur time.Duration) bool {
func (c *CloudCredentials) ValidUntil(account *Account, dur time.Duration) bool {
if account == nil || c == nil {
return false
}
Expand All @@ -86,7 +86,7 @@ func (c *CloudCredentials) ValidUntil(account *Account, cloudFlag string, dur ti
}

const (
aws_shellTypePowershell = `$Env:AWS_ACCESS_KEY_ID = "%v"
awsShellTypePowershell = `$Env:AWS_ACCESS_KEY_ID = "%v"
$Env:AWS_SECRET_ACCESS_KEY = "%v"
$Env:AWS_SESSION_TOKEN = "%v"
$Env:AWS_SECURITY_TOKEN = "%v"
Expand All @@ -96,7 +96,7 @@ $Env:TF_VAR_token = $Env:AWS_SESSION_TOKEN
$Env:AWSKEY_EXPIRATION = "%v"
$Env:AWSKEY_ACCOUNT = "%v"
`
tencent_shellTypePowershell = `$Env:TENCENTCLOUD_SECRET_ID = "%v"
tencentShellTypePowershell = `$Env:TENCENTCLOUD_SECRET_ID = "%v"
$Env:TENCENTCLOUD_SECRET_KEY = "%v"
$Env:TENCENTCLOUD_TOKEN = "%v"
$Env:TENCENTCLOUD_SECURITY_TOKEN = "%v"
Expand All @@ -106,7 +106,7 @@ $Env:TF_VAR_token = $Env:TENCENTCLOUD_TOKEN
$Env:TENCENT_KEY_EXPIRATION = "%v"
$Env:TENCENT_KEY_ACCOUNT = "%v"
`
aws_shellTypeBasic = `SET AWS_ACCESS_KEY_ID=%v
awsShellTypeBasic = `SET AWS_ACCESS_KEY_ID=%v
SET AWS_SECRET_ACCESS_KEY=%v
SET AWS_SESSION_TOKEN=%v
SET AWS_SECURITY_TOKEN=%v
Expand All @@ -116,7 +116,7 @@ SET TF_VAR_token=%%AWS_SESSION_TOKEN%%
SET AWSKEY_EXPIRATION=%v
SET AWSKEY_ACCOUNT=%v
`
tencent_shellTypeBasic = `SET TENCENTCLOUD_SECRET_ID=%v
tencentShellTypeBasic = `SET TENCENTCLOUD_SECRET_ID=%v
SET TENCENTCLOUD_SECRET_KEY=%v
SET TENCENTCLOUD_TOKEN=%v
SET TENCENTCLOUD_SECURITY_TOKEN=%v
Expand All @@ -125,7 +125,7 @@ SET TF_VAR_secret_key=%%TENCENTCLOUD_SECRET_KEY%%
SET TF_VAR_token=%%TENCENTCLOUD_TOKEN%%
SET TENCENTKEY_EXPIRATION=%v
SET TENCENTKEY_ACCOUNT=%v`
aws_shellTypeBash = `export AWS_ACCESS_KEY_ID=%v
awsShellTypeBash = `export AWS_ACCESS_KEY_ID=%v
export AWS_SECRET_ACCESS_KEY=%v
export AWS_SESSION_TOKEN=%v
export AWS_SECURITY_TOKEN=%v
Expand All @@ -135,7 +135,7 @@ export TF_VAR_token=$AWS_SESSION_TOKEN
export AWSKEY_EXPIRATION=%v
export AWSKEY_ACCOUNT=%v
`
tencent_shellTypeBash = `export TENCENTCLOUD_SECRET_ID=%v
tencentShellTypeBash = `export TENCENTCLOUD_SECRET_ID=%v
export TENCENTCLOUD_SECRET_KEY=%v
export TENCENTCLOUD_TOKEN=%v
export TENCENT_SECURITY_TOKEN=%v
Expand All @@ -155,19 +155,19 @@ func (c CloudCredentials) WriteFormat(w io.Writer, format ShellType) (int, error

switch format {
case shellTypePowershell:
str = aws_shellTypePowershell
str = awsShellTypePowershell
if c.credentialsType == cloudTencent {
str = tencent_shellTypePowershell
str = tencentShellTypePowershell
}
case shellTypeBasic:
str = aws_shellTypeBasic
str = awsShellTypeBasic
if c.credentialsType == cloudTencent {
str = tencent_shellTypeBasic
str = tencentShellTypeBasic
}
case shellTypeBash:
str = aws_shellTypeBash
str = awsShellTypeBash
if c.credentialsType == cloudTencent {
str = tencent_shellTypeBash
str = tencentShellTypeBash
}
}

Expand Down
37 changes: 10 additions & 27 deletions cli/credentials_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,6 @@ import (
"github.com/stretchr/testify/assert"
)

/*
interesting thread on using ENV in unit testing
https://www.reddit.com/r/golang/comments/ar5z3i/how_to_set_env_variables_while_unit_testing/
*/

var envsToUse []string

func init() {
envsToUse = []string{
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWSKEY_EXPIRATION",
"AWSKEY_ACCOUNT",
}
}

func setEnv(t *testing.T, valid bool) *Account {
t.Setenv("AWS_ACCESS_KEY_ID", "1234")
t.Setenv("AWS_SECRET_ACCESS_KEY", "accesskey")
Expand All @@ -47,7 +30,7 @@ func setEnv(t *testing.T, valid bool) *Account {
func TestGetValidEnvCreds(t *testing.T) {
account := setEnv(t, true)
creds := LoadAWSCredentialsFromEnvironment()
assert.True(t, creds.ValidUntil(account, "aws", 0), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, 0), "credentials should be valid")
}

func TestGetInvalidEnvCreds(t *testing.T) {
Expand All @@ -56,31 +39,31 @@ func TestGetInvalidEnvCreds(t *testing.T) {
// test incorrect time first
t.Log("testing expired timestamp for key")
creds := LoadAWSCredentialsFromEnvironment()
assert.False(t, creds.ValidUntil(account, "aws", 0), "credentials should be invalid due to timestamp")
assert.False(t, creds.ValidUntil(account, 0), "credentials should be invalid due to timestamp")

account = setEnv(t, true)
account.ID = ""
creds = LoadAWSCredentialsFromEnvironment()

assert.False(t, creds.ValidUntil(account, "aws", 0), "credentials should be invalid due to non-matching id")
assert.False(t, creds.ValidUntil(account, 0), "credentials should be invalid due to non-matching id")

account = setEnv(t, true)
t.Setenv("AWSKEY_EXPIRATION", "definitely not a timestamp")
creds = LoadAWSCredentialsFromEnvironment()
assert.False(t, creds.ValidUntil(account, "aws", 0), "credentials should be invalid due to non-parsable timestamp")
assert.False(t, creds.ValidUntil(account, 0), "credentials should be invalid due to non-parsable timestamp")
}

func TestTimeWindowEnvCreds(t *testing.T) {
account := setEnv(t, true)

t.Log("testing minutes window still within 1hr period for test creds")
creds := LoadAWSCredentialsFromEnvironment()
assert.True(t, creds.ValidUntil(account, "aws", 0), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, "aws", 5), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, "aws", 30), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, "aws", 58), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, 0), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, 5), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, 30), "credentials should be valid")
assert.True(t, creds.ValidUntil(account, 58), "credentials should be valid")

t.Log("testing minutes window is outside 1hr period for test creds")
assert.False(t, creds.ValidUntil(account, "aws", 60*time.Minute), "credentials should be valid")
assert.False(t, creds.ValidUntil(account, "aws", 61*time.Minute), "credentials should be valid")
assert.False(t, creds.ValidUntil(account, 60*time.Minute), "credentials should be valid")
assert.False(t, creds.ValidUntil(account, 61*time.Minute), "credentials should be valid")
}
19 changes: 9 additions & 10 deletions cli/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,11 @@ func isMemberOfSlice(slice []string, val string) bool {
return false
}

func resolveApplicationInfo(cfg *Config, bypassCache bool, nameOrId string) (*Account, bool) {
func resolveApplicationInfo(cfg *Config, bypassCache bool, nameOrID string) (*Account, bool) {
if bypassCache {
return &Account{ID: nameOrId, Name: nameOrId}, true
} else {
return cfg.FindAccount(nameOrId)
return &Account{ID: nameOrID, Name: nameOrID}, true
}
return cfg.FindAccount(nameOrID)
}

var getCmd = &cobra.Command{
Expand Down Expand Up @@ -128,11 +127,11 @@ A role must be specified when using this command through the --role flag. You ma
credentials = LoadTencentCredentialsFromEnvironment()
}

if credentials.ValidUntil(account, cloudType, time.Duration(timeRemaining)*time.Minute) {
return echoCredentials(args[0], args[0], credentials, outputType, shellType, awsCliPath, tencentCliPath, cloudType)
if credentials.ValidUntil(account, time.Duration(timeRemaining)*time.Minute) {
return echoCredentials(args[0], args[0], credentials, outputType, shellType, awsCliPath, tencentCliPath)
}

oauthCfg, _, err := DiscoverOAuth2Config(cmd.Context(), oidcDomain, clientID)
oauthCfg, err := DiscoverOAuth2Config(cmd.Context(), oidcDomain, clientID)
if err != nil {
cmd.PrintErrf("could not discover oauth2 config: %s\n", err)
return nil
Expand All @@ -157,7 +156,7 @@ A role must be specified when using this command through the --role flag. You ma
return nil
}

pair, _, ok := FindRoleInSAML(roleName, samlResponse)
pair, ok := FindRoleInSAML(roleName, samlResponse)
if !ok {
cmd.PrintErrf("you do not have access to the role %s on application %s\n", roleName, args[0])
return nil
Expand Down Expand Up @@ -199,10 +198,10 @@ A role must be specified when using this command through the --role flag. You ma
account.MostRecentRole = roleName
}

return echoCredentials(args[0], args[0], credentials, outputType, shellType, awsCliPath, tencentCliPath, cloudType)
return echoCredentials(args[0], args[0], credentials, outputType, shellType, awsCliPath, tencentCliPath)
}}

func echoCredentials(id, name string, credentials CloudCredentials, outputType, shellType, awsCliPath, tencentCliPath, cloudFlag string) error {
func echoCredentials(id, name string, credentials CloudCredentials, outputType, shellType, awsCliPath, tencentCliPath string) error {
switch outputType {
case outputTypeEnvironmentVariable:
credentials.WriteFormat(os.Stdout, shellType)
Expand Down
Loading

0 comments on commit 8ce6fac

Please sign in to comment.