Skip to content

Commit

Permalink
Merge pull request #4 from one2nc/issue-1-aws-credentials-expired
Browse files Browse the repository at this point in the history
Fix credentials expire bug (#1)
  • Loading branch information
chinmay185 authored Mar 9, 2023
2 parents d4c437a + 54987a8 commit b14ff08
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 84 deletions.
7 changes: 3 additions & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,12 @@ func run(cmd *cobra.Command, args []string) {
profiles := readAndValidateProfile()
if profiles[0] == "default" && len(region) == 0 {
region = getDefaultAWSRegion()
} else {
} else if len(region) == 0 {
region = "ap-south-1"
}

regions := readAndValidateRegion()
//TODO Move this in the AWS folder
sess, err := config.GetSession(profiles[0], getDefaultAWSRegion())
sess, err := aws.GetSession(profiles[0], regions[0])
if err != nil {
panic(fmt.Sprintf("aws session init failed -- %v", err))
}
Expand All @@ -85,7 +84,7 @@ func run(cmd *cobra.Command, args []string) {
}

func readAndValidateProfile() []string {
profiles, err := config.GetProfiles()
profiles, err := aws.GetProfiles()
if err != nil {
panic(fmt.Sprintf("failed to read profiles -- %v", err))
}
Expand Down
86 changes: 86 additions & 0 deletions internal/aws/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package aws

import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"strings"

awsV2 "github.com/aws/aws-sdk-go-v2/aws"
awsV2Config "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/session"
)

type credentialProvider struct {
awsV2.Credentials
}

func (c credentialProvider) Retrieve() (credentials.Value, error) {
return credentials.Value{AccessKeyID: c.AccessKeyID, SecretAccessKey: c.SecretAccessKey, SessionToken: os.Getenv("AWS_SESSION_TOKEN")}, nil
}

func (c credentialProvider) IsExpired() bool {
return c.Expired()
}

func GetSession(profile, region string) (*session.Session, error) {
cfg, err := awsV2Config.LoadDefaultConfig(context.TODO(),
awsV2Config.WithSharedConfigProfile(profile),
awsV2Config.WithRegion(region),
)
if err != nil {
fmt.Printf("failed to load config")
return nil, err
}
creds, err := cfg.Credentials.Retrieve(context.TODO())
if err != nil {
fmt.Printf("failed to read credentials")
return nil, err
}
credentialProvider := credentialProvider{Credentials: creds}
if credentialProvider.IsExpired() {
fmt.Println("Credentials have expired")
return nil, errors.New("AWS Credentials expired")
}

// create session
sess, err := session.NewSessionWithOptions(session.Options{Config: aws.Config{
//TODO: remove hardcoded enpoint
//Endpoint: aws.String(localstackEndpoint),
Credentials: credentials.NewCredentials(credentialProvider),
Region: aws.String(region),
S3ForcePathStyle: aws.Bool(true),
},
Profile: profile})
if err != nil {
fmt.Println("Error creating session:", err)
return nil, err
}
return sess, nil
}

func GetProfiles() (profiles []string, err error) {
filepath := defaults.SharedCredentialsFilename()
fileContent, err := ioutil.ReadFile(filepath)
if err != nil {
return profiles, err
}
lines := strings.Split(string(fileContent), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
profile := line[1 : len(line)-1]
profiles = append(profiles, profile)
}
}
if len(profiles) < 1 {
err = errors.New("NO PROFILES FOUND")
return nil, err
}

return profiles, nil
}
101 changes: 23 additions & 78 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
package config

import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"

"github.com/adrg/xdg"
awsV2 "github.com/aws/aws-sdk-go-v2/aws"
awsV2Config "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v2"
)
Expand All @@ -41,7 +32,6 @@ func CloudlensHome() string {
//log.Debug().Msg("env CL: " + env)
return env
}

xdgCLHome, err := xdg.ConfigFile("cloudlens")
//log.Debug().Msg("xdgsclhome: " + xdgCLHome)

Expand Down Expand Up @@ -89,71 +79,26 @@ func (c *Config) SaveFile(path string) error {
return os.WriteFile(path, cfg, 0644)
}

var config Config

func GetSession(profile, region string) (*session.Session, error) {
sess, err := session.NewSessionWithOptions(session.Options{Config: aws.Config{
//TODO: remove hardcoded enpoint
// Endpoint: aws.String(localstackEndpoint),
Region: aws.String(region),
S3ForcePathStyle: aws.Bool(true),
},
Profile: profile})
if err != nil {
fmt.Println("Error creating session:", err)
return nil, err
}

//comment this if using localstack
isExp := sess.Config.Credentials.IsExpired()
if err != nil {
fmt.Println("Error creating session:", err)
return nil, err
}
if isExp {
fmt.Println("Credentials have expired")
return nil, errors.New("AWS Credentials expired")
}
return sess, nil
}

func Get() (Config, error) {
emptyCfg := Config{}
if reflect.DeepEqual(emptyCfg, config) {
profiles, err := GetProfiles()
if err != nil {
return emptyCfg, err
}
config.Profiles = profiles
if LookupForValue(config.Profiles, "default") {
// Load the Shared AWS Configuration (~/.aws/config)
awsLocalCfg, err := awsV2Config.LoadDefaultConfig(context.TODO())
if err != nil {
return emptyCfg, err
}
config.AwsConfig = awsLocalCfg
}
}
return config, nil
}

func GetProfiles() (profiles []string, err error) {
filepath := defaults.SharedCredentialsFilename()
fileContent, err := ioutil.ReadFile(filepath)
if err != nil {
return profiles, err
}
lines := strings.Split(string(fileContent), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
profile := line[1 : len(line)-1]
profiles = append(profiles, profile)
}
}
if len(profiles) < 1 {
err = errors.New("NO PROFILES FOUND")
return nil, err
}

return profiles, nil
}
// Unsed for now

// var config Config

// func Get() (Config, error) {
// emptyCfg := Config{}
// if reflect.DeepEqual(emptyCfg, config) {
// profiles, err := GetProfiles()
// if err != nil {
// return emptyCfg, err
// }
// config.Profiles = profiles
// if LookupForValue(config.Profiles, "default") {
// // Load the Shared AWS Configuration (~/.aws/config)
// awsLocalCfg, err := awsV2Config.LoadDefaultConfig(context.TODO())
// if err != nil {
// return emptyCfg, err
// }
// config.AwsConfig = awsLocalCfg
// }
// }
// return config, nil
// }
4 changes: 2 additions & 2 deletions internal/view/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/derailed/tview"
"github.com/gdamore/tcell/v2"
"github.com/one2nc/cloudlens/internal"
"github.com/one2nc/cloudlens/internal/config"
"github.com/one2nc/cloudlens/internal/aws"
"github.com/one2nc/cloudlens/internal/model"
"github.com/one2nc/cloudlens/internal/ui"
"github.com/one2nc/cloudlens/internal/ui/dialog"
Expand Down Expand Up @@ -252,7 +252,7 @@ func (a *App) regionChanged(region string, index int) {
}

func (a *App) refreshSession(profile string, region string) {
sess, err := config.GetSession(profile, region)
sess, err := aws.GetSession(profile, region)
if err != nil {
a.App.Flash().Err(err)
return
Expand Down

0 comments on commit b14ff08

Please sign in to comment.