diff --git a/sdk/src/Core/AWSConfigs.cs b/sdk/src/Core/AWSConfigs.cs index 882dc2a7c944..181536123028 100644 --- a/sdk/src/Core/AWSConfigs.cs +++ b/sdk/src/Core/AWSConfigs.cs @@ -80,9 +80,6 @@ public static partial class AWSConfigs // Deprecated configs internal static string _awsRegion = GetConfig(AWSRegionKey); - internal static LoggingOptions _logging = GetLoggingSetting(); - internal static ResponseLoggingOption _responseLogging = GetConfigEnum(ResponseLoggingKey); - internal static bool _logMetrics = GetConfigBool(LogMetricsKey); internal static string _awsProfileName = GetConfig(AWSProfileNameKey); internal static string _awsAccountsLocation = GetConfig(AWSProfilesLocationKey); internal static bool _useSdkCache = GetConfigBool(UseSdkCacheKey, defaultValue: true); @@ -123,9 +120,6 @@ public static TimeSpan? ManualClockCorrection /// by determining the correct server time and reissuing the /// request with the correct time. /// Default value of this field is True. - /// will be updated with the calculated - /// offset even if this field is set to false, though requests - /// will not be corrected or retried. /// Ignored if is set. /// public static bool CorrectForClockSkew @@ -133,23 +127,6 @@ public static bool CorrectForClockSkew get { return _rootConfig.CorrectForClockSkew; } set { _rootConfig.CorrectForClockSkew = value; } } - - /// - /// The calculated clock skew correction, if there is one. - /// This field will be set if a service call resulted in an exception - /// and the SDK has determined that there is a difference between local - /// and server times. - /// - /// If is set to true, this - /// value will be set to the correction, but it will not be used by the - /// SDK and clock skew errors will not be retried. - /// - [Obsolete("This value is deprecated in favor of IClientConfig.ClockOffset, use CorrectClockSkew.GetClockCorrectionForEndpoint(string endpoint) instead.")] - public static TimeSpan ClockOffset - { - get; - internal set; - } #endregion #region Region @@ -215,7 +192,6 @@ public static string AWSProfileName /// /// Key for the AWSProfilesLocation property. - /// /// public const string AWSProfilesLocationKey = "AWSProfilesLocation"; @@ -244,110 +220,6 @@ public static string AWSProfilesLocation #endregion - #region Logging - - /// - /// Key for the Logging property. - /// - /// - public const string LoggingKey = "AWSLogging"; - - /// - /// Configures how the SDK should log events, if at all. - /// Changes to this setting will only take effect in newly-constructed clients. - /// - /// The setting can be configured through App.config, for example: - /// - /// <appSettings> - /// <add key="AWSLogging" value="log4net"/> - /// </appSettings> - /// - /// - [Obsolete("This property is obsolete. Use LoggingConfig.LogTo instead.")] - public static LoggingOptions Logging - { - get { return _rootConfig.Logging.LogTo; } - set { _rootConfig.Logging.LogTo = value; } - } - - private static LoggingOptions GetLoggingSetting() - { - string value = GetConfig(LoggingKey); - if (string.IsNullOrEmpty(value)) - return LoggingOptions.None; - - string[] settings = value.Split(validSeparators, StringSplitOptions.RemoveEmptyEntries); - if (settings == null || settings.Length == 0) - return LoggingOptions.None; - - LoggingOptions totalSetting = LoggingOptions.None; - foreach (string setting in settings) - { - LoggingOptions l = ParseEnum(setting); - totalSetting |= l; - } - return totalSetting; - } - - #endregion - - #region Response Logging - - /// - /// Key for the ResponseLogging property. - /// - /// - /// - public const string ResponseLoggingKey = "AWSResponseLogging"; - - /// - /// Configures when the SDK should log service responses. - /// Changes to this setting will take effect immediately. - /// - /// The setting can be configured through App.config, for example: - /// - /// <appSettings> - /// <add key="AWSResponseLogging" value="OnError"/> - /// </appSettings> - /// - /// - [Obsolete("This property is obsolete. Use LoggingConfig.LogResponses instead.")] - public static ResponseLoggingOption ResponseLogging - { - get { return _rootConfig.Logging.LogResponses; } - set { _rootConfig.Logging.LogResponses = value; } - } - - #endregion - - #region Log Metrics - - /// - /// Key for the LogMetrics property. - /// - /// - public const string LogMetricsKey = "AWSLogMetrics"; - - /// - /// Configures if the SDK should log performance metrics. - /// This setting configures the default LogMetrics property for all clients/configs. - /// Changes to this setting will only take effect in newly-constructed clients. - /// - /// The setting can be configured through App.config, for example: - /// - /// <appSettings> - /// <add key="AWSLogMetrics" value="true"/> - /// </appSettings> - /// - /// - [Obsolete("This property is obsolete. Use LoggingConfig.LogMetrics instead.")] - public static bool LogMetrics - { - get { return _rootConfig.Logging.LogMetrics; } - set { _rootConfig.Logging.LogMetrics = value; } - } - - #endregion #region SDK Cache diff --git a/sdk/src/Core/AWSSDK.Core.NetStandard.csproj b/sdk/src/Core/AWSSDK.Core.NetStandard.csproj index 7c27358a46f1..2b9d68baa3f4 100644 --- a/sdk/src/Core/AWSSDK.Core.NetStandard.csproj +++ b/sdk/src/Core/AWSSDK.Core.NetStandard.csproj @@ -21,8 +21,8 @@ false $(NoWarn);CS1591;CA1822 - true - True + true + True true diff --git a/sdk/src/Core/Amazon.Auth/AccessControlPolicy/ConditionFactory.cs b/sdk/src/Core/Amazon.Auth/AccessControlPolicy/ConditionFactory.cs index 3fc36d9714f4..157d927f864a 100644 --- a/sdk/src/Core/Amazon.Auth/AccessControlPolicy/ConditionFactory.cs +++ b/sdk/src/Core/Amazon.Auth/AccessControlPolicy/ConditionFactory.cs @@ -237,23 +237,6 @@ public static Condition NewCondition(string key, bool value) return new Condition("Bool", key, value.ToString().ToLowerInvariant()); } - /// - /// This method is deprecated. Invoking this method results in non-UTC DateTimes - /// not being marshalled correctly. Use NewConditionUtc instead. - /// Constructs a new access policy condition that compares the current time - /// (on the AWS servers) to the specified date. - /// - /// The type of comparison to perform. For example, - /// DateComparisonType.DateLessThan will cause this policy - /// condition to evaluate to true if the current date is less than - /// the date specified in the second argument. - /// The date to compare against. - [Obsolete("Invoking this method results in non-UTC DateTimes not being marshalled correctly. Use NewConditionUtc instead.", false)] - public static Condition NewCondition(DateComparisonType type, DateTime date) - { - return new Condition(type.ToString(), CURRENT_TIME_CONDITION_KEY, date.ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture)); - } - /// /// Constructs a new access policy condition that compares the current time /// (on the AWS servers) to the specified date. diff --git a/sdk/src/Core/Amazon.Runtime/AmazonServiceClient.cs b/sdk/src/Core/Amazon.Runtime/AmazonServiceClient.cs index 8cd1feafece7..c1952acf446f 100644 --- a/sdk/src/Core/Amazon.Runtime/AmazonServiceClient.cs +++ b/sdk/src/Core/Amazon.Runtime/AmazonServiceClient.cs @@ -195,17 +195,6 @@ protected virtual void Initialize() #region Invoke methods - [Obsolete("Invoke taking marshallers is obsolete. Use Invoke taking InvokeOptionsBase instead.")] - protected TResponse Invoke(TRequest request, - IMarshaller marshaller, ResponseUnmarshaller unmarshaller) - where TRequest : AmazonWebServiceRequest - where TResponse : AmazonWebServiceResponse - { - var options = new InvokeOptions(); - options.RequestMarshaller = marshaller; - options.ResponseUnmarshaller = unmarshaller; - return Invoke(request, options); - } protected TResponse Invoke(AmazonWebServiceRequest request, InvokeOptionsBase options) where TResponse : AmazonWebServiceResponse @@ -232,21 +221,6 @@ protected TResponse Invoke(AmazonWebServiceRequest request, InvokeOpt #if AWS_ASYNC_API - [Obsolete("InvokeAsync taking marshallers is obsolete. Use InvokeAsync taking InvokeOptionsBase instead.")] - protected System.Threading.Tasks.Task InvokeAsync( - TRequest request, - IMarshaller marshaller, - ResponseUnmarshaller unmarshaller, - System.Threading.CancellationToken cancellationToken) - where TRequest: AmazonWebServiceRequest - where TResponse : AmazonWebServiceResponse, new() - { - var options = new InvokeOptions(); - options.RequestMarshaller = marshaller; - options.ResponseUnmarshaller = unmarshaller; - return InvokeAsync(request, options, cancellationToken); - } - protected System.Threading.Tasks.Task InvokeAsync( AmazonWebServiceRequest request, InvokeOptionsBase options, diff --git a/sdk/src/Core/Amazon.Runtime/CapacityManager.cs b/sdk/src/Core/Amazon.Runtime/CapacityManager.cs index dff0a29e9479..db09bb79171b 100644 --- a/sdk/src/Core/Amazon.Runtime/CapacityManager.cs +++ b/sdk/src/Core/Amazon.Runtime/CapacityManager.cs @@ -111,17 +111,7 @@ public bool TryAcquireCapacity(RetryCapacity retryCapacity, CapacityType capacit } } - /// - /// This method calls a method to release capacity back - /// based on whether it was a successful response or a successful retry response. This is invoked by a retry request response. - /// - /// if this request is a retry, use a different capacity cost - /// Contains the RetryCapacity object for the said ServiceURL. - [Obsolete("This method is no longer used in favor of allowing the caller to specify the type of capacity to release.")] - public void TryReleaseCapacity(bool isRetryRequest, RetryCapacity retryCapacity) - { - ReleaseCapacity(isRetryRequest ? CapacityType.Retry : CapacityType.Increment, retryCapacity); - } + /// /// This method calls a method to release capacity back diff --git a/sdk/src/Core/Amazon.Runtime/ClientConfig.cs b/sdk/src/Core/Amazon.Runtime/ClientConfig.cs index d768cdaf4667..4eea36eb633c 100644 --- a/sdk/src/Core/Amazon.Runtime/ClientConfig.cs +++ b/sdk/src/Core/Amazon.Runtime/ClientConfig.cs @@ -65,7 +65,6 @@ public abstract partial class ClientConfig : IClientConfig private string signatureVersion = "4"; private string clientAppId = null; private SigningAlgorithm signatureMethod = SigningAlgorithm.HmacSHA256; - private bool readEntireResponse = false; private bool logResponse = false; private int bufferSize = AWSSDKUtils.DefaultBufferSize; private long progressUpdateInterval = AWSSDKUtils.DefaultProgressUpdateInterval; @@ -387,15 +386,7 @@ public bool UseHttp set { this.useHttp = value; } } - /// - /// Given this client configuration, return a DNS suffix for service endpoint url. - /// - [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, use the service-specific client.DetermineServiceOperationEndPoint method instead.")] - public virtual string DetermineDnsSuffix() - { - var endpoint = regionEndpoint.GetEndpointForService(this); - return endpoint.DnsSuffix; - } + internal static string GetUrl(IClientConfig config, RegionEndpoint regionEndpoint) { @@ -499,19 +490,7 @@ public bool LogResponse set { this.logResponse = value; } } - /// - /// Gets and sets the ReadEntireResponse property. - /// NOTE: This property does not effect response processing and is deprecated. - /// To enable response logging, the ClientConfig.LogResponse and AWSConfigs.LoggingConfig - /// properties can be used. - /// - [Obsolete("This property does not effect response processing and is deprecated." + - "To enable response logging, the ClientConfig.LogResponse and AWSConfigs.LoggingConfig.LogResponses properties can be used.")] - public bool ReadEntireResponse - { - get { return this.readEntireResponse; } - set { this.readEntireResponse = value; } - } + /// /// Gets and Sets the BufferSize property. @@ -949,31 +928,9 @@ public virtual void Validate() #endif } - /// - /// Returns the current UTC now after clock correction for AWSConfigs.ManualClockCorrection. - /// - [Obsolete("Please use CorrectClockSkew.GetCorrectedUtcNowForEndpoint(string endpoint) instead.", false)] - public DateTime CorrectedUtcNow - { - get - { - // Passing null will cause GetCorrectedUtcNowForEndpoint to skip calculating ClockSkew based on - // endpoint and only use ManualClockCorrection if is set. - return CorrectClockSkew.GetCorrectedUtcNowForEndpoint(null); - } - } - /// - /// Wrapper around - /// - [Obsolete("Please use CorrectClockSkew.GetClockCorrectionForEndpoint(string endpoint) instead.", false)] - public TimeSpan ClockOffset - { - get - { - return AWSConfigs.ManualClockCorrection.GetValueOrDefault(); - } - } + + /// /// Gets and sets the DisableHostPrefixInjection flag. If true, host prefix injection will be disabled for this client, the default value of this flag is false. diff --git a/sdk/src/Core/Amazon.Runtime/CorrectClockSkew.cs b/sdk/src/Core/Amazon.Runtime/CorrectClockSkew.cs index c6a6f359ae65..9b780effc1d1 100644 --- a/sdk/src/Core/Amazon.Runtime/CorrectClockSkew.cs +++ b/sdk/src/Core/Amazon.Runtime/CorrectClockSkew.cs @@ -127,9 +127,6 @@ internal static void SetClockCorrectionForEndpoint(string endpoint, TimeSpan cor try { clockCorrectionDictionary[endpoint] = correction; -#pragma warning disable CS0618 // Type or member is obsolete - AWSConfigs.ClockOffset = correction; -#pragma warning restore CS0618 // Type or member is obsolete } finally { diff --git a/sdk/src/Core/Amazon.Runtime/CredentialManagement/SharedCredentialsFile.cs b/sdk/src/Core/Amazon.Runtime/CredentialManagement/SharedCredentialsFile.cs index 5d6b46840f26..449e6d84877a 100644 --- a/sdk/src/Core/Amazon.Runtime/CredentialManagement/SharedCredentialsFile.cs +++ b/sdk/src/Core/Amazon.Runtime/CredentialManagement/SharedCredentialsFile.cs @@ -447,7 +447,7 @@ private void RegisterProfileInternal(CredentialProfile profile) private void UpdateConfigSectionsFromProfile(CredentialProfile profile, Dictionary profileDictionary) { - if (_configFile == null || !_configFile.TryGetSection(profile.Name, out var configProperties)) + if (_configFile == null || !_configFile.TryGetSection(profile.Name, false, false, out var configProperties, out _)) return; var configPropertiesNames = configProperties.Keys.ToArray(); diff --git a/sdk/src/Core/Amazon.Runtime/Credentials/ECSTaskCredentials.cs b/sdk/src/Core/Amazon.Runtime/Credentials/ECSTaskCredentials.cs deleted file mode 100644 index 01a84df929b7..000000000000 --- a/sdk/src/Core/Amazon.Runtime/Credentials/ECSTaskCredentials.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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.Util; -using Amazon.Util.Internal; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Net; - -namespace Amazon.Runtime -{ - /// - /// When running in an ECS container and AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set, - /// use the given end point to retrieve the credentials. - /// - [Obsolete("ECSTaskCredentials only supports Amazon ECS, newer versions of the SDK use the GenericContainerCredentials provider (which also supports EKS Pod Identities)")] - public class ECSTaskCredentials : URIBasedRefreshingCredentialHelper - { - /// - /// These constants should not be consumed by client code. They are only relevant - /// in the context of ECS container and, especially, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, AWS_CONTAINER_CREDENTIALS_FULL_URI & AWS_CONTAINER_AUTHORIZATION_TOKEN - /// environment variable should not be overriden by the client code. - /// - public const string ContainerCredentialsURIEnvVariable = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; - public const string ContainerCredentialsFullURIEnvVariable = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; - public const string ContainerCredentialsAuthorizationTokenEnvVariable = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; - public const string EndpointAddress = "http://169.254.170.2"; - - private Uri Uri { - get - { - var relativeUri = Environment.GetEnvironmentVariable(ContainerCredentialsURIEnvVariable); - var fullUri = Environment.GetEnvironmentVariable(ContainerCredentialsFullURIEnvVariable); - - // AWS_CONTAINER_CREDENTIALS_FULL_URI variable is not compatible with AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, and will not be used if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set. - if (!string.IsNullOrEmpty(relativeUri)) - { - var uriBuilder = new UriBuilder(Server); - uriBuilder.Path = relativeUri; - return uriBuilder.Uri; - } - else if (!string.IsNullOrEmpty(fullUri)) - { - return new Uri(fullUri); - } - else - { - throw new ArgumentException($"Cannot fetch credentials from container - neither {ContainerCredentialsURIEnvVariable} or {ContainerCredentialsFullURIEnvVariable}" + - $" environment variables are set."); - } - } - } - - private string Server = null; - private static int MaxRetries = 5; - - private IWebProxy Proxy; - - public ECSTaskCredentials() : this(null) { PreemptExpiryTime = TimeSpan.FromMinutes(15); } - - public ECSTaskCredentials(IWebProxy proxy) - { - Server = EndpointAddress; - Proxy = proxy; - PreemptExpiryTime = TimeSpan.FromMinutes(15); - } - - protected override CredentialsRefreshState GenerateNewCredentials() - { - SecurityCredentials credentials = null; - Uri ecsEndpointUri = Uri; - JitteredDelay retry = new JitteredDelay(new TimeSpan(0, 0, 0, 0, 200), new TimeSpan(0, 0, 0, 0, 50)); - // Attempt to get the credentials 4 times ignoring null return/exceptions and on the 5th try, escalate the exception if there is one. - for (int i = 1; ; i++) - { - try - { - // AWS_CONTAINER_AUTHORIZATION_TOKEN is optional environment variable - // If this variable is set the SDK will set the Authorization header on the HTTP request with the environment variable's value. - var headers = CreateAuthorizationHeader(); - - credentials = GetObjectFromResponse(ecsEndpointUri, Proxy, headers); - if (credentials != null) - { - break; - } - } - catch (Exception e) - { - if (i == MaxRetries) - { - throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, - "Unable to retrieve credentials. Message = \"{0}\".", - e.Message)); - } - }; - Util.AWSSDKUtils.Sleep(retry.Next()); - } - - return new CredentialsRefreshState(new ImmutableCredentials(credentials.AccessKeyId, credentials.SecretAccessKey, credentials.Token), credentials.Expiration); - } - - private static Dictionary CreateAuthorizationHeader() - { - Dictionary headers = null; - var authorizationToken = Environment.GetEnvironmentVariable(ContainerCredentialsAuthorizationTokenEnvVariable); - if (!string.IsNullOrEmpty(authorizationToken)) - { - headers = new Dictionary - { - {HeaderKeys.AuthorizationHeader, authorizationToken} - }; - } - - return headers; - } - } -} \ No newline at end of file diff --git a/sdk/src/Core/Amazon.Runtime/Credentials/StoredProfileAWSCredentials.cs b/sdk/src/Core/Amazon.Runtime/Credentials/StoredProfileAWSCredentials.cs deleted file mode 100644 index 674b7451e93e..000000000000 --- a/sdk/src/Core/Amazon.Runtime/Credentials/StoredProfileAWSCredentials.cs +++ /dev/null @@ -1,261 +0,0 @@ -/* - * 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.CredentialManagement; -using Amazon.Runtime.Internal; -using Amazon.Runtime.Internal.Util; -using Amazon.Util; -using System; -using System.IO; - -namespace Amazon.Runtime -{ - /// - /// - /// Credentials that are retrieved using a stored profile. - /// - /// - /// Unless otherwise specified priority is given to loading credentials from the SDK credential store - /// file which is shared between the SDK, PowerShell CLI and Toolkit. Credentials in profiles in this - /// file are encrypted and can only be used by the user account on the current machine that stored the - /// profile. Credentials can also be loaded from the plain-text ini-format credential file which is - /// shared with other AWS SDKs. This file is expected to exist in a '.aws' folder in the user's home - /// directory but alternate locations can be specified using either the AWSProfilesLocation setting in - /// the application configuration file, or by using the AWS_SHARED_CREDENTIALS_FILE environment variable. - /// - /// - /// The profile name can be specified in the App.config using the AWSProfileName setting. - /// - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.NetSDKCredentialsFile or SharedCredentialsFile.. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public class StoredProfileAWSCredentials : AWSCredentials - { - private AWSCredentials _wrappedCredentials; - - public AWSCredentials WrappedCredentials - { - get - { - return _wrappedCredentials; - } - } - - #region Public constructors - - /// - /// Constructs an instance for credentials stored in a profile. This constructor searches for credentials - /// using the account name specified using the AWSProfileName setting, if set, in the application configuration - /// file. If the configuration file setting is not set the SDK will attempt to locate a profile with the name - /// 'default'. - /// - public StoredProfileAWSCredentials() - : this(AWSConfigs.AWSProfileName) - { - - } - - /// - /// Constructs an instance for credentials stored in a profile with the specified name. The SDK will - /// check the SDK credential store file first before looking for the shared ini-format credentials - /// file unless the application configuration file contains a setting for the 'AWSProfilesLocation' - /// indicating the search should be constrained to the shared credentials file at the specified - /// location. - /// - /// The name of the profile in which the credentials were stored. - public StoredProfileAWSCredentials(string profileName) - : this(profileName, AWSConfigs.AWSProfilesLocation) - { - - } - - /// - /// Constructs an instance for credentials stored in a profile with the specified name. - /// - /// The profile name to search for credentials for - /// - /// Optional; instructs the SDK to check for the profile in the shared credentials file at the - /// specified location. If not set, the SDK will inspect its own credential store file first before - /// attempting to locate a shared credential file using either the default location beneath the user's - /// home profile folder or the location specified in the AWS_SHARED_CREDENTIALS_FILE environment - /// variable. - /// - /// - /// If credential materials cannot be read or are invalid due to missing data an InvalidDataException - /// is thrown. If no credentials can be located with the specified profile name, an ArgumentException - /// is thrown. - /// - public StoredProfileAWSCredentials(string profileName, string profilesLocation) - { - var lookupName = string.IsNullOrEmpty(profileName) - ? StoredProfileCredentials.DEFAULT_PROFILE_NAME - : profileName; - - ProfileName = lookupName; - ProfilesLocation = null; - - // If not overriding the credentials lookup location check the SDK Store for credentials. If an override is being used then - // assume the intent is to use the credentials file. - if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(lookupName) && ProfileManager.IsAvailable) - { - if (ProfileManager.IsProfileKnown(lookupName) && AWSCredentialsProfile.CanCreateFrom(lookupName)) - { - _wrappedCredentials = ProfileManager.GetAWSCredentials(lookupName); - var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); - logger.InfoFormat("Credentials found using account name {0} and looking in SDK account store.", lookupName); - } - } - - // If credentials weren't found in the SDK store then search the shared credentials file. - if (this._wrappedCredentials == null) - { - var credentialsFilePath = StoredProfileCredentials.ResolveSharedCredentialFileLocation(profilesLocation); - if (!string.IsNullOrEmpty(credentialsFilePath)) - { - var sharedCredentialsFile = new SharedCredentialsFile(credentialsFilePath); - CredentialProfile profile; - if (sharedCredentialsFile.TryGetProfile(lookupName, out profile) - && AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out _wrappedCredentials)) - { - var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); - logger.InfoFormat("Credentials found using account name {0} and looking in {1}.", lookupName, credentialsFilePath); - } - - ProfilesLocation = credentialsFilePath; - } - } - - // No credentials found so error out. - if (this._wrappedCredentials == null) - { - throw new ArgumentException("App.config does not contain credentials information. Either add the AWSAccessKey and AWSSecretKey properties or the AWSProfileName property."); - } - } - - #endregion - - #region Public properties - - /// - /// Name of the profile being used. - /// - public string ProfileName { get; private set; } - - /// - /// Location of the profiles, if used. - /// - public string ProfilesLocation { get; private set; } - - #endregion - - /// - /// Tests if a profile has been registered in either the SDK store or the specified credential - /// file. - /// - /// The name of the profile to test - /// - /// Optional; instructs the SDK to check for the profile in the shared credentials file at the - /// specified location. If not set, the SDK will inspect its own credential store file first before - /// attempting to locate a shared credential file using either the default location beneath the user's - /// home profile folder or the location specified in the AWS_SHARED_CREDENTIALS_FILE environment - /// variable. - /// - /// True if a profile with the specified name has been registered. - public static bool IsProfileKnown(string profileName, string profilesLocation) - { - if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(profileName)) - { - return true; - } - else - { - return ValidCredentialsExistInSharedFile(profilesLocation, profileName); - } - } - - /// - /// Tests if an instance can be created from the persisted profile data. - /// If profilesLocation is null/empty, the SDK store is searched for the - /// profile data before probing for the profile in the shared the ini-format - /// credential file. - /// - /// The name of the profile to test - /// - /// If null/empty, the SDK store is searched for the named profile otherwise - /// the ini-format credential file at the specified location is inspected. - /// - /// True if the persisted data would yield a valid credentials instance. - public static bool CanCreateFrom(string profileName, string profilesLocation) - { - if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(profileName)) - { - return AWSCredentialsProfile.CanCreateFrom(profileName); - } - else - { - return ValidCredentialsExistInSharedFile(profilesLocation, profileName); - } - } - - private static bool ValidCredentialsExistInSharedFile(string profilesLocation, string profileName) - { - var credentialsFilePath = StoredProfileCredentials.ResolveSharedCredentialFileLocation(profilesLocation); - if (!string.IsNullOrEmpty(credentialsFilePath)) - { - var doLog = false; - try - { - var file = new SharedCredentialsFile(credentialsFilePath); - CredentialProfile profile = null; - if (file.TryGetProfile(profileName, out profile) && profile.CanCreateAWSCredentials) - { - return true; - } - else - { - doLog = true; - } - } - catch (InvalidDataException) - { - doLog = true; - } - - if (doLog) - { - var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); - logger.InfoFormat("Credentials file {0} does not contain a valid profile named {1}.", credentialsFilePath, profileName); - } - } - else - { - var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); - logger.InfoFormat("Credentials file not found {0}.", credentialsFilePath); - } - return false; - } - - #region Abstract class overrides - - /// - /// Returns an instance of ImmutableCredentials for this instance - /// - /// - public override ImmutableCredentials GetCredentials() - { - return _wrappedCredentials.GetCredentials(); - } - - #endregion - } -} diff --git a/sdk/src/Core/Amazon.Runtime/Credentials/StoredProfileCredentials.cs b/sdk/src/Core/Amazon.Runtime/Credentials/StoredProfileCredentials.cs deleted file mode 100644 index f576921c6576..000000000000 --- a/sdk/src/Core/Amazon.Runtime/Credentials/StoredProfileCredentials.cs +++ /dev/null @@ -1,164 +0,0 @@ -/* - * 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.Util; -using System; -using System.Globalization; -using System.IO; -using System.Text; - -namespace Amazon.Runtime -{ - /// - /// Helper routiners for AWS and Federated credential profiles. Probes the - /// profile type for the supplied profile name and returns the appropriate profile - /// instance. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.NetSDKCredentialsFile or SharedCredentialsFile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public abstract class StoredProfileCredentials - { - public const string DEFAULT_PROFILE_NAME = "default"; - public const string SHARED_CREDENTIALS_FILE_ENVVAR = "AWS_SHARED_CREDENTIALS_FILE"; - - private static string[] PotentialEnvironmentPathsToCredentialsFile = new string[]{ - "HOME", - "USERPROFILE", - }; - - public const string DefaultSharedCredentialFilename = "credentials"; - public const string DefaultSharedCredentialLocation = ".aws/" + DefaultSharedCredentialFilename; - - /// - /// Determines the type of the requested profile and returns the - /// appropriate profile instance. - /// - /// The name of the profile (AWS or federated) to be loaded. - /// Instantiated profile type. - public static AWSCredentials GetProfile(string profileName) - { - return GetProfile(profileName, AWSConfigs.AWSProfilesLocation); - } - - /// - /// Determines the type of the requested profile and returns the - /// appropriate profile instance. - /// - /// The name of the profile (AWS or federated) to be loaded. - /// - /// The location of the shared credentials (.ini) file, for profiles that are not stored in the - /// SDK credential store. - /// - /// Instantiated profile type. - public static AWSCredentials GetProfile(string profileName, string profileLocation) - { - if (StoredProfileAWSCredentials.CanCreateFrom(profileName, profileLocation)) - return new StoredProfileAWSCredentials(profileName, profileLocation); - -#if !NETSTANDARD - if (StoredProfileFederatedCredentials.CanCreateFrom(profileName, profileLocation)) - return new StoredProfileFederatedCredentials(profileName, profileLocation); -#endif - var sb = new StringBuilder(); - sb.AppendFormat(CultureInfo.InvariantCulture, "Profile {0} was not found in the SDK credential store", profileName); - if (!string.IsNullOrEmpty(profileLocation)) - sb.AppendFormat(CultureInfo.InvariantCulture, " or at location '{0}'.", profileLocation); - - throw new ArgumentException(sb.ToString()); - } - - /// - /// Probes for and returns the fully qualified name of the shared ini-format credentials - /// file. - /// - /// - /// Contains the file or folder name of the credential file. If not specified, the - /// routine will first check the application configuration file for a setting indicating - /// the file location or filename. If the configuration file does not yield a credential - /// file location then an environment variable is examined. Finally the routine will - /// inspect the fallback default location beneath the user's home folder location. - /// - /// - /// The fully qualified name to the credential file that was located, or null - /// if no credential file could be found. - /// - public static string ResolveSharedCredentialFileLocation(string profileLocation) - { - var logger = Logger.GetLogger(typeof(StoredProfileCredentials)); - - string credentialFile = TestSharedCredentialFileExists(profileLocation); - if (!string.IsNullOrEmpty(credentialFile)) - { - logger.InfoFormat("Credentials file found at supplied location: {0}", credentialFile); - return credentialFile; - } - - credentialFile = TestSharedCredentialFileExists(AWSConfigs.AWSProfilesLocation); - if (!string.IsNullOrEmpty(credentialFile)) - { - logger.InfoFormat("Credentials file found using application configuration setting: {0}", credentialFile); - return credentialFile; - } - - credentialFile = TestSharedCredentialFileExists(Environment.GetEnvironmentVariable(SHARED_CREDENTIALS_FILE_ENVVAR)); - if (!string.IsNullOrEmpty(credentialFile)) - { - logger.InfoFormat("Credentials file found using environment variable '{0}': {1}", SHARED_CREDENTIALS_FILE_ENVVAR, credentialFile); - return credentialFile; - } - - foreach (string environmentVariable in PotentialEnvironmentPathsToCredentialsFile) - { - string envPath = Environment.GetEnvironmentVariable(environmentVariable); - if (!string.IsNullOrEmpty(envPath)) - { - credentialFile = TestSharedCredentialFileExists(Path.Combine(envPath, DefaultSharedCredentialLocation)); - if (!string.IsNullOrEmpty(credentialFile)) - { - logger.InfoFormat("Credentials file found using environment variable '{0}': {1}", environmentVariable, credentialFile); - return credentialFile; - } - } - } - - var profileFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - if (!string.IsNullOrEmpty(profileFolder)) - { - credentialFile = TestSharedCredentialFileExists(Path.Combine(profileFolder, DefaultSharedCredentialLocation)); - if (!string.IsNullOrEmpty(credentialFile)) - { - logger.InfoFormat("Credentials file found in user profile location: {0}", credentialFile); - return credentialFile; - } - } - - logger.InfoFormat("No credentials file found using location probing."); - return null; - } - - private static string TestSharedCredentialFileExists(string pathOrFilename) - { - if (!string.IsNullOrEmpty(pathOrFilename)) - { - string testLocation = Directory.Exists(pathOrFilename) - ? Path.Combine(pathOrFilename, DefaultSharedCredentialFilename) - : pathOrFilename; - - if (File.Exists(testLocation)) - return testLocation; - } - - return null; - } - } -} diff --git a/sdk/src/Core/Amazon.Runtime/Credentials/_bcl+netstandard/SSOAWSCredentials.cs b/sdk/src/Core/Amazon.Runtime/Credentials/_bcl+netstandard/SSOAWSCredentials.cs index 2e3084efc87a..56d5fc185f13 100644 --- a/sdk/src/Core/Amazon.Runtime/Credentials/_bcl+netstandard/SSOAWSCredentials.cs +++ b/sdk/src/Core/Amazon.Runtime/Credentials/_bcl+netstandard/SSOAWSCredentials.cs @@ -233,16 +233,6 @@ private async Task GetSsoCredentialsAsync(ICoreAmazonSSO s return await GetSsoRoleCredentialsAsync(sso, token.AccessToken).ConfigureAwait(false); } - /// - /// Returns true if there is already a non-expired cached login access token in the token cache. - /// - /// - /// Obsolete: ALWAYS RETURNS FALSE - [Obsolete("This method is no longer used or supported and will be removed in a future version.", error: false)] - public static bool HasCachedAccessTokenAvailable(string startUrl) - { - return false; - } #if BCL /// diff --git a/sdk/src/Core/Amazon.Runtime/Credentials/_bcl/EnvironmentAWSCredentials.cs b/sdk/src/Core/Amazon.Runtime/Credentials/_bcl/EnvironmentAWSCredentials.cs deleted file mode 100644 index ea013aba50c3..000000000000 --- a/sdk/src/Core/Amazon.Runtime/Credentials/_bcl/EnvironmentAWSCredentials.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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.Util; -using System; -using System.Collections.Specialized; -using System.Configuration; - -namespace Amazon.Runtime -{ - /// - /// Credentials that are retrieved from ConfigurationManager.AppSettings - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please update your code to use AppConfigAWSCredentials instead.")] - public class EnvironmentAWSCredentials : AWSCredentials - { - private const string ACCESSKEY = "AWSAccessKey"; - private const string SECRETKEY = "AWSSecretKey"; - - private ImmutableCredentials _wrappedCredentials; - - #region Public constructors - - /// - /// Constructs an instance of EnvironmentAWSCredentials and attempts - /// to load AccessKey and SecretKey from ConfigurationManager.AppSettings - /// - public EnvironmentAWSCredentials() - { - NameValueCollection appConfig = ConfigurationManager.AppSettings; - - // Use hardcoded credentials - if (!string.IsNullOrEmpty(appConfig[ACCESSKEY]) && !string.IsNullOrEmpty(appConfig[SECRETKEY])) - { - var accessKey = appConfig[ACCESSKEY]; - var secretKey = appConfig[SECRETKEY]; - this._wrappedCredentials = new ImmutableCredentials(accessKey, secretKey, null); - var logger = Logger.GetLogger(typeof(EnvironmentAWSCredentials)); - logger.InfoFormat("Credentials found with {0} and {1} app settings", ACCESSKEY, SECRETKEY); - } - // Fallback to the StoredProfileAWSCredentials provider - else - { - this._wrappedCredentials = new StoredProfileAWSCredentials().GetCredentials(); - } - } - - #endregion - - #region Abstract class overrides - - /// - /// Returns an instance of ImmutableCredentials for this instance - /// - /// - public override ImmutableCredentials GetCredentials() - { - return this._wrappedCredentials.Copy(); - } - - #endregion - } -} diff --git a/sdk/src/Core/Amazon.Runtime/Credentials/_bcl/StoredProfileFederatedCredentials.cs b/sdk/src/Core/Amazon.Runtime/Credentials/_bcl/StoredProfileFederatedCredentials.cs deleted file mode 100644 index 5acb3ff08dd3..000000000000 --- a/sdk/src/Core/Amazon.Runtime/Credentials/_bcl/StoredProfileFederatedCredentials.cs +++ /dev/null @@ -1,419 +0,0 @@ -/* - * 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.Net; - -namespace Amazon.Runtime -{ - /// - /// Temporary credentials that are created following successful authentication with - /// a federated endpoint supporting SAML. - /// - /// - /// 1. Currently only the SDK store supports profiles that contain the necessary data to support - /// authentication and role-based credential generation. The ini-format files used by the AWS CLI - /// and some other SDKs are not supported at this time. - ///
- /// 2. In order to use the StoredProfileFederatedCredentials class the AWSSDK.SecurityToken assembly - /// must be available to your application at runtime. - ///
- [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.FederatedAWSCredentials. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public class StoredProfileFederatedCredentials : RefreshingAWSCredentials - { - #region Private data - - private object _synclock = new object(); - - private RegionEndpoint DefaultSTSClientRegion = RegionEndpoint.USEast1; - - private const int MaxAuthenticationRetries = 3; - - private static readonly TimeSpan _preemptExpiryTime = TimeSpan.FromMinutes(5); - private TimeSpan _credentialDuration = MaximumCredentialTimespan; - - private RequestUserCredential _credentialRequestCallback = null; - private object _customCallbackState = null; - - private WebProxy _proxySettings = null; - - #endregion - - #region Public properties - - /// - /// Custom state to return to the registered callback to handle credential requests. - /// The data will be contained in the CredentialRequestCallbackArgs instance supplied - /// to the callback. - /// - public object CustomCallbackState - { - get - { - lock (_synclock) - { - return _customCallbackState; - } - } - } - - /// - /// The minimum allowed timespan for generated credentials, per STS documentation. - /// - public static readonly TimeSpan MinimumCredentialTimespan = TimeSpan.FromMinutes(15); - - /// - /// The maximum allowed timespan for generated credentials, per STS documentation. - /// - public static readonly TimeSpan MaximumCredentialTimespan = TimeSpan.FromHours(1); - - /// - /// Name of the profile being used. - /// - public string ProfileName { get; private set; } - - /// - /// Location of the profiles, if used. - /// - public string ProfilesLocation { get; private set; } - - /// - /// The data about the SAML endpoint and any required user credentials parsed from the - /// profile. - /// - public SAMLRoleProfile ProfileData { get; private set; } - - /// - /// Callback signature for obtaining user credentials that may be needed for authentication. - /// - /// - /// Data about the credential demand including any custom state data that was supplied - /// when the callback was registered. - /// - /// - /// The network credential to use in user authentication. Return null to signal the user - /// declined to provide credentials and authentication should not proceed. - /// - public delegate NetworkCredential RequestUserCredential(CredentialRequestCallbackArgs args); - - #endregion - - #region Public constructors - - /// - /// Constructs an instance of StoredProfileFederatedCredentials using the profile name specified - /// in the App.config. If no profile name is specified then the default credentials are used. - /// - public StoredProfileFederatedCredentials() - : this(AWSConfigs.AWSProfileName) - { - - } - - /// - /// Constructs an instance of StoredProfileFederatedCredentials. Credentials will be searched - /// for using the profileName parameter. - /// - /// The profile name to search for credentials for - public StoredProfileFederatedCredentials(string profileName) - : this(profileName, AWSConfigs.AWSProfilesLocation) - { - - } - - /// - /// - /// Constructs an instance of StoredProfileFederatedCredentials. After construction call one of the Authenticate - /// methods to authenticate the user/process and obtain temporary AWS credentials. - /// - /// - /// For users who are domain joined (the role profile does not contain user identity information) the temporary - /// credentials will be refreshed automatically as needed. Non domain-joined users (those with user identity - /// data in the profile) are required to re-authenticate when credential refresh is required. An exception is - /// thrown when attempt is made to refresh credentials in this scenario. The consuming code of this class - /// should catch the exception and prompt the user for credentials, then call Authenticate to re-initialize - /// with a new set of temporary AWS credentials. - /// - /// - /// - /// The name of the profile holding the necessary role data to enable authentication and credential generation. - /// - /// Reserved for future use. - /// - /// The ini-format credentials file is not currently supported for SAML role profiles. - /// - public StoredProfileFederatedCredentials(string profileName, string profilesLocation) - : this(profileName, profilesLocation, null) - { - - } - - /// - /// - /// Constructs an instance of StoredProfileFederatedCredentials. After construction call one of the Authenticate - /// methods to authenticate the user/process and obtain temporary AWS credentials. - /// - /// - /// For users who are domain joined (the role profile does not contain user identity information) the temporary - /// credentials will be refreshed automatically as needed. Non domain-joined users (those with user identity - /// data in the profile) are required to re-authenticate when credential refresh is required. An exception is - /// thrown when attempt is made to refresh credentials in this scenario. The consuming code of this class - /// should catch the exception and prompt the user for credentials, then call Authenticate to re-initialize - /// with a new set of temporary AWS credentials. - /// - /// - /// - /// The name of the profile holding the necessary role data to enable authentication and credential generation. - /// - /// Reserved for future use. - /// - /// Null or proxy settings to be used during the HHTPS authentication calls when generating credentials. - /// /// - /// The ini-format credentials file is not currently supported for SAML role profiles. - public StoredProfileFederatedCredentials(string profileName, string profilesLocation, WebProxy proxySettings) - { - this._proxySettings = proxySettings; - this.PreemptExpiryTime = _preemptExpiryTime; - - var lookupName = string.IsNullOrEmpty(profileName) - ? StoredProfileCredentials.DEFAULT_PROFILE_NAME - : profileName; - - ProfileName = lookupName; - ProfilesLocation = null; - - // If not overriding the credentials lookup location check the SDK Store for credentials. If - // an override location is specified, assume we should only use the shared credential file. - if (string.IsNullOrEmpty(profilesLocation)) - { - if (ProfileManager.IsProfileKnown(lookupName) && SAMLRoleProfile.CanCreateFrom(lookupName)) - { - var profileData = ProfileManager.GetProfile(lookupName); - ProfileData = profileData; - var logger = Logger.GetLogger(typeof(StoredProfileFederatedCredentials)); - logger.InfoFormat("SAML role profile found using account name {0} and looking in SDK account store.", lookupName); - } - } - - // we currently do not support the shared ini-format credential file for SAML role profile data - // so end the search now if not found - if (ProfileData == null) - { - var msg = string.Format(CultureInfo.InvariantCulture, - "Profile '{0}' was not found or could not be loaded from the SDK credential store. Verify that the profile name and data are correct.", - profileName); - throw new ArgumentException(msg); - } - } - - #endregion - - /// - /// - /// Registers a callback handler for scenarios where credentials need to be supplied - /// during user authentication (primarily the non-domain-joined use case). Custom data, - /// which will be supplied in the CredentialRequestCallbackArgs instance passed to the - /// callback, can also be supplied. - /// - /// - /// The callback will only be invoked if the underlying SAML role profile indicates it - /// was set up for use with a specific identity. For profiles that do not contain any user - /// identity the SDK will default to using the identity of the current process during - /// authentication. Additionally, if the profile contain user identity information but no - /// callback has been registered, the SDK will also attempt to use the current process - /// identity during authentication. - /// - /// - /// The handler to be called - /// - /// Custom state data to be supplied in the arguments to the callback. - /// - /// - /// Only one callback handler can be registered. The call to the handler will be made on - /// whatever thread is executing at the time a demand to provide AWS credentials is made. - /// If the handler code requires that UI need to be displayed, the handler should - /// transition to the UI thread as appropriate. - /// - public void SetCredentialCallbackData(RequestUserCredential callback, object customData) - { - lock (_synclock) - { - _credentialRequestCallback = callback; - _customCallbackState = customData; - } - } - - /// - /// Tests if an instance can be created from the persisted profile data. - /// - /// The name of the profile to test. - /// The location of the shared ini-format credential file. - /// True if the persisted data would yield a valid credentials instance. - /// - /// This profile type is currently only supported in the SDK credential store file. - /// The shared ini-format file is not currently supported; any value supplied - /// for the profilesLocation value is ignored. - /// - public static bool CanCreateFrom(string profileName, string profilesLocation) - { - if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(profileName)) - return SAMLRoleProfile.CanCreateFrom(profileName); - - return false; - } - - - /// - /// Performs any additional validation we may require on the profile content. - /// - protected override void Validate() - { - } - - /// - /// Refresh credentials after expiry. If the role profile is configured with user identity - /// information and a callback has been registered to obtain the user credential the callback - /// will be invoked ahead of authentication. For role profiles configured with user identity - /// but no callback registration, the SDK will fall back to attempting to use the default - /// user identity of the current process. - /// - /// - protected override CredentialsRefreshState GenerateNewCredentials() - { - Validate(); - - // lock across the entire process for generating credentials so multiple - // threads don't attempt to invoke any registered callback at the same time - // and if we do callback, we only do it once to get the user authentication - // data - lock (_synclock) - { - // If the profile indicates the user has already authenticated and received - // credentials which are still valid, adopt them instead of requiring a fresh - // authentication - var currentSession = ProfileData.GetCurrentSession(); - if (currentSession != null) - return new CredentialsRefreshState(currentSession, currentSession.Expires); - - CredentialsRefreshState newState = null; - var attempts = 0; - do - { - try - { - NetworkCredential userCredential = null; - if (!ProfileData.UseDefaultUserIdentity) - { - if (_credentialRequestCallback != null) - { - var callbackArgs = new CredentialRequestCallbackArgs - { - ProfileName = ProfileData.Name, - UserIdentity = ProfileData.UserIdentity, - CustomState = CustomCallbackState, - PreviousAuthenticationFailed = attempts > 0 - }; - - userCredential = _credentialRequestCallback(callbackArgs); - - if (userCredential == null) // user declined to authenticate - throw new FederatedAuthenticationCancelledException("User cancelled credential request."); - } - else - { - var logger = Logger.GetLogger(typeof(StoredProfileFederatedCredentials)); - logger.InfoFormat("Role profile {0} is configured for a specific user but no credential request callback registered; falling back to default identity.", ProfileName); - } - } - - newState = Authenticate(userCredential, _credentialDuration); - } - catch (FederatedAuthenticationFailureException) - { - if (attempts < MaxAuthenticationRetries) - attempts++; - else - throw; - } - } while (newState == null && attempts < MaxAuthenticationRetries); - - return newState; - } - } - - private CredentialsRefreshState Authenticate(ICredentials userCredential, TimeSpan credentialDuration) - { - CredentialsRefreshState state; - - var configuredRegion = !string.IsNullOrEmpty(ProfileData.Region) ? ProfileData.Region : AWSConfigs.AWSRegion; - var region = string.IsNullOrEmpty(configuredRegion) - ? DefaultSTSClientRegion - : RegionEndpoint.GetBySystemName(configuredRegion); - - ICoreAmazonSTS coreSTSClient = null; - - try - { - var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, - ServiceClientHelpers.STS_SERVICE_CONFIG_NAME); - stsConfig.RegionEndpoint = region; - if (_proxySettings != null) - stsConfig.SetWebProxy(_proxySettings); - - coreSTSClient - = ServiceClientHelpers.CreateServiceFromAssembly(ServiceClientHelpers.STS_ASSEMBLY_NAME, - ServiceClientHelpers.STS_SERVICE_CLASS_NAME, - new AnonymousAWSCredentials(), - stsConfig); - } - 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 this profile class.", - ServiceClientHelpers.STS_ASSEMBLY_NAME); - throw new InvalidOperationException(msg, e); - } - - try - { - var credentials - = coreSTSClient.CredentialsFromSAMLAuthentication(ProfileData.EndpointSettings.Endpoint.ToString(), - ProfileData.EndpointSettings.AuthenticationType, - ProfileData.RoleArn, - credentialDuration, - userCredential); - - ProfileData.PersistSession(credentials); - - state = new CredentialsRefreshState(credentials, credentials.Expires); - } - catch (Exception e) - { - var wrappedException = new AmazonClientException("Credential generation from SAML authentication failed.", e); - - var logger = Logger.GetLogger(typeof(StoredProfileFederatedCredentials)); - logger.Error(wrappedException, wrappedException.Message); - - throw wrappedException; - } - - return state; - } - } -} diff --git a/sdk/src/Core/Amazon.Runtime/EndpointDiscoveryEnabled.cs b/sdk/src/Core/Amazon.Runtime/EndpointDiscoveryEnabled.cs deleted file mode 100644 index b29b2dc9f635..000000000000 --- a/sdk/src/Core/Amazon.Runtime/EndpointDiscoveryEnabled.cs +++ /dev/null @@ -1,179 +0,0 @@ -/* - * 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 System; -using System.Globalization; - -using Amazon.Runtime.Internal.Util; -using System.Collections.Generic; -using Amazon.Util; -using Amazon.Runtime.CredentialManagement; - -namespace Amazon.Runtime -{ - /// - /// Determines the endpoint discovery enabled value based on an environment variable. If no value is found in the - /// environment then an InvalidOperationException is thrown. - /// - [Obsolete("This class has been deprecated in favor of EnvironmentVariableAWSConfiguration.")] - public class EnvironmentVariableAWSEndpointDiscoveryEnabled - { - public const string ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY = "AWS_ENABLE_ENDPOINT_DISCOVERY"; - public bool Enabled { get; private set; } - - /// - /// Attempts to construct an instance of EnvironmentVariable AWS_ENABLED_ENDPOINT_DISCOVERY. If no value is found in the - /// environment then an InvalidOperationException is thrown. - /// - public EnvironmentVariableAWSEndpointDiscoveryEnabled() - { - string enabledValue = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY); - if (string.IsNullOrEmpty(enabledValue)) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, - "The environment variable {0} was not set with a boolean value.", ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY)); - } - - bool enabled; - if(!bool.TryParse(enabledValue, out enabled)) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, - "The environment variable {0} was set with value {1}, but it could not be parsed as a valid boolean value.", ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY, enabledValue)); - } - - this.Enabled = enabled; - - var logger = Logger.GetLogger(typeof(EnvironmentVariableAWSEndpointDiscoveryEnabled)); - logger.InfoFormat("Endpoint discovery enabled found using environment variable."); - } - } - - /// - /// Determines endpoint discovery enabled based on a stored in an . - /// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown. - /// - [Obsolete("This class has been deprecated in favor of ProfileAWSConfiguration.")] - public class ProfileAWSEndpointDiscoveryEnabled - { - public bool Enabled { get; private set; } - - /// - /// Attempts to construct an instance of . - /// If the AWS_PROFILE environment variable is set the instance will be constructed using that profile, - /// otherwise it will use the default profile. - /// - /// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown. - /// - /// The ICredentialProfileSource to read the profile from. - public ProfileAWSEndpointDiscoveryEnabled(ICredentialProfileSource source) - { - var profileName = FallbackCredentialsFactory.GetProfileName(); - Setup(source, profileName); - } - - /// - /// Attempts to construct an instance of . - /// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown. - /// - /// The ICredentialProfileSource to read the profile from. - /// The name of the profile. - public ProfileAWSEndpointDiscoveryEnabled(ICredentialProfileSource source, string profileName) - { - Setup(source, profileName); - } - - private void Setup(ICredentialProfileSource source, string profileName) - { - bool? enabled = null; - CredentialProfile profile; - if (source.TryGetProfile(profileName, out profile)) - { - enabled = profile.EndpointDiscoveryEnabled; - } - else - throw new InvalidOperationException("Unable to find a profile named '" + profileName + "' in store " + source.GetType()); - - if (enabled == null) - throw new InvalidOperationException("There is no endpoint_discovery_enabled set in the profile named '" + profileName + "' in store " + source.GetType()); - else - { - this.Enabled = enabled.Value; - var logger = Logger.GetLogger(typeof(ProfileAWSEndpointDiscoveryEnabled)); - logger.InfoFormat("endpoint_discovery_enabled found in profile '" + profileName + "' in store " + source.GetType()); - } - } - } - - /// - /// Probing mechanism to determine the endpoint discovery enabled value from various sources. - /// - [Obsolete("This class has been deprecated in favor of FallbackConfigurationFactory.")] - public static class FallbackEndpointDiscoveryEnabledFactory - { - private static CredentialProfileStoreChain credentialProfileChain = new CredentialProfileStoreChain(); - - private static object _lock = new object(); - - static FallbackEndpointDiscoveryEnabledFactory() - { - Reset(); - } - - private delegate bool ConfigGenerator(); - - private static List EnabledGenerators { get; set; } - - public static void Reset() - { - endpointDiscoveryEnabled = null; - EnabledGenerators = new List - { - () => (new EnvironmentVariableAWSEndpointDiscoveryEnabled()).Enabled, - () => (new ProfileAWSEndpointDiscoveryEnabled(credentialProfileChain)).Enabled, - }; - } - - private static bool? endpointDiscoveryEnabled; - - public static bool? GetEnabled() - { - lock (_lock) - { - if (endpointDiscoveryEnabled != null) - return endpointDiscoveryEnabled; - - List errors = new List(); - - //Determine the Enabled flag - foreach (var generator in EnabledGenerators) - { - try - { - endpointDiscoveryEnabled = generator(); - } - catch (Exception e) - { - errors.Add(e); - continue; - } - - if (endpointDiscoveryEnabled.HasValue) - break; - } - - return endpointDiscoveryEnabled; - } - } - } -} diff --git a/sdk/src/Core/Amazon.Runtime/IClientConfig.cs b/sdk/src/Core/Amazon.Runtime/IClientConfig.cs index d3a36aeece0c..34b57932f754 100644 --- a/sdk/src/Core/Amazon.Runtime/IClientConfig.cs +++ b/sdk/src/Core/Amazon.Runtime/IClientConfig.cs @@ -169,12 +169,7 @@ public partial interface IClientConfig ///
bool LogResponse { get; } - /// - /// Gets the ReadEntireResponse. - /// If this property is set to true, the service response - /// is read in its entirety before being processed. - /// - bool ReadEntireResponse { get; } + /// @@ -298,11 +293,7 @@ public partial interface IClientConfig /// A Container class for parameters used for endpoint resolution. /// The resolved endpoint for the given request. Endpoint DetermineServiceOperationEndpoint(ServiceOperationEndpointParameters parameters); - /// - /// Given this client configuration, return a DNS suffix for service endpoint url. - /// - [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, use the service-specific client.DetermineServiceOperationEndPoint method instead.")] - string DetermineDnsSuffix(); + /// /// Performs validation on this config object. @@ -311,16 +302,9 @@ public partial interface IClientConfig /// The timeout specified is null. void Validate(); - /// - /// Returns the clock skew adjusted utc now. This value is affected by AWSConfigs.ManualClockCorrection - /// - DateTime CorrectedUtcNow { get; } - /// - /// Returns the calculated clock skew value for this config's service endpoint. If AWSConfigs.CorrectForClockSkew is false, - /// this value won't be used to construct service requests. - /// - TimeSpan ClockOffset { get; } + + /// /// Gets the DisableHostPrefixInjection flag. If true, host prefix injection will be disabled for this client, the default value of this flag is false. diff --git a/sdk/src/Core/Amazon.Runtime/Internal/AmazonWebServiceRequest.cs b/sdk/src/Core/Amazon.Runtime/Internal/AmazonWebServiceRequest.cs index 0fce10e54ecc..188dcab45c79 100644 --- a/sdk/src/Core/Amazon.Runtime/Internal/AmazonWebServiceRequest.cs +++ b/sdk/src/Core/Amazon.Runtime/Internal/AmazonWebServiceRequest.cs @@ -24,27 +24,6 @@ namespace Amazon.Runtime { public abstract partial class AmazonWebServiceRequest : IAmazonWebServiceRequest { - /// - /// This flag specifies if SigV4 will be used for the current request. - /// - [Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")] - bool IAmazonWebServiceRequest.UseSigV4 - { - get { return UseSigV4; } - set { UseSigV4 = value; } - } - - /// - /// This flag specifies if SigV4 will be used for the current request. - /// Returns true if the request will use SigV4. - /// Setting it to false will use SigV2. - /// - [Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")] - protected bool UseSigV4 - { - get { return ((IAmazonWebServiceRequest)this).SignatureVersion == SignatureVersion.SigV4; } - set { ((IAmazonWebServiceRequest)this).SignatureVersion = value ? SignatureVersion.SigV4 : SignatureVersion.SigV2; } - } /// /// Specifies which signature version will be used for the current request. diff --git a/sdk/src/Core/Amazon.Runtime/Internal/Auth/S3Signer.cs b/sdk/src/Core/Amazon.Runtime/Internal/Auth/S3Signer.cs index 08c5a09df364..74fb3aac853a 100644 --- a/sdk/src/Core/Amazon.Runtime/Internal/Auth/S3Signer.cs +++ b/sdk/src/Core/Amazon.Runtime/Internal/Auth/S3Signer.cs @@ -213,11 +213,9 @@ static string BuildCanonicalizedResource(IRequest request) // CanonicalResourcePrefix will hold the bucket name if we switched to virtual host addressing // during request preprocessing (where it would have been removed from ResourcePath) var sb = new StringBuilder(request.CanonicalResourcePrefix); -#pragma warning disable CS0618 // Type or member is obsolete sb.Append(!string.IsNullOrEmpty(request.ResourcePath) ? AWSSDKUtils.ResolveResourcePathV2(request.ResourcePath, request.PathResources) : "/"); -#pragma warning restore CS0618 // Type or member is obsolete // form up the set of all subresources and specific query parameters that must be // included in the canonical resource, then append them ordered by key to the diff --git a/sdk/src/Core/Amazon.Runtime/Internal/DefaultRequest.cs b/sdk/src/Core/Amazon.Runtime/Internal/DefaultRequest.cs index 80eb41c2b7cd..f980714ffc6b 100644 --- a/sdk/src/Core/Amazon.Runtime/Internal/DefaultRequest.cs +++ b/sdk/src/Core/Amazon.Runtime/Internal/DefaultRequest.cs @@ -70,9 +70,6 @@ public DefaultRequest(AmazonWebServiceRequest request, String serviceName) this.serviceName = serviceName; this.originalRequest = request; this.requestName = this.originalRequest.GetType().Name; -#pragma warning disable CS0612,CS0618 - this.UseSigV4 = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)this.originalRequest).UseSigV4; -#pragma warning restore CS0612,CS0618 this.SignatureVersion = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)this.originalRequest).SignatureVersion; this.HostPrefix = string.Empty; @@ -448,18 +445,6 @@ public string CanonicalResourcePrefix set; } - /// - /// This flag specifies if SigV4 is required for the current request. - /// Returns true if the request will use SigV4. - /// Setting it to false will use SigV2. - /// - [Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")] - public bool UseSigV4 - { - get { return SignatureVersion == SignatureVersion.SigV4; } - set { this.SignatureVersion = value ? SignatureVersion.SigV4 : SignatureVersion.SigV2; } - } - /// /// Specifies which signature version shall be used for the current request. /// diff --git a/sdk/src/Core/Amazon.Runtime/Internal/IAmazonWebServiceRequest.cs b/sdk/src/Core/Amazon.Runtime/Internal/IAmazonWebServiceRequest.cs index eac8f9a97cac..e98043be9946 100644 --- a/sdk/src/Core/Amazon.Runtime/Internal/IAmazonWebServiceRequest.cs +++ b/sdk/src/Core/Amazon.Runtime/Internal/IAmazonWebServiceRequest.cs @@ -15,8 +15,6 @@ public interface IAmazonWebServiceRequest Dictionary RequestState { get; } - [Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")] - bool UseSigV4 { get; set; } SignatureVersion SignatureVersion { get; set; } } diff --git a/sdk/src/Core/Amazon.Runtime/Internal/IRequest.cs b/sdk/src/Core/Amazon.Runtime/Internal/IRequest.cs index 241f0ef6195a..1264cb75aca9 100644 --- a/sdk/src/Core/Amazon.Runtime/Internal/IRequest.cs +++ b/sdk/src/Core/Amazon.Runtime/Internal/IRequest.cs @@ -314,11 +314,6 @@ string CanonicalResourcePrefix set; } - /// - /// This flag specifies if SigV4 is required for the current request. - /// - [Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")] - bool UseSigV4 { get; set; } /// /// Specifies which signature version shall be used for the current request. diff --git a/sdk/src/Core/Amazon.Runtime/Internal/Util/ProfileIniFile.cs b/sdk/src/Core/Amazon.Runtime/Internal/Util/ProfileIniFile.cs index e2ac11293c30..d5772c5d6737 100644 --- a/sdk/src/Core/Amazon.Runtime/Internal/Util/ProfileIniFile.cs +++ b/sdk/src/Core/Amazon.Runtime/Internal/Util/ProfileIniFile.cs @@ -79,36 +79,6 @@ public bool TryGetSection(string sectionName, bool isSsoSession, bool isServices return hasCredentialsProperties; } -#pragma warning disable CS0809 - [Obsolete("TryGetSection(string sectionName, bool isSsoSession, out Dictionary properties is deprecated. Please use the overloaded" + - "method with nestedProperties instead")] - public override bool TryGetSection(string sectionName, out Dictionary properties) - { - return this.TryGetSection(sectionName, isSsoSession: false, out properties); - } -#pragma warning restore CS0809 - - // This is no longer used, as this implementation didn't take into account nested properties - // The overloaded method above correctly fills out a dictionary of nested properties - [Obsolete("TryGetSection(string sectionName, bool isSsoSession, out Dictionary properties is deprecated. Please use the overloaded" + - "method with nestedProperties instead")] - public bool TryGetSection(string sectionName, bool isSsoSession, out Dictionary properties) - { - bool hasCredentialsProperties = false; - properties = null; - - if (!ProfileMarkerRequired && !isSsoSession) - hasCredentialsProperties = base.TryGetSection(sectionName, out properties); - - if (!hasCredentialsProperties) - { - var marker = isSsoSession ? SsoSessionMarker : ProfileMarker; - - var credentialSectionNameRegex = new Regex("^" + marker + "[ \\t]+" + Regex.Escape(sectionName) + "$", RegexOptions.Singleline); - hasCredentialsProperties = this.TryGetSection(credentialSectionNameRegex, out properties); - } - return hasCredentialsProperties; - } public override void EditSection(string sectionName, SortedDictionary properties) { diff --git a/sdk/src/Core/Amazon.Runtime/Internal/Util/StringUtils.cs b/sdk/src/Core/Amazon.Runtime/Internal/Util/StringUtils.cs index 37ea49c9ebe5..eac4e89ed472 100644 --- a/sdk/src/Core/Amazon.Runtime/Internal/Util/StringUtils.cs +++ b/sdk/src/Core/Amazon.Runtime/Internal/Util/StringUtils.cs @@ -154,11 +154,6 @@ public static string FromBool(bool value) return value ? "true" : "false"; } - [Obsolete("This method doesn't handle correctly non-UTC DateTimes. Use FromDateTimeToISO8601 instead.", false)] - public static string FromDateTime(DateTime value) - { - return value.ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture); - } /// /// Converts a DateTime to ISO8601 formatted string. diff --git a/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/Unmarshaller.cs b/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/Unmarshaller.cs index 977865905b7a..d69f3f0e5c2d 100644 --- a/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/Unmarshaller.cs +++ b/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/Unmarshaller.cs @@ -104,7 +104,9 @@ private void Unmarshall(IExecutionContext executionContext) var unmarshaller = requestContext.Unmarshaller; try { - var readEntireResponse = _supportsResponseLogging; + var readEntireResponse = _supportsResponseLogging && + (requestContext.ClientConfig.LogResponse + || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never); var context = unmarshaller.CreateContext(responseContext.HttpResponse, readEntireResponse, @@ -161,7 +163,7 @@ private async System.Threading.Tasks.Task UnmarshallAsync(IExecutionContext exec try { var readEntireResponse = _supportsResponseLogging && - (requestContext.ClientConfig.LogResponse || requestContext.ClientConfig.ReadEntireResponse + (requestContext.ClientConfig.LogResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never); var responseStream = await responseContext.HttpResponse. diff --git a/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/DefaultRetryPolicy.cs b/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/DefaultRetryPolicy.cs index 768ceb15c394..76df4ecf5222 100644 --- a/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/DefaultRetryPolicy.cs +++ b/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/DefaultRetryPolicy.cs @@ -251,24 +251,5 @@ private static int CalculateRetryDelay(int retries, int maxBackoffInMilliseconds return delay; } - [Obsolete("This method is no longer used within DefaultRetryPolicy")] - protected static bool ContainErrorMessage(Exception exception) - { - return ContainErrorMessage(exception, _netStandardRetryErrorMessages); - } - - [Obsolete("This method has been moved to AWSSDK.Runtime.Internal.Util.ExceptionUtils")] - protected static bool IsInnerException(Exception exception) - where T : Exception - { - return ExceptionUtils.IsInnerException(exception); - } - - [Obsolete("This method has been moved to AWSSDK.Runtime.Internal.Util.ExceptionUtils")] - protected static bool IsInnerException(Exception exception, out T inner) - where T : Exception - { - return ExceptionUtils.IsInnerException(exception, out inner); - } } } diff --git a/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/RetryPolicy.cs b/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/RetryPolicy.cs index 18aedfea8a15..a2e0f5695cdd 100644 --- a/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/RetryPolicy.cs +++ b/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/RetryPolicy.cs @@ -453,7 +453,7 @@ private bool IsClockskew(IExecutionContext executionContext, Exception exception var absDiff = diff.Ticks < 0 ? -diff : diff; Logger.InfoFormat(clockSkewMessageFormat, - realNow, correctedNow, clientConfig.ClockOffset, serverTime, endpoint); + realNow, correctedNow, CorrectClockSkew.GetClockCorrectionForEndpoint(endpoint), serverTime, endpoint); // Always set the correction, for informational purposes CorrectClockSkew.SetClockCorrectionForEndpoint(endpoint, newCorrection); diff --git a/sdk/src/Core/Amazon.Runtime/RequestHandler.cs b/sdk/src/Core/Amazon.Runtime/RequestHandler.cs index 5ce4f05e0016..abdd85ad4112 100644 --- a/sdk/src/Core/Amazon.Runtime/RequestHandler.cs +++ b/sdk/src/Core/Amazon.Runtime/RequestHandler.cs @@ -41,14 +41,10 @@ protected WebServiceRequestEventArgs() { } #region Properties public IDictionary Headers { get; protected set; } - [Obsolete("Parameters property has been deprecated in favor of the ParameterCollection property")] - public IDictionary Parameters { get; protected set; } public ParameterCollection ParameterCollection { get; protected set; } public string ServiceName { get; protected set; } public Uri Endpoint { get; protected set; } public AmazonWebServiceRequest Request { get; protected set; } - [Obsolete("OriginalRequest property has been deprecated in favor of the Request property")] - public AmazonWebServiceRequest OriginalRequest { get { return Request; } } #endregion @@ -59,12 +55,8 @@ internal static WebServiceRequestEventArgs Create(IRequest request) WebServiceRequestEventArgs args = new WebServiceRequestEventArgs { Headers = request.Headers, -#pragma warning disable CS0618 // Type or member is obsolete - Parameters = request.Parameters, -#pragma warning restore CS0618 // Type or member is obsolete ParameterCollection = request.ParameterCollection, ServiceName = request.ServiceName, - Request = request.OriginalRequest, Endpoint = request.Endpoint }; return args; diff --git a/sdk/src/Core/Amazon.Runtime/SharedInterfaces/_async/ICoreAmazonS3.cs b/sdk/src/Core/Amazon.Runtime/SharedInterfaces/_async/ICoreAmazonS3.cs index 1c30095bffed..4dae71dd1cf2 100644 --- a/sdk/src/Core/Amazon.Runtime/SharedInterfaces/_async/ICoreAmazonS3.cs +++ b/sdk/src/Core/Amazon.Runtime/SharedInterfaces/_async/ICoreAmazonS3.cs @@ -100,13 +100,5 @@ public partial interface ICoreAmazonS3 /// /// Task EnsureBucketExistsAsync(string bucketName); - - /// - /// Check to see if the bucket exists. - /// - /// - /// - [Obsolete("This method is deprecated: its behavior is inconsistent and always uses HTTP. Please use Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async instead.")] - Task DoesS3BucketExistAsync(string bucketName); } } diff --git a/sdk/src/Core/Amazon.Util/AWSConfigs.Models.cs b/sdk/src/Core/Amazon.Util/AWSConfigs.Models.cs index 0367f315a1df..81841085698d 100644 --- a/sdk/src/Core/Amazon.Util/AWSConfigs.Models.cs +++ b/sdk/src/Core/Amazon.Util/AWSConfigs.Models.cs @@ -122,10 +122,7 @@ public LoggingOptions LogTo internal LoggingConfig() { - LogTo = AWSConfigs._logging; - LogResponses = AWSConfigs._responseLogging; LogResponsesSizeLimit = DefaultLogResponsesSizeLimit; - LogMetrics = AWSConfigs._logMetrics; } } diff --git a/sdk/src/Core/Amazon.Util/AWSSDKUtils.cs b/sdk/src/Core/Amazon.Util/AWSSDKUtils.cs index c028c248871c..773ad7449c16 100644 --- a/sdk/src/Core/Amazon.Util/AWSSDKUtils.cs +++ b/sdk/src/Core/Amazon.Util/AWSSDKUtils.cs @@ -534,39 +534,6 @@ public static string JoinResourcePathSegmentsV2(IEnumerable pathSe } - /// - /// Takes a patterned resource path and resolves it using the key/value path resources into - /// a segmented encoded URL. - /// - /// The patterned resourcePath - /// The key/value lookup for the patterned resourcePath - /// A segmented encoded URL - [Obsolete("ResolveResourcePath has been deprecated in favor of ResolveResourcePathV2 due to an encoding issue. Use ResolveResourcePathV2 instead.")] - public static string ResolveResourcePath(string resourcePath, IDictionary pathResources) - { -#pragma warning disable 0618 - return ResolveResourcePath(resourcePath, pathResources, true); -#pragma warning restore 0618 - } - - /// - /// Takes a patterned resource path and resolves it using the key/value path resources into - /// a segmented encoded URL. - /// - /// The patterned resourcePath - /// The key/value lookup for the patterned resourcePath - /// If true valid path characters {/+:} are not encoded - /// A segmented encoded URL - [Obsolete("This method has been deprecated in favor of ResolveResourcePathV2 due to an encoding issue with special characters. Please use ResolveResourcePathV2.")] - public static string ResolveResourcePath(string resourcePath, IDictionary pathResources, bool skipEncodingValidPathChars) - { - if (string.IsNullOrEmpty(resourcePath)) - { - return resourcePath; - } - - return JoinResourcePathSegments(SplitResourcePathIntoSegments(resourcePath, pathResources), skipEncodingValidPathChars); - } /// /// Takes a patterned resource path and resolves it using the key/value path resources into /// a segmented encoded URL. @@ -677,11 +644,6 @@ public static string ConvertToUnixEpochSecondsString(DateTime dateTime) return Convert.ToInt64(GetTimeSpanInTicks(dateTime).TotalSeconds).ToString(CultureInfo.InvariantCulture); } - [Obsolete("This method isn't named correctly: it returns seconds instead of milliseconds. Use ConvertToUnixEpochSecondsDouble instead.", false)] - public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime) - { - return ConvertToUnixEpochSecondsDouble(dateTime); - } public static double ConvertToUnixEpochSecondsDouble(DateTime dateTime) { @@ -1235,45 +1197,6 @@ internal static string EncodeTraceIdHeaderValue(string value) return encoded.ToString(); } - /// - /// URL encodes a string per the specified RFC with the exception of preserving the encoding of previously encoded slashes. - /// If the path property is specified, the accepted path characters {/+:} are not encoded. - /// - /// The string to encode - /// Whether the string is a URL path or not - /// The encoded string with any previously encoded %2F preserved - [Obsolete("This method is not supported in AWSSDK 3.5")] - public static string ProtectEncodedSlashUrlEncode(string data, bool path) - { - if (string.IsNullOrEmpty(data)) - { - return data; - } - - var index = 0; - var sb = new StringBuilder(); - var findIndex = data.IndexOf(EncodedSlash, index, StringComparison.OrdinalIgnoreCase); - while (findIndex != -1) - { - sb.Append(UrlEncode(data.Substring(index, findIndex - index), path)); - sb.Append(EncodedSlash); - index = findIndex + EncodedSlash.Length; - findIndex = data.IndexOf(EncodedSlash, index, StringComparison.OrdinalIgnoreCase); - } - - //If encoded slash was not found return the original data - if(index == 0) - { - return UrlEncode(data, path); - } - - if(data.Length > index) - { - sb.Append(UrlEncode(data.Substring(index), path)); - } - - return sb.ToString(); - } /// /// Generates an MD5 Digest for the stream specified diff --git a/sdk/src/Core/Amazon.Util/EC2InstanceMetadata.cs b/sdk/src/Core/Amazon.Util/EC2InstanceMetadata.cs index 3c5f0e4aa538..b7804559de36 100644 --- a/sdk/src/Core/Amazon.Util/EC2InstanceMetadata.cs +++ b/sdk/src/Core/Amazon.Util/EC2InstanceMetadata.cs @@ -51,20 +51,6 @@ namespace Amazon.Util /// public static class EC2InstanceMetadata { - [Obsolete("EC2_METADATA_SVC is obsolete, refer to ServiceEndpoint instead to respect environment and profile overrides.")] - public static readonly string EC2_METADATA_SVC = "http://169.254.169.254"; - - [Obsolete("EC2_METADATA_ROOT is obsolete, refer to EC2MetadataRoot instead to respect environment and profile overrides.")] - public static readonly string EC2_METADATA_ROOT = EC2_METADATA_SVC + LATEST + "/meta-data"; - - [Obsolete("EC2_USERDATA_ROOT is obsolete, refer to EC2UserDataRoot instead to respect environment and profile overrides.")] - public static readonly string EC2_USERDATA_ROOT = EC2_METADATA_SVC + LATEST + "/user-data"; - - [Obsolete("EC2_DYNAMICDATA_ROOT is obsolete, refer to EC2DynamicDataRoot instead to respect environment and profile overrides.")] - public static readonly string EC2_DYNAMICDATA_ROOT = EC2_METADATA_SVC + LATEST + "/dynamic"; - - [Obsolete("EC2_APITOKEN_URL is obsolete, refer to EC2ApiTokenUrl instead to respect environment and profile overrides.")] - public static readonly string EC2_APITOKEN_URL = EC2_METADATA_SVC + LATEST + "/api/token"; public static readonly string LATEST = "/latest", diff --git a/sdk/src/Core/Amazon.Util/Internal/TypeWrapper.cs b/sdk/src/Core/Amazon.Util/Internal/TypeWrapper.cs deleted file mode 100644 index 3c0012fed7d9..000000000000 --- a/sdk/src/Core/Amazon.Util/Internal/TypeWrapper.cs +++ /dev/null @@ -1,220 +0,0 @@ -/******************************************************************************* - * 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. - * ***************************************************************************** - * __ _ _ ___ - * ( )( \/\/ )/ __) - * /__\ \ / \__ \ - * (_)(_) \/\/ (___/ - * - * AWS SDK for .NET - * - */ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Reflection; -using System.Text; - -namespace Amazon.Util.Internal -{ - [Obsolete("The TypeFactory abstraction should not be used. This was needed when the SDK targeted .NET Standard 1.3 which was removed as part of version 3.7. Type information should be accessed directly from the System.Type class.")] - public interface ITypeInfo - { - Type BaseType { get; } - - Type Type { get; } - - Assembly Assembly { get; } - bool IsArray { get; } - - Array ArrayCreateInstance(int length); - - Type GetInterface(string name); - Type[] GetInterfaces(); - - IEnumerable GetProperties(); - - IEnumerable GetFields(); - FieldInfo GetField(string name); - - MethodInfo GetMethod(string name); - MethodInfo GetMethod(string name, ITypeInfo[] paramTypes); - - MemberInfo[] GetMembers(); - - - ConstructorInfo GetConstructor(ITypeInfo[] paramTypes); - - PropertyInfo GetProperty(string name); - - bool IsAssignableFrom(ITypeInfo typeInfo); - - bool IsEnum {get;} - - bool IsClass { get; } - bool IsValueType { get; } - - bool IsInterface { get; } - bool IsAbstract { get; } - bool IsSealed { get; } - - object EnumToObject(object value); - - object CreateInstance(); - - bool IsType(Type type); - - string FullName { get; } - string Name { get; } - - bool IsGenericTypeDefinition { get; } - bool IsGenericType { get; } - bool ContainsGenericParameters { get; } - Type GetGenericTypeDefinition(); - Type[] GetGenericArguments(); - - object[] GetCustomAttributes(bool inherit); - object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit); - - } - - [Obsolete("The TypeFactory abstraction should not be used. This was needed when the SDK targeted .NET Standard 1.3 which was removed as part of version 3.7. Type information should be accessed directly from the System.Type class.")] - public static partial class TypeFactory - { - public static readonly ITypeInfo[] EmptyTypes = new ITypeInfo[] { }; - -#if NET8_0_OR_GREATER - - public static ITypeInfo GetTypeInfo([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) -#else - public static ITypeInfo GetTypeInfo(Type type) -#endif - - { - if (type == null) - return null; - - - return new TypeInfoWrapper(type); - } - - abstract class AbstractTypeInfo : ITypeInfo - { -#if NET8_0_OR_GREATER - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] -#endif - protected Type _type; - -#if NET8_0_OR_GREATER - internal AbstractTypeInfo([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) -#else - internal AbstractTypeInfo(Type type) -#endif - { - this._type = type; - } - - public Type Type - { - get{return this._type;} - } - - public override int GetHashCode() - { - return this._type.GetHashCode(); - } - - public override bool Equals(object obj) - { - var typeWrapper = obj as AbstractTypeInfo; - if (typeWrapper == null) - return false; - - return this._type.Equals(typeWrapper._type); - } - - public bool IsType(Type type) - { - return this._type == type; - } - - public abstract Type BaseType { get; } - public abstract Assembly Assembly { get; } - public abstract Type GetInterface(string name); - public abstract Type[] GetInterfaces(); - public abstract IEnumerable GetProperties(); - public abstract IEnumerable GetFields(); - public abstract FieldInfo GetField(string name); - public abstract MethodInfo GetMethod(string name); - public abstract MethodInfo GetMethod(string name, ITypeInfo[] paramTypes); - public abstract MemberInfo[] GetMembers(); - public abstract PropertyInfo GetProperty(string name); - public abstract bool IsAssignableFrom(ITypeInfo typeInfo); - public abstract bool IsClass { get; } - public abstract bool IsInterface { get; } - public abstract bool IsAbstract { get; } - public abstract bool IsSealed { get; } - public abstract bool IsEnum { get; } - public abstract bool IsValueType { get; } - public abstract ConstructorInfo GetConstructor(ITypeInfo[] paramTypes); - - public abstract object[] GetCustomAttributes(bool inherit); - public abstract object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit); - - public abstract bool ContainsGenericParameters { get; } - public abstract bool IsGenericTypeDefinition { get; } - public abstract bool IsGenericType {get;} - public abstract Type GetGenericTypeDefinition(); - public abstract Type[] GetGenericArguments(); - - public bool IsArray - { - get { return this._type.IsArray; } - } - - - public object EnumToObject(object value) - { - return Enum.ToObject(this._type, value); - } - - public object CreateInstance() - { - return Activator.CreateInstance(this._type); - } - - public Array ArrayCreateInstance(int length) - { - return Array.CreateInstance(this._type, length); - } - - public string FullName - { - get - { - return this._type.FullName; - } - } - - public string Name - { - get - { - return this._type.Name; - } - } - } - } - - -} diff --git a/sdk/src/Core/Amazon.Util/Internal/_bcl/TypeWrapper.bcl.cs b/sdk/src/Core/Amazon.Util/Internal/_bcl/TypeWrapper.bcl.cs deleted file mode 100644 index 2942f021dcdf..000000000000 --- a/sdk/src/Core/Amazon.Util/Internal/_bcl/TypeWrapper.bcl.cs +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * 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. - * ***************************************************************************** - * __ _ _ ___ - * ( )( \/\/ )/ __) - * /__\ \ / \__ \ - * (_)(_) \/\/ (___/ - * - * AWS SDK for .NET - * - */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; - - -namespace Amazon.Util.Internal -{ - public static partial class TypeFactory - { - class TypeInfoWrapper : AbstractTypeInfo - { - - internal TypeInfoWrapper(Type type) - : base(type) - { - } - - public override Type BaseType - { - get { return this._type.BaseType; } - } - - public override FieldInfo GetField(string name) - { - return this._type.GetField(name); - } - - public override Type GetInterface(string name) - { - return this._type.GetInterfaces().FirstOrDefault(x => (x.Namespace + "." + x.Name) == name); - } - - public override Type[] GetInterfaces() - { - return this._type.GetInterfaces(); - } - - public override IEnumerable GetProperties() - { - return this._type.GetProperties(); - } - - public override IEnumerable GetFields() - { - return this._type.GetFields(); - } - - public override MemberInfo[] GetMembers() - { - return this._type.GetMembers(); - } - - public override bool IsClass - { - get { return this._type.IsClass; } - } - - public override bool IsValueType - { - get { return this._type.IsValueType; } - } - - public override bool IsInterface - { - get { return this._type.IsInterface; } - } - - public override bool IsAbstract - { - get { return this._type.IsAbstract; } - } - - public override bool IsSealed - { - get { return this._type.IsSealed; } - } - - public override bool IsEnum - { - get { return this._type.IsEnum; } - } - - public override MethodInfo GetMethod(string name) - { - return this._type.GetMethod(name); - } - - public override MethodInfo GetMethod(string name, ITypeInfo[] paramTypes) - { - Type[] types = new Type[paramTypes.Length]; - for (int i = 0; i < paramTypes.Length; i++) - types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; - return this._type.GetMethod(name, types); - } - - public override ConstructorInfo GetConstructor(ITypeInfo[] paramTypes) - { - Type[] types = new Type[paramTypes.Length]; - for (int i = 0; i < paramTypes.Length; i++) - types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; - var constructor = this._type.GetConstructor(types); - return constructor; - } - - public override PropertyInfo GetProperty(string name) - { - return this._type.GetProperty(name); - } - - public override bool IsAssignableFrom(ITypeInfo typeInfo) - { - return this._type.IsAssignableFrom(((AbstractTypeInfo)typeInfo).Type); - } - - public override bool ContainsGenericParameters - { - get { return this._type.ContainsGenericParameters; } - } - - public override bool IsGenericTypeDefinition - { - get { return this._type.IsGenericTypeDefinition; } - } - - public override bool IsGenericType - { - get { return this._type.IsGenericType; } - } - - public override Type GetGenericTypeDefinition() - { - return this._type.GetGenericTypeDefinition(); - } - - public override Type[] GetGenericArguments() - { - return this._type.GetGenericArguments(); - } - - public override object[] GetCustomAttributes(bool inherit) - { - return this._type.GetCustomAttributes(inherit); - } - - public override object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit) - { - return this._type.GetCustomAttributes(((TypeInfoWrapper)attributeType)._type, inherit); - } - - public override Assembly Assembly - { - get { return this._type.Assembly; } - } - } - - } -} diff --git a/sdk/src/Core/Amazon.Util/Internal/_netstandard/TypeWrapper.netstandard.cs b/sdk/src/Core/Amazon.Util/Internal/_netstandard/TypeWrapper.netstandard.cs deleted file mode 100644 index 5c5b9125684d..000000000000 --- a/sdk/src/Core/Amazon.Util/Internal/_netstandard/TypeWrapper.netstandard.cs +++ /dev/null @@ -1,236 +0,0 @@ -/******************************************************************************* - * 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. - * ***************************************************************************** - * __ _ _ ___ - * ( )( \/\/ )/ __) - * /__\ \ / \__ \ - * (_)(_) \/\/ (___/ - * - * AWS SDK for .NET - * - */ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Reflection; -using System.Text; - -namespace Amazon.Util.Internal -{ - public static partial class TypeFactory - { - class TypeInfoWrapper : AbstractTypeInfo - { -#if NET8_0_OR_GREATER - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] -#endif - TypeInfo _typeInfo; - -#if NET8_0_OR_GREATER - internal TypeInfoWrapper([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) -#else - internal TypeInfoWrapper(Type type) -#endif - : base(type) - { - this._typeInfo = type.GetTypeInfo(); - } - - public override Type BaseType - { - get { return _typeInfo.BaseType; } - } - - public override Type GetInterface(string name) - { - return this._typeInfo.ImplementedInterfaces.FirstOrDefault(x => (x.Namespace + "." + x.Name) == name); - } - - public override Type[] GetInterfaces() - { - return this._typeInfo.ImplementedInterfaces.ToArray(); - } - - public override IEnumerable GetProperties() - { - return this._type.GetProperties(); - } - - public override IEnumerable GetFields() - { - return this._type.GetFields(); - } - - public override FieldInfo GetField(string name) - { - return this._type.GetField(name); - } - - public override MemberInfo[] GetMembers() - { - var members = GetMembers_Helper(this._typeInfo).Distinct().ToArray(); - return members; - } - private static readonly Type objectType = typeof(object); - private static bool IsBackingField(MemberInfo mi) - { - var isBackingField = mi.Name.IndexOf("k__BackingField", StringComparison.Ordinal) >= 0; - return isBackingField; - } - -#if NET8_0_OR_GREATER - private static IEnumerable GetMembers_Helper([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TypeInfo ti) -#else - private static IEnumerable GetMembers_Helper(TypeInfo ti) -#endif - - { - // Keep track of properties already returned. This makes sure properties that are overridden in sub classes are not returned back multiple times. - var processedProperties = new HashSet(); - Func alreadyProcessProperty = (member) => - { - return (member is PropertyInfo) && !processedProperties.Add(member.Name); - }; - - var members = ti.DeclaredMembers; - foreach (var member in members) - { - if (!IsBackingField(member) && !alreadyProcessProperty(member)) - yield return member; - } - - var baseType = ti.BaseType; - var isObject = (baseType == objectType); - if (baseType != null && !isObject) - { - var baseTi = baseType.GetTypeInfo(); - var baseMembers = GetMembers_Helper(baseTi).ToList(); - - foreach (var baseMember in baseMembers) - { - if(!alreadyProcessProperty(baseMember)) - { - yield return baseMember; - } - } - } - } - - public override bool IsClass - { - get { return this._typeInfo.IsClass; } - } - - public override bool IsValueType - { - get { return this._typeInfo.IsValueType; } - } - - public override bool IsInterface - { - get { return this._typeInfo.IsInterface; } - } - - public override bool IsAbstract - { - get { return this._typeInfo.IsAbstract; } - } - - public override bool IsSealed - { - get { return this._typeInfo.IsSealed; } - } - - public override bool IsEnum - { - get { return this._typeInfo.IsEnum; } - } - - public override MethodInfo GetMethod(string name) - { - return this._type.GetMethod(name); - } - - public override bool ContainsGenericParameters - { - get { return this._typeInfo.ContainsGenericParameters; } - } - - public override bool IsGenericTypeDefinition - { - get { return this._typeInfo.IsGenericTypeDefinition; } - } - - public override bool IsGenericType - { - get - { - return this._typeInfo.IsGenericType; - } - } - - public override Type GetGenericTypeDefinition() - { - return this._typeInfo.GetGenericTypeDefinition(); - } - - public override Type[] GetGenericArguments() - { - return this._typeInfo.GenericTypeArguments; - } - - public override MethodInfo GetMethod(string name, ITypeInfo[] paramTypes) - { - Type[] types = new Type[paramTypes.Length]; - for (int i = 0; i < paramTypes.Length; i++) - types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; - - return this._type.GetMethod(name, types); - } - - public override PropertyInfo GetProperty(string name) - { - return this._type.GetProperty(name); - } - - public override bool IsAssignableFrom(ITypeInfo typeInfo) - { - return this._typeInfo.IsAssignableFrom(((TypeInfoWrapper)typeInfo)._typeInfo); - } - - public override object[] GetCustomAttributes(bool inherit) - { - return CustomAttributeExtensions.GetCustomAttributes(this.Type.GetTypeInfo(), inherit).ToArray(); - } - - public override object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit) - { - return CustomAttributeExtensions.GetCustomAttributes(this.Type.GetTypeInfo(), attributeType.Type, inherit).ToArray(); - } - - public override Assembly Assembly - { - get { return this._typeInfo.Assembly; } - } - - public override ConstructorInfo GetConstructor(ITypeInfo[] paramTypes) - { - Type[] types = new Type[paramTypes.Length]; - for (int i = 0; i < paramTypes.Length; i++) - types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; - - return this._type.GetConstructor(types); - } - } - } -} diff --git a/sdk/src/Core/Amazon.Util/ProfileManager.cs b/sdk/src/Core/Amazon.Util/ProfileManager.cs deleted file mode 100644 index 7216800b010b..000000000000 --- a/sdk/src/Core/Amazon.Util/ProfileManager.cs +++ /dev/null @@ -1,1215 +0,0 @@ -/******************************************************************************* - * 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. - * ***************************************************************************** - * __ _ _ ___ - * ( )( \/\/ )/ __) - * /__\ \ / \__ \ - * (_)(_) \/\/ (___/ - * - * AWS SDK for .NET - */ -using Amazon.Runtime; -using Amazon.Runtime.Internal.Settings; -using Amazon.Runtime.Internal.Util; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; - -namespace Amazon.Util -{ - /// - /// This class allows profiles supporting AWS credentials and SAML-based authentication to be registered with - /// the SDK so that they can later be reference by a profile name. The credential profiles will be available - /// for use in the AWS Toolkit for Visual Studio and the AWS Tools for Windows PowerShell. - /// - /// The credentials are stored under the current users AppData folder encrypted using Windows Data Protection API. - /// - /// - /// To reference a profile from an application's App.config or Web.config use the AWSProfileName setting. - /// - /// <?xml version="1.0" encoding="utf-8" ?> - /// <configuration> - /// <appSettings> - /// <add key="AWSProfileName" value="development"/> - /// </appSettings> - /// </configuration> - /// - /// - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.NetSDKCredentialsFile, SharedCredentialsFile, or SAMLEndpointManager. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public static class ProfileManager - { - - // if a profile does not contain a profile type entry, we assume AWS credentials - public const string AWSCredentialsProfileType = "AWS"; - public const string SAMLRoleProfileType = "SAML"; - - public static bool IsAvailable - { - get { return UserCrypto.IsUserCryptAvailable; } - } - - /// - /// Registers an AWS credentials profile that can later be referenced by the profileName. - /// This profile will only be visible for the current user. - /// - /// Name given to the AWS credentials. - /// The AWS access key id - /// The AWS secret key - public static void RegisterProfile(string profileName, string accessKeyId, string secretKey) - { - AWSCredentialsProfile.Persist(profileName, accessKeyId, secretKey); - } - - /// - /// - /// Registers a role-based profile to be used with SAML authentication. The profile contains - /// details of the role to be assumed when AWS credentials are requested based on the role and - /// a reference to a SAML endpoint profile containing details of the endpoint to be called to - /// authenticate the user. - /// - /// - /// If user identity information is not supplied then the identity of the logged-in user will - /// be used when authenticaton is performed against the endpoint referenced in the SAML endpoint - /// profile. If identity is provided, no password information is stored in the role profile and - /// the user must supply the password for the identity prior to authentication with the endpoint. - /// - /// - /// Name to be assigned to the profile - /// - /// The name assigned to the endpoint settings, previously saved with RegisterSAMLEndpoint. - /// - /// - /// The arn of the role that the user wants to assume when using this profile. This - /// must be one of the set returned by the saml endpoint when the user authenticates. - /// - /// - /// Optional. By default the identity of the logged-in user will be used when authentication - /// is performed - the user will not be prompted to supply a password. By supplying a custom - /// identity for this parameter, the user will be prompted to supply the password for the - /// identity prior to authentication. - /// - public static void RegisterSAMLRoleProfile(string profileName, - string endpointName, - string roleArn, - string userIdentity) - { - RegisterSAMLRoleProfile(profileName, endpointName, roleArn, userIdentity, null); - } - - /// - /// - /// Registers a role-based profile to be used with SAML authentication. The profile contains - /// details of the role to be assumed when AWS credentials are requested based on the role and - /// a reference to a SAML endpoint profile containing details of the endpoint to be called to - /// authenticate the user. - /// - /// - /// If user identity information is not supplied then the identity of the logged-in user will - /// be used when authenticaton is performed against the endpoint referenced in the SAML endpoint - /// profile. If identity is provided, no password information is stored in the role profile and - /// the user must supply the password for the identity prior to authentication with the endpoint. - /// - /// - /// Name to be assigned to the profile - /// - /// The name assigned to the endpoint settings, previously saved with RegisterSAMLEndpoint. - /// - /// - /// The arn of the role that the user wants to assume when using this profile. This - /// must be one of the set returned by the saml endpoint when the user authenticates. - /// - /// - /// Optional. By default the identity of the logged-in user will be used when authentication - /// is performed - the user will not be prompted to supply a password. By supplying a custom - /// identity for this parameter, the user will be prompted to supply the password for the - /// identity prior to authentication. - /// - /// - /// Set for profiles intended to be used in regions where a region-specific STS endpoint - /// must be used (eg cn-north-1). If left empty/null, the global sts.amazonaws.com endpoint - /// will be used when credentials are obtained for this profile. - /// - public static void RegisterSAMLRoleProfile(string profileName, - string endpointName, - string roleArn, - string userIdentity, - string stsRegion) - { - SAMLRoleProfile.Persist(profileName, endpointName, roleArn, userIdentity, null, stsRegion); - } - - /// - /// Registers an endpoint to be used in conjunction with SAML role profiles. The role profiles - /// reference the endpoint settings to obtain the actual endpoint and any customization settings - /// needed to perform authentication. - /// - /// Name to be assigned to the endpoint settings. - /// The full uri of the authentication endpoint. - /// - /// The authentication type to use when performing calls against the endpoint. Valid values are 'NTLM', - /// 'Digest', 'Kerberos' and 'Negotiate'. The default if not configured (null/empty string) is 'Kerberos'. - /// - /// The unique id assigned to the new settings. - public static string RegisterSAMLEndpoint(string endpointName, - Uri endpoint, - string authenticationType) - { - return SAMLEndpointSettings.Persist(endpointName, endpoint, authenticationType); - } - - /// - /// Deletes the settings for an AWS credentials or SAML role profile from the SDK account store. - /// - /// The name of the profile to remove. - public static void UnregisterProfile(string profileName) - { - var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); - var os = ReadProfileSettings(settings, profileName); - if (os != null) - { - settings.Remove(os.UniqueKey); - PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, settings); - } - } - - /// - /// Lists all profile names registered with the SDK account store. - /// - /// The profile names. - public static IEnumerable ListProfileNames() - { - var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); - return settings.Select(os => os.GetValueOrDefault(SettingsConstants.DisplayNameField, null)).ToList(); - } - - /// - /// Loads and returns all available credential profiles registered in the store. - /// - /// Collection of profiles. - public static IEnumerable ListProfiles() - { - var profiles = new List(); - var profileNames = ListProfileNames(); - foreach (var profileName in profileNames) - { - try - { - if (SAMLRoleProfile.CanCreateFrom(profileName)) - profiles.Add(SAMLRoleProfile.LoadFrom(profileName)); - else if (AWSCredentialsProfile.CanCreateFrom(profileName)) - profiles.Add(AWSCredentialsProfile.LoadFrom(profileName)); - } - catch (Exception e) - { - Logger.GetLogger(typeof(ProfileManager)).Error(e, "Error loading AWS credential or SAML role profile '{0}'", profileName); - } - } - - return profiles; - } - - /// - /// Checks if a given profile is known in the SDK credential store. - /// - /// The name of the profile to test for existence - /// True if the profile exists. - public static bool IsProfileKnown(string profileName) - { - return (ReadProfileSettings(profileName) != null); - } - - /// - /// Copies the contents of the source profile to the destination. If the destination - /// profile does not exist a new profile is created. Note that if the destination - /// profile exists, all keys it contains are removed and replaced with keys from the - /// source profile. - /// - /// The name of the profile to copy from. - /// The name of the profile to create or update. - /// The unique id assigned to the destination settings. - public static string CopyProfileSettings(string sourceProfileName, string destinationProfileName) - { - var sourceSettings = ReadProfileSettings(sourceProfileName); - if (sourceSettings == null) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "An AWS credentials or SAML role profile with name '{0}' could not be found.", sourceProfileName)); - - return CopyProfileSettings(sourceSettings, destinationProfileName); - } - - /// - /// Copies the contents of the source profile to the destination. If the destination - /// profile does not exist a new profile is created. Note that if the destination - /// profile exists, all keys it contains are removed and replaced with keys from the - /// source profile. - /// - /// The source profile to copy keys and values from. - /// The name of the profile to create or update. - /// The unique id assigned to the destination settings. - public static string CopyProfileSettings(SettingsCollection.ObjectSettings source, string destinationProfileName) - { - var allSettings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); - var destination = ReadProfileSettings(allSettings, destinationProfileName); - // overwrite with new object if dest exists, not merge, otherwise we can potentially mix credential - // profile types - if (destination == null) - destination = allSettings.NewObjectSettings(Guid.NewGuid().ToString()); - else - destination = allSettings.NewObjectSettings(destination.UniqueKey); - - destination[SettingsConstants.DisplayNameField] = destinationProfileName; - foreach (var k in source.Keys) - { - if (!k.Equals(SettingsConstants.DisplayNameField)) - destination[k] = source[k]; - } - - PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, allSettings); - - return destination.UniqueKey; - } - - /// - /// Tries to get the AWS credentials from a profile in the SDK account store. - /// - /// The profile to get the credentials for. - /// Outputs the credentials for the profile. - /// Returns true if the profile exists otherwise false is returned. - public static bool TryGetAWSCredentials(string profileName, out AWSCredentials credentials) - { - credentials = null; - - try - { - AWSCredentialsProfile profile; - if (TryGetProfile(profileName, out profile)) - credentials = profile.Credentials; - } - catch (Exception e) - { - Logger.GetLogger(typeof(ProfileManager)).Error(e, "Error loading AWS credentials from profile {0}", profileName); - } - - return credentials != null; - } - - /// - /// Gets the AWS credentials from a profile in the SDK account store. - /// - /// The profile to get the credentials for. - /// The AWS credentials for the profile. - /// Thrown if the profile does not exist - public static AWSCredentials GetAWSCredentials(string profileName) - { - AWSCredentialsProfile profile; - if (TryGetProfile(profileName, out profile)) - return profile.Credentials; - - throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A profile named {0} has not been registered or contains invalid data.", profileName)); - } - - /// - /// Returns the profile with the specified name, if it has been registered in the SDK store. - /// - /// The name of the registered profile - /// The loaded profile data - public static ProfileSettingsBase GetProfile(string profileName) - { - if (!IsProfileKnown(profileName)) - throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A profile named {0} has not been registered.", profileName)); - - var profile = GetProfile(profileName) ?? (ProfileSettingsBase) GetProfile(profileName); - if (profile == null) - throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A profile named {0} was found but could not be loaded.", profileName)); - - return profile; - } - - /// - /// Returns the persisted data in the SDK store as a profile of the specified type T. - /// - /// The name of the profile holding the settings. - /// The loaded profile. An exception is thrown if the profile could not be loaded. - /// Thrown if the profile does not exist - /// - /// Currently supported profile types: AWSCredentialsProfile and SAMLRoleProfile. - /// - public static T GetProfile(string profileName) where T : ProfileSettingsBase - { - if (typeof(T) == typeof(AWSCredentialsProfile)) - return AWSCredentialsProfile.LoadFrom(profileName) as T; - - if (typeof(T) == typeof(SAMLRoleProfile)) - return SAMLRoleProfile.LoadFrom(profileName) as T; - - throw new ArgumentException("Unrecognized profile type parameter"); - } - - /// - /// Tries to load the specified profile data corresponding to profile type T from a named - /// profile in the SDK account store. - /// - /// The name of the profile holding the settings. - /// The loaded profile data. - /// Returns true if the profile exists otherwise false is returned. - /// - /// Currently supported profile types: AWSCredentialsProfile and SAMLRoleProfile. - /// - public static bool TryGetProfile(string profileName, out T profile) where T : ProfileSettingsBase - { - profile = null; - - try - { - if (typeof(T) == typeof(AWSCredentialsProfile)) - profile = AWSCredentialsProfile.LoadFrom(profileName) as T; - else if (typeof(T) == typeof(SAMLRoleProfile)) - profile = SAMLRoleProfile.LoadFrom(profileName) as T; - else - throw new ArgumentException("Unrecognized profile type parameter", (typeof(T).FullName)); - } - catch (Exception e) - { - Logger.GetLogger(typeof(ProfileManager)).Error(e, "Unable to load profile {0}, unknown profile, missing/invalid data or unrecognized profile type.", profileName); - } - - return profile != null; - } - - /// - /// Attempts to load the settings defining a SAML endpoint. - /// - /// The name assigned to the settings for the endpoint. - /// The instantiated endpoint. - /// True if the settings were successfully loaded. - public static bool TryGetSAMLEndpoint(string endpointName, out SAMLEndpointSettings endpointSettings) - { - endpointSettings = null; - - try - { - endpointSettings = SAMLEndpointSettings.LoadFrom(endpointName); - } - catch (Exception e) - { - Logger.GetLogger(typeof(ProfileManager)).Error(e, "Unable to load SAML endpoint profile '{0}', unknown profile or missing/invalid data.", endpointName); - } - - return endpointSettings != null; - } - - /// - /// Loads the settings defining a SAML endpoint. - /// - /// The name assigned to the settings for the endpoint. - /// The loaded settings. An exception is thrown if they could not be loaded. - /// Thrown if the endpoint settings do not exist. - public static SAMLEndpointSettings GetSAMLEndpoint(string endpointName) - { - SAMLEndpointSettings endpointSettings; - if (!TryGetSAMLEndpoint(endpointName, out endpointSettings)) - throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A SAML endpoint profile with name {0} has not been registered or is invalid.", endpointName)); - - return endpointSettings; - } - - internal static SettingsCollection.ObjectSettings ReadProfileSettings(string profileName) - { - var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); - return ReadProfileSettings(settings, profileName); - } - - internal static SettingsCollection.ObjectSettings ReadProfileSettings(SettingsCollection settings, string profileName) - { - return settings.FirstOrDefault(x => string.Equals(x[SettingsConstants.DisplayNameField], profileName, StringComparison.OrdinalIgnoreCase)); - } - - internal static SettingsCollection.ObjectSettings ReadSettings(SettingsCollection settings, string settingsKey) - { - return settings.FirstOrDefault(x => string.Equals(x.UniqueKey, settingsKey, StringComparison.OrdinalIgnoreCase)); - } - } - - /// - /// Common base contract for all types of credential and role profiles. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.CredentialProfile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public abstract class ProfileSettingsBase - { - /// - /// The user-defined name for the settings. - /// - public string Name { get; protected set; } - - /// - /// The unique id of the profile in the backing store. - /// - public string UniqueId { get; protected set; } - - /// - /// Saves the profile data to backing store, returning the unique id - /// assigned to the data. - /// - public abstract string Persist(); - - protected static SettingsCollection.ObjectSettings LoadCredentialsProfile(string profileName) - { - var os = ProfileManager.ReadProfileSettings(profileName); - if (os == null) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "An AWS credentials or SAML role profile with name '{0}' could not be found.", profileName)); - - return os; - } - } - - /// - /// The persisted data for a set of AWS credentials. At a minimum this - /// is access key and secret key data. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.CredentialProfile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public class AWSCredentialsProfile : ProfileSettingsBase - { - public BasicAWSCredentials Credentials { get; private set; } - - /// - /// Tests if an AWSCredentialsProfile instance could be instantiated from - /// the persisted settings data. - /// - /// The name given to the persisted settings (previously verified as existing). - /// True if the settings are compatible with an AWSCredentialsProfile type. - public static bool CanCreateFrom(string profileName) - { - var os = LoadCredentialsProfile(profileName); - return CanCreateFrom(os); - } - - /// - /// Tests if an AWSCredentialsProfile instance could be instantiated from - /// the persisted settings data. - /// - /// The persisted settings. - /// True if the settings are compatible with an AWSCredentialsProfile type. - public static bool CanCreateFrom(SettingsCollection.ObjectSettings os) - { - var osProfileType = os.GetValueOrDefault(SettingsConstants.ProfileTypeField, null); - // legacy AWS profiles will not have the type key present - if (osProfileType == null || osProfileType.Equals(ProfileManager.AWSCredentialsProfileType, StringComparison.OrdinalIgnoreCase)) - { - try - { - Validate(os); - return true; - } - catch (InvalidDataException) - { - var msg = (string.Format(CultureInfo.InvariantCulture, - "Profile '{0}' indicates AWS credential type but does not contain AWS credential key materials", - os[SettingsConstants.DisplayNameField])); - Logger.GetLogger(typeof(AWSCredentialsProfile)).InfoFormat(msg); - } - } - - return false; - } - - /// - /// Instantiates an AWSCredentialsProfile instance from the specified profile name. - /// - /// The name of the profile holding the settings. - /// New credentials profile instance. An exception is thrown if the profile data is invalid. - public static AWSCredentialsProfile LoadFrom(string profileName) - { - var os = LoadCredentialsProfile(profileName); - return LoadFrom(os); - } - - /// - /// Instantiates an AWSCredentialsProfile instance from the supplied settings collection. - /// - /// The settings representing the stored profile. - /// New credentials profile instance. An exception is thrown if the profile data is invalid. - public static AWSCredentialsProfile LoadFrom(SettingsCollection.ObjectSettings os) - { - if (os == null) - throw new ArgumentNullException("os"); - - if (!CanCreateFrom(os)) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, - "Profile '{0}' does not contain AWS credential materials", - os[SettingsConstants.DisplayNameField])); - - Validate(os); - - var accessKeyId = os.GetValueOrDefault(SettingsConstants.AccessKeyField, null); - var secretkey = os.GetValueOrDefault(SettingsConstants.SecretKeyField, null); - - return new AWSCredentialsProfile(os[SettingsConstants.DisplayNameField], accessKeyId, secretkey); - } - - /// - /// Validates the contents of the specified profile. - /// - /// The name of the AWS credentials profile to validate. - /// Thrown if the profile settings fail to validate. - public static void Validate(string profileName) - { - var os = LoadCredentialsProfile(profileName); - Validate(os); - } - - /// - /// Verifies that the persisted settings contains the minimal viable data to - /// instantiate an AWSCredentialsProfile instance. - /// - /// The persisted settings. - /// Thrown if the profile settings fail to validate. - private static void Validate(SettingsCollection.ObjectSettings os) - { - var accessKeyId = os.GetValueOrDefault(SettingsConstants.AccessKeyField, null); - if (accessKeyId == null) - throw new InvalidDataException("Missing or invalid access key value in the profile settings."); - - var secretkey = os.GetValueOrDefault(SettingsConstants.SecretKeyField, null); - if (secretkey == null) - throw new InvalidDataException("Missing or invalid secret key value in the profile settings."); - } - - /// - /// Persists the profile data to the store file. - /// - /// The unique ID assigned to the settings. - public override string Persist() - { - return Persist(Name, Credentials.GetCredentials().AccessKey, Credentials.GetCredentials().SecretKey); - } - - /// - /// Creates or updates the profile data in the store file. - /// - /// The unique ID assigned to the settings. - public static string Persist(string profileName, string accessKeyId, string secretKey) - { - var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); - var os = ProfileManager.ReadProfileSettings(settings, profileName); - if (os == null) - os = settings.NewObjectSettings(Guid.NewGuid().ToString()); - - os[SettingsConstants.ProfileTypeField] = ProfileManager.AWSCredentialsProfileType; - os[SettingsConstants.DisplayNameField] = profileName; - os[SettingsConstants.AccessKeyField] = accessKeyId; - os[SettingsConstants.SecretKeyField] = secretKey; - - PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, settings); - - return os.UniqueKey; - } - - private AWSCredentialsProfile(string profileName, string accessKeyId, string secretKey) - { - Name = profileName; - Credentials = new BasicAWSCredentials(accessKeyId, secretKey); - } - } - - /// - /// The persisted data for a SAML endpoint. One or more role profiles - /// will reference this to obtain the common endpoint and other data needed - /// to perform authentication with a set of user credentials. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.SAMLEndpoint. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public class SAMLEndpointSettings : ProfileSettingsBase - { - /// - /// The default authentication type to use when attempting to perform an - /// authentication call against the configured endpoint. - /// - public static readonly string DefaultAuthenticationType = "Kerberos"; - - /// - /// The authentication endpoint which must be a HTTPS scheme. - /// - public Uri Endpoint { get; private set; } - - private string _authenticationType = null; - - /// - /// The authentication type to use when calling the endpoint. - /// - public string AuthenticationType - { - get - { - return string.IsNullOrEmpty(_authenticationType) ? DefaultAuthenticationType : _authenticationType; - } - } - - /// - /// Tests if a SAMLEndpointSettings instance could be instantiated from - /// the persisted settings data. - /// - /// The name given to the persisted settings. - /// True if the settings are compatible. - public static bool CanCreateFrom(string endpointName) - { - var os = LoadSettings(endpointName); - return CanCreateFrom(os); - } - - /// - /// Tests if a SAMLEndpointSettings instance could be instantiated from - /// the persisted settings data. - /// - /// The persisted settings. - /// True if the settings are compatible. - public static bool CanCreateFrom(SettingsCollection.ObjectSettings os) - { - var endpoint = os.GetValueOrDefault(SettingsConstants.EndpointField, null); - return !string.IsNullOrEmpty(endpoint); - } - - /// - /// Instantiates an instance from settings stored with the specified name. - /// - /// The name of the endpoint settings in the store. - /// Profile instance or an exception if the profile data does not exist/contains invalid data. - public static SAMLEndpointSettings LoadFrom(string endpointName) - { - var os = LoadSettings(endpointName); - return LoadFrom(os); - } - - /// - /// Instantiates an instance from the supplied settings. - /// - /// The persisted settings. - /// Profile instance or an exception if the profile data is invalid. - public static SAMLEndpointSettings LoadFrom(SettingsCollection.ObjectSettings os) - { - if (os == null) - throw new ArgumentNullException("os"); - - if (!CanCreateFrom(os)) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Endpoint settings '{0}' does not contain SAML endpoint materials", os[SettingsConstants.DisplayNameField])); - - Validate(os); - - var endpoint = os.GetValueOrDefault(SettingsConstants.EndpointField, null); - string authenticationType = os.GetValueOrDefault(SettingsConstants.AuthenticationTypeField, null); - - return new SAMLEndpointSettings(os[SettingsConstants.DisplayNameField], new Uri(endpoint, UriKind.RelativeOrAbsolute), authenticationType); - } - - /// - /// Validates the contents of the specified endpoint settings. - /// - /// The name of the SAML endpoint settings to validate. - /// Thrown if the settings fail to validate. - public static void Validate(string endpointName) - { - var os = LoadSettings(endpointName); - Validate(os); - } - - /// - /// Verifies that the persisted settings contains the minimal viable data to - /// instantiate a SAMLEndpointSettings instance. - /// - /// The persisted settings. - /// Thrown if the settings fail to validate. - private static void Validate(SettingsCollection.ObjectSettings os) - { - var endpoint = os.GetValueOrDefault(SettingsConstants.EndpointField, null); - if (endpoint == null) - throw new InvalidDataException("Missing endpoint value in the profile settings."); - - try - { - var u = new Uri(endpoint); - if (!string.Equals(u.Scheme, "https", StringComparison.OrdinalIgnoreCase)) - throw new InvalidDataException("The scheme of the endpoint must be HTTPS."); - } - catch (UriFormatException e) - { - throw new InvalidDataException("The configured endpoint is not valid.", e); - } - } - - /// - /// Persists the settings to the storage file. - /// - /// The unique id assigned to the profile - public override string Persist() - { - return Persist(Name, Endpoint, AuthenticationType); - } - - /// - /// Creates or updates the settings data for a SAML endpoint in the backing store file. An error is - /// thrown if the scheme for the endpoint is not https. - /// - /// The name of the settings to create or update - /// The authentication endpoint - /// Optional authentication type to use when performing calls against the endpoint - /// The unique id assigned to the profile - public static string Persist(string settingsName, Uri endpoint, string authenticationType) - { - if (!string.Equals(endpoint.Scheme, "https", StringComparison.OrdinalIgnoreCase)) - throw new AmazonClientException("Endpoint uri is not Https protocol."); - - var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredSAMLEndpoints); - var os = ProfileManager.ReadProfileSettings(settings, settingsName); - if (os == null) - os = settings.NewObjectSettings(Guid.NewGuid().ToString()); - - os[SettingsConstants.EndpointField] = endpoint.ToString(); - os[SettingsConstants.DisplayNameField] = settingsName; - - if (!string.IsNullOrEmpty(authenticationType) && !authenticationType.Equals(DefaultAuthenticationType, StringComparison.OrdinalIgnoreCase)) - os[SettingsConstants.AuthenticationTypeField] = authenticationType; - - PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredSAMLEndpoints, settings); - - return os.UniqueKey; - } - - /// - /// Constructs an endpoint settings instance. - /// - /// The user-defined name to assign to the settings. - /// - /// The absolute uri, including any query and relyingParty data, of the endpoint. - /// - /// - /// The authentication type to use when performing requests against the endpoint. - /// - private SAMLEndpointSettings(string settingsName, Uri endpoint, string authenticationType) - { - Name = settingsName; - Endpoint = endpoint; - if (!string.IsNullOrEmpty(authenticationType)) - _authenticationType = authenticationType; - } - - private static SettingsCollection.ObjectSettings LoadSettings(string endpointName) - { - var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredSAMLEndpoints); - var os = ProfileManager.ReadProfileSettings(settings, endpointName); - if (os == null) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "SAML endpoint settings with name '{0}' could not be found.", endpointName)); - - return os; - } - } - - /// - /// - /// The persisted data for a saml role profile for a user. This profile - /// references an endpoint profile containing the actual endpoint to be used, and - /// adds details of the role to be assumed when the profile is selected. - /// - /// - /// Optionally the profile can store a username and domain to be used during - /// authentication (default behavior, if this is not specified, is to use the user's - /// default network credentials). - /// - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialProfile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public class SAMLRoleProfile : ProfileSettingsBase - { - private object _synclock = new object(); - - /// - /// The ARN of the role that is to be assumed. - /// - public string RoleArn { get; internal set; } - - /// - /// If non-default network credentials are to used contains - /// the user identity (in domain\user format, domain optional) that - /// should be used to supply credentials when the profile is used in - /// authentication. The user must be prompted to supply the - /// corresponding password prior to authentication. - /// - public string UserIdentity { get; internal set; } - - /// - /// If a specific user identity was specified in the profile, - /// returns true to indicate a password needs to be obtained from - /// the user before obtaining network credentials to be used on - /// authentication. The default is to use the credentials - /// associated with the currently logged-in user or process to - /// perform authentication, which does not require the user to be - /// prompted. - /// - public bool UseDefaultUserIdentity - { - get - { - return string.IsNullOrEmpty(UserIdentity); - } - } - - /// - /// - /// For regions with a region-specific endpoint for STS (eg cn-north-1) this - /// field can be set to ensure calls to obtain temporary credentials - /// after successful authentication are forwarded to the correct regional - /// endpoint. - /// - /// - /// This field does not need to be set when running in a region for - /// which the sts.amazonaws.com endpoint is valid. - /// - /// - public string Region { get; private set; } - - private SAMLImmutableCredentials _session = null; - - /// - /// Retrieves the active credential session, if any, associated with the - /// role profile. - /// - /// - /// The current credentials valid for the role specified in the profile. Returns - /// null if no active session is available, or the active session has expired. - /// - /// - /// When a user successfully authenticates and receives temporary AWS - /// credentials for a role, the profile is updated with details of the - /// session. When the profile is loaded by other processes or tools, if - /// session data is present and still valid it can be retrieved using this - /// method avoiding the need to re-authenticate and get additional temporary - /// credentials. - /// - public SAMLImmutableCredentials GetCurrentSession() - { - SAMLImmutableCredentials session = null; - lock (_synclock) - { - if (_session != null && _session.Expires <= AWSSDKUtils.CorrectedUtcNow) - { - UpdateProfileSessionData(null); - _session = null; - } - - session = _session; - } - - return session; - } - - /// - /// Persists the current credentials to a 'session' key in the RoleSessions.json file. - /// This enables external applications and tools using the same profile to obtain credentials - /// without needing to separately re-authenticate the user prior to expiry of the current - /// credentials. After persisting the session data it can be retrieved using GetCurrentSession(). - /// - /// - /// Although the credentials are temporary we still encrypt the stored data when at rest in - /// the sdk credential store. - /// - /// - /// The current credentials valid for the role specified in the profile. - /// - public void PersistSession(SAMLImmutableCredentials credentials) - { - lock (_synclock) - { - UpdateProfileSessionData(credentials); - _session = credentials; - } - } - - /// - /// Stores or clears the persisted session data. - /// - /// - private void UpdateProfileSessionData(SAMLImmutableCredentials credentials) - { - string sessionData = null; - if (credentials != null) - sessionData = credentials.ToJson(); - - Persist(sessionData); - } - - /// - /// The endpoint settings from which the actual endpoint to use in authentication - /// is obtained. - /// - public SAMLEndpointSettings EndpointSettings { get; internal set; } - - /// - /// Tests if a SAMLRoleProfile instance could be instantiated from - /// the persisted settings data. - /// - /// The name given to the persisted settings. - /// True if the settings are compatible with a SAMLRoleProfile type. - public static bool CanCreateFrom(string profileName) - { - var os = LoadCredentialsProfile(profileName); - return CanCreateFrom(os); - } - - /// - /// Tests if a SAMLRoleProfile instance could be instantiated from - /// the persisted settings data. - /// - /// The persisted settings. - /// True if the settings are compatible with a SAMLRoleProfile type. - public static bool CanCreateFrom(SettingsCollection.ObjectSettings os) - { - var osProfileType = os.GetValueOrDefault(SettingsConstants.ProfileTypeField, null); - return osProfileType != null && osProfileType.Equals(ProfileManager.SAMLRoleProfileType, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Instantiates an instance from settings stored with the specified name. - /// - /// The name of the endpoint profile. - /// Profile instance or an exception if the profile data does not exist/contains invalid data. - public static SAMLRoleProfile LoadFrom(string profileName) - { - var os = LoadCredentialsProfile(profileName); - return LoadFrom(os); - } - - /// - /// Instantiates an instance from the supplied settings. In addition to the profile settings - /// the SDK will inspect for a RoleSessions.json file containing active session data and if - /// an entry for the profile is present, will add the session data to the returned profile - /// object. - /// - /// The persisted settings. - /// Profile instance or an exception if the profile data is invalid. - public static SAMLRoleProfile LoadFrom(SettingsCollection.ObjectSettings os) - { - if (os == null) - throw new ArgumentNullException("os"); - - if (!CanCreateFrom(os)) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Profile '{0}' does not contain SAML role materials", os[SettingsConstants.DisplayNameField])); - - Validate(os); - - var endpointName = os[SettingsConstants.EndpointNameField]; - var endpointSettings = ProfileManager.GetSAMLEndpoint(endpointName); - - var profileName = os[SettingsConstants.DisplayNameField]; - var roleArn = os[SettingsConstants.RoleArnField]; - var userIdentity = os.GetValueOrDefault(SettingsConstants.UserIdentityField, null); - var region = os.GetValueOrDefault(SettingsConstants.Region, null); - - SAMLImmutableCredentials activeCredentials = LoadActiveSessionCredentials(profileName); - - return new SAMLRoleProfile(profileName, endpointSettings, roleArn, userIdentity, activeCredentials, region); - } - - /// - /// Validates the contents of the specified profile. - /// - /// The name of the SAML role profile to validate. - /// Thrown if the profile settings fail to validate. - public static void Validate(string profileName) - { - var os = LoadCredentialsProfile(profileName); - Validate(os); - } - - /// - /// Validates that the presented settings would result in a valid role profile - /// instance. - /// - /// The persisted settings. - /// Thrown if the profile settings fail to validate. - private static void Validate(SettingsCollection.ObjectSettings os) - { - var endpointName = os.GetValueOrDefault(SettingsConstants.EndpointNameField, null); - if (endpointName == null) - throw new InvalidDataException("Missing EndpointName data."); - - SAMLEndpointSettings endpointSettings; - if (!ProfileManager.TryGetSAMLEndpoint(endpointName, out endpointSettings)) - throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "Endpoint settings with the name '{0}' could not be found.", endpointName)); - - if (string.IsNullOrEmpty(os[SettingsConstants.RoleArnField])) - throw new InvalidDataException("Missing role ARN data."); - } - - /// - /// Stores the data in the role profile to the backing store file. - /// - public override string Persist() - { - return Persist(Name, EndpointSettings.Name, RoleArn, UserIdentity, null, Region); - } - - private string Persist(string session) - { - return Persist(Name, EndpointSettings.Name, RoleArn, UserIdentity, session, Region); - } - - /// - /// - /// Registers a role-based profile to be used with SAML authentication. The profile contains - /// details of the role to be assumed when AWS credentials are requested based on the role and - /// a reference to a SAML endpoint profile containing details of the endpoint to be called to - /// authenticate the user. - /// - /// - /// If user identity information is not supplied then the identity of the logged-in user will - /// be used when authenticaton is performed against the endpoint referenced in the SAML endpoint - /// profile. If identity is provided, no password information is stored in the role profile and - /// the user must supply the password for the identity prior to authentication with the endpoint. - /// - /// - /// Name to be assigned to the profile - /// - /// The name of the settings in the SAML endpoints file containing details of the - /// endpoint to authenticate with. - /// - /// - /// The arn of the role that the user wants to assume when using this profile. This - /// must be one of the set returned by the saml endpoint when the user authenticates. - /// - /// - /// Optional, can be used to prompt the user for a password for the account when authentication - /// is performed from a system that is not domain-joined. - /// - /// - /// Optional, details of the currently active credentials for the role that we want to - /// persist into the profile for other tools or processes to pick up, avoiding the need - /// to continually re-authenticate the user as they switch between tools. The active session, - /// if any, is stored separately from the profile using the file RoleSessions.json. - /// - /// - /// Set for profiles intended to be used in regions where a region-specific STS endpoint - /// must be used (eg cn-north-1). If left empty/null, the global sts.amazonaws.com endpoint - /// will be used when credentials are obtained for this profile. - /// - /// The unique id assigned to the profile. - public static string Persist(string profileName, - string endpointSettingsName, - string roleArn, - string userIdentity, - string session, - string region) - { - if (string.IsNullOrEmpty(profileName) || string.IsNullOrEmpty(endpointSettingsName) || string.IsNullOrEmpty(roleArn)) - throw new ArgumentException("Profile name, endpoint settings name and role ARN must be supplied."); - - SAMLEndpointSettings endpointSettings; - if (!ProfileManager.TryGetSAMLEndpoint(endpointSettingsName, out endpointSettings)) - { - var msg = string.Format(CultureInfo.CurrentCulture, "Failed to load SAML endpoint settings with name {0}", endpointSettingsName); - throw new ArgumentException(msg); - } - - var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); - var os = ProfileManager.ReadProfileSettings(settings, profileName); - if (os == null) - os = settings.NewObjectSettings(Guid.NewGuid().ToString()); - - os[SettingsConstants.ProfileTypeField] = ProfileManager.SAMLRoleProfileType; - os[SettingsConstants.DisplayNameField] = profileName; - os[SettingsConstants.EndpointNameField] = endpointSettings.Name; - os[SettingsConstants.RoleArnField] = roleArn; - os[SettingsConstants.UserIdentityField] = userIdentity; - if (!string.IsNullOrEmpty(region)) - os[SettingsConstants.Region] = region; - - PersistActiveSessionCredentials(profileName, session); - - PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, settings); - - return os.UniqueKey; - } - - /// - /// Tests for and loads any active session credentials for the specified profile. The session data - /// exists in a separate file from the profile, RoleSessions.json. - /// - /// - /// - private static SAMLImmutableCredentials LoadActiveSessionCredentials(string profileName) - { - SAMLImmutableCredentials sessionCredentials = null; - - var roleSessions = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredRoleSessions); - if (roleSessions != null) - { - var settings = ProfileManager.ReadSettings(roleSessions, profileName); - if (settings != null) - { - var roleSession = settings[SettingsConstants.RoleSession]; - sessionCredentials = SAMLImmutableCredentials.FromJson(roleSession); - } - } - - return sessionCredentials; - } - - /// - /// Stores the supplied session data into the RoleSessions.json backing file. - /// - /// - /// - private static void PersistActiveSessionCredentials(string profileName, string session) - { - var roleSessions = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredRoleSessions); - if (string.IsNullOrEmpty(session) && roleSessions == null) - return; - - var settings = ProfileManager.ReadSettings(roleSessions, profileName); - if (settings == null) - settings = roleSessions.NewObjectSettings(profileName); - - settings[SettingsConstants.RoleSession] = session; - PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredRoleSessions, roleSessions); - } - - /// - /// Constructs a profile data instance that will use the specified network identity - /// during authentication with configured endpoint. - /// - /// The user-defined name of the profile that sourced this data. - /// The settings for the authentication endpoint. - /// The role that should be assumed on successful authentication. - /// The credentials to supply in authentication, in domain\user format. - /// - /// Deserialized credential data from the profile, if still valid. Null if the profile does not - /// contain any active credentials, or the credentials it did hold are now invalid. - /// - /// - /// Set for profiles intended to be used in regions where a region-specific STS endpoint - /// must be used (eg cn-north-1). If left empty/null, the global sts.amazonaws.com endpoint - /// will be used when credentials are obtained for this profile. - /// - private SAMLRoleProfile(string profileName, - SAMLEndpointSettings endpointSettings, - string roleArn, - string userIdentity, - SAMLImmutableCredentials currentSession, - string region) - { - Name = profileName; - EndpointSettings = endpointSettings; - RoleArn = roleArn; - UserIdentity = userIdentity; - _session = currentSession; - Region = region; - } - - } -} diff --git a/sdk/src/Services/EC2/Custom/AmazonEC2Client.Extensions.cs b/sdk/src/Services/EC2/Custom/AmazonEC2Client.Extensions.cs index a5b22570243e..b1c10f012355 100644 --- a/sdk/src/Services/EC2/Custom/AmazonEC2Client.Extensions.cs +++ b/sdk/src/Services/EC2/Custom/AmazonEC2Client.Extensions.cs @@ -95,9 +95,7 @@ private void SetDryRunParameterCallback(object sender, RequestEventArgs args) WebServiceRequestEventArgs wsrea = args as WebServiceRequestEventArgs; if (wsrea != null) { -#pragma warning disable CS0612,CS0618 - wsrea.Parameters["DryRun"] = "true"; -#pragma warning restore CS0612,CS0618 + wsrea.ParameterCollection["DryRun"] = new StringParameterValue("true"); } } } diff --git a/sdk/src/Services/ImportExport/AWSSDK.ImportExport.NetStandard.csproj b/sdk/src/Services/ImportExport/AWSSDK.ImportExport.NetStandard.csproj index f09b275f8675..be4555e8c1bc 100644 --- a/sdk/src/Services/ImportExport/AWSSDK.ImportExport.NetStandard.csproj +++ b/sdk/src/Services/ImportExport/AWSSDK.ImportExport.NetStandard.csproj @@ -20,7 +20,8 @@ false false true - true + true + CA1822 diff --git a/sdk/src/Services/S3/Custom/_async/AmazonS3Client.Extensions.cs b/sdk/src/Services/S3/Custom/_async/AmazonS3Client.Extensions.cs index 3b20b449551f..80849418440a 100644 --- a/sdk/src/Services/S3/Custom/_async/AmazonS3Client.Extensions.cs +++ b/sdk/src/Services/S3/Custom/_async/AmazonS3Client.Extensions.cs @@ -148,11 +148,6 @@ Task ICoreAmazonS3.EnsureBucketExistsAsync(string bucketName) return this.PutBucketAsync(bucketName); } - [Obsolete("This method is deprecated: its behavior is inconsistent and always uses HTTP. Please use Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async instead.")] - Task ICoreAmazonS3.DoesS3BucketExistAsync(string bucketName) - { - return Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistAsync(this, bucketName); - } #endregion } } diff --git a/sdk/src/Services/SecurityToken/Custom/_bcl/SAML/StoredProfileSAMLCredentials.cs b/sdk/src/Services/SecurityToken/Custom/_bcl/SAML/StoredProfileSAMLCredentials.cs deleted file mode 100644 index 011529ae93be..000000000000 --- a/sdk/src/Services/SecurityToken/Custom/_bcl/SAML/StoredProfileSAMLCredentials.cs +++ /dev/null @@ -1,391 +0,0 @@ -/* - * 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 System; -using System.Globalization; -using System.Net; - -using Amazon.Runtime; -using Amazon.Runtime.Internal.Util; -using Amazon.Util; - -namespace Amazon.SecurityToken.SAML -{ - /// - /// Temporary credentials that are created following successful authentication with - /// a federated endpoint supporting SAML. - /// - /// - /// Currently only the SDK store supports profiles that contain the necessary data to support - /// authentication and role-based credential generation. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.FederatedAWSCredentials. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] - public class StoredProfileSAMLCredentials : RefreshingAWSCredentials - { - private const int MaxAuthenticationRetries = 3; - private RegionEndpoint DefaultSTSClientRegion = RegionEndpoint.USEast1; - - private static readonly TimeSpan _preemptExpiryTime = TimeSpan.FromMinutes(5); - private TimeSpan _credentialDuration = MaximumCredentialTimespan; - - /// - /// Any custom state passed when a credential callback was registered. - /// - public object CustomCallbackState { get; set; } - - /// - /// The minimum allowed timespan for generated credentials, per STS documentation. - /// - public static readonly TimeSpan MinimumCredentialTimespan = TimeSpan.FromMinutes(15); - - /// - /// The maximum allowed timespan for generated credentials, per STS documentation. - /// - public static readonly TimeSpan MaximumCredentialTimespan = TimeSpan.FromHours(1); - - /// - /// Callback signature for obtaining user credentials for authentication demands when - /// the role profile is configured to not use the default identity. - /// - /// - /// Data about the credential demand including any custom state data that was supplied - /// when the callback was registered. - /// - /// - /// The network credential to use in user authentication. Return null to signal the user - /// declined to provide credentials and authentication should not proceed. - /// - public delegate NetworkCredential RequestUserCredential(CredentialCallbackArgs args); - - /// - /// Registered callback for obtaining credentials to use in authentication. - /// Required to be set if the role profile is not configured to use the default - /// identity. - /// - public RequestUserCredential RequestUserCredentialCallback { get; set; } - - #region Public constructors - - /// - /// Constructs an instance of StoredProfileSAMLCredentials. This constructor searches for details - /// of the role to assume, and optional credentials to use with the endpoint, using the - /// profile name specified in the App.config. - /// - public StoredProfileSAMLCredentials() - : this(AWSConfigs.AWSProfileName, null) - { - } - - /// - /// - /// Constructs an instance of StoredProfileSAMLCredentials. After construction call one of the Authenticate - /// methods to authenticate the user/process and obtain temporary AWS credentials. - /// - /// - /// For users who are domain joined (the role profile does not contain user identity information) the temporary - /// credentials will be refreshed automatically as needed. Non domain-joined users (those with user identity - /// data in the profile) are required to re-authenticate when credential refresh is required. An exception is - /// thrown when attempt is made to refresh credentials in this scenario. The consuming code of this class - /// should catch the exception and prompt the user for credentials, then call Authenticate to re-initialize - /// with a new set of temporary AWS credentials. - /// - /// - /// - /// The name of the profile holding the necessary role data to enable authentication and credential generation. - /// - /// Reserved for future use. - /// The ini-format credentials file is not currently supported. - public StoredProfileSAMLCredentials(string profileName, string profilesLocation) - { - this.PreemptExpiryTime = _preemptExpiryTime; - this.CustomCallbackState = null; - - var lookupName = string.IsNullOrEmpty(profileName) - ? StoredProfileCredentials.DEFAULT_PROFILE_NAME - : profileName; - - ProfileName = lookupName; - ProfilesLocation = null; - - // If not overriding the credentials lookup location check the SDK Store for credentials. If an override - // is being used then assume the intent is to use the credentials file. - if (string.IsNullOrEmpty(profilesLocation)) - { - SAMLRoleProfile profileData; - if (ProfileManager.TryGetProfile(lookupName, out profileData)) - { - ProfileData = profileData; - var logger = Logger.GetLogger(typeof(StoredProfileSAMLCredentials)); - logger.InfoFormat("SAML role profile found using account name {0} and looking in SDK account store.", lookupName); - } - } - - // No credentials found so error out. We do not currently support the ini-format credentials - // file to obtain SAML role profile data. - if (ProfileData == null) - { - var msg = string.Format(CultureInfo.InvariantCulture, - "Profile '{0}' was not found or could not be loaded. Verify that the profile name and data are correct.", - profileName); - throw new ArgumentException(msg); - } - } - - #endregion - - #region Public properties - - /// - /// Name of the profile being used. - /// - public string ProfileName { get; private set; } - - /// - /// Location of the profiles, if used. - /// - public string ProfilesLocation { get; private set; } - - /// - /// The data about the SAML endpoint and any required user credentials parsed from the - /// profile. - /// - public SAMLRoleProfile ProfileData { get; private set; } - - #endregion - - /// - /// If non-default credentials are to be used for authentication, - /// validates that the authentication required callback has been - /// populated. - /// - protected override void Validate() - { - if (!ProfileData.UseDefaultUserIdentity && RequestUserCredentialCallback == null) - throw new CredentialCallbackRequiredException("RequestUserCredentialCallback must be set for profiles that do not use the default user identity for authentication."); - } - - /// - /// Refresh credentials after expiry. If the role profile is configured to not - /// use the default user identity, an exception is thrown if the UserAuthenticationCallback - /// property has not been set. - /// - /// - protected override CredentialsRefreshState GenerateNewCredentials() - { - Validate(); - - CredentialsRefreshState newState = null; - var attempts = 0; - do - { - try - { - NetworkCredential userCredential = null; - if (!ProfileData.UseDefaultUserIdentity) - { - var callbackArgs = new CredentialCallbackArgs - { - UserIdentity = ProfileData.UserIdentity, - CustomState = CustomCallbackState, - PreviousAuthenticationFailed = attempts > 0 - }; - - userCredential = RequestUserCredentialCallback(callbackArgs); - - if (userCredential == null) // user declined to authenticate - throw new AuthenticationFailedException("No credentials supplied, credential refresh abandoned"); - } - - newState = Authenticate(userCredential, _credentialDuration); - } - catch (AuthenticationFailedException) - { - if (attempts < MaxAuthenticationRetries) - attempts++; - else - throw; - } - } while (newState == null && attempts < MaxAuthenticationRetries); - - return newState; - } - - private CredentialsRefreshState Authenticate(ICredentials userCredential, TimeSpan credentialDuration) - { - CredentialsRefreshState state; - SAMLAssertion assertion; - - var configuredRegion = AWSConfigs.AWSRegion; - var region = string.IsNullOrEmpty(configuredRegion) - ? DefaultSTSClientRegion - : RegionEndpoint.GetBySystemName(configuredRegion); - - try - { - assertion = new SAMLAuthenticationController().GetSAMLAssertion(ProfileData.EndpointSettings.Endpoint.ToString(), - userCredential, - ProfileData.EndpointSettings.AuthenticationType); - } - catch (Exception e) - { - throw new AuthenticationFailedException("Authentication failure, unable to obtain SAML assertion.", e); - } - - try - { - using (var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials(), region)) - { - var credentials = assertion.GetRoleCredentials(stsClient, ProfileData.RoleArn, credentialDuration); - state = new CredentialsRefreshState(credentials, stsClient.Config.CorrectedUtcNow + credentialDuration); - } - } - catch (Exception e) - { - var wrappedException = new AmazonClientException("Credential generation failed following successful authentication.", e); - - var logger = Logger.GetLogger(typeof(StoredProfileSAMLCredentials)); - logger.Error(wrappedException, wrappedException.Message); - - throw wrappedException; - } - - return state; - } - } - - /// - /// State class passed on callback to demand user credentials when authentication - /// is performed using a non-default identity. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please update your code to use the Amazon.Runtime.CredentialRequestCallbackArgs class instead.")] - public class CredentialCallbackArgs - { - /// - /// Contains the user identity that the user should supply a password - /// for. - /// - public string UserIdentity { get; set; } - - /// - /// Any custom state that was registered with the callback. - /// - public object CustomState { get; set; } - - /// - /// Set if the callback was due to a failed authentication attempt. - /// If false we are beginning to obtain or refresh credentials. - /// - public bool PreviousAuthenticationFailed { get; set; } - } - - /// - /// Exception thrown on validation of a StoredProfileSAMLCredentials instance if the role profile - /// is configured to use a non-default user identity and the QueryUserCredentialCallback on the - /// instance has not been set. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please update your code to use the Amazon.Runtime.CredentialRequestCallbackRequiredException class instead.")] -#if !NETSTANDARD - [Serializable] -#endif - public class CredentialCallbackRequiredException : Exception - { - /// - /// Initializes a new exception instance. - /// - /// - public CredentialCallbackRequiredException(string msg) - : base(msg) - { - } - - /// - /// Initializes a new exception instance. - /// - /// - /// - public CredentialCallbackRequiredException(string msg, Exception innerException) - : base(msg, innerException) - { - } - - /// - /// Initializes a new exception instance. - /// - /// - public CredentialCallbackRequiredException(Exception innerException) - : base(innerException.Message, innerException) - { - } - -#if !NETSTANDARD - /// - /// Constructs a new instance of the AdfsAuthenticationControllerException class with serialized data. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). - protected CredentialCallbackRequiredException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - } -#endif - } - - /// - /// Custom exception type thrown when authentication for a user against the - /// configured endpoint fails and a valid SAML assertion document could not be - /// obtained. - /// - [Obsolete("This class is obsolete and will be removed in a future release. Please update your code to use the Amazon.Runtime.FederatedAuthenticationFailureException class instead.")] -#if !NETSTANDARD - [Serializable] -#endif - public class AuthenticationFailedException : Exception - { - /// - /// Initializes a new exception instance. - /// - /// - public AuthenticationFailedException(string msg) - : base(msg) - { - } - - /// - /// Initializes a new exception instance. - /// - /// - /// - public AuthenticationFailedException(string msg, Exception inner) - : base(msg, inner) - { - } - -#if !NETSTANDARD - /// - /// Constructs a new instance of the AuthenticationFailedException class with serialized data. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). - protected AuthenticationFailedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - } -#endif - } -} diff --git a/sdk/test/Common/Utils/AssertExtensions.cs b/sdk/test/Common/Utils/AssertExtensions.cs index ff3753ca8481..37302cd89620 100644 --- a/sdk/test/Common/Utils/AssertExtensions.cs +++ b/sdk/test/Common/Utils/AssertExtensions.cs @@ -142,7 +142,7 @@ public static void AssertEnumUnchanged(Type type, string expectedHash, string no private static void AssertStringListUnchanged(List list, string expectedHash, string whatChanged, string notes) { - SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider(); + SHA256 provider = SHA256.Create(); // make sure string to hash is repeatable list.Sort(); var stringToHash = string.Join("::", list.ToArray()); @@ -170,7 +170,7 @@ public static void AssertSourceCodeUnchanged(List srcRelativeFilenames, { sourceCodeSB.Append(File.ReadAllText(Path.Combine(sourceRoot, srcRelativeFilename))); } - SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider(); + SHA256 provider = SHA256.Create(); var actualHash = BitConverter.ToString(provider.ComputeHash(Encoding.Default.GetBytes(sourceCodeSB.ToString()))).Replace("-", ""); // compare the hash to the expected hash diff --git a/sdk/test/IntegrationTests/Tests/General.CommonUtilities.cs b/sdk/test/IntegrationTests/Tests/General.CommonUtilities.cs index ecb5daf9e868..e468e64d970d 100644 --- a/sdk/test/IntegrationTests/Tests/General.CommonUtilities.cs +++ b/sdk/test/IntegrationTests/Tests/General.CommonUtilities.cs @@ -23,10 +23,5 @@ private static void SetUtcNowSource(Func source) var field = typeof(AWSConfigs).GetField("utcNowSource", BindingFlags.Static | BindingFlags.NonPublic); field.SetValue(null, source); } - public static void SetClockSkewCorrection(TimeSpan value) - { - var property = typeof(AWSConfigs).GetProperty("ClockOffset", BindingFlags.Static | BindingFlags.Public); - property.SetValue(null, value); - } } } \ No newline at end of file diff --git a/sdk/test/IntegrationTests/Tests/General.cs b/sdk/test/IntegrationTests/Tests/General.cs index d5288e88f06b..c234cfa509be 100644 --- a/sdk/test/IntegrationTests/Tests/General.cs +++ b/sdk/test/IntegrationTests/Tests/General.cs @@ -28,6 +28,7 @@ using Amazon.DynamoDBv2; using Amazon.ElasticTranscoder; using System.Threading; +using AWSSDK_DotNet.CommonTest.Utils; namespace AWSSDK_DotNet.IntegrationTests.Tests { @@ -197,16 +198,6 @@ public void TestSerializingExceptions() var aace = new AdfsAuthenticationControllerException("Message"); TestException(aace); -#pragma warning disable 618 - - var ccre = new CredentialCallbackRequiredException("Message"); - TestException(ccre); - - var afe = new AuthenticationFailedException("Message"); - TestException(afe); - -#pragma warning restore 618 - } } @@ -779,21 +770,23 @@ private static void TestServiceCallForClockSkew(ClockSkewTestContext context) try { AWSConfigs.CorrectForClockSkew = true; - SetClockSkewCorrection(TimeSpan.Zero); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), TimeSpan.Zero }); context.TestAction(); -#pragma warning disable CS0618 // Type or member is obsolete - Assert.IsTrue(AWSConfigs.ClockOffset == TimeSpan.Zero); + Assert.IsTrue(CorrectClockSkew.GetClockCorrectionForEndpoint(context.Config.RegionEndpoint.ToString()) == TimeSpan.Zero); - SetClockSkewCorrection(IncorrectPositiveClockSkewOffset); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), IncorrectPositiveClockSkewOffset}); context.TestAction(); -#pragma warning disable CS0618 // Type or member is obsolete - Assert.AreEqual(IncorrectPositiveClockSkewOffset, AWSConfigs.ClockOffset); - SetClockSkewCorrection(IncorrectNegativeClockSkewOffset); + Assert.AreEqual(IncorrectPositiveClockSkewOffset, CorrectClockSkew.GetClockCorrectionForEndpoint(context.Config.RegionEndpoint.ToString())); + + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), IncorrectNegativeClockSkewOffset }); context.TestAction(); -#pragma warning disable CS0618 // Type or member is obsolete - Assert.AreEqual(IncorrectNegativeClockSkewOffset, AWSConfigs.ClockOffset); + + Assert.AreEqual(IncorrectNegativeClockSkewOffset, CorrectClockSkew.GetClockCorrectionForEndpoint(context.Config.RegionEndpoint.ToString())); Console.WriteLine("Simulating positive clock skew"); SetUtcNowSource(() => DateTime.UtcNow + IncorrectPositiveClockSkewOffset); @@ -801,13 +794,16 @@ private static void TestServiceCallForClockSkew(ClockSkewTestContext context) AssertExtensions.ExpectException(context.TestAction); AWSConfigs.CorrectForClockSkew = true; - SetClockSkewCorrection(TimeSpan.Zero); + + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), TimeSpan.Zero }); context.TestAction(); Console.WriteLine("Simulating negative clock skew"); SetUtcNowSource(() => DateTime.UtcNow + IncorrectNegativeClockSkewOffset); AWSConfigs.CorrectForClockSkew = true; - SetClockSkewCorrection(TimeSpan.Zero); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), TimeSpan.Zero }); context.TestAction(); AWSConfigs.CorrectForClockSkew = false; @@ -860,8 +856,6 @@ private class ClientTest new ClientTest { Client = typeof(AmazonS3Client), Method = "ListBuckets" }, new ClientTest { Client = typeof(Amazon.Glacier.AmazonGlacierClient), Method = "ListVaults" }, new ClientTest { Client = typeof(Amazon.IdentityManagement.AmazonIdentityManagementServiceClient), Method = "ListGroups" }, - // ImportExport returns a 500. Investigating... - //new ClientTest { Client = typeof(Amazon.ImportExport.AmazonImportExportClient), Method = "ListJobs" }, }; // Reflection helpers diff --git a/sdk/test/IntegrationTests/Utils/RetryUtilities.cs b/sdk/test/IntegrationTests/Utils/RetryUtilities.cs index ee9dd91fb52f..3a6670ed751b 100644 --- a/sdk/test/IntegrationTests/Utils/RetryUtilities.cs +++ b/sdk/test/IntegrationTests/Utils/RetryUtilities.cs @@ -2,6 +2,7 @@ using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; +using AWSSDK_DotNet.CommonTest.Utils; using AWSSDK_DotNet.IntegrationTests.Tests; using System; using System.Collections.Generic; @@ -99,7 +100,8 @@ private static void SetIncorrectOffset() offset = General.IncorrectPositiveClockSkewOffset; else offset = General.IncorrectNegativeClockSkewOffset; - General.SetClockSkewCorrection(offset); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] {AWSConfigs.RegionEndpoint.ToString(), offset }); } #endregion diff --git a/sdk/test/NetStandard/IntegrationTests/IntegrationTests.NetStandard.csproj b/sdk/test/NetStandard/IntegrationTests/IntegrationTests.NetStandard.csproj index 022f99bc816f..2a1b3d20ee18 100644 --- a/sdk/test/NetStandard/IntegrationTests/IntegrationTests.NetStandard.csproj +++ b/sdk/test/NetStandard/IntegrationTests/IntegrationTests.NetStandard.csproj @@ -13,6 +13,7 @@ + diff --git a/sdk/test/NetStandard/IntegrationTests/IntegrationTests/General.cs b/sdk/test/NetStandard/IntegrationTests/IntegrationTests/General.cs index 5a60652da8eb..34cc9df5e07c 100644 --- a/sdk/test/NetStandard/IntegrationTests/IntegrationTests/General.cs +++ b/sdk/test/NetStandard/IntegrationTests/IntegrationTests/General.cs @@ -12,7 +12,7 @@ using System.Threading.Tasks; using Xunit; using Amazon.DNXCore.IntegrationTests; - +using AWSSDK_DotNet.CommonTest.Utils; namespace Amazon.DNXCore.IntegrationTests { @@ -132,7 +132,7 @@ protected override CredentialsRefreshState GenerateNewCredentials() } } - //[Fact] + [Fact] public void TestManualClockCorrection() { TestClients(TestServiceCallForManualClockCorrection); @@ -141,7 +141,7 @@ public void TestManualClockCorrection() // This test verifies that all service clients are able to // correctly handle clock skew errors. // By default it only tests a small subset of services. - //[Fact] + [Fact] public void TestClockSkewCorrection() { TestClients(TestServiceCallForClockSkew); @@ -177,7 +177,7 @@ private static void TestServiceCallForManualClockCorrection(ClockSkewTestContext { var oldManualClockCorrection = AWSConfigs.ManualClockCorrection; var oldCorrectClockSkew = AWSConfigs.CorrectForClockSkew; - var oldClockSkewCorrection = context.Config.ClockOffset; + var oldClockSkewCorrection = CorrectClockSkew.GetClockCorrectionForEndpoint(context.Config.RegionEndpoint.ToString()); var oldUtcNowSource = GetUtcNowSource(); try @@ -205,7 +205,8 @@ private static void TestServiceCallForManualClockCorrection(ClockSkewTestContext { AWSConfigs.ManualClockCorrection = oldManualClockCorrection; AWSConfigs.CorrectForClockSkew = oldCorrectClockSkew; - SetClockSkewCorrection(oldClockSkewCorrection); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), oldClockSkewCorrection }); SetUtcNowSource(oldUtcNowSource); } } @@ -213,37 +214,44 @@ private static void TestServiceCallForManualClockCorrection(ClockSkewTestContext private static void TestServiceCallForClockSkew(ClockSkewTestContext context) { var oldCorrectClockSkew = AWSConfigs.CorrectForClockSkew; - var oldClockSkewCorrection = context.Config.ClockOffset; var oldUtcNowSource = GetUtcNowSource(); try { AWSConfigs.CorrectForClockSkew = true; - SetClockSkewCorrection(TimeSpan.Zero); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), TimeSpan.Zero }); context.TestAction(); - Assert.True(context.Config.ClockOffset == TimeSpan.Zero); - SetClockSkewCorrection(IncorrectPositiveClockSkewOffset); + Assert.True(CorrectClockSkew.GetClockCorrectionForEndpoint(context.Config.RegionEndpoint.ToString()) == TimeSpan.Zero); + + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), IncorrectPositiveClockSkewOffset}); context.TestAction(); - Assert.NotStrictEqual(IncorrectPositiveClockSkewOffset, context.Config.ClockOffset); - SetClockSkewCorrection(IncorrectNegativeClockSkewOffset); + Assert.Equal(IncorrectPositiveClockSkewOffset, CorrectClockSkew.GetClockCorrectionForEndpoint(context.Config.RegionEndpoint.ToString())); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), IncorrectNegativeClockSkewOffset }); context.TestAction(); - Assert.NotStrictEqual(IncorrectNegativeClockSkewOffset, context.Config.ClockOffset); + + Assert.Equal(IncorrectNegativeClockSkewOffset, CorrectClockSkew.GetClockCorrectionForEndpoint(context.Config.RegionEndpoint.ToString())); Console.WriteLine("Simulating positive clock skew"); SetUtcNowSource(() => DateTime.UtcNow + IncorrectPositiveClockSkewOffset); AWSConfigs.CorrectForClockSkew = false; AssertExtensions.ExpectException(context.TestAction); - + AWSConfigs.CorrectForClockSkew = true; - SetClockSkewCorrection(TimeSpan.Zero); + + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), TimeSpan.Zero }); context.TestAction(); Console.WriteLine("Simulating negative clock skew"); SetUtcNowSource(() => DateTime.UtcNow + IncorrectNegativeClockSkewOffset); AWSConfigs.CorrectForClockSkew = true; - SetClockSkewCorrection(TimeSpan.Zero); + ReflectionHelpers.Invoke(typeof(CorrectClockSkew), "SetClockCorrectionForEndpoint", +new object[] { context.Config.RegionEndpoint.ToString(), TimeSpan.Zero }); context.TestAction(); AWSConfigs.CorrectForClockSkew = false; @@ -252,7 +260,6 @@ private static void TestServiceCallForClockSkew(ClockSkewTestContext context) finally { AWSConfigs.CorrectForClockSkew = oldCorrectClockSkew; - SetClockSkewCorrection(oldClockSkewCorrection); SetUtcNowSource(oldUtcNowSource); } } @@ -310,7 +317,8 @@ private class ClientTest new ClientTest { ClientType = typeof(AmazonS3Client), Method = "ListBuckets" }, new ClientTest { ClientType = typeof(Amazon.Glacier.AmazonGlacierClient), Method = "ListVaults" }, new ClientTest { ClientType = typeof(Amazon.IdentityManagement.AmazonIdentityManagementServiceClient), Method = "ListGroups" }, - new ClientTest { ClientType = typeof(Amazon.ImportExport.AmazonImportExportClient), Method = "ListJobs" }, + // This call returns a 500 error. + //new ClientTest { ClientType = typeof(Amazon.ImportExport.AmazonImportExportClient), Method = "ListJobs" }, }; // Reflection helpers @@ -326,11 +334,7 @@ private static void SetUtcNowSource(Func source) var field = typeof(AWSConfigs).GetField("utcNowSource", BindingFlags.Static | BindingFlags.NonPublic); field.SetValue(null, source); } - public static void SetClockSkewCorrection(TimeSpan value) - { - var property = typeof(CorrectClockSkew).GetProperty("GlobalClockCorrection", BindingFlags.Static | BindingFlags.NonPublic); - property.SetValue(null, value); - } + private AbstractAWSSigner GetSigner(object client) { var signerProperty = typeof(AmazonServiceClient).GetTypeInfo().GetDeclaredProperty("Signer"); diff --git a/sdk/test/NetStandard/UnitTests/ClientConfigTests.cs b/sdk/test/NetStandard/UnitTests/ClientConfigTests.cs index a832f40cb958..616ab545d418 100644 --- a/sdk/test/NetStandard/UnitTests/ClientConfigTests.cs +++ b/sdk/test/NetStandard/UnitTests/ClientConfigTests.cs @@ -26,7 +26,6 @@ public class ClientConfigTests "AuthenticationServiceName", "MaxErrorRetry", "LogResponse", - "ReadEntireResponse", "AWSTokenProvider", "BufferSize", "ProgressUpdateInterval", @@ -45,8 +44,6 @@ public class ClientConfigTests "MaxConnectionsPerServer", "HttpClientCacheSize", "ReadWriteTimeout", - "CorrectedUtcNow", - "ClockOffset", "HttpClientFactory", "DisableHostPrefixInjection", "EndpointDiscoveryEnabled", diff --git a/sdk/test/Services/ECS/IntegrationTests/CredentialsTests.cs b/sdk/test/Services/ECS/IntegrationTests/CredentialsTests.cs index e50c7d62fcb1..d716a52b790d 100644 --- a/sdk/test/Services/ECS/IntegrationTests/CredentialsTests.cs +++ b/sdk/test/Services/ECS/IntegrationTests/CredentialsTests.cs @@ -11,6 +11,7 @@ using System.Diagnostics; using System.Reflection; using AWSSDK_DotNet.CommonTest.Utils; +using Amazon.Runtime.CredentialManagement; namespace AWSSDK_DotNet.IntegrationTests.Tests { @@ -77,10 +78,13 @@ private static void TestCredentialsFile(ImmutableCredentials ic) { var profileName = "testProfile"; var profilesLocation = WriteCreds(profileName, ic); -#pragma warning disable 618 - var creds = new StoredProfileAWSCredentials(profileName, profilesLocation); -#pragma warning restore 618 - var rc = creds.GetCredentials(); + + var sharedCredentialsFile = new SharedCredentialsFile(profilesLocation); + CredentialProfile credentialProfile; + sharedCredentialsFile.TryGetProfile(profileName, out credentialProfile); + var awsCredentials = credentialProfile.GetAWSCredentials(sharedCredentialsFile); + var rc = awsCredentials.GetCredentials(); + Assert.AreEqual(ic.SecretKey, rc.SecretKey); Assert.AreEqual(ic.AccessKey, rc.AccessKey); Assert.AreEqual(ic.UseToken, rc.UseToken); @@ -89,12 +93,11 @@ private static void TestCredentialsFile(ImmutableCredentials ic) for (int i = 0; i < 4; i++) { var shouldHaveToken = (i % 2 == 1); -#pragma warning disable 618 - creds = new StoredProfileAWSCredentials(profileName + i, profilesLocation); -#pragma warning restore 618 - Assert.IsNotNull(creds); + sharedCredentialsFile.TryGetProfile(profileName + i, out credentialProfile); + Assert.IsNotNull(credentialProfile); + - rc = creds.GetCredentials(); + rc = credentialProfile.GetAWSCredentials(sharedCredentialsFile).GetCredentials(); Assert.IsNotNull(rc.AccessKey); Assert.IsNotNull(rc.SecretKey); Assert.AreEqual(shouldHaveToken, rc.UseToken); diff --git a/sdk/test/Services/SecurityToken/UnitTests/Custom/FallbackCredentialsFactorySTSTests.cs b/sdk/test/Services/SecurityToken/UnitTests/Custom/FallbackCredentialsFactorySTSTests.cs index 34f5bd7dc30c..9fdea0fa6e6d 100644 --- a/sdk/test/Services/SecurityToken/UnitTests/Custom/FallbackCredentialsFactorySTSTests.cs +++ b/sdk/test/Services/SecurityToken/UnitTests/Custom/FallbackCredentialsFactorySTSTests.cs @@ -261,7 +261,6 @@ public FallbackFactoryTestFixture(Dictionary newEnvironmentVaria // reset before use to ensure the new credentialProfileChains are used. FallbackCredentialsFactory.Reset(); FallbackRegionFactory.Reset(); - FallbackEndpointDiscoveryEnabledFactory.Reset(); FallbackInternalConfigurationFactory.Reset(); } @@ -274,7 +273,6 @@ public void Dispose() FallbackCredentialsFactory.Reset(); FallbackRegionFactory.Reset(); - FallbackEndpointDiscoveryEnabledFactory.Reset(); FallbackInternalConfigurationFactory.Reset(); } } diff --git a/sdk/test/UnitTests/Custom/Runtime/Credentials/FallbackFactoryTest.cs b/sdk/test/UnitTests/Custom/Runtime/Credentials/FallbackFactoryTest.cs index 05513cca8359..8356070d1f09 100644 --- a/sdk/test/UnitTests/Custom/Runtime/Credentials/FallbackFactoryTest.cs +++ b/sdk/test/UnitTests/Custom/Runtime/Credentials/FallbackFactoryTest.cs @@ -109,10 +109,7 @@ public void TestDefaultProfile(string awsProfileValue) var region = FallbackRegionFactory.GetRegionEndpoint(false); Assert.AreEqual(RegionEndpoint.USWest2, region); - var enabled = FallbackEndpointDiscoveryEnabledFactory.GetEnabled(); - Assert.IsFalse(enabled.HasValue); - - enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; + var enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; Assert.IsFalse(enabled.HasValue); var retryMode = FallbackInternalConfigurationFactory.RetryMode; @@ -140,11 +137,8 @@ public void TestOtherProfile() var region = FallbackRegionFactory.GetRegionEndpoint(false); Assert.AreEqual(RegionEndpoint.USWest1, region); - var enabled = FallbackEndpointDiscoveryEnabledFactory.GetEnabled(); - Assert.IsTrue(enabled.HasValue); - Assert.IsFalse(enabled.Value); - enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; + var enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; Assert.IsTrue(enabled.HasValue); Assert.IsFalse(enabled.Value); } @@ -154,12 +148,8 @@ public void TestOtherProfile() public void TestOther2Profile() { using (new FallbackFactoryTestFixture(ProfileText, "other2")) - { - var enabled = FallbackEndpointDiscoveryEnabledFactory.GetEnabled(); - Assert.IsTrue(enabled.HasValue); - Assert.IsTrue(enabled.Value); - - enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; + { + var enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; Assert.IsTrue(enabled.HasValue); Assert.IsTrue(enabled.Value); } @@ -261,11 +251,7 @@ public void TestEnableEndpointDiscoveryEnvVariable() using (new FallbackFactoryTestFixture(ProfileText, "other2", envVariables)) { - var enabled = FallbackEndpointDiscoveryEnabledFactory.GetEnabled(); - Assert.IsTrue(enabled.HasValue); - Assert.IsFalse(enabled.Value); - - enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; + var enabled = FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled; Assert.IsTrue(enabled.HasValue); Assert.IsFalse(enabled.Value); } @@ -861,7 +847,6 @@ public class FallbackFactoryTestFixture : IDisposable private readonly CredentialProfileStoreChain originalCredsChain; private readonly CredentialProfileStoreChain originalRegionChain; - private readonly CredentialProfileStoreChain originalEndpointDiscoveryEnabledChain; private readonly CredentialProfileStoreChain originalConfigurationChain; private readonly string originalAWSProfileValue; @@ -883,8 +868,6 @@ public FallbackFactoryTestFixture(string sharedCredsFileContent, string awsProfi originalRegionChain = (CredentialProfileStoreChain)ReflectionHelpers.Invoke(typeof(FallbackRegionFactory), "credentialProfileChain"); ReflectionHelpers.Invoke(typeof(FallbackRegionFactory), "credentialProfileChain", new CredentialProfileStoreChain(sharedFixture.CredentialsFilePath)); - originalEndpointDiscoveryEnabledChain = (CredentialProfileStoreChain)ReflectionHelpers.Invoke(typeof(FallbackEndpointDiscoveryEnabledFactory), "credentialProfileChain"); - ReflectionHelpers.Invoke(typeof(FallbackEndpointDiscoveryEnabledFactory), "credentialProfileChain", new CredentialProfileStoreChain(sharedFixture.CredentialsFilePath)); originalConfigurationChain = (CredentialProfileStoreChain)ReflectionHelpers.Invoke(typeof(FallbackInternalConfigurationFactory), "_credentialProfileChain"); ReflectionHelpers.Invoke(typeof(FallbackInternalConfigurationFactory), "_credentialProfileChain", new CredentialProfileStoreChain(sharedFixture.CredentialsFilePath)); @@ -915,7 +898,6 @@ public FallbackFactoryTestFixture(string sharedCredsFileContent, string awsProfi // reset before use to ensure the new credentialProfileChains are used. FallbackCredentialsFactory.Reset(); FallbackRegionFactory.Reset(); - FallbackEndpointDiscoveryEnabledFactory.Reset(); FallbackInternalConfigurationFactory.Reset(); } catch (Exception ex) @@ -940,7 +922,6 @@ public void Dispose() ReflectionHelpers.Invoke(typeof(FallbackRegionFactory), "credentialProfileChain", originalRegionChain); ReflectionHelpers.Invoke(typeof(FallbackCredentialsFactory), "credentialProfileChain", originalCredsChain); - ReflectionHelpers.Invoke(typeof(FallbackEndpointDiscoveryEnabledFactory), "credentialProfileChain", originalEndpointDiscoveryEnabledChain); ReflectionHelpers.Invoke(typeof(FallbackInternalConfigurationFactory), "_credentialProfileChain", originalConfigurationChain); netSdkFixture.Dispose(); @@ -948,7 +929,6 @@ public void Dispose() FallbackCredentialsFactory.Reset(); FallbackRegionFactory.Reset(); - FallbackEndpointDiscoveryEnabledFactory.Reset(); FallbackInternalConfigurationFactory.Reset(); } } diff --git a/sdk/test/UnitTests/Custom/Runtime/Credentials/NetSDKCredentialsFileTest.cs b/sdk/test/UnitTests/Custom/Runtime/Credentials/NetSDKCredentialsFileTest.cs index 30a34e3b08b4..516515888331 100644 --- a/sdk/test/UnitTests/Custom/Runtime/Credentials/NetSDKCredentialsFileTest.cs +++ b/sdk/test/UnitTests/Custom/Runtime/Credentials/NetSDKCredentialsFileTest.cs @@ -636,109 +636,7 @@ public void CopyProfileTargetAlreadyExistsForce() } } - [TestMethod] - public void TestReadCompatibilityBasic() - { - using (var tester = new NetSDKCredentialsFileTestFixture()) - { - // write with old ProfileManager - ProfileManager.RegisterProfile("BasicProfile", "AccessKey", "SecretKey"); - - // read with new NetSDKCredentialsFile - CredentialProfile profile; - Assert.IsTrue(tester.ProfileStore.TryGetProfile("BasicProfile", out profile)); - Assert.IsNotNull(profile); - Assert.AreEqual("BasicProfile", profile.Name); - Assert.AreEqual("AccessKey", profile.Options.AccessKey); - Assert.AreEqual("SecretKey", profile.Options.SecretKey); - Assert.AreEqual(CredentialProfileType.Basic, CredentialProfileTypeDetector.DetectProfileType(profile.Options).Value); - } - } - - [TestMethod] - public void TestWriteCompatibilityBasic() - { - using (var tester = new NetSDKCredentialsFileTestFixture()) - { - // write with new NetSDKCredentialsFile - CredentialProfile profile = CredentialProfileTestHelper.GetCredentialProfile( - Guid.NewGuid(), "BasicProfile", CredentialProfileTestHelper.GetRandomOptions(CredentialProfileType.Basic)); - tester.ProfileStore.RegisterProfile(profile); - - // read with old ProfileManager - AWSCredentials credentials; - Assert.IsTrue(ProfileManager.TryGetAWSCredentials("BasicProfile", out credentials)); - Assert.IsNotNull(credentials); - var immutableCredentials = credentials.GetCredentials(); - Assert.AreEqual(profile.Options.AccessKey, immutableCredentials.AccessKey); - Assert.AreEqual(profile.Options.SecretKey, immutableCredentials.SecretKey); - } - } - - [TestMethod] - public void TestReadCompatibilitySAML() - { - using (var tester = new NetSDKCredentialsFileTestFixture()) - { - // write with old ProfileManager - ProfileManager.RegisterSAMLEndpoint("EndpointName", new Uri("https://somesamlendpoint/"), null); - ProfileManager.RegisterSAMLRoleProfile("SAMLProfile", "EndpointName", "RoleArn", "UserIdentity"); - - // read with new NetSDKCredentialsFile - CredentialProfile profile; - Assert.IsTrue(tester.ProfileStore.TryGetProfile("SAMLProfile", out profile)); - Assert.IsNotNull(profile); - Assert.AreEqual("SAMLProfile", profile.Name); - Assert.AreEqual("EndpointName", profile.Options.EndpointName); - Assert.AreEqual("RoleArn", profile.Options.RoleArn); - Assert.AreEqual("UserIdentity", profile.Options.UserIdentity); - Assert.AreEqual(CredentialProfileType.SAMLRoleUserIdentity, CredentialProfileTypeDetector.DetectProfileType(profile.Options).Value); - } - } - - [TestMethod] - public void TestWriteCompatibilitySAML() - { - using (var tester = new NetSDKCredentialsFileTestFixture()) - { - // write with new NetSDKCredentialsFile - CredentialProfile profile = CredentialProfileTestHelper.GetCredentialProfile( - Guid.NewGuid(), "SAMLProfile", CredentialProfileTestHelper.GetRandomOptions(CredentialProfileType.SAMLRoleUserIdentity)); - tester.ProfileStore.RegisterProfile(profile); - - // TODO do this with the new SAML Endpoint Manager - ProfileManager.RegisterSAMLEndpoint(profile.Options.EndpointName, new Uri("https://somesamlendpoint/"), null); - - // read with old ProfileManager - SAMLRoleProfile samlProfile; - Assert.IsTrue(ProfileManager.TryGetProfile("SAMLProfile", out samlProfile)); - Assert.IsNotNull(samlProfile); - Assert.AreEqual(profile.Options.EndpointName, samlProfile.EndpointSettings.Name); - Assert.AreEqual(profile.Options.RoleArn, samlProfile.RoleArn); - Assert.AreEqual(profile.Options.UserIdentity, samlProfile.UserIdentity); - } - } - [TestMethod] - public void TestWriteCompatibilitySession() - { - using (var tester = new NetSDKCredentialsFileTestFixture()) - { - // write a type that's not supported by ProfileManager - tester.ProfileStore.RegisterProfile(CredentialProfileTestHelper.GetCredentialProfile( - Guid.NewGuid(), "SessionProfile", CredentialProfileTestHelper.GetRandomOptions(CredentialProfileType.Session))); - - // make sure profile manager can't read it as a basic profile, and that there aren't any errors. - AWSCredentials credentials; - Assert.IsFalse(ProfileManager.TryGetAWSCredentials("SessionProfile", out credentials)); - Assert.IsNull(credentials); - - // make sure profile manager can't read it as a SAML profile, and that there aren't any errors. - SAMLRoleProfile samlProfile; - Assert.IsFalse(ProfileManager.TryGetProfile("SessionProfile", out samlProfile)); - Assert.IsNull(samlProfile); - } - } private static void Create2Profiles(NetSDKCredentialsFileTestFixture tester) { diff --git a/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLEndpointManagerTest.cs b/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLEndpointManagerTest.cs index a001a19f1294..557b5becfb95 100644 --- a/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLEndpointManagerTest.cs +++ b/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLEndpointManagerTest.cs @@ -190,40 +190,5 @@ public void GetEndpointInvalidAuthenticationType() }, typeof(AmazonClientException), new Regex("Error reading A SAML endpoint with name")).InnerException; }, typeof(ArgumentException), "Requested value 'BLAH!' was not found."); } - - [TestMethod] - public void ProfileManagerWriteSAMLEndpointManagerReadDefaultAuth() - { - ProfileManager.RegisterSAMLEndpoint(EndpointName, EndpointUri, null); - var samlEndpoint = manager.GetEndpoint(EndpointName); - - Assert.IsNotNull(samlEndpoint); - Assert.AreEqual(DefaultAuthSamlEndpoint.Name, samlEndpoint.Name); - Assert.AreEqual(DefaultAuthSamlEndpoint.AuthenticationType, samlEndpoint.AuthenticationType); - Assert.AreEqual(DefaultAuthSamlEndpoint.EndpointUri, samlEndpoint.EndpointUri); - } - - [TestMethod] - public void ProfileManagerWriteSAMLEndpointManagerReadExplicitAuth() - { - ProfileManager.RegisterSAMLEndpoint(EndpointName, OtherEndpointUri, SAMLAuthenticationType.NTLM.ToString()); - var samlEndpoint = manager.GetEndpoint(EndpointName); - - Assert.IsNotNull(samlEndpoint); - Assert.AreEqual(ExplicitAuthSamlEndpoint.Name, samlEndpoint.Name); - Assert.AreEqual(ExplicitAuthSamlEndpoint.AuthenticationType, samlEndpoint.AuthenticationType); - Assert.AreEqual(ExplicitAuthSamlEndpoint.EndpointUri, samlEndpoint.EndpointUri); - } - - [TestMethod] - public void SAMLEndpointManagerWriteProfileManagerRead() - { - manager.RegisterEndpoint(DefaultAuthSamlEndpoint); - - var endpointSettings = ProfileManager.GetSAMLEndpoint(EndpointName); - Assert.AreEqual(DefaultAuthSamlEndpoint.Name, endpointSettings.Name); - Assert.AreEqual(DefaultAuthSamlEndpoint.AuthenticationType.ToString(), endpointSettings.AuthenticationType); - Assert.AreEqual(DefaultAuthSamlEndpoint.EndpointUri, endpointSettings.Endpoint); - } } } diff --git a/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLRoleSessionManagerTest.cs b/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLRoleSessionManagerTest.cs index ddcce7a4d4d1..7a173de57177 100644 --- a/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLRoleSessionManagerTest.cs +++ b/sdk/test/UnitTests/Custom/Runtime/Credentials/SAMLRoleSessionManagerTest.cs @@ -129,40 +129,5 @@ public void Clear() manager.Clear(); fixture.AssertFileExists(false); } - - [TestMethod] - public void WriteSAMLRoleSessionManagerReadSAMLRoleProfile() - { - // write new - manager.RegisterRoleSession(RoleSessionName, samlCredentials); - // read old - var readCredentials = (SAMLImmutableCredentials)ReflectionHelpers.Invoke( - typeof(SAMLRoleProfile), "LoadActiveSessionCredentials", RoleSessionName); - - Assert.IsNotNull(readCredentials); - Assert.AreEqual(samlCredentials.AccessKey, readCredentials.AccessKey); - Assert.AreEqual(samlCredentials.Expires, readCredentials.Expires); - Assert.AreEqual(samlCredentials.SecretKey, readCredentials.SecretKey); - Assert.AreEqual(samlCredentials.Subject, readCredentials.Subject); - Assert.AreEqual(samlCredentials.Token, readCredentials.Token); - } - - [TestMethod] - public void WriteSAMLRoleProfileReadSAMLRoleSessionManager() - { - // write old - var json = (string)ReflectionHelpers.Invoke(samlCredentials, "ToJson"); - ReflectionHelpers.Invoke(typeof(SAMLRoleProfile), "PersistActiveSessionCredentials", RoleSessionName, json); - // read new - SAMLImmutableCredentials readCredentials; - Assert.IsTrue(manager.TryGetRoleSession(RoleSessionName, out readCredentials)); - - Assert.IsNotNull(readCredentials); - Assert.AreEqual(samlCredentials.AccessKey, readCredentials.AccessKey); - Assert.AreEqual(samlCredentials.Expires, readCredentials.Expires); - Assert.AreEqual(samlCredentials.SecretKey, readCredentials.SecretKey); - Assert.AreEqual(samlCredentials.Subject, readCredentials.Subject); - Assert.AreEqual(samlCredentials.Token, readCredentials.Token); - } } } diff --git a/sdk/test/UnitTests/Custom/Runtime/StringUtilsTests.cs b/sdk/test/UnitTests/Custom/Runtime/StringUtilsTests.cs index f8a8a3b7c5a1..c05beea48f25 100644 --- a/sdk/test/UnitTests/Custom/Runtime/StringUtilsTests.cs +++ b/sdk/test/UnitTests/Custom/Runtime/StringUtilsTests.cs @@ -34,38 +34,6 @@ public class StringUtilsTests const string EXPECTED_FROM_DATE_STRING = "2018-07-18T00:00:00.000Z"; static readonly DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); -#pragma warning disable CS0618 // Type or member is obsolete - [TestMethod] - [TestCategory("UnitTest")] - [TestCategory("Runtime")] - public void TestStringUtilsFromDateTimeUtc() - { - string convertedDateTime = StringUtils.FromDateTime(new DateTime(2018, 7, 18, 0, 0, 0, DateTimeKind.Utc)); - - Assert.AreEqual(EXPECTED_FROM_DATE_STRING, convertedDateTime); - } - - [TestMethod] - [TestCategory("UnitTest")] - [TestCategory("Runtime")] - public void TestStringUtilsFromDateTimeUnspecified() - { - string convertedDateTime = StringUtils.FromDateTime(new DateTime(2018, 7, 18, 0, 0, 0)); - - Assert.AreEqual(EXPECTED_FROM_DATE_STRING, convertedDateTime); - } - - [TestMethod] - [TestCategory("UnitTest")] - [TestCategory("Runtime")] - public void TestStringUtilsFromDateTimeLocal() - { - string convertedDateTime = StringUtils.FromDateTime(new DateTime(2018, 7, 18, 0, 0, 0, DateTimeKind.Local)); - - Assert.AreEqual(EXPECTED_FROM_DATE_STRING, convertedDateTime); - } -#pragma warning restore CS0618 // Type or member is obsolete - [TestMethod] [TestCategory("UnitTest")] [TestCategory("Runtime")]