-
Notifications
You must be signed in to change notification settings - Fork 862
/
AssumeRoleWithWebIdentityCredentials.cs
241 lines (216 loc) · 11.5 KB
/
AssumeRoleWithWebIdentityCredentials.cs
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
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Util;
using Amazon.Runtime.SharedInterfaces;
using Amazon.Util;
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
#if AWS_ASYNC_API
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime
{
/// <summary>
/// AWS Credentials that automatically refresh by calling AssumeRole on
/// the Amazon Security Token Service.
/// </summary>
public class AssumeRoleWithWebIdentityCredentials : RefreshingAWSCredentials
{
private const int PREEMPT_EXPIRY_MINUTES = 5;
private static readonly RegionEndpoint _defaultSTSClientRegion = RegionEndpoint.USEast1;
private static readonly string _roleSessionNameDefault = Guid.NewGuid().ToString();
/// <summary>
/// As established by STS, the regex used to validate the role session names is a string of 2-64 characters consisting of
/// upper- and lower-case alphanumeric characters with no spaces. You can also include
/// underscores or any of the following characters: =,.@-
/// </summary>
public const string WebIdentityTokenFileEnvVariable = "AWS_WEB_IDENTITY_TOKEN_FILE";
public const string RoleArnEnvVariable = "AWS_ROLE_ARN";
public const string RoleSessionNameEnvVariable = "AWS_ROLE_SESSION_NAME";
private static readonly Regex _roleSessionNameRegex = new Regex(@"^[\w+=,.@-]{2,64}$", RegexOptions.Compiled);
private readonly Logger _logger = Logger.GetLogger(typeof(AssumeRoleWithWebIdentityCredentials));
/// <summary>
/// Options to be used in the call to AssumeRole.
/// </summary>
private AssumeRoleWithWebIdentityCredentialsOptions _options;
#region Properties
/// <summary>
/// The absolute path to the file on disk containing an OIDC token
/// </summary>
public string WebIdentityTokenFile { get; }
/// <summary>
/// The Amazon Resource Name (ARN) of the role to assume.
/// </summary>
public string RoleArn { get; }
/// <summary>
/// An identifier for the assumed role session.
/// </summary>
public string RoleSessionName { get; }
#endregion Properties
/// <summary>
/// Constructs an AssumeRoleWithWebIdentityCredentials object.
/// </summary>
/// <param name="webIdentityTokenFile">The absolute path to the file on disk containing an OIDC token.</param>
/// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param>
/// <param name="roleSessionName">An identifier for the assumed role session.</param>
public AssumeRoleWithWebIdentityCredentials(string webIdentityTokenFile, string roleArn, string roleSessionName)
: this(webIdentityTokenFile, roleArn, roleSessionName, new AssumeRoleWithWebIdentityCredentialsOptions()) { }
/// <summary>
/// Constructs an AssumeRoleWithWebIdentityCredentials object.
/// </summary>
/// <param name="webIdentityTokenFile">The absolute path to the file on disk containing an OIDC token.</param>
/// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param>
/// <param name="roleSessionName">An identifier for the assumed role session.</param>
/// <param name="options">Options to be used in the call to AssumeRole.</param>
public AssumeRoleWithWebIdentityCredentials(string webIdentityTokenFile, string roleArn, string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options)
{
if (string.IsNullOrEmpty(webIdentityTokenFile))
{
throw new ArgumentNullException(nameof(webIdentityTokenFile), $"The {nameof(webIdentityTokenFile)} must be an absolute path.");
}
else if (!AWSSDKUtils.IsAbsolutePath(webIdentityTokenFile))
{
throw new ArgumentException($"The {nameof(webIdentityTokenFile)} must be an absolute path.", nameof(webIdentityTokenFile));
}
if (string.IsNullOrEmpty(roleArn))
{
throw new ArgumentNullException(nameof(roleArn), "The role ARN must be specified.");
}
if (!string.IsNullOrEmpty(roleSessionName) && !_roleSessionNameRegex.IsMatch(roleSessionName))
{
throw new ArgumentOutOfRangeException(nameof(roleSessionName), roleSessionName, $"The value must match the regex pattern @\"{_roleSessionNameRegex}\".");
}
WebIdentityTokenFile = webIdentityTokenFile;
RoleArn = roleArn;
RoleSessionName = string.IsNullOrEmpty(roleSessionName) ? _roleSessionNameDefault : roleSessionName;
_options = options;
// Make sure to fetch new credentials well before the current credentials expire to avoid
// any request being made with expired credentials.
PreemptExpiryTime = TimeSpan.FromMinutes(PREEMPT_EXPIRY_MINUTES);
}
/// <summary>
/// Creates an instance of <see cref="AssumeRoleWithWebIdentityCredentials"/> from environment variables.
/// </summary>
/// <exception>Throws an <see cref="InvalidOperationException"/> if the needed environment variables are not set.</exception>
/// <returns>The new credentials.</returns>
public static AssumeRoleWithWebIdentityCredentials FromEnvironmentVariables()
{
var webIdentityTokenFile = Environment.GetEnvironmentVariable(WebIdentityTokenFileEnvVariable);
var roleArn = Environment.GetEnvironmentVariable(RoleArnEnvVariable);
var roleSessionName = Environment.GetEnvironmentVariable(RoleSessionNameEnvVariable);
return new AssumeRoleWithWebIdentityCredentials(webIdentityTokenFile, roleArn, roleSessionName);
}
protected override CredentialsRefreshState GenerateNewCredentials()
{
string token = null;
for (var retry = 0; retry <= AWSSDKUtils.DefaultMaxRetry; retry++)
{
try
{
using (var fileStream = new FileStream(WebIdentityTokenFile, FileMode.Open, FileAccess.Read)) // Using FileStream to support NetStandard 1.3
{
using (var streamReader = new StreamReader(fileStream))
{
token = streamReader.ReadToEnd();
}
}
break;
}
catch (Exception e)
{
if (retry == AWSSDKUtils.DefaultMaxRetry)
{
_logger.Debug(e, $"A token could not be loaded from the WebIdentityTokenFile at {WebIdentityTokenFile}.");
throw new InvalidOperationException("A token could not be loaded from the WebIdentityTokenFile.", e);
}
DefaultRetryPolicy.WaitBeforeRetry(retry, 1000);
}
}
AssumeRoleImmutableCredentials credentials;
using (var coreStsClient = CreateClient())
{
credentials = coreStsClient.CredentialsFromAssumeRoleWithWebIdentityAuthentication(token, RoleArn, RoleSessionName, _options); // Will retry InvalidIdentityToken and IDPCommunicationError
}
_logger.InfoFormat("New credentials created using assume role with web identity that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
return new CredentialsRefreshState(credentials, credentials.Expiration);
}
#if AWS_ASYNC_API
protected override async Task<CredentialsRefreshState> GenerateNewCredentialsAsync()
{
string token = null;
for (var retry = 0; retry <= AWSSDKUtils.DefaultMaxRetry; retry++)
{
try
{
using (var fileStream = new FileStream(WebIdentityTokenFile, FileMode.Open, FileAccess.Read)) // Using FileStream to support NetStandard 1.3
{
using (var streamReader = new StreamReader(fileStream))
{
token = await streamReader.ReadToEndAsync().ConfigureAwait(false);
}
}
break;
}
catch (Exception e)
{
if (retry == AWSSDKUtils.DefaultMaxRetry)
{
_logger.Debug(e, $"A token could not be loaded from the WebIdentityTokenFile at {WebIdentityTokenFile}.");
throw new InvalidOperationException("A token could not be loaded from the WebIdentityTokenFile.", e);
}
DefaultRetryPolicy.WaitBeforeRetry(retry, 1000);
}
}
AssumeRoleImmutableCredentials credentials;
using (var coreStsClient = CreateClient())
{
credentials = await coreStsClient.CredentialsFromAssumeRoleWithWebIdentityAuthenticationAsync(token, RoleArn, RoleSessionName, _options).ConfigureAwait(false); // Will retry InvalidIdentityToken and IDPCommunicationError
}
_logger.InfoFormat("New credentials created using assume role with web identity that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
return new CredentialsRefreshState(credentials, credentials.Expiration);
}
#endif
/// <summary>
/// Gets a client to be used for AssumeRoleWithWebIdentity requests.
/// </summary>
/// <returns>The STS client.</returns>
protected virtual ICoreAmazonSTS_WebIdentity CreateClient()
{
var region = FallbackRegionFactory.GetRegionEndpoint() ?? _defaultSTSClientRegion;
try
{
var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);
stsConfig.RegionEndpoint = region;
if (_options?.ProxySettings != null)
{
stsConfig.SetWebProxy(_options.ProxySettings);
}
return ServiceClientHelpers.CreateServiceFromAssembly<ICoreAmazonSTS_WebIdentity>(
ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, new AnonymousAWSCredentials(), region);
}
catch (Exception e)
{
var msg = string.Format(CultureInfo.CurrentCulture,
"Assembly {0} could not be found or loaded. This assembly must be available at runtime to use Amazon.Runtime.AssumeRoleAWSCredentials.",
ServiceClientHelpers.STS_ASSEMBLY_NAME);
throw new InvalidOperationException(msg, e);
}
}
}
}