Skip to content

Commit

Permalink
Merge pull request #14 from jaxxstorm/lint
Browse files Browse the repository at this point in the history
  • Loading branch information
jaxxstorm authored Oct 18, 2022
2 parents b570ea6 + 2055223 commit c30c3d0
Show file tree
Hide file tree
Showing 14 changed files with 141 additions and 66 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: golangci-lint
on:
push:
branches:
- master
- main
pull_request:
permissions:
contents: read
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: 1.17
- uses: actions/checkout@v3
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: latest
6 changes: 3 additions & 3 deletions cmd/aws-sso-creds/export/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import (

func Command() *cobra.Command {
command := &cobra.Command{
Use: "export",
Short: "Generates a set of shell commands to export AWS temporary creds to your environment",
Long: "Generates a set of shell commands to export AWS temporary creds to your environment",
Use: "export",
Short: "Generates a set of shell commands to export AWS temporary creds to your environment",
Long: "Generates a set of shell commands to export AWS temporary creds to your environment",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {

Expand Down
13 changes: 6 additions & 7 deletions cmd/aws-sso-creds/get/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"

. "github.com/logrusorgru/aurora"
"github.com/logrusorgru/aurora"
)


func Command() *cobra.Command {
command := &cobra.Command{
Use: "get",
Short: "Get AWS temporary credentials to use on the command line",
Long: "Retrieve AWS temporary credentials",
Use: "get",
Short: "Get AWS temporary credentials to use on the command line",
Long: "Retrieve AWS temporary credentials",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {

Expand All @@ -36,7 +35,7 @@ func Command() *cobra.Command {
return err
}

fmt.Println(Sprintf("Your temporary credentials for account %s are:", White(accountID)))
fmt.Println(aurora.Sprintf("Your temporary credentials for account %s are:", aurora.White(accountID)))
fmt.Println("")

fmt.Fprintln(os.Stdout, "AWS_ACCESS_KEY_ID\t", *creds.RoleCredentials.AccessKeyId)
Expand All @@ -45,7 +44,7 @@ func Command() *cobra.Command {

fmt.Println("")

fmt.Println("These credentials will expire at:", Red(time.UnixMilli(*creds.RoleCredentials.Expiration).UTC()))
fmt.Println("These credentials will expire at:", aurora.Red(time.UnixMilli(*creds.RoleCredentials.Expiration).UTC()))

return nil
},
Expand Down
10 changes: 5 additions & 5 deletions cmd/aws-sso-creds/helper/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (

type CredentialsProcessOutput struct {
Version int `json:"page"`
AccessKeyId string `json:"AccessKeyId"`
AccessKeyID string `json:"AccessKeyId"`
SecretAccessKey string `json:"SecretAccessKey"`
SessionToken string `json:"SessionToken"`
Expiration string `json:"Expiration"`
Expand Down Expand Up @@ -41,11 +41,11 @@ func Command() *cobra.Command {
}

rawCreds := CredentialsProcessOutput{
Version: 1,
AccessKeyId: *creds.RoleCredentials.AccessKeyId,
Version: 1,
AccessKeyID: *creds.RoleCredentials.AccessKeyId,
SecretAccessKey: *creds.RoleCredentials.SecretAccessKey,
SessionToken: *creds.RoleCredentials.SessionToken,
Expiration: time.Unix(*creds.RoleCredentials.Expiration / 1000, 0).Format(time.RFC3339),
SessionToken: *creds.RoleCredentials.SessionToken,
Expiration: time.Unix(*creds.RoleCredentials.Expiration/1000, 0).Format(time.RFC3339),
}

output, err := json.Marshal(rawCreds)
Expand Down
15 changes: 12 additions & 3 deletions cmd/aws-sso-creds/list/accounts/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package accounts

import (
"fmt"
"io/ioutil"
"io/fs"
"os"
"path/filepath"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
Expand Down Expand Up @@ -47,12 +48,17 @@ func Command() *cobra.Command {
return fmt.Errorf("error retrieving SSO config: %w", err)
}

cacheFiles, err := ioutil.ReadDir(fmt.Sprintf("%s/.aws/sso/cache", homeDir))
cacheFiles, err := os.ReadDir(filepath.Join(homeDir, ".aws", "sso", "cache"))
if err != nil {
return fmt.Errorf("error retrieving cache files - perhaps you need to login?: %w", err)
}

token, err := config.GetSSOToken(cacheFiles, *ssoConfig, homeDir)
files := make([]fs.FileInfo, 0, len(cacheFiles))

token, err := config.GetSSOToken(files, *ssoConfig, homeDir)
if err != nil {
return fmt.Errorf("error retrieving SSO token from cache files: %v", err)
}

sess := session.Must(session.NewSession())
svc := sso.New(sess, aws.NewConfig().WithRegion(ssoConfig.Region))
Expand All @@ -61,6 +67,9 @@ func Command() *cobra.Command {
AccessToken: &token,
MaxResults: &results,
})
if err != nil {
return fmt.Errorf("error listing accounts: %v", err)
}

writer := tabwriter.NewWriter(os.Stdout, tabwriterMinWidth, tabwriterWidth, tabwriterPadding, tabwriterPadChar, tabwriterFlags)
fmt.Fprintln(writer, "ID\tNAME\tEMAIL ADDRESS")
Expand Down
24 changes: 17 additions & 7 deletions cmd/aws-sso-creds/list/roles/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ package roles

import (
"fmt"
"io/fs"
"os"
"path/filepath"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sso"
"github.com/jaxxstorm/aws-sso-creds/pkg/config"
"github.com/liggitt/tabwriter"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"io/ioutil"
"os"
)

const (
Expand All @@ -22,7 +24,7 @@ const (
)

var (
results int64
results int64
accountID string
)

Expand All @@ -48,12 +50,17 @@ func Command() *cobra.Command {
return fmt.Errorf("error retrieving SSO config: %w", err)
}

cacheFiles, err := ioutil.ReadDir(fmt.Sprintf("%s/.aws/sso/cache", homeDir))
cacheFiles, err := os.ReadDir(filepath.Join(homeDir, ".aws", "sso", "cache"))
if err != nil {
return fmt.Errorf("error retrieving cache files - perhaps you need to login?: %w", err)
}

token, err := config.GetSSOToken(cacheFiles, *ssoConfig, homeDir)
files := make([]fs.FileInfo, 0, len(cacheFiles))

token, err := config.GetSSOToken(files, *ssoConfig, homeDir)
if err != nil {
return fmt.Errorf("error retrieving SSO token from cache files: %v", err)
}

sess := session.Must(session.NewSession())
svc := sso.New(sess, aws.NewConfig().WithRegion(ssoConfig.Region))
Expand All @@ -62,9 +69,12 @@ func Command() *cobra.Command {

roles, err := svc.ListAccountRoles(&sso.ListAccountRolesInput{
AccessToken: &token,
MaxResults: &results,
AccountId: &accountID,
MaxResults: &results,
AccountId: &accountID,
})
if err != nil {
return fmt.Errorf("error listing roles: %v", err)
}

writer := tabwriter.NewWriter(os.Stdout, tabwriterMinWidth, tabwriterWidth, tabwriterPadding, tabwriterPadChar, tabwriterFlags)
fmt.Fprintln(writer, "ID\tROLE NAME")
Expand Down
12 changes: 9 additions & 3 deletions cmd/aws-sso-creds/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,15 @@ func configureCLI() *cobra.Command {

rootCommand.PersistentFlags().StringVarP(&profile, "profile", "p", "", "the AWS profile to use")
rootCommand.PersistentFlags().StringVarP(&homeDir, "home-directory", "H", homeDir, "specify a path to a home directory")
viper.BindEnv("profile", "AWS_PROFILE")
viper.BindPFlag("profile", rootCommand.PersistentFlags().Lookup("profile"))
viper.BindPFlag("home-directory", rootCommand.PersistentFlags().Lookup("home-directory"))
if err := viper.BindEnv("profile", "AWS_PROFILE"); err != nil {
panic(err)
}
if err := viper.BindPFlag("profile", rootCommand.PersistentFlags().Lookup("profile")); err != nil {
panic(err)
}
if err := viper.BindPFlag("home-directory", rootCommand.PersistentFlags().Lookup("home-directory")); err != nil {
panic(err)
}

return rootCommand
}
Expand Down
59 changes: 40 additions & 19 deletions cmd/aws-sso-creds/set/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package set
import (
"fmt"
"os"
"time"
"path/filepath"
"time"

"github.com/jaxxstorm/aws-sso-creds/pkg/credentials"
"github.com/spf13/cobra"
Expand All @@ -13,6 +13,10 @@ import (
"github.com/bigkevmcd/go-configparser"
)

var (
credsFile *configparser.ConfigParser
)

func Command() *cobra.Command {
command := &cobra.Command{
Use: "set PROFILE",
Expand All @@ -24,7 +28,7 @@ func Command() *cobra.Command {
cmd.SilenceUsage = true
profile := viper.GetString("profile")
homeDir := viper.GetString("home-directory")

credsPath := filepath.Join(homeDir, ".aws", "credentials")
cfgPath := filepath.Join(homeDir, ".aws", "config")

Expand All @@ -40,17 +44,18 @@ func Command() *cobra.Command {
return err
}

credsFile, err := configparser.NewConfigParserFromFile(credsPath)
if os.IsNotExist(err) {
// Ensure the new empty credentials file is not readable by others.
if f, err := os.OpenFile(credsPath, os.O_CREATE, 0600); err != nil {
return err
} else {
f.Close()
credsFile, err = configparser.NewConfigParserFromFile(credsPath)
if err != nil {
if os.IsNotExist(err) {
// Ensure the new empty credentials file is not readable by others.
if f, err := os.OpenFile(credsPath, os.O_CREATE, 0600); err != nil {
f.Close()
return err
}

credsFile = configparser.New()
}
credsFile = configparser.New()
} else if err != nil {
return err
return fmt.Errorf("error parsing config file: %v", err)
}

configFile, err := configparser.NewConfigParserFromFile(cfgPath)
Expand All @@ -59,15 +64,31 @@ func Command() *cobra.Command {
}

// create a new credentials section
credsFile.AddSection(args[0])
configFile.AddSection(fmt.Sprintf("profile %s", args[0]))
if err := credsFile.AddSection(args[0]); err != nil {
return fmt.Errorf("error creating credentials section in creds file: %v", err)
}

credsFile.Set(args[0], "aws_access_key_id", *creds.RoleCredentials.AccessKeyId)
credsFile.Set(args[0], "aws_secret_access_key", *creds.RoleCredentials.SecretAccessKey)
credsFile.Set(args[0], "aws_session_token", *creds.RoleCredentials.SessionToken)
if err := configFile.AddSection(fmt.Sprintf("profile %s", args[0])); err != nil {
return fmt.Errorf("error creating credentials section in config file: %v", err)
}

if err := credsFile.Set(args[0], "aws_access_key_id", *creds.RoleCredentials.AccessKeyId); err != nil {
return fmt.Errorf("error setting access key id: %v", err)
}
if err := credsFile.Set(args[0], "aws_secret_access_key", *creds.RoleCredentials.SecretAccessKey); err != nil {
return fmt.Errorf("error setting secret access key: %v", err)
}
if err := credsFile.Set(args[0], "aws_session_token", *creds.RoleCredentials.SessionToken); err != nil {
return fmt.Errorf("error setting session token: %v", err)
}

if err := credsFile.SaveWithDelimiter(credsPath, "="); err != nil {
return fmt.Errorf("error saving credentials file: %v", err)
}

credsFile.SaveWithDelimiter(credsPath, "=")
configFile.SaveWithDelimiter(cfgPath, "=")
if err := configFile.SaveWithDelimiter(cfgPath, "="); err != nil {
return fmt.Errorf("error saving config file: %v", err)
}

fmt.Printf("credentials saved to profile: %s\n", args[0])
fmt.Printf("these credentials will expire: %s\n", time.Unix(*creds.RoleCredentials.Expiration, 0).Format(time.UnixDate))
Expand Down
2 changes: 1 addition & 1 deletion cmd/aws-sso-creds/version/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"os"

"github.com/go-git/go-git/v5/plumbing"
"github.com/pulumi/pulumictl/pkg/gitversion"
"github.com/jaxxstorm/aws-sso-creds/pkg/version"
"github.com/pulumi/pulumictl/pkg/gitversion"
"github.com/spf13/cobra"
)

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/jaxxstorm/aws-sso-creds

go 1.17
go 1.19

require (
github.com/aws/aws-sdk-go v1.43.15
Expand Down
15 changes: 8 additions & 7 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ func GetSSOConfig(profile string, homedir string) (*SSOConfig, error) {

// FIXME: make this better
if p.HasSection(section) {
ssoStartUrl, err := p.Get(section, "sso_start_url")
ssoStartURL, err := p.Get(section, "sso_start_url")
if err != nil {
return nil, fmt.Errorf("no SSO url in profile: %s", profile)
}
ssoRegion, err := p.Get(section, "sso_region")
if err != nil {
return nil, fmt.Errorf("no SSO region in profile: %s", profile)
return nil, fmt.Errorf("no SSO region in profile: %s", profile)
}
ssoAccountId, err := p.Get(section, "sso_account_id")
ssoAccountID, err := p.Get(section, "sso_account_id")
if err != nil {
return nil, fmt.Errorf("no SSO account id in profile: %s", profile)
}
Expand All @@ -40,13 +40,14 @@ func GetSSOConfig(profile string, homedir string) (*SSOConfig, error) {
}

return &SSOConfig{
StartUrl: ssoStartUrl,
StartURL: ssoStartURL,
Region: ssoRegion,
AccountID: ssoAccountId,
AccountID: ssoAccountID,
RoleName: ssoRoleName,
}, nil

} else {
return nil, fmt.Errorf("unable to find profile %s", profile)
}

return nil, fmt.Errorf("unable to find profile %s", profile)

}
Loading

0 comments on commit c30c3d0

Please sign in to comment.