-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
173 lines (159 loc) · 4.57 KB
/
main.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"os/user"
"time"
"github.com/urfave/cli/v2"
)
var app = cli.NewApp()
func main() {
info()
commands()
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func info() {
app.Name = "aws-one-punch"
app.Usage = "one command to grant all command prompts AWS access with IAM role credentials in OSX for AWS SSO users."
app.Version = "2.0.0"
}
func commands() {
domain, err := getDomain()
if err != nil {
log.Fatal(err)
}
awsService := NewAWSService(&http.Client{
Timeout: time.Second * 20,
})
app.Commands = []*cli.Command{
{
Name: "list-accounts",
Aliases: []string{"ls-a"},
Usage: "List all assigned AWS accounts",
Action: func(c *cli.Context) error {
token, err := GetAwsSsoTokenWithRetry(domain)
if err != nil {
return err
}
accounts, err := awsService.getAccounts("https://portal.sso.ap-southeast-2.amazonaws.com/instance/appinstances", token)
if err != nil {
return err
}
if len(accounts.Result) > 0 {
for i := 0; i < len(accounts.Result); i++ {
fmt.Printf("AccountId: %s, accountName: %s\n", accounts.Result[i].Id, accounts.Result[i].Name)
}
}
return nil
},
},
{
Name: "list-roles",
Aliases: []string{"ls-r"},
Usage: "List all assigned AWS IAM role in an AWS account",
Flags: []cli.Flag{
&cli.StringFlag{Name: "account-id", Required: true},
},
Action: func(c *cli.Context) error {
accountId := c.Value("account-id")
token, err := GetAwsSsoTokenWithRetry(domain)
if err != nil {
log.Fatalln(err)
}
roles, err := awsService.getRoles(fmt.Sprintf("https://portal.sso.ap-southeast-2.amazonaws.com/instance/appinstance/%s/profiles", accountId), token)
if err != nil {
log.Fatalln(err)
}
if len(roles.Result) > 0 {
for i := 0; i < len(roles.Result); i++ {
fmt.Printf("RoleName: %s\n", roles.Result[i].Name)
}
return nil
}
fmt.Printf("no IAM roles found for account %s\n", accountId)
return nil
},
},
{
Name: "access",
Aliases: []string{"a"},
Usage: "Grant all command promopts AWS access with temporary credentails from an IAM role",
Flags: []cli.Flag{
&cli.StringFlag{Name: "account-name", Required: true},
&cli.StringFlag{Name: "role-name", Required: true},
},
Action: func(c *cli.Context) error {
accountId := c.Value("account-name")
roleName := c.Value("role-name")
token, err := GetAwsSsoTokenWithRetry(domain)
if err != nil {
log.Fatalln(err)
}
cs, err := awsService.getCredentials(fmt.Sprintf("https://portal.sso.ap-southeast-2.amazonaws.com/federation/credentials/?account_id=%s&role_name=%s&debug=true", accountId, roleName), token)
if err != nil {
log.Fatalln(err)
}
err = updateCredentialFile(cs)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("AWS access granted for account %s and IAM role %s\n", accountId, roleName)
return nil
},
},
}
}
func getDomain() (string, error) {
doamin := os.Getenv("AWS_CONSOLE_DOMAIN")
if len(doamin) == 0 {
return "", fmt.Errorf("invaid AWS_CONSOLE_DOMAIN configured")
}
return doamin, nil
}
func updateCredentialFile(c credentials) error {
usr, _ := user.Current()
folderPath := fmt.Sprintf("%s/.aws", usr.HomeDir)
if awsFolderExists, _ := pathExists(folderPath); !awsFolderExists {
err := os.Mkdir(folderPath, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create aws folder %s due to %s", folderPath, err.Error())
}
}
filePath := fmt.Sprintf("%s/credentials", folderPath)
// remove credential file if it exists
if exists, _ := pathExists(filePath); exists {
err := os.Remove(filePath)
if err != nil {
return fmt.Errorf("failed to remove existing credentials file %s", err.Error())
}
}
// create the credentials file
f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to create credentials file %s due to %s", filePath, err.Error())
}
defer f.Close()
// update the credentials file
content := fmt.Sprintf("[default]\naws_access_key_id=%s\naws_secret_access_key=%s\naws_session_token=%s", c.RoleCredentials.AccessKeyId, c.RoleCredentials.SecretAccessKey, c.RoleCredentials.SessionToken)
_, err = f.Write([]byte(content))
if err != nil {
return fmt.Errorf("failed to update the credentials file %s", err.Error())
}
return nil
}
func pathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}