-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
83 lines (67 loc) · 1.97 KB
/
exec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package commands
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/pkg/errors"
"github.com/versent/saml2aws/pkg/awsconfig"
"github.com/versent/saml2aws/pkg/flags"
"github.com/versent/saml2aws/pkg/shell"
)
// Exec execute the supplied command after seeding the environment
func Exec(execFlags *flags.LoginExecFlags, cmdline []string) error {
if len(cmdline) < 1 {
return fmt.Errorf("Command to execute required")
}
sharedCreds := awsconfig.NewSharedCredentials(execFlags.Profile)
// this checks if the credentials file has been created yet
// can only really be triggered if saml2aws exec is run on a new
// system prior to creating $HOME/.aws
exist, err := sharedCreds.CredsExists()
if err != nil {
return errors.Wrap(err, "error loading credentials")
}
if !exist {
fmt.Println("unable to load credentials, login required to create them")
return nil
}
ok, err := checkToken(execFlags.Profile)
if err != nil {
return errors.Wrap(err, "error validating token")
}
if !ok {
err = Login(execFlags)
}
if err != nil {
return errors.Wrap(err, "error logging in")
}
id, secret, token, err := sharedCreds.Load()
if err != nil {
return errors.Wrap(err, "error loading credentials")
}
return shell.ExecShellCmd(cmdline, shell.BuildEnvVars(id, secret, token))
}
func checkToken(profile string) (bool, error) {
sess, err := session.NewSessionWithOptions(session.Options{
Profile: profile,
})
if err != nil {
return false, err
}
svc := sts.New(sess)
params := &sts.GetCallerIdentityInput{}
resp, err := svc.GetCallerIdentity(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "ExpiredToken" || awsErr.Code() == "NoCredentialProviders" {
return false, nil
}
}
return false, err
}
fmt.Fprintln(os.Stderr, "Running command as:", aws.StringValue(resp.Arn))
return true, nil
}