-
Notifications
You must be signed in to change notification settings - Fork 862
/
AmazonS3Config.cs
439 lines (391 loc) · 17.8 KB
/
AmazonS3Config.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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
* 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;
using System;
using System.Globalization;
using Amazon.Internal;
using Amazon.Runtime.CredentialManagement;
using Amazon.Runtime.Internal;
namespace Amazon.S3
{
/// <summary>
/// Configuration for accessing AmazonS3 service
/// </summary>
public partial class AmazonS3Config : ClientConfig
{
private const string UseArnRegionEnvName = "AWS_S3_USE_ARN_REGION";
private const string DisableS3ExpressSessionAuthEnvName = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH";
private const string AccelerateEndpointSuffix = "s3-accelerate.amazonaws.com";
private const string AccelerateDualstackEndpointSuffix = "s3-accelerate.dualstack.amazonaws.com";
private const string AwsProfileEnvironmentVariable = "AWS_PROFILE";
private const string DefaultProfileName = "default";
private const string AwsS3UsEast1RegionalEndpointsEnvironmentVariable = "AWS_S3_US_EAST_1_REGIONAL_ENDPOINT";
private const string DisableMRAPEnvName = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS";
private bool forcePathStyle = false;
private bool useAccelerateEndpoint = false;
private S3UsEast1RegionalEndpointValue? s3UsEast1RegionalEndpointValue;
private readonly string legacyUSEast1GlobalRegionSystemName = RegionEndpoint.USEast1.SystemName;
private static CredentialProfileStoreChain credentialProfileChain = new CredentialProfileStoreChain();
// we cache this per execution process to avoid excessive file I/O
private static CredentialProfile _profile;
private static object _triedToResolveProfileLock = new object();
private static bool _triedToResolveProfile = false;
private IS3ExpressCredentialProvider s3ExpressCredentialProvider;
/// <summary>
/// Gets and sets S3Express credential provider property.
/// This property is used to provide credentials for requests that uses S3Express authentication.
/// During client initialization it is set to default S3Express credential provider,
/// but can be changed to use custom user supplied S3Express credential provider.
/// </summary>
public IS3ExpressCredentialProvider S3ExpressCredentialProvider
{
get { return s3ExpressCredentialProvider; }
set { s3ExpressCredentialProvider = value; }
}
/// <summary>
/// When true, requests will always use path style addressing.
/// </summary>
public bool ForcePathStyle
{
get { return forcePathStyle; }
set { forcePathStyle = value; }
}
/// <summary>
/// Enables S3 accelerate by sending requests to the accelerate endpoint instead of the regular region endpoint.
/// To use this feature, the bucket name should be DNS compliant names and should not contain periods (.).
/// The following APIs are not supported and are sent to the regular region endpoint, even if this option is enabled:
/// <ol>
/// <li>PutBucket</li>
/// <li>ListBuckets</li>
/// <li>DeleteBucket</li>
/// </ol>
/// </summary>
/// <remarks>
/// This option cannot be used at the same time as UseDualstackEndpoint.
/// </remarks>
public bool UseAccelerateEndpoint
{
get { return useAccelerateEndpoint; }
set { useAccelerateEndpoint = value; }
}
bool? _useArnRegion;
private object _useArnRegionLock = new object();
/// <summary>
/// If set to true and the service package supports it the region identified in the arn for a resource
/// will be used when making the service request.
/// </summary>
public bool UseArnRegion
{
get
{
if (_useArnRegion.HasValue)
{
return _useArnRegion.GetValueOrDefault();
}
ResolveCredentialProfile();
lock (_useArnRegionLock)
{
if (_useArnRegion.HasValue)
{
return _useArnRegion.Value;
}
_useArnRegion = _profile?.S3UseArnRegion;
if (!_useArnRegion.HasValue && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(UseArnRegionEnvName)))
{
if (bool.TryParse(Environment.GetEnvironmentVariable(UseArnRegionEnvName), out var value))
{
_useArnRegion = value;
}
}
if (!_useArnRegion.HasValue)
{
// To maintain consistency with buckets default UseArnRegion to true when client configured for us-east-1.
_useArnRegion = RegionEndpoint?.SystemName == RegionEndpoint.USEast1.SystemName;
}
return _useArnRegion.Value;
}
}
set
{
lock (_useArnRegionLock)
{
_useArnRegion = value;
}
}
}
bool? _disableS3ExpressSessionAuth;
private object _disableS3ExpressSessionAuthLock = new object();
/// <summary>
/// If set to true the use of S3Express auth disabled.
/// </summary>
public bool DisableS3ExpressSessionAuth
{
get
{
if (_disableS3ExpressSessionAuth.HasValue)
{
return _disableS3ExpressSessionAuth.GetValueOrDefault();
}
ResolveCredentialProfile();
lock (_disableS3ExpressSessionAuthLock)
{
if (_disableS3ExpressSessionAuth.HasValue)
{
return _disableS3ExpressSessionAuth.Value;
}
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DisableS3ExpressSessionAuthEnvName)))
{
if (bool.TryParse(Environment.GetEnvironmentVariable(DisableS3ExpressSessionAuthEnvName), out var value))
{
_disableS3ExpressSessionAuth = value;
return _disableS3ExpressSessionAuth.Value;
}
}
_disableS3ExpressSessionAuth = _profile?.S3DisableExpressSessionAuth;
return _disableS3ExpressSessionAuth.GetValueOrDefault();
}
}
set
{
lock (_disableS3ExpressSessionAuthLock)
{
_disableS3ExpressSessionAuth = value;
}
}
}
private static void ResolveCredentialProfile()
{
if (!_triedToResolveProfile)
{
lock (_triedToResolveProfileLock)
{
if (!_triedToResolveProfile)
{
var profileName = Environment.GetEnvironmentVariable(AwsProfileEnvironmentVariable) ?? DefaultProfileName;
credentialProfileChain.TryGetProfile(profileName, out _profile);
_triedToResolveProfile = true;
}
}
}
}
bool? _disableMultiregionAccessPoints;
/// <summary>
/// If set to true, prevents calls to multi-region access points.
/// If not explicitly set here it will fallback first to the value of
/// AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS environment variable, then to
/// s3_disable_multiregion_access_points in the shared configuration file.
/// Once a valid value is found in the environment variable or configuration file
/// it will be cached for this AmazonS3Config instance.
/// </summary>
public bool DisableMultiregionAccessPoints
{
get
{
if (_disableMultiregionAccessPoints == null)
{
_disableMultiregionAccessPoints = CheckDisableMRAPEnvironmentVariable() ?? CheckDisableMRAPCredentialsFile();
}
return _disableMultiregionAccessPoints.GetValueOrDefault();
}
set { _disableMultiregionAccessPoints = value; }
}
/// <summary>
/// USEast1RegionalEndpointValue determines whether or not
/// to send the us-east-1 s3 requests to the regional endpoint or to
/// the legacy global endpoint.
/// This flags takes precedence over the AWS_S3_US_EAST_1_REGIONAL_ENDPOINT
/// environment variable and the credential file.
/// </summary>
public S3UsEast1RegionalEndpointValue? USEast1RegionalEndpointValue
{
get
{
if (s3UsEast1RegionalEndpointValue == null)
{
s3UsEast1RegionalEndpointValue =
CheckS3EnvironmentVariable() ??
CheckCredentialsFile() ??
DefaultConfiguration.S3UsEast1RegionalEndpoint;
}
return s3UsEast1RegionalEndpointValue;
}
set { s3UsEast1RegionalEndpointValue = value; }
}
/// <summary>
/// This method contains custom initializations for the config object.
/// </summary>
protected override void Initialize()
{
this.AllowAutoRedirect = false;
#if BCL45 || NETSTANDARD
// Set Timeout and ReadWriteTimeout for S3 to max timeout as per-request
// timeouts are not supported.
this.Timeout = ClientConfig.MaxTimeout;
#pragma warning disable CS0612,CS0618
this.ReadWriteTimeout = ClientConfig.MaxTimeout;
#pragma warning restore CS0612, CS0618
#endif
}
/// <summary>
/// Given this client configuration, returns the service url
/// </summary>
/// <returns>The service url in the form of a string</returns>
[Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")]
public override string DetermineServiceURL()
{
if (this.ServiceURL != null)
{
return this.ServiceURL;
}
var actual = this.RegionEndpoint;
if (actual?.SystemName == legacyUSEast1GlobalRegionSystemName && !UseAccelerateEndpoint && !UseDualstackEndpoint
&& USEast1RegionalEndpointValue == S3UsEast1RegionalEndpointValue.Regional)
{
actual = RegionEndpoint.GetBySystemName("us-east-1-regional");
}
return GetUrl(this, actual);
}
/// <summary>
/// If the client is configured to hit us-east-1 with the S3UsEast1RegionalEndpointValue flag not set,
/// this method checks whether the environment variable is present or the credential file contains a valid value
/// </summary>
/// <returns>A Nullable of S3UsEast1RegionalEndpointValue representing the client configuration for the regional us-east-1 endpoint</returns>
private S3UsEast1RegionalEndpointValue? GetEndpointFlagValueForUsEast1Regional()
{
if (this.USEast1RegionalEndpointValue.HasValue)
{
return this.USEast1RegionalEndpointValue;
}
else
{
// Environment variable takes precedence over the credential file
return CheckS3EnvironmentVariable() ?? CheckCredentialsFile();
}
}
internal static string GetUrl(IClientConfig config, RegionEndpoint regionEndpoint)
{
var endpoint = regionEndpoint.GetEndpointForService(config);
string url = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", config.UseHttp ? "http://" : "https://", endpoint.Hostname)).AbsoluteUri;
return url;
}
/// <summary>
/// Validate that the config object is properly configured.
/// </summary>
public override void Validate()
{
base.Validate();
if (this.ForcePathStyle && this.UseAccelerateEndpoint)
{
throw new AmazonClientException(
@"S3 accelerate is not compatible with Path style requests. Disable Path style requests" +
" using AmazonS3Config.ForcePathStyle property to use S3 accelerate.");
}
var isExplicitAccelerateEndpoint = !string.IsNullOrEmpty(this.ServiceURL) &&
(this.ServiceURL.IndexOf(AccelerateEndpointSuffix, StringComparison.OrdinalIgnoreCase) >= 0 ||
this.ServiceURL.IndexOf(AccelerateDualstackEndpointSuffix, StringComparison.OrdinalIgnoreCase) >= 0);
if (isExplicitAccelerateEndpoint)
{
if (this.RegionEndpoint == null && string.IsNullOrEmpty(this.AuthenticationRegion))
{
throw new AmazonClientException(
@"Specify a region using AmazonS3Config.RegionEndpoint or AmazonS3Config.AuthenticationRegion" +
" to use S3 accelerate.");
}
else
{
if (this.RegionEndpoint == null && !string.IsNullOrEmpty(this.AuthenticationRegion))
{
this.RegionEndpoint = RegionEndpoint.GetBySystemName(this.AuthenticationRegion);
}
this.UseAccelerateEndpoint = true;
}
}
}
/// <summary>
/// Checks the AWS_S3_US_EAST_1_REGIONAL_ENDPOINT environment variable for the presence of the s3 regional flag
/// </summary>
/// <returns>A nullable of S3UsEast1RegionalEndpointValue</returns>
private static S3UsEast1RegionalEndpointValue? CheckS3EnvironmentVariable()
{
string s3RegionalFlag = Environment.GetEnvironmentVariable(AwsS3UsEast1RegionalEndpointsEnvironmentVariable);
if (!string.IsNullOrEmpty(s3RegionalFlag))
{
#if BCL35
S3UsEast1RegionalEndpointValue? s3RegionalFlagValue = null;
try
{
s3RegionalFlagValue = (S3UsEast1RegionalEndpointValue)Enum.Parse(typeof(S3UsEast1RegionalEndpointValue), s3RegionalFlag, true);
}
catch (Exception)
{
throw new InvalidOperationException("Invalid value for AWS_S3_US_EAST_1_REGIONAL_ENDPOINT environment variable. A string regional/legacy is expected.");
}
#else
if (!Enum.TryParse<S3UsEast1RegionalEndpointValue>(s3RegionalFlag, true, out var s3RegionalFlagValue))
{
throw new InvalidOperationException("Invalid value for AWS_S3_US_EAST_1_REGIONAL_ENDPOINT variable. A string regional/legacy is expected.");
}
#endif
return s3RegionalFlagValue;
}
return null;
}
/// <summary>
/// Checks the credential file for the presence of the s3 regional flag
/// </summary>
/// <returns>A nullable of S3UsEast1RegionalEndpointValue</returns>
private static S3UsEast1RegionalEndpointValue? CheckCredentialsFile()
{
ResolveCredentialProfile();
return _profile?.S3RegionalEndpoint;
}
/// <summary>
/// Validates and returns the value of AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS
/// </summary>
/// <returns>Value of AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS if it is set and valid, else null</returns>
private static bool? CheckDisableMRAPEnvironmentVariable()
{
bool? disableMultiregionAccessPoints = null;
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DisableMRAPEnvName)))
{
if (bool.TryParse(Environment.GetEnvironmentVariable(DisableMRAPEnvName), out var value))
{
disableMultiregionAccessPoints = value;
}
else
{
throw new InvalidOperationException($"Invalid value for {DisableMRAPEnvName} environment variable. true/false is expected.");
}
}
return disableMultiregionAccessPoints;
}
/// <summary>
/// Returns the value of s3_disable_multiregion_access_points for the current profile
/// </summary>
/// <returns>Value of s3_disable_multiregion_access_points if it is set, else null</returns>
private static bool? CheckDisableMRAPCredentialsFile()
{
ResolveCredentialProfile();
return _profile?.S3DisableMultiRegionAccessPoints;
}
internal string AccelerateEndpoint
{
get
{
return this.UseDualstackEndpoint ? AccelerateDualstackEndpointSuffix : AccelerateEndpointSuffix;
}
}
}
}