-
Notifications
You must be signed in to change notification settings - Fork 863
/
Copy pathAssumeRoleAWSCredentials.cs
140 lines (121 loc) · 6.66 KB
/
AssumeRoleAWSCredentials.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
/*
* 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.RuntimeDependencies;
using Amazon.Util.Internal;
using System;
using System.Globalization;
using System.Net;
namespace Amazon.Runtime
{
/// <summary>
/// AWS Credentials that automatically refresh by calling AssumeRole on
/// the Amazon Security Token Service.
/// </summary>
public class AssumeRoleAWSCredentials : RefreshingAWSCredentials
{
private RegionEndpoint DefaultSTSClientRegion = RegionEndpoint.USEast1;
private Logger _logger = Logger.GetLogger(typeof(AssumeRoleAWSCredentials));
/// <summary>
/// The credentials of the user that will be used to call AssumeRole.
/// </summary>
public AWSCredentials SourceCredentials { get; private set; }
/// <summary>
/// The Amazon Resource Name (ARN) of the role to assume.
/// </summary>
public string RoleArn { get; private set; }
/// <summary>
/// An identifier for the assumed role session.
/// </summary>
public string RoleSessionName { get; private set; }
/// <summary>
/// Options to be used in the call to AssumeRole.
/// </summary>
public AssumeRoleAWSCredentialsOptions Options { get; private set; }
/// <summary>
/// Constructs an AssumeRoleAWSCredentials object.
/// </summary>
/// <param name="sourceCredentials">The credentials of the user that will be used to call AssumeRole.</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 AssumeRoleAWSCredentials(AWSCredentials sourceCredentials, string roleArn, string roleSessionName)
: this(sourceCredentials, roleArn, roleSessionName, new AssumeRoleAWSCredentialsOptions())
{
}
/// <summary>
/// Constructs an AssumeRoleAWSCredentials object.
/// </summary>
/// <param name="sourceCredentials">The credentials of the user that will be used to call AssumeRole.</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 AssumeRoleAWSCredentials(AWSCredentials sourceCredentials, string roleArn, string roleSessionName, AssumeRoleAWSCredentialsOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
SourceCredentials = sourceCredentials;
RoleArn = roleArn;
RoleSessionName = 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(15);
}
#if NET8_0_OR_GREATER
[System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026",
Justification = "Reflection code is only used as a fallback in case the SDK was not trimmed. Trimmed scenarios should register dependencies with Amazon.RuntimeDependencyRegistry.GlobalRuntimeDependencyRegistry")]
#endif
protected override CredentialsRefreshState GenerateNewCredentials()
{
var region = FallbackRegionFactory.GetRegionEndpoint() ?? DefaultSTSClientRegion;
ICoreAmazonSTS coreSTSClient = GlobalRuntimeDependencyRegistry.Instance.GetInstance<ICoreAmazonSTS>(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME,
new CreateInstanceContext(new SecurityTokenServiceClientContext {Action = SecurityTokenServiceClientContext.ActionContext.AssumeRoleAWSCredentials, Region = region, ProxySettings = Options?.ProxySettings } ));
if (coreSTSClient == null)
{
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);
}
coreSTSClient = ServiceClientHelpers.CreateServiceFromAssembly<ICoreAmazonSTS>(
ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, SourceCredentials, stsConfig);
}
catch (Exception e)
{
if (InternalSDKUtils.IsRunningNativeAot())
{
throw new MissingRuntimeDependencyException(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, nameof(GlobalRuntimeDependencyRegistry.RegisterSecurityTokenServiceClient));
}
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);
var exception = new InvalidOperationException(msg, e);
Logger.GetLogger(typeof(AssumeRoleAWSCredentials)).Error(exception, exception.Message);
throw exception;
}
}
var credentials = coreSTSClient.CredentialsFromAssumeRoleAuthentication(RoleArn, RoleSessionName, Options);
_logger.InfoFormat("New credentials created for assume role that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
return new CredentialsRefreshState(credentials, credentials.Expiration);
}
}
}