-
Notifications
You must be signed in to change notification settings - Fork 95
/
ssotoken.go
222 lines (191 loc) · 5.05 KB
/
ssotoken.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package cfaws
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/common-fate/granted/pkg/securestorage"
)
const (
// permission for user to read/write/execute.
USER_READ_WRITE_PERM = 0700
)
type SSOPlainTextOut struct {
AccessToken string `json:"accessToken"`
ExpiresAt string `json:"expiresAt"`
SSOSessionName string `json:"ssoSessionName"`
StartUrl string `json:"startUrl"`
Region string `json:"region"`
}
// CreatePlainTextSSO is currently unused. In a future version of the Granted CLI,
// we'll allow users to export a plaintext token from their keychain for compatibility
// purposes with other AWS tools.
func CreatePlainTextSSO(awsConfig config.SharedConfig, token *securestorage.SSOToken) *SSOPlainTextOut {
ssoRegion := awsConfig.SSORegion
if ssoRegion == "" && awsConfig.SSOSession != nil {
ssoRegion = awsConfig.SSOSession.SSORegion
}
ssoStartURL := awsConfig.SSOStartURL
if ssoStartURL == "" && awsConfig.SSOSession != nil {
ssoStartURL = awsConfig.SSOSession.SSOStartURL
}
return &SSOPlainTextOut{
AccessToken: token.AccessToken,
ExpiresAt: token.Expiry.Format(time.RFC3339),
Region: ssoRegion,
SSOSessionName: awsConfig.SSOSessionName,
StartUrl: ssoStartURL,
}
}
func (s *SSOPlainTextOut) DumpToCacheDirectory() error {
jsonOut, err := json.Marshal(s)
if err != nil {
return fmt.Errorf("unable to parse token to json with err %s", err)
}
// AWS uses the session name if present, else use startUrl
key := s.SSOSessionName
if key == "" {
key = s.StartUrl
}
err = dumpTokenFile(jsonOut, key)
if err != nil {
return err
}
return nil
}
func getCacheFileName(key string) (string, error) {
hash := sha1.New()
_, err := hash.Write([]byte(key))
if err != nil {
return "", err
}
return strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json", nil
}
// Write SSO token as JSON output to default cache location.
func dumpTokenFile(jsonToken []byte, key string) error {
key, err := getCacheFileName(key)
if err != nil {
return err
}
path, err := getDefaultCacheLocation()
if err != nil {
return err
}
if _, err := os.Stat(path); os.IsNotExist(err) {
err := os.MkdirAll(path, USER_READ_WRITE_PERM)
if err != nil {
return fmt.Errorf("unable to create sso cache directory with err: %s", err)
}
}
err = os.WriteFile(filepath.Join(path, key), jsonToken, USER_READ_WRITE_PERM)
if err != nil {
return err
}
return nil
}
// Find the ~/.aws/sso/cache absolute path based on OS.
func getDefaultCacheLocation() (string, error) {
h, err := os.UserHomeDir()
if err != nil {
return "", err
}
cachePath := filepath.Join(h, ".aws", "sso", "cache")
return cachePath, nil
}
// check if a valid ~/.aws/sso/cache file exists
func SsoCredsAreInConfigCache() bool {
path, err := getDefaultCacheLocation()
if err != nil {
return false
}
// now open the folder
f, err := os.Open(path)
if err != nil {
return false
}
// close the folder
defer f.Close()
return true
}
func ReadPlaintextSsoCreds(startUrl string) (SSOPlainTextOut, error) {
/**
The path will like this so we'll want to open the folder then scan over json files.
~/.aws/sso/cache
+└── a092ca4eExample27b5add8ec31d9b.json
+└── a092ca4eExample27b5add8ec31d9b.json
*/
path, err := getDefaultCacheLocation()
if err != nil {
return SSOPlainTextOut{}, err
}
// now open the folder
f, err := os.Open(path)
if err != nil {
return SSOPlainTextOut{}, err
}
// now read the folder
files, err := f.Readdir(-1)
if err != nil {
return SSOPlainTextOut{}, err
}
// close the folder
defer f.Close()
for _, file := range files {
// check if the file is a json file
if filepath.Ext(file.Name()) == ".json" {
// open the file
f, err := os.Open(filepath.Join(path, file.Name()))
if err != nil {
return SSOPlainTextOut{}, err
}
// read the file
data, err := io.ReadAll(f)
if err != nil {
return SSOPlainTextOut{}, err
}
// if file doesn't start with botocore
if !strings.HasPrefix(file.Name(), "botocore") {
// close the file
defer f.Close()
// unmarshal the json
var sso SSOPlainTextOut
err = json.Unmarshal(data, &sso)
if err != nil {
return SSOPlainTextOut{}, err
}
// check if the startUrl matches
if sso.StartUrl == startUrl {
return sso, nil
}
}
}
}
return SSOPlainTextOut{}, fmt.Errorf("no valid sso token found")
}
func GetValidSSOTokenFromPlaintextCache(startUrl string) *securestorage.SSOToken {
if SsoCredsAreInConfigCache() {
creds, err := ReadPlaintextSsoCreds(startUrl)
if err != nil {
return nil
}
var ssoPlaintextOutput securestorage.SSOToken
ssoPlaintextOutput.AccessToken = creds.AccessToken
// from iso string to time.Time
ssoPlaintextOutput.Expiry, err = time.Parse(time.RFC3339, creds.ExpiresAt)
if err != nil {
return nil
}
// if it's expired return nil
if ssoPlaintextOutput.Expiry.Before(time.Now()) {
return nil
}
return &ssoPlaintextOutput
}
return nil
}