-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSetupAwsCredentials.scala
343 lines (302 loc) · 11.2 KB
/
SetupAwsCredentials.scala
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package org.encalmo.aws
import org.encalmo.utils.CommandLineUtils.*
import os.Path
import upickle.default.ReadWriter
import upickle.default.read
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import scala.io.AnsiColor.*
import scala.util.Try
object SetupAwsCredentials {
def main(args: Array[String]): Unit = {
val profile: String = requiredScriptParameter('p', "profile")(args)
val accountIdArg: Option[String] = optionalScriptParameter('a', "account")(args)
val roleNameArg: Option[String] = optionalScriptParameter('r', "role")(args)
val force: Boolean = optionalScriptFlag('f', "force")(args)
val verbose: Boolean = optionalScriptFlag('v', "verbose")(args)
val credentials = apply(profile, accountIdArg, roleNameArg, force, verbose)
credentials.fold(
error =>
System.err.println(error)
System.exit(2)
,
credentials =>
println(
s"""|export AWS_ACCESS_KEY_ID=${credentials.accessKeyId}
|export AWS_SECRET_ACCESS_KEY=${credentials.secretAccessKey}
|export AWS_SESSION_TOKEN=${credentials.sessionToken}
|export AWS_PROFILE=${credentials.profile}
|export AWS_DEFAULT_REGION=${credentials.defaultRegion}
|export AWS_REGION=${credentials.defaultRegion}
""".stripMargin
)
)
}
lazy val awsConfigFile: Path =
os.Path(System.getProperty("user.home")) / ".aws" / "config"
lazy val awsSsoCacheFolder: Path =
os.Path(System.getProperty("user.home")) / ".aws" / "sso" / "cache"
def apply(
profile: String,
accountIdArg: Option[String] = None,
roleNameArg: Option[String] = None,
force: Boolean = false,
verbose: Boolean = false
): Either[String, Credentials] = {
val credentialsCacheFile = awsSsoCacheFolder / s"credentials-$profile.json"
val existingCredentials: Option[Credentials] =
if !force && (os.exists(credentialsCacheFile) && os.isFile(credentialsCacheFile))
then Some(read[Credentials](os.read(credentialsCacheFile)))
else None
if (!os.exists(awsConfigFile))
then
Left(
s"${RED}File ${YELLOW}$awsConfigFile${RESET}${RED} does not exist ${YELLOW}${BOLD}$profile${RESET}"
)
else {
val awsConfigOpt: Option[AwsConfig] = readAwsConfig(awsConfigFile, verbose)
val defaultRegion: String = awsConfigOpt
.flatMap(_.getProfileProperty(profile, "region"))
.getOrElse("us-east-1")
if (!awsConfigOpt.exists(_.getProfile(profile).isDefined))
then
Left(
s"${RED}File ${YELLOW}$awsConfigFile${RESET}${RED} does not know about profile ${YELLOW}${BOLD}$profile${RESET}"
)
else {
val loginProfile = awsConfigOpt
.flatMap(_.getSourceProfileOf(profile, "sso_start_url"))
.getOrElse(profile)
for {
accountId <- accountIdArg
.orElse {
awsConfigOpt.flatMap(_.getProfileProperty(profile, "sso_account_id"))
}
.toRight {
s"${RED}${BOLD}Missing accountId parameter${RESET}.\n${RED}Tried to find ${YELLOW}sso_account_id${RESET}${RED} property in the ~/.aws/config profile ${YELLOW}$profile${RESET}${RED} but found none.${RESET}"
}
roleName <- roleNameArg
.orElse {
awsConfigOpt.flatMap(_.getProfileProperty(profile, "sso_role_name"))
}
.toRight {
s"${RED}${BOLD}Missing accountId parameter${RESET}.\n${RED}Tried to find ${YELLOW}sso_role_name${RESET}${RED} property in the ~/.aws/config profile ${YELLOW}$profile${RESET}${RED} but found none.${RESET}"
}
effectiveCredentials <- existingCredentials match {
case Some(credentials) if (credentials.expiration > (System.currentTimeMillis() - 5000L)) =>
if (credentials.accountId == accountId && credentials.roleName == roleName)
then Right(credentials)
else computeNewCredentials(accountId, roleName, profile, loginProfile, defaultRegion, verbose)
case _ =>
computeNewCredentials(accountId, roleName, profile, loginProfile, defaultRegion, verbose)
}
} yield effectiveCredentials
}
}
}
def computeNewCredentials(
accountId: String,
roleName: String,
profile: String,
loginProfile: String,
defaultRegion: String,
verbose: Boolean
): Either[String, Credentials] = {
val credentials =
getAwsCredentials(accountId, roleName, profile, loginProfile, verbose)
.map(c =>
Credentials(
accessKeyId = c.roleCredentials.accessKeyId,
secretAccessKey = c.roleCredentials.secretAccessKey,
sessionToken = c.roleCredentials.sessionToken,
expiration = c.roleCredentials.expiration,
accountId = accountId,
roleName = roleName,
profile = profile,
defaultRegion = defaultRegion
)
)
// save new credentials in a file
credentials.map(c =>
os.write.over(
awsSsoCacheFolder / s"credentials-$profile.json",
upickle.default.write(c),
perms = os.PermSet.fromString("rw-------")
)
)
credentials
}
def getAwsCredentials(
accountId: String,
roleName: String,
profile: String,
loginProfile: String,
verbose: Boolean
): Either[String, AwsCredentials] = {
if (verbose) then println(s"Log in using profile $loginProfile")
os
.list(awsSsoCacheFolder)
.map(path =>
try (Some(upickle.default.read[AwsSsoConfig](os.read(path))))
catch { case e => None }
)
.collect { case Some(x) => x }
.sortBy(_.timestamp)
.foldLeft[Either[String, AwsCredentials]](Left("None AWS SSO credentials file found")) { case (result, config) =>
result.orElse {
if config.timestamp.isAfter(ZonedDateTime.now())
then {
val result = os
.proc(
"aws",
"sso",
"get-role-credentials",
"--role-name",
roleName,
"--account-id",
accountId,
"--access-token",
config.accessToken,
"--profile",
loginProfile
)
.call(os.pwd, check = false, stdout = os.Pipe, stderr = os.Pipe, mergeErrIntoOut = true)
if (result.exitCode == 0)
then
if (verbose) then System.out.println(s"${WHITE}${result.out.text()}${RESET}")
Try(read[AwsCredentials](result.out.text())).toEither.left.map(_.toString())
else Left(result.err.text())
} else result
}
}
.orElse {
loginUsingAwsSso(loginProfile, verbose)
.flatMap(_ => getAwsCredentials(accountId, roleName, profile, loginProfile, verbose))
}
}
def loginUsingAwsSso(profile: String, verbose: Boolean): Either[String, Unit] = {
val result = os
.proc(
"aws",
"sso",
"login",
"--profile",
profile
)
.call(
os.pwd,
check = false
)
if (result.exitCode == 0)
then {
if (verbose) then System.out.println(s"${WHITE}${result.out.text()}${RESET}")
Right(())
} else
System.err.println(s"${RED}${result.err.text()}${RESET}")
Left(result.err.text())
}
def readAwsConfig(awsConfigFile: os.Path, verbose: Boolean): Option[AwsConfig] = {
val profileHeaderRegex = "\\[\\s*profile (.+)\\s*\\]".r
val propertyRegex = "(.+)=(.+)".r
if (os.exists(awsConfigFile) && os.isFile(awsConfigFile))
then {
val awsConfig =
os.read(awsConfigFile)
.linesIterator
.foldLeft(new AwsConfig(verbose)) { case (config, line) =>
line.trim() match {
case profileHeaderRegex(profileName) => config.startProfile(profileName.trim())
case propertyRegex(key, value) => config.addProperty(key.trim(), value.trim())
case _ => config
}
}
if (verbose) println(s"${GREEN}AWS config file read successfully.${RESET}")
Some(awsConfig)
} else None
}
case class AwsSsoConfig(accessToken: String, expiresAt: String) derives ReadWriter {
val timestamp =
ZonedDateTime.parse(expiresAt, DateTimeFormatter.ISO_DATE_TIME)
}
case class Credentials(
accessKeyId: String,
secretAccessKey: String,
sessionToken: String,
expiration: Long,
accountId: String,
roleName: String,
profile: String,
defaultRegion: String
) derives ReadWriter {
def toEnvironmentVariables: Map[String, String] =
Map(
"AWS_ACCESS_KEY_ID" -> accessKeyId,
"AWS_SECRET_ACCESS_KEY" -> secretAccessKey,
"AWS_SESSION_TOKEN" -> sessionToken,
"AWS_PROFILE" -> profile,
"AWS_DEFAULT_REGION" -> defaultRegion,
"AWS_REGION" -> defaultRegion
)
}
case class RoleCredentials(
accessKeyId: String,
secretAccessKey: String,
sessionToken: String,
expiration: Long
) derives ReadWriter
case class AwsCredentials(roleCredentials: RoleCredentials) derives ReadWriter
class AwsConfig(verbose: Boolean) {
class AwsProfile(val name: String, verbose: Boolean) {
private val properties = collection.mutable.Map.empty[String, String]
def addProperty(key: String, value: String): Unit = {
properties.update(key, value)
if (verbose) println(s"${CYAN}$key${RESET}${BLUE}=${RESET}${WHITE}$value${RESET}")
}
def getProperty(key: String): Option[String] = {
properties.get(key)
}
}
private val profiles = collection.mutable.Map.empty[String, AwsProfile]
private var currentProfile: AwsProfile = new AwsProfile("default", verbose)
profiles.update("default", currentProfile)
def startProfile(name: String): AwsConfig = {
currentProfile = new AwsProfile(name, verbose)
profiles.update(name, currentProfile)
if (verbose) println(s"${GREEN}[profile ${BOLD}$name${RESET}${GREEN}]${RESET}")
this
}
def addProperty(key: String, value: String): AwsConfig = {
currentProfile.addProperty(key, value)
this
}
def getProfile(profileName: String): Option[AwsProfile] =
profiles.get(profileName)
def getProfileProperty(profileName: String, key: String): Option[String] =
profiles
.get(profileName)
.flatMap(profileConfig =>
profileConfig.getProperty(key).orElse {
profileConfig
.getProperty("source_profile")
.flatMap { sourceProfileName =>
getProfileProperty(sourceProfileName, key)
}
}
)
def getSourceProfileOf(profileName: String, key: String): Option[String] =
profiles
.get(profileName)
.flatMap(profileConfig =>
profileConfig
.getProperty(key)
.map(_ => profileName)
.orElse {
profileConfig
.getProperty("source_profile")
.flatMap { sourceProfileName =>
getSourceProfileOf(sourceProfileName, key)
}
}
)
}
}