aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_cached_token.go
blob: 3b97e6dd406f19fde1cddbe6cb72acfde230fce3 (plain) (blame)
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
223
224
225
226
227
228
229
230
231
232
233
package ssocreds

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/internal/sdk"
	"github.com/aws/aws-sdk-go-v2/internal/shareddefaults"
)

var osUserHomeDur = shareddefaults.UserHomeDir

// StandardCachedTokenFilepath returns the filepath for the cached SSO token file, or
// error if unable get derive the path. Key that will be used to compute a SHA1
// value that is hex encoded.
//
// Derives the filepath using the Key as:
//
//	~/.aws/sso/cache/<sha1-hex-encoded-key>.json
func StandardCachedTokenFilepath(key string) (string, error) {
	homeDir := osUserHomeDur()
	if len(homeDir) == 0 {
		return "", fmt.Errorf("unable to get USER's home directory for cached token")
	}
	hash := sha1.New()
	if _, err := hash.Write([]byte(key)); err != nil {
		return "", fmt.Errorf("unable to compute cached token filepath key SHA1 hash, %w", err)
	}

	cacheFilename := strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json"

	return filepath.Join(homeDir, ".aws", "sso", "cache", cacheFilename), nil
}

type tokenKnownFields struct {
	AccessToken string   `json:"accessToken,omitempty"`
	ExpiresAt   *rfc3339 `json:"expiresAt,omitempty"`

	RefreshToken string `json:"refreshToken,omitempty"`
	ClientID     string `json:"clientId,omitempty"`
	ClientSecret string `json:"clientSecret,omitempty"`
}

type token struct {
	tokenKnownFields
	UnknownFields map[string]interface{} `json:"-"`
}

func (t token) MarshalJSON() ([]byte, error) {
	fields := map[string]interface{}{}

	setTokenFieldString(fields, "accessToken", t.AccessToken)
	setTokenFieldRFC3339(fields, "expiresAt", t.ExpiresAt)

	setTokenFieldString(fields, "refreshToken", t.RefreshToken)
	setTokenFieldString(fields, "clientId", t.ClientID)
	setTokenFieldString(fields, "clientSecret", t.ClientSecret)

	for k, v := range t.UnknownFields {
		if _, ok := fields[k]; ok {
			return nil, fmt.Errorf("unknown token field %v, duplicates known field", k)
		}
		fields[k] = v
	}

	return json.Marshal(fields)
}

func setTokenFieldString(fields map[string]interface{}, key, value string) {
	if value == "" {
		return
	}
	fields[key] = value
}
func setTokenFieldRFC3339(fields map[string]interface{}, key string, value *rfc3339) {
	if value == nil {
		return
	}
	fields[key] = value
}

func (t *token) UnmarshalJSON(b []byte) error {
	var fields map[string]interface{}
	if err := json.Unmarshal(b, &fields); err != nil {
		return nil
	}

	t.UnknownFields = map[string]interface{}{}

	for k, v := range fields {
		var err error
		switch k {
		case "accessToken":
			err = getTokenFieldString(v, &t.AccessToken)
		case "expiresAt":
			err = getTokenFieldRFC3339(v, &t.ExpiresAt)
		case "refreshToken":
			err = getTokenFieldString(v, &t.RefreshToken)
		case "clientId":
			err = getTokenFieldString(v, &t.ClientID)
		case "clientSecret":
			err = getTokenFieldString(v, &t.ClientSecret)
		default:
			t.UnknownFields[k] = v
		}

		if err != nil {
			return fmt.Errorf("field %q, %w", k, err)
		}
	}

	return nil
}

func getTokenFieldString(v interface{}, value *string) error {
	var ok bool
	*value, ok = v.(string)
	if !ok {
		return fmt.Errorf("expect value to be string, got %T", v)
	}
	return nil
}

func getTokenFieldRFC3339(v interface{}, value **rfc3339) error {
	var stringValue string
	if err := getTokenFieldString(v, &stringValue); err != nil {
		return err
	}

	timeValue, err := parseRFC3339(stringValue)
	if err != nil {
		return err
	}

	*value = &timeValue
	return nil
}

func loadCachedToken(filename string) (token, error) {
	fileBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return token{}, fmt.Errorf("failed to read cached SSO token file, %w", err)
	}

	var t token
	if err := json.Unmarshal(fileBytes, &t); err != nil {
		return token{}, fmt.Errorf("failed to parse cached SSO token file, %w", err)
	}

	if len(t.AccessToken) == 0 || t.ExpiresAt == nil || time.Time(*t.ExpiresAt).IsZero() {
		return token{}, fmt.Errorf(
			"cached SSO token must contain accessToken and expiresAt fields")
	}

	return t, nil
}

func storeCachedToken(filename string, t token, fileMode os.FileMode) (err error) {
	tmpFilename := filename + ".tmp-" + strconv.FormatInt(sdk.NowTime().UnixNano(), 10)
	if err := writeCacheFile(tmpFilename, fileMode, t); err != nil {
		return err
	}

	if err := os.Rename(tmpFilename, filename); err != nil {
		return fmt.Errorf("failed to replace old cached SSO token file, %w", err)
	}

	return nil
}

func writeCacheFile(filename string, fileMode os.FileMode, t token) (err error) {
	var f *os.File
	f, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, fileMode)
	if err != nil {
		return fmt.Errorf("failed to create cached SSO token file %w", err)
	}

	defer func() {
		closeErr := f.Close()
		if err == nil && closeErr != nil {
			err = fmt.Errorf("failed to close cached SSO token file, %w", closeErr)
		}
	}()

	encoder := json.NewEncoder(f)

	if err = encoder.Encode(t); err != nil {
		return fmt.Errorf("failed to serialize cached SSO token, %w", err)
	}

	return nil
}

type rfc3339 time.Time

func parseRFC3339(v string) (rfc3339, error) {
	parsed, err := time.Parse(time.RFC3339, v)
	if err != nil {
		return rfc3339{}, fmt.Errorf("expected RFC3339 timestamp: %w", err)
	}

	return rfc3339(parsed), nil
}

func (r *rfc3339) UnmarshalJSON(bytes []byte) (err error) {
	var value string

	// Use JSON unmarshal to unescape the quoted value making use of JSON's
	// unquoting rules.
	if err = json.Unmarshal(bytes, &value); err != nil {
		return err
	}

	*r, err = parseRFC3339(value)

	return nil
}

func (r *rfc3339) MarshalJSON() ([]byte, error) {
	value := time.Time(*r).Format(time.RFC3339)

	// Use JSON unmarshal to unescape the quoted value making use of JSON's
	// quoting rules.
	return json.Marshal(value)
}