repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
aws-sdk-net | aws | C# | /*
* 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.CredentialManagement.Internal;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
namespace Amazon.Runtime
{
/// <summary>
/// Obtains credentials from access key/secret key or AWSProfileName settings
/// in the application's app.config or web.config file.
/// </summary>
public class AppConfigAWSCredentials : AWSCredentials
{
private const string ACCESSKEY = "AWSAccessKey";
private const string SECRETKEY = "AWSSecretKey";
private AWSCredentials _wrappedCredentials;
#region Public constructors
public AppConfigAWSCredentials()
{
NameValueCollection appConfig = ConfigurationManager.AppSettings;
var logger = Logger.GetLogger(typeof(AppConfigAWSCredentials));
// Attempt hardcoded key credentials first, then look for an explicit profile name
// in either the SDK credential store or the shared credentials file. When using a profile
// name, if a location is not given the search will use the default locations and name for
// the credential file (assuming the profile is not found in the SDK store first)
if (!string.IsNullOrEmpty(appConfig[ACCESSKEY]) && !string.IsNullOrEmpty(appConfig[SECRETKEY]))
{
var accessKey = appConfig[ACCESSKEY];
var secretKey = appConfig[SECRETKEY];
this._wrappedCredentials = new BasicAWSCredentials(accessKey, secretKey);
logger.InfoFormat("Credentials found with {0} and {1} app settings", ACCESSKEY, SECRETKEY);
}
else if (!string.IsNullOrEmpty(AWSConfigs.AWSProfileName))
{
CredentialProfileStoreChain chain = new CredentialProfileStoreChain(AWSConfigs.AWSProfilesLocation);
CredentialProfile profile;
if (chain.TryGetProfile(AWSConfigs.AWSProfileName, out profile))
{
// Will throw a descriptive exception if profile.CanCreateAWSCredentials is false.
_wrappedCredentials = profile.GetAWSCredentials(profile.CredentialProfileStore, true);
}
}
if (this._wrappedCredentials == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"The app.config/web.config files for the application did not contain credential information"));
}
}
#endregion
#region Abstract class overrides
/// <summary>
/// Returns an instance of ImmutableCredentials for this instance
/// </summary>
/// <returns></returns>
public override ImmutableCredentials GetCredentials()
{
return this._wrappedCredentials.GetCredentials();
}
#endregion
}
}
| 89 |
aws-sdk-net | aws | C# | /*
* 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;
namespace Amazon.Runtime
{
/// <summary>
/// Exception thrown on validation of a StoredProfileFederatedCredentials instance if the role profile
/// is configured to use a non-default user identity and the QueryUserCredentialCallback on the
/// instance has not been set.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public class CredentialRequestCallbackRequiredException : Exception
{
/// <summary>
/// Initializes a new exception instance.
/// </summary>
/// <param name="msg"></param>
public CredentialRequestCallbackRequiredException(string msg)
: base(msg)
{
}
/// <summary>
/// Initializes a new exception instance.
/// </summary>
/// <param name="msg"></param>
/// <param name="innerException"></param>
public CredentialRequestCallbackRequiredException(string msg, Exception innerException)
: base(msg, innerException)
{
}
/// <summary>
/// Initializes a new exception instance.
/// </summary>
/// <param name="innerException"></param>
public CredentialRequestCallbackRequiredException(Exception innerException)
: base(innerException.Message, innerException)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the CredentialRequestCallbackRequiredException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected CredentialRequestCallbackRequiredException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 72 |
aws-sdk-net | aws | C# | /*
* 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
{
/// <summary>
/// Credentials that are retrieved from ConfigurationManager.AppSettings
/// </summary>
[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
/// <summary>
/// Constructs an instance of EnvironmentAWSCredentials and attempts
/// to load AccessKey and SecretKey from ConfigurationManager.AppSettings
/// </summary>
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
/// <summary>
/// Returns an instance of ImmutableCredentials for this instance
/// </summary>
/// <returns></returns>
public override ImmutableCredentials GetCredentials()
{
return this._wrappedCredentials.Copy();
}
#endregion
}
}
| 75 |
aws-sdk-net | aws | C# | /*
* 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
{
/// <summary>
/// Temporary credentials that are created following successful authentication with
/// a federated endpoint supporting SAML.
/// </summary>
/// <remarks>
/// 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.
/// <br/>
/// 2. In order to use the StoredProfileFederatedCredentials class the AWSSDK.SecurityToken assembly
/// must be available to your application at runtime.
/// </remarks>
[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
/// <summary>
/// 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.
/// </summary>
public object CustomCallbackState
{
get
{
lock (_synclock)
{
return _customCallbackState;
}
}
}
/// <summary>
/// The minimum allowed timespan for generated credentials, per STS documentation.
/// </summary>
public static readonly TimeSpan MinimumCredentialTimespan = TimeSpan.FromMinutes(15);
/// <summary>
/// The maximum allowed timespan for generated credentials, per STS documentation.
/// </summary>
public static readonly TimeSpan MaximumCredentialTimespan = TimeSpan.FromHours(1);
/// <summary>
/// Name of the profile being used.
/// </summary>
public string ProfileName { get; private set; }
/// <summary>
/// Location of the profiles, if used.
/// </summary>
public string ProfilesLocation { get; private set; }
/// <summary>
/// The data about the SAML endpoint and any required user credentials parsed from the
/// profile.
/// </summary>
public SAMLRoleProfile ProfileData { get; private set; }
/// <summary>
/// Callback signature for obtaining user credentials that may be needed for authentication.
/// </summary>
/// <param name="args">
/// Data about the credential demand including any custom state data that was supplied
/// when the callback was registered.
/// </param>
/// <returns>
/// The network credential to use in user authentication. Return null to signal the user
/// declined to provide credentials and authentication should not proceed.
/// </returns>
public delegate NetworkCredential RequestUserCredential(CredentialRequestCallbackArgs args);
#endregion
#region Public constructors
/// <summary>
/// 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.
/// </summary>
public StoredProfileFederatedCredentials()
: this(AWSConfigs.AWSProfileName)
{
}
/// <summary>
/// Constructs an instance of StoredProfileFederatedCredentials. Credentials will be searched
/// for using the profileName parameter.
/// </summary>
/// <param name="profileName">The profile name to search for credentials for</param>
public StoredProfileFederatedCredentials(string profileName)
: this(profileName, AWSConfigs.AWSProfilesLocation)
{
}
/// <summary>
/// <para>
/// Constructs an instance of StoredProfileFederatedCredentials. After construction call one of the Authenticate
/// methods to authenticate the user/process and obtain temporary AWS credentials.
/// </para>
/// <para>
/// 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.
/// </para>
/// </summary>
/// <param name="profileName">
/// The name of the profile holding the necessary role data to enable authentication and credential generation.
/// </param>
/// <param name="profilesLocation">Reserved for future use.</param>
/// <remarks>
/// The ini-format credentials file is not currently supported for SAML role profiles.
/// </remarks>
public StoredProfileFederatedCredentials(string profileName, string profilesLocation)
: this(profileName, profilesLocation, null)
{
}
/// <summary>
/// <para>
/// Constructs an instance of StoredProfileFederatedCredentials. After construction call one of the Authenticate
/// methods to authenticate the user/process and obtain temporary AWS credentials.
/// </para>
/// <para>
/// 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.
/// </para>
/// </summary>
/// <param name="profileName">
/// The name of the profile holding the necessary role data to enable authentication and credential generation.
/// </param>
/// <param name="profilesLocation">Reserved for future use.</param>
/// <param name="proxySettings">
/// Null or proxy settings to be used during the HHTPS authentication calls when generating credentials.
/// /// </param>
/// <remarks>The ini-format credentials file is not currently supported for SAML role profiles.</remarks>
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<SAMLRoleProfile>(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
/// <summary>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </summary>
/// <param name="callback">The handler to be called</param>
/// <param name="customData">
/// Custom state data to be supplied in the arguments to the callback.
/// </param>
/// <remarks>
/// 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.
/// </remarks>
public void SetCredentialCallbackData(RequestUserCredential callback, object customData)
{
lock (_synclock)
{
_credentialRequestCallback = callback;
_customCallbackState = customData;
}
}
/// <summary>
/// Tests if an instance can be created from the persisted profile data.
/// </summary>
/// <param name="profileName">The name of the profile to test.</param>
/// <param name="profilesLocation">The location of the shared ini-format credential file.</param>
/// <returns>True if the persisted data would yield a valid credentials instance.</returns>
/// <remarks>
/// 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.
/// </remarks>
public static bool CanCreateFrom(string profileName, string profilesLocation)
{
if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(profileName))
return SAMLRoleProfile.CanCreateFrom(profileName);
return false;
}
/// <summary>
/// Performs any additional validation we may require on the profile content.
/// </summary>
protected override void Validate()
{
}
/// <summary>
/// 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.
/// </summary>
/// <returns></returns>
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<ICoreAmazonSTS>(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;
}
}
}
| 420 |
aws-sdk-net | aws | C# | /*
* 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 System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Runtime.Credentials.Internal;
using Amazon.Util;
using Amazon.Util.Internal;
namespace Amazon.Runtime
{
/// <summary>
/// AWS Credentials that resolve using AWS SSO.
/// </summary>
public class SSOAWSCredentials : RefreshingAWSCredentials
{
private readonly Logger _logger = Logger.GetLogger(typeof(SSOAWSCredentials));
private readonly ISSOTokenManager _ssoTokenManager;
/// <summary>
/// The AWS account ID that temporary AWS credentials will be resolved for.
/// </summary>
public string AccountId { get; private set; }
/// <summary>
/// The AWS region where the SSO directory for <see cref="StartUrl"/> is hosted.
/// </summary>
public string Region { get; private set; }
/// <summary>
/// The corresponding IAM role in the AWS account that temporary AWS credentials will be resolved for.
/// </summary>
public string RoleName { get; private set; }
/// <summary>
/// The main URL for users to login to their SSO directory.
/// Provided by the SSO service via the web console.
/// </summary>
public string StartUrl { get; private set; }
/// <summary>
/// Options to be used in the SSO flow to resolve credentials.
/// Developers wishing to support AWS SSO would want to provide the following:
/// - <seealso cref="SSOAWSCredentialsOptions.ClientName"/>
/// - <seealso cref="SSOAWSCredentialsOptions.SsoVerificationCallback"/>
/// </summary>
public SSOAWSCredentialsOptions Options { get; private set; }
/// <summary>
/// Constructs an SSOAWSCredentials object.
/// </summary>
/// <param name="accountId">The AWS account ID that temporary AWS credentials will be resolved for.</param>
/// <param name="region">The AWS region where the SSO directory for <paramref name="startUrl"/> is hosted.</param>
/// <param name="roleName">The corresponding IAM role in the AWS account that temporary AWS credentials will be resolved for.</param>
/// <param name="startUrl">The main URL for users to login to their SSO directory.</param>
public SSOAWSCredentials(string accountId, string region, string roleName, string startUrl)
: this(accountId, region, roleName, startUrl, new SSOAWSCredentialsOptions())
{
}
/// <summary>
/// Constructs an SSOAWSCredentials object.
/// </summary>
/// <param name="accountId">The AWS account ID that temporary AWS credentials will be resolved for.</param>
/// <param name="region">The AWS region where the SSO directory for <paramref name="startUrl"/> is hosted.</param>
/// <param name="roleName">The corresponding IAM role in the AWS account that temporary AWS credentials will be resolved for.</param>
/// <param name="startUrl">The main URL for users to login to their SSO directory.</param>
/// <param name="options">Options to be used in the SSO flow to resolve credentials.</param>
public SSOAWSCredentials(
string accountId, string region,
string roleName, string startUrl,
SSOAWSCredentialsOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (string.IsNullOrEmpty(region))
throw new ArgumentNullException(nameof(region));
AccountId = accountId;
Region = region;
RoleName = roleName;
StartUrl = startUrl;
Options = options;
_ssoTokenManager = new SSOTokenManager(
SSOServiceClientHelpers.BuildSSOIDCClient(
RegionEndpoint.GetBySystemName(region),
options.ProxySettings),
new SSOTokenFileCache(
CryptoUtilFactory.CryptoInstance,
new FileRetriever(),
new DirectoryRetriever())
);
}
#if BCL
protected override CredentialsRefreshState GenerateNewCredentials()
{
ValidateCredentialsInputs();
var ssoClient =
SSOServiceClientHelpers.BuildSSOClient(
RegionEndpoint.GetBySystemName(Region),
Options.ProxySettings);
var credentials = GetSsoCredentials(ssoClient) as SSOImmutableCredentials;
if (credentials == null)
{
throw new NotSupportedException("Unable to get credentials from SSO");
}
_logger.InfoFormat("New SSO credentials created that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
return new CredentialsRefreshState(credentials, credentials.Expiration);
}
#else
protected override CredentialsRefreshState GenerateNewCredentials()
{
return GenerateNewCredentialsAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
#endif
protected override async Task<CredentialsRefreshState> GenerateNewCredentialsAsync()
{
ValidateCredentialsInputs();
var ssoClient =
SSOServiceClientHelpers.BuildSSOClient(
RegionEndpoint.GetBySystemName(Region),
Options.ProxySettings);
var credentials =
await GetSsoCredentialsAsync(ssoClient).ConfigureAwait(false) as SSOImmutableCredentials;
if (credentials == null)
{
throw new NotSupportedException("Unable to get credentials from SSO");
}
_logger.InfoFormat("New SSO credentials created that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
return new CredentialsRefreshState(credentials, credentials.Expiration);
}
private void ValidateCredentialsInputs()
{
// Get the name of any empty properties
var emptyPropertyNames = new Dictionary<string, string>
{
{nameof(AccountId), AccountId},
{nameof(Region), Region},
{nameof(RoleName), RoleName},
{nameof(StartUrl), StartUrl},
}.Where(propNameToValue => string.IsNullOrWhiteSpace(propNameToValue.Value))
.Select(propNameToValue => propNameToValue.Key)
.ToList();
if (emptyPropertyNames.Any())
{
throw new ArgumentNullException($"Property cannot be empty: {string.Join(", ", emptyPropertyNames)}");
}
}
#if BCL
/// <summary>
/// Performs the SSO flow to authenticate and get credentials
/// </summary>
/// <param name="oidc">SSO OIDC client</param>
/// <param name="sso">SSO client</param>
/// <returns>Resolved credentials</returns>
private ImmutableCredentials GetSsoCredentials(ICoreAmazonSSO sso)
{
var ssoTokenManagerGetTokenOptions = new SSOTokenManagerGetTokenOptions
{
ClientName = Options.ClientName,
Region = Region,
SsoVerificationCallback = Options.SsoVerificationCallback,
StartUrl = StartUrl,
Session = Options.SessionName
};
var token = _ssoTokenManager.GetToken(ssoTokenManagerGetTokenOptions);
// Use SSO token to get credentials
return GetSsoRoleCredentials(sso, token.AccessToken);
}
#endif
/// <summary>
/// Performs the SSO flow to authenticate and get credentials
/// </summary>
/// <param name="sso">SSO client</param>
/// <returns>Resolved credentials</returns>
private async Task<ImmutableCredentials> GetSsoCredentialsAsync(ICoreAmazonSSO sso)
{
var ssoTokenManagerGetTokenOptions = new SSOTokenManagerGetTokenOptions
{
ClientName = Options.ClientName,
Region = Region,
SsoVerificationCallback = Options.SsoVerificationCallback,
StartUrl = StartUrl,
Session = Options.SessionName
};
var token = await _ssoTokenManager.GetTokenAsync(ssoTokenManagerGetTokenOptions).ConfigureAwait(false);
// Use SSO token to get credentials
return await GetSsoRoleCredentialsAsync(sso, token.AccessToken).ConfigureAwait(false);
}
/// <summary>
/// Returns true if there is already a non-expired cached login access token in the token cache.
/// </summary>
/// <param name="startUrl"></param>
/// <returns>Obsolete: ALWAYS RETURNS FALSE</returns>
[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
/// <summary>
/// Get resolved credentials from an AWS SSO access token
/// </summary>
/// <param name="sso">AWS SSO Client</param>
/// <param name="accessToken">AWS SSO access token obtained from a user's authorization</param>
/// <returns>Resolved credentials</returns>
private ImmutableCredentials GetSsoRoleCredentials(ICoreAmazonSSO sso, string accessToken)
{
return sso.CredentialsFromSsoAccessToken(AccountId, RoleName, accessToken, null);
}
#endif
/// <summary>
/// Get resolved credentials from an AWS SSO access token
/// </summary>
/// <param name="sso">AWS SSO Client</param>
/// <param name="accessToken">AWS SSO access token obtained from a user's authorization</param>
/// <returns>Resolved credentials</returns>
private async Task<ImmutableCredentials> GetSsoRoleCredentialsAsync(ICoreAmazonSSO sso, string accessToken)
{
return await sso.CredentialsFromSsoAccessTokenAsync(AccountId, RoleName, accessToken, null)
.ConfigureAwait(false);
}
}
}
| 268 |
aws-sdk-net | aws | C# | /*
* 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 System;
using System.Globalization;
using System.Net;
namespace Amazon.Runtime
{
public class SsoVerificationArguments
{
/// <summary>
/// The end-user verification code that is provided (by the user or on their behalf) when
/// the user logs in using <see cref="VerificationUri"/>
/// </summary>
public string UserCode { get; set; }
/// <summary>
/// End-user verification URI on the authorization server.
/// </summary>
public string VerificationUri { get; set; }
/// <summary>
/// A verification URI that includes the "user_code", designed for non-textual transmission.
/// </summary>
public string VerificationUriComplete { get; set; }
/// <summary>
/// Produces a stock message that can be presented to users, instructing them how to log in through SSO.
/// </summary>
public string GetSsoSigninMessage()
{
return string.Format(
$"Using a browser, visit: {VerificationUri}{0}" +
$"And enter the code: {UserCode}{0}",
Environment.NewLine
);
}
}
public class SSOAWSCredentialsOptions
{
/// <summary>
/// Required - Name of the application or system used during SSO client registration.
/// A timestamp indicating when the client was registered will be appended to requests made to the SSOOIDC service.
/// </summary>
public string ClientName { get; set; }
/// <summary>
/// The name of the sso_session section in the shared configuration file specified to be used when loading the token.
/// </summary>
public string SessionName { get; set; }
/// <summary>
/// A callback that is used to initiate the SSO Login flow with the user.
/// </summary>
public Action<SsoVerificationArguments> SsoVerificationCallback { get; set; }
/// <summary>
/// The proxy settings to use when calling SSOOIDC and SSO Services.
/// </summary>
#if BCL
public WebProxy ProxySettings { get; set; }
#elif NETSTANDARD
public IWebProxy ProxySettings { get; set; }
#endif
}
}
| 84 |
aws-sdk-net | aws | C# | /*
* 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 Amazon.Util;
using System;
namespace Amazon.Runtime
{
/// <summary>
/// Immutable representation of AWS credentials obtained as a result of
/// authenticating through AWS SSO.
/// </summary>
public class SSOImmutableCredentials : ImmutableCredentials
{
/// <summary>
/// The expiry time of the credentials, obtained from the AWS SSO service.
/// </summary>
public DateTime Expiration { get; private set; }
/// <summary>
/// Constructs an instance with supplied keys, token, and expiration.
/// </summary>
/// <param name="awsAccessKeyId">The AccessKey for the credentials.</param>
/// <param name="awsSecretAccessKey">The SecretKey for the credentials.</param>
/// <param name="token">The security token for the credentials.</param>
/// <param name="expiration">The expiration time for the credentials.</param>
public SSOImmutableCredentials(
string awsAccessKeyId, string awsSecretAccessKey,
string token, DateTime expiration)
: base(awsAccessKeyId, awsSecretAccessKey, token)
{
if (string.IsNullOrEmpty(token)) throw new ArgumentNullException(nameof(token));
Expiration = expiration;
}
/// <summary>
/// Get a copy of this SSOImmutableCredentials object.
/// </summary>
/// <returns>A copy of this object.</returns>
public new SSOImmutableCredentials Copy()
{
return new SSOImmutableCredentials(AccessKey, SecretKey, Token, Expiration);
}
public override int GetHashCode()
{
return Hashing.Hash(AccessKey, SecretKey, Token, Expiration);
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
SSOImmutableCredentials ssoImmutableCredentials = obj as SSOImmutableCredentials;
if (ssoImmutableCredentials == null)
return false;
return AWSSDKUtils.AreEqual(
new object[] { AccessKey, SecretKey, Token, Expiration },
new object[] { ssoImmutableCredentials.AccessKey, ssoImmutableCredentials.SecretKey, ssoImmutableCredentials.Token, Expiration });
}
}
}
| 78 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.Runtime.Internal
{
public class CSMConfiguration
{
// Host that the Agent Monitoring connects. Defaults to 127.0.0.1
public string Host { get; internal set; } = Amazon.Util.CSMConfig.DEFAULT_HOST;
// Port number that the Agent Monitoring Listener writes to. Defaults to 31000
public int Port { get; internal set; } = Amazon.Util.CSMConfig.DEFAULT_PORT;
// Determines whether or not the Agent Monitoring Listener is enabled
public bool Enabled { get; internal set; }
// Contains the clientId to all monitoring events generated by the SDK
public string ClientId { get; internal set; } = string.Empty;
}
}
| 35 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Amazon.Runtime.CredentialManagement;
using Amazon.Runtime.Internal.Util;
using Amazon.Util.Internal;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This class gets the CSM configuration if set.
/// The priority goes
/// 1. App.config / instantiate on the AWSConfigs class
/// 2. Environment variable
/// 3. Shared Profile
/// </summary>
public class CSMFallbackConfigChain
{
private readonly ILogger LOGGER = Logger.GetLogger(typeof(CSMFallbackConfigChain));
private static CredentialProfileStoreChain credentialProfileChain = new CredentialProfileStoreChain(AWSConfigs.AWSProfilesLocation);
public delegate void ConfigurationSource();
public List<ConfigurationSource> AllGenerators { get; set; }
internal bool IsConfigSet { get; set; }
public string ConfigSource { get; set; }
public CSMConfiguration CSMConfiguration { get; internal set; }
public CSMFallbackConfigChain()
{
CSMConfiguration = new CSMConfiguration();
AllGenerators = new List<ConfigurationSource>
{
() => new AppConfigCSMConfigs(this),
() => new EnvironmentVariableCSMConfigs(this),
() => new ProfileCSMConfigs(credentialProfileChain, this)
};
}
public CSMConfiguration GetCSMConfig()
{
foreach (var generator in AllGenerators)
{
try
{
generator();
if (IsConfigSet)
{
break;
}
}
catch(Exception e)
{
LOGGER.Error(e, "Error looking for CSM configuration");
}
}
return CSMConfiguration;
}
}
/// <summary>
/// Determine CSM configs from shared profile file.
/// </summary>
public class ProfileCSMConfigs
{
private const string CSM_ENABLED = "csm_enabled";
private const string CSM_CLIENTID = "csm_clientid";
private const string CSM_HOST = "csm_host";
private const string CSM_PORT = "csm_port";
private const string CSM_PROFILE_ERROR_MSG = "CSM configurations not found using profile store.";
private string ProfileName { get; set; }
public ProfileCSMConfigs(CSMFallbackConfigChain cSMFallbackConfigChain, string profileName, IDictionary<string, string> profileProperties)
{
ProfileName = profileName;
Setup(cSMFallbackConfigChain, profileProperties);
}
public ProfileCSMConfigs(ICredentialProfileSource source, CSMFallbackConfigChain cSMFallbackConfigChain)
{
ProfileName = FallbackCredentialsFactory.GetProfileName();
CredentialProfile profile;
if (!source.TryGetProfile(ProfileName, out profile))
{
return;
}
Setup(cSMFallbackConfigChain, profile.Properties);
}
private void Setup(CSMFallbackConfigChain cSMFallbackConfigChain, IDictionary<string, string> profileProperties)
{
var logger = Logger.GetLogger(typeof(ProfileCSMConfigs));
var csmConfiguration = cSMFallbackConfigChain.CSMConfiguration;
string csm_enabled;
if (!profileProperties.TryGetValue(CSM_ENABLED, out csm_enabled))
{
return;
}
cSMFallbackConfigChain.IsConfigSet = true;
cSMFallbackConfigChain.ConfigSource = "shared profile";
bool enabled;
if (bool.TryParse(csm_enabled, out enabled))
{
csmConfiguration.Enabled = enabled;
}
else
{
throw new AmazonClientException("Unexpected profile variable value type " + CSM_ENABLED + ". Set a valid boolean value.");
}
if (csmConfiguration.Enabled)
{
string clientId;
if (profileProperties.TryGetValue(CSM_CLIENTID, out clientId))
{
csmConfiguration.ClientId = clientId;
}
string csm_port;
if (profileProperties.TryGetValue(CSM_PORT, out csm_port))
{
int port;
if (int.TryParse(csm_port, out port))
{
csmConfiguration.Port = port;
}
else
{
throw new AmazonClientException("Unexpected profile variable value type " + CSM_PORT + ". Set a valid integer value.");
}
}
string csm_host;
if (profileProperties.TryGetValue(CSM_HOST, out csm_host))
{
if (!string.IsNullOrEmpty(csm_host))
{
csmConfiguration.Host = csm_host;
}
}
}
logger.InfoFormat(string.Format(CultureInfo.InvariantCulture,
"CSM configurations found using profile store for the profile = {0}: values are CSM enabled = {1}, host = {2}, port = {3}, clientid = {4}",
ProfileName, csmConfiguration.Enabled, csmConfiguration.Host, csmConfiguration.Port, csmConfiguration.ClientId));
}
}
/// <summary>
/// Determine CSM configs from environment variables.
/// </summary>
public class EnvironmentVariableCSMConfigs
{
private const string CSM_ENABLED = "AWS_CSM_ENABLED";
private const string CSM_CLIENTID = "AWS_CSM_CLIENT_ID";
private const string CSM_HOST = "AWS_CSM_HOST";
private const string CSM_PORT = "AWS_CSM_PORT";
private IEnvironmentVariableRetriever environmentRetriever { get; set; } = EnvironmentVariableSource.Instance.EnvironmentVariableRetriever;
public EnvironmentVariableCSMConfigs(IEnvironmentVariableRetriever environmentRetriever, CSMFallbackConfigChain cSMFallbackConfigChain)
{
this.environmentRetriever = environmentRetriever;
SetupConfiguration(cSMFallbackConfigChain);
}
public EnvironmentVariableCSMConfigs(CSMFallbackConfigChain cSMFallbackConfigChain)
{
SetupConfiguration(cSMFallbackConfigChain);
}
private void SetupConfiguration(CSMFallbackConfigChain cSMFallbackConfigChain)
{
var csmConfiguration = cSMFallbackConfigChain.CSMConfiguration;
var logger = Logger.GetLogger(typeof(EnvironmentVariableCSMConfigs));
var enabled = environmentRetriever.GetEnvironmentVariable(CSM_ENABLED);
if (string.IsNullOrEmpty(enabled))
{
return;
}
cSMFallbackConfigChain.IsConfigSet = true;
cSMFallbackConfigChain.ConfigSource = "environment variable";
bool csm_enabled;
if (bool.TryParse(enabled, out csm_enabled))
{
csmConfiguration.Enabled = csm_enabled;
}
else
{
throw new AmazonClientException("Unexpected environment variable value type " + CSM_ENABLED + ". Set a valid boolean value.");
}
if (csmConfiguration.Enabled)
{
csmConfiguration.ClientId = environmentRetriever.GetEnvironmentVariable(CSM_CLIENTID) ?? csmConfiguration.ClientId;
string portValue = environmentRetriever.GetEnvironmentVariable(CSM_PORT);
if (!string.IsNullOrEmpty(portValue))
{
int port;
if (int.TryParse(portValue, out port))
{
csmConfiguration.Port = port;
}
else
{
throw new AmazonClientException("Unexpected environment variable value type " + CSM_PORT + ". Set a valid integer value.");
}
}
string hostValue = environmentRetriever.GetEnvironmentVariable(CSM_HOST);
if(!string.IsNullOrEmpty(hostValue))
{
csmConfiguration.Host = hostValue;
}
}
logger.InfoFormat(string.Format(CultureInfo.InvariantCulture,
"CSM configurations found using environment variable. values are CSM enabled = {0}, host = {1}, port = {2}, clientid = {3}",
csmConfiguration.Enabled, csmConfiguration.Host, csmConfiguration.Port, csmConfiguration.ClientId));
}
}
/// <summary>
/// Determine CSM configs from AWSConfigs class.
/// </summary>
public class AppConfigCSMConfigs
{
public AppConfigCSMConfigs(CSMFallbackConfigChain cSMFallbackConfigChain)
{
var csmConfiguration = cSMFallbackConfigChain.CSMConfiguration;
var logger = Logger.GetLogger(typeof(AppConfigCSMConfigs));
if(!AWSConfigs.CSMConfig.CSMEnabled.HasValue)
{
return;
}
cSMFallbackConfigChain.IsConfigSet = true;
if (!AWSConfigs.CSMConfig.CSMEnabled.GetValueOrDefault())
{
return;
}
cSMFallbackConfigChain.ConfigSource = "app config";
csmConfiguration.Enabled = AWSConfigs.CSMConfig.CSMEnabled.GetValueOrDefault();
if (csmConfiguration.Enabled)
{
if (!string.IsNullOrEmpty(AWSConfigs.CSMConfig.CSMClientId))
{
csmConfiguration.ClientId = AWSConfigs.CSMConfig.CSMClientId;
}
csmConfiguration.Host = AWSConfigs.CSMConfig.CSMHost;
csmConfiguration.Port = AWSConfigs.CSMConfig.CSMPort;
logger.InfoFormat(string.Format(CultureInfo.InvariantCulture,
"CSM configurations found using application configuration file. values are CSM enabled = {0}, host = {1}, port = {2}, clientid = {3}",
csmConfiguration.Enabled, csmConfiguration.Host, csmConfiguration.Port, csmConfiguration.ClientId));
}
}
}
}
| 269 |
aws-sdk-net | aws | C# | /*
* 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.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
#if AWS_ASYNC_API
using System.Threading.Tasks;
#endif
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Utility class for CSM.
/// Contains logic to serialize CSM events to Json.
/// </summary>
public static class CSMUtilities
{
private const string requestKey = "Request";
#if AWS_ASYNC_API
public static Task SerializetoJsonAndPostOverUDPAsync(MonitoringAPICall monitoringAPICall)
{
var monitoringAPICallAttempt = monitoringAPICall as MonitoringAPICallAttempt;
if (monitoringAPICallAttempt != null)
{
if (CreateUDPMessage(monitoringAPICallAttempt, out string response))
{
return MonitoringListener.Instance.PostMessagesOverUDPAsync(response);
}
}
else
{
if (CreateUDPMessage((MonitoringAPICallEvent)monitoringAPICall, out string response))
{
return MonitoringListener.Instance.PostMessagesOverUDPAsync(response);
}
}
return Task.FromResult(0);
}
#else
public static void BeginSerializetoJsonAndPostOverUDP(MonitoringAPICall monitoringAPICall)
{
string response = string.Empty;
var monitoringAPICallAttempt = monitoringAPICall as MonitoringAPICallAttempt;
if (monitoringAPICallAttempt != null)
{
if (CreateUDPMessage(monitoringAPICallAttempt, out response))
{
MonitoringListener.Instance.BeginPostMessagesOverUDPInvoke(response);
}
}
else
{
if (CreateUDPMessage((MonitoringAPICallEvent)monitoringAPICall, out response))
{
MonitoringListener.Instance.BeginPostMessagesOverUDPInvoke(response);
}
}
}
#endif
public static void SerializetoJsonAndPostOverUDP(MonitoringAPICall monitoringAPICall)
{
string response = string.Empty;
var monitoringAPICallAttempt = monitoringAPICall as MonitoringAPICallAttempt;
if (monitoringAPICallAttempt != null)
{
if (CreateUDPMessage(monitoringAPICallAttempt, out response))
{
MonitoringListener.Instance.PostMessagesOverUDP(response);
}
}
else
{
if (CreateUDPMessage((MonitoringAPICallEvent)monitoringAPICall, out response))
{
MonitoringListener.Instance.PostMessagesOverUDP(response);
}
}
}
/// <summary>
/// Method to retrieve the API name from the request name.
/// </summary>
public static string GetApiNameFromRequest(string requestName, IDictionary<string, string> serviceApiNameMapping, string serviceName)
{
var logger = Logger.GetLogger(typeof(CSMUtilities));
// Verify that the requestName has the requestKey(Request) as a suffix.
if (requestName.EndsWith(requestKey, StringComparison.Ordinal))
{
// The API name is extracted from the requestName like so -
// PutObjectRequest is converted PutObject by removing the
// 'Request' keyword.
var apiName = requestName.Substring(0, requestName.Length - requestKey.Length);
if (serviceApiNameMapping.Count > 0)
{
string actualApiName;
if(serviceApiNameMapping.TryGetValue(apiName, out actualApiName))
{
apiName = actualApiName;
}
}
return apiName;
}
else
{
logger.InfoFormat(string.Format(CultureInfo.InvariantCulture, "Invalid request name: Request {0} does not end with the keyword '{1}'. Investigate possible generator bug for service:{2} and operation name:{3}", requestName, requestKey, serviceName, requestName));
return string.Empty;
}
}
/// <summary>
/// Method to serialize MonitoringAPICallAttempt CSM event to json.
/// </summary>
private static bool CreateUDPMessage(MonitoringAPICallAttempt monitoringAPICallAttempt, out string response)
{
JsonWriter jw = new JsonWriter();
jw.WriteObjectStart();
jw = CreateUDPMessage(monitoringAPICallAttempt, jw);
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.AccessKey))
{
jw.WritePropertyName("AccessKey");
jw.Write(monitoringAPICallAttempt.AccessKey);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.AWSException))
{
jw.WritePropertyName("AWSException");
jw.Write(monitoringAPICallAttempt.AWSException);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.Fqdn))
{
jw.WritePropertyName("Fqdn");
jw.Write(monitoringAPICallAttempt.Fqdn);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.SdkException))
{
jw.WritePropertyName("SdkException");
jw.Write(monitoringAPICallAttempt.SdkException);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.AWSExceptionMessage))
{
jw.WritePropertyName("AWSExceptionMessage");
jw.Write(monitoringAPICallAttempt.AWSExceptionMessage);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.SdkExceptionMessage))
{
jw.WritePropertyName("SdkExceptionMessage");
jw.Write(monitoringAPICallAttempt.SdkExceptionMessage);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.SessionToken))
{
jw.WritePropertyName("SessionToken");
jw.Write(monitoringAPICallAttempt.SessionToken);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.XAmzId2))
{
jw.WritePropertyName("XAmzId2");
jw.Write(monitoringAPICallAttempt.XAmzId2);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.XAmznRequestId))
{
jw.WritePropertyName("XAmznRequestId");
jw.Write(monitoringAPICallAttempt.XAmznRequestId);
}
if (!string.IsNullOrEmpty(monitoringAPICallAttempt.XAmzRequestId))
{
jw.WritePropertyName("XAmzRequestId");
jw.Write(monitoringAPICallAttempt.XAmzRequestId);
}
if (monitoringAPICallAttempt.HttpStatusCode != null)
{
jw.WritePropertyName("HttpStatusCode");
jw.Write((int)monitoringAPICallAttempt.HttpStatusCode);
}
jw.WritePropertyName("AttemptLatency");
jw.Write(monitoringAPICallAttempt.AttemptLatency);
jw.WriteObjectEnd();
response = jw.ToString();
return ASCIIEncoding.Unicode.GetByteCount(response) <= (8 * 1024);
}
/// <summary>
/// Method to serialize MonitoringAPICallEvent CSM event to json.
/// </summary>
private static bool CreateUDPMessage(MonitoringAPICallEvent monitoringAPICallEvent, out string response)
{
JsonWriter jw = new JsonWriter();
jw.WriteObjectStart();
jw = CreateUDPMessage(monitoringAPICallEvent, jw);
jw.WritePropertyName("Latency");
jw.Write(monitoringAPICallEvent.Latency);
jw.WritePropertyName("AttemptCount");
jw.Write(monitoringAPICallEvent.AttemptCount);
jw.WritePropertyName("MaxRetriesExceeded");
int maxRetriesValue = 0;
if (monitoringAPICallEvent.IsLastExceptionRetryable)
{
maxRetriesValue = 1;
}
jw.Write(maxRetriesValue);
if (monitoringAPICallEvent.FinalHttpStatusCode != null)
{
jw.WritePropertyName("FinalHttpStatusCode");
jw.Write((int)monitoringAPICallEvent.FinalHttpStatusCode);
}
if (!string.IsNullOrEmpty(monitoringAPICallEvent.FinalAWSException))
{
jw.WritePropertyName("FinalAWSException");
jw.Write(monitoringAPICallEvent.FinalAWSException);
}
if (!string.IsNullOrEmpty(monitoringAPICallEvent.FinalSdkException))
{
jw.WritePropertyName("FinalSdkException");
jw.Write(monitoringAPICallEvent.FinalSdkException);
}
if (!string.IsNullOrEmpty(monitoringAPICallEvent.FinalAWSExceptionMessage))
{
jw.WritePropertyName("FinalAWSExceptionMessage");
jw.Write(monitoringAPICallEvent.FinalAWSExceptionMessage);
}
if (!string.IsNullOrEmpty(monitoringAPICallEvent.FinalSdkExceptionMessage))
{
jw.WritePropertyName("FinalSdkExceptionMessage");
jw.Write(monitoringAPICallEvent.FinalSdkExceptionMessage);
}
jw.WriteObjectEnd();
response = jw.ToString();
return ASCIIEncoding.Unicode.GetByteCount(response) <= (8 * 1024);
}
/// <summary>
/// Method to serialize MonitoringAPICall CSM event to json.
/// </summary>
private static JsonWriter CreateUDPMessage(MonitoringAPICall monitoringAPICall, JsonWriter jw)
{
string response = string.Empty;
if (!string.IsNullOrEmpty(monitoringAPICall.Api))
{
jw.WritePropertyName("Api");
jw.Write(monitoringAPICall.Api);
}
if (!string.IsNullOrEmpty(monitoringAPICall.Service))
{
jw.WritePropertyName("Service");
jw.Write(monitoringAPICall.Service);
}
if (!string.IsNullOrEmpty(monitoringAPICall.ClientId))
{
jw.WritePropertyName("ClientId");
jw.Write(monitoringAPICall.ClientId);
}
jw.WritePropertyName("Version");
jw.Write(monitoringAPICall.Version);
if (!string.IsNullOrEmpty(monitoringAPICall.Type))
{
jw.WritePropertyName("Type");
jw.Write(monitoringAPICall.Type);
}
jw.WritePropertyName("Timestamp");
jw.Write(monitoringAPICall.Timestamp);
if (!string.IsNullOrEmpty(monitoringAPICall.Region))
{
jw.WritePropertyName("Region");
jw.Write(monitoringAPICall.Region);
}
if (!string.IsNullOrEmpty(monitoringAPICall.UserAgent))
{
jw.WritePropertyName("UserAgent");
jw.Write(monitoringAPICall.UserAgent);
}
return jw;
}
}
}
| 329 |
aws-sdk-net | aws | C# | /*
* 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.Internal;
using System;
using System.Collections.Generic;
using System.Text;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Internal class that has the CSM configurations for the Monitoring Listener
/// after being derived from the CSMConfigChain class.
/// </summary>
public sealed class DeterminedCSMConfiguration
{
private static readonly DeterminedCSMConfiguration instance = new DeterminedCSMConfiguration();
public CSMConfiguration CSMConfiguration { get; set; }
private DeterminedCSMConfiguration()
{
CSMConfiguration = new CSMFallbackConfigChain().GetCSMConfig();
}
static DeterminedCSMConfiguration()
{
}
public static DeterminedCSMConfiguration Instance
{
get
{
return instance;
}
}
}
}
| 49 |
aws-sdk-net | aws | C# | /*
* 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 System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// CSM event base class
/// </summary>
public class MonitoringAPICall
{
public MonitoringAPICall(IRequestContext requestContext)
: this()
{
Service = requestContext.ServiceMetaData.ServiceId;
Api = CSMUtilities.GetApiNameFromRequest(requestContext.RequestName, requestContext.ServiceMetaData.OperationNameMapping, Service);
}
public MonitoringAPICall()
{
Timestamp = AWSSDKUtils.ConvertDateTimetoMilliseconds(DateTime.UtcNow);
ClientId = DeterminedCSMConfiguration.Instance.CSMConfiguration.ClientId;
}
/// <summary>
/// Contains the operation name for the api call being made
/// </summary>
public string Api { get; internal set; }
/// <summary>
/// Contains the service id ServiceId Sep of the service
/// against which the call is being made
/// </summary>
public string Service { get; internal set; }
/// <summary>
/// Contains the "ClientId" configuration value
/// computed from the CSMConfigChain class
/// </summary>
public string ClientId { get; internal set; }
/// <summary>
/// Contains the elapsed time, in milliseconds,
/// since January 1st, 1970, for the time point
/// at which the event occurred
/// </summary>
public long Timestamp { get; internal set; }
/// <summary>
/// Contains "ApiCall" or "ApiCallAttempt"
/// based on what the monitoring event is describing
/// </summary>
public string Type { get; internal set; }
/// <summary>
/// Contains the enum of the above CSM type property
/// </summary>
protected enum CSMType
{
ApiCall,
ApiCallAttempt
}
/// <summary>
/// Contains the "Version" configuration value
/// computed from the CSMConfigChain class
/// Defaults to 1.
/// </summary>
public int Version { get; internal set; } = 1;
/// <summary>
/// Contains the signing region used by the
/// service client that made the request attempt.
/// </summary>
public string Region { get; internal set; }
/// <summary>
/// Contains the full value of the SDK's default
/// user agent header for http requests.
/// </summary>
public string UserAgent { get; internal set; }
}
}
| 103 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Net;
using System.Text;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Class that captures the CSM Api Call Attempt Monitoring Events
/// for each http request and its subsequent response.
/// </summary>
public class MonitoringAPICallAttempt : MonitoringAPICall
{
public MonitoringAPICallAttempt(IRequestContext requestContext)
:base(requestContext)
{
Type = CSMType.ApiCallAttempt.ToString();
}
/// <summary>
/// Contains the fully-qualified domain name of the endpoint that
/// the request attempt was submitted to.
/// </summary>
public string Fqdn { get; internal set; }
/// <summary>
/// Contains the session token passed
/// in the x-amz-security-token header.
/// </summary>
public string SessionToken { get; internal set; }
/// <summary>
/// Contains the aws_access_key value that
/// was used to sign the http request.
/// </summary>
public string AccessKey { get; internal set; }
/// <summary>
/// Contains the attempt's response status code,
/// as returned by the http client.
/// </summary>
public int? HttpStatusCode { get; internal set; } = null;
/// <summary>
/// Contains the full text (exception object converted to String,
/// for example) for any attempt-level failure that is due to
/// something other than an Aws exception. The value of this entry
/// has a maximum length of 512.
/// </summary>
public string SdkExceptionMessage { get; internal set; }
/// <summary>
/// Contains the short error name (exception class name, for example)
/// for any attempt-level failure that is due to something other
/// than an Aws exception.The value of this entry has a maximum length of 128.
/// </summary>
public string SdkException { get; internal set; }
/// <summary>
/// Contains the Aws exception code returned in the response.
/// </summary>
public string AWSException { get; internal set; }
/// <summary>
/// Contains the full text of the Aws exception message.
/// </summary>
public string AWSExceptionMessage { get; internal set; }
/// <summary>
/// Contains the value of the response's x-amzn-RequestId header.
/// </summary>
public string XAmznRequestId { get; internal set; }
/// <summary>
/// Contains the value of the response's x-amz-request-id header.
/// </summary>
public string XAmzRequestId { get; internal set; }
/// <summary>
/// Contains the value of the response's x-amz-id-2 header.
/// </summary>
public string XAmzId2 { get; internal set; }
/// <summary>
/// Contains the elapsed time, in milliseconds,
/// between the construction of the http request and the
/// point in time where the http response has been parsed
/// or the attempt has definitively failed.
/// </summary>
public long AttemptLatency { get; internal set; }
}
}
| 107 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Class that captures the CSM Api Call Monitoring Events
/// for the entire SDK call. This is processed once.
/// </summary>
public class MonitoringAPICallEvent : MonitoringAPICall
{
public MonitoringAPICallEvent(IRequestContext requestContext)
:base(requestContext)
{
Type = CSMType.ApiCall.ToString();
}
/// <summary>
/// Contains the total number of attempts that were made
/// by the service client to fulfill this request before succeeding or failing
/// </summary>
public int AttemptCount { get; internal set; }
/// <summary>
/// Contains the elapsed time, in milliseconds,
/// between when the Api Call was begun and when a
/// final response or error is manifested to the caller
/// </summary>
public long Latency { get; internal set; }
/// <summary>
/// a boolean (0/1) value that is 0 unless the Api call failed
/// and the final attempt returned a retryable error.This entry should be
/// serialized as a numeric 0/1 value. This is mapped to MaxRetriesExceeded
/// when serialized to a UDP datagram.
/// </summary>
public bool IsLastExceptionRetryable { get; internal set; }
/// <summary>
/// Contains the full text (exception object
/// converted to String, for example) for an attempt-level failure that is due to
/// something other than an Aws exception that occurred on the last attempt to
/// fulfill the Api call.The value of this entry has a maximum length of 512.
/// </summary>
public string FinalSdkExceptionMessage { get; internal set; }
/// <summary>
/// Contains the short error name (exception
/// class name, for example) for a failure that is due to something other than an
/// Aws exception that occurred on the last attempt to fulfill an Api call.See
/// the SdkException entry for more details.The value of this entry has a
/// maximum length of 128.
/// </summary>
public string FinalSdkException { get; internal set; }
/// <summary>
/// Contains the Aws exception code
/// returned in the response to the final attempt at fulfilling this API call.
/// The value of this entry has a maximum length of 128.
/// </summary>
public string FinalAWSException { get; internal set; }
/// <summary>
/// Contains the full text of the
/// Aws exception message returned in the response to the final attempt at
/// fulfilling this API call.The value of this entry has a maximum length limit
/// of 512.
/// </summary>
public string FinalAWSExceptionMessage { get; internal set; }
/// <summary>
/// Contains the attempt's response status code,
/// as returned by the http client.
/// </summary>
public int? FinalHttpStatusCode { get; internal set; } = null;
}
}
| 94 |
aws-sdk-net | aws | C# | /*
* 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.Net;
using System.Net.Sockets;
using System.Text;
#if AWS_ASYNC_API
using System.Threading.Tasks;
#endif
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime
{
/// <summary>
/// Class that posts the CSM event to a UDP portconfig
/// This is a singleton class and is created once
/// per AmazonServiceClient.
/// </summary>
internal sealed class MonitoringListener:IDisposable
{
private static readonly MonitoringListener csmMonitoringListenerInstance = new MonitoringListener();
/// <summary>
/// The CSMevents are always posted to the localhost
/// </summary>
private readonly string _host;
private readonly UdpClient _udpClient;
private readonly Logger logger;
private readonly int _port;
private MonitoringListener()
{
_host = DeterminedCSMConfiguration.Instance.CSMConfiguration.Host;
_port = DeterminedCSMConfiguration.Instance.CSMConfiguration.Port;
_udpClient = new UdpClient();
logger = Logger.GetLogger(typeof(MonitoringListener));
}
static MonitoringListener()
{
}
public static MonitoringListener Instance
{
get
{
return csmMonitoringListenerInstance;
}
}
/// <summary>
/// Method to post UDP datagram for sync calls
/// </summary>
public void PostMessagesOverUDP(string response)
{
#if BCL
try
{
_udpClient.Send(Encoding.UTF8.GetBytes(response),
Encoding.UTF8.GetBytes(response).Length, _host, _port);
}
catch (Exception e)
{
// If UDP post fails, the errors is logged and is returned without rethrowing the exception
logger.InfoFormat("Error when posting UDP datagrams. " + e.Message);
}
#endif
}
/// <summary>
/// Method to post UDP datagram for async calls
/// </summary>
#if AWS_ASYNC_API
public async Task PostMessagesOverUDPAsync(string response)
{
try
{
await _udpClient.SendAsync(Encoding.UTF8.GetBytes(response),
Encoding.UTF8.GetBytes(response).Length, _host, _port).ConfigureAwait(false);
}
catch(Exception e)
{
// If UDP post fails, the errors is logged and is returned without rethrowing the exception
logger.InfoFormat("Error when posting UDP datagrams. " + e.Message);
}
}
/// <summary>
/// Method to post UDP datagram for bcl35 async calls
/// </summary>
#else
public void BeginPostMessagesOverUDPInvoke(string response)
{
try
{
_udpClient.BeginSend(Encoding.UTF8.GetBytes(response),
Encoding.UTF8.GetBytes(response).Length, _host, _port, new AsyncCallback(EndSendMessagesOverUDPInvoke), _udpClient);
}
catch (Exception e)
{
// If UDP post fails, the errors is logged and is returned without rethrowing the exception
logger.InfoFormat("Error when posting UDP datagrams. " + e.Message);
}
}
private void EndSendMessagesOverUDPInvoke(IAsyncResult ar)
{
try
{
var udpClient = (UdpClient)ar.AsyncState;
if (!ar.IsCompleted)
{
ar.AsyncWaitHandle.WaitOne();
}
udpClient.EndSend(ar);
}
catch (Exception e)
{
// If UDP post fails, the errors is logged and is returned without rethrowing the exception
logger.InfoFormat("Error when posting UDP datagrams. " + e.Message);
}
}
#endif
private bool _disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
#if NETSTANDARD
_udpClient.Dispose();
#else
_udpClient.Close();
#endif
}
_disposed = true;
}
}
}
| 158 |
aws-sdk-net | aws | C# | /*
* 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.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Documents
{
/// <summary>
/// A specialized type that is used to carry open content. A <see cref="Document"/> can represent primitives like
/// <see cref="bool"/>, <see cref="double"/> <see cref="int"/>, <see cref="long"/> and <see cref="string"/>, complex objects
/// (represented as a Dictionary<string,Document>) and lists of <see cref="Document"/>.
/// <para />
/// When working with a <see cref="Document"/> it's necessary to first convert it to its backing type via one of the provided AsX() methods.
/// Type checking can be done via IsX() method.
/// <example><code><![CDATA[
/// public void ConsumeDocument(Document doc)
/// {
/// if (doc.IsInt())
/// {
/// int intValue = doc.AsInt();
/// // do work with intValue
/// }
/// else if (doc.IsString())
/// {
/// string stringValue = doc.AsString();
/// // do work with stringValue
/// }
/// }
/// ]]></code></example>
/// </summary>
/// <remarks>
/// Document Types specification specifies support for arbitrary precision integers. However, the dotnet implementation
/// is limited to representing numbers as either <see cref="double"/>, <see cref="int"/> or <see cref="long"/>.
/// </remarks>
public partial struct Document : IEquatable<Document>, IEnumerable<Document>, IEnumerable<KeyValuePair<string, Document>>
{
private readonly bool _dataBool;
private readonly double _dataDouble;
private readonly int _dataInt;
private readonly long _dataLong;
private readonly string _dataString;
private List<Document> _dataList;
private Dictionary<string, Document> _dataDictionary;
public DocumentType Type { get; private set; }
#region Constructors
public Document(bool value) : this()
{
Type = DocumentType.Bool;
_dataBool = value;
}
public Document(double value) : this()
{
Type = DocumentType.Double;
_dataDouble = value;
}
public Document(int value) : this()
{
Type = DocumentType.Int;
_dataInt = value;
}
public Document(long value) : this()
{
Type = DocumentType.Long;
_dataLong = value;
}
public Document(string value) : this()
{
Type = DocumentType.String;
_dataString = value;
}
public Document(List<Document> values) : this()
{
Type = DocumentType.List;
_dataList = values;
}
public Document(params Document[] values) : this(values.ToList()) { }
public Document(Dictionary<string, Document> values) : this()
{
Type = DocumentType.Dictionary;
_dataDictionary = values;
}
#endregion
#region Implicit Conversion Operators
public static implicit operator Document(bool value) => new Document(value);
public static implicit operator Document(double value) => new Document(value);
public static implicit operator Document(int value) => new Document(value);
public static implicit operator Document(long value) => new Document(value);
public static implicit operator Document(string value) => new Document(value);
public static implicit operator Document(Document[] values) => new Document(values);
public static implicit operator Document(Dictionary<string, Document> values) => new Document(values);
#endregion
#region Type Checking/Conversion
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.Bool"/>
/// </summary>
public bool IsBool() => Type == DocumentType.Bool;
/// <summary>
/// Returns the Document's backing value as a <see cref="bool"/>.
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.Bool"/></exception>
public bool AsBool()
{
AssertIsType(DocumentType.Bool);
return _dataBool;
}
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.Dictionary"/>
/// </summary>
public bool IsDictionary() => Type == DocumentType.Dictionary;
/// <summary>
/// Returns the Document's backing value as a <see cref="Dictionary{string,Document}"/>.
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.Dictionary"/></exception>
public Dictionary<string, Document> AsDictionary()
{
AssertIsType(DocumentType.Dictionary);
return _dataDictionary;
}
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.Double"/>
/// </summary>
public bool IsDouble() => Type == DocumentType.Double;
/// <summary>
/// Returns the Document's backing value as a <see cref="Double"/>.
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.Double"/></exception>
public double AsDouble()
{
AssertIsType(DocumentType.Double);
return _dataDouble;
}
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.Int"/>
/// </summary>
public bool IsInt() => Type == DocumentType.Int;
/// <summary>
/// Returns the Document's backing value as a <see cref="int"/>.
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.Int"/></exception>
public int AsInt()
{
AssertIsType(DocumentType.Int);
return _dataInt;
}
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.List"/>
/// </summary>
public bool IsList() => Type == DocumentType.List;
/// <summary>
/// Returns the Document's backing value as a <see cref="List{Document}"/>.
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.List"/></exception>
public List<Document> AsList()
{
AssertIsType(DocumentType.List);
return _dataList;
}
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.Long"/>
/// </summary>
public bool IsLong() => Type == DocumentType.Long;
/// <summary>
/// Returns the Document's backing value as a <see cref="long"/>.
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.Long"/></exception>
public long AsLong()
{
AssertIsType(DocumentType.Long);
return _dataLong;
}
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.Null"/>
/// </summary>
public bool IsNull() => Type == DocumentType.Null;
/// <summary>
/// Returns true if <see cref="Type"/> is <see cref="DocumentType.String"/>
/// </summary>
public bool IsString() => Type == DocumentType.String;
/// <summary>
/// Returns the Document's backing value as a <see cref="string"/>.
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.String"/></exception>
public string AsString()
{
AssertIsType(DocumentType.String);
return _dataString;
}
private void AssertIsType(DocumentType type)
{
if (Type != type)
throw new InvalidDocumentTypeConversionException(type, Type);
}
#endregion
#region Equality
public bool Equals(Document other)
{
if (Type != other.Type)
return false;
switch (Type)
{
case DocumentType.Null:
return true;
case DocumentType.Bool:
return _dataBool == other.AsBool();
case DocumentType.Double:
return _dataDouble.Equals(other.AsDouble());
case DocumentType.Int:
return _dataInt == other.AsInt();
case DocumentType.Long:
return _dataLong == other.AsLong();
case DocumentType.String:
return _dataString.Equals(other.AsString());
// use reference equality
case DocumentType.List:
return _dataList.Equals(other.AsList());
case DocumentType.Dictionary:
return _dataDictionary.Equals(other.AsDictionary());
default:
return false;
}
}
public bool Equals(Document? other)
{
if (!other.HasValue)
return false;
return Equals(other.Value);
}
public override bool Equals(object obj)
{
return Equals(obj as Document?);
}
public override int GetHashCode() => base.GetHashCode();
public static bool operator ==(Document left, Document right) => left.Equals(right);
public static bool operator !=(Document left, Document right) => !left.Equals(right);
#endregion
#region Collection Initializers
IEnumerator<Document> IEnumerable<Document>.GetEnumerator()
{
return AsList().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
if (Type == DocumentType.List)
return AsList().GetEnumerator();
if (Type == DocumentType.Dictionary)
return AsDictionary().GetEnumerator();
return new[]{this}.GetEnumerator();
}
/// <summary>
/// This method is meant to support Collection Initializers and should not be used directly.
/// Use <see cref="AsList"/>.Add() instead.
/// <para />
/// Supports:
/// <code><![CDATA[
/// request.Document = new Document
/// {
/// "foo", "bar", "baz"
/// };
/// ]]></code>
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.List"/></exception>
public void Add(Document document)
{
// special type case to support collection initializer
if (Type == DocumentType.Null)
{
Type = DocumentType.List;
_dataList = new List<Document>();
}
AssertIsType(DocumentType.List);
_dataList.Add(document);
}
IEnumerator<KeyValuePair<string, Document>> IEnumerable<KeyValuePair<string, Document>>.GetEnumerator()
{
return AsDictionary().GetEnumerator();
}
/// <summary>
/// This method is meant to support Collection Initializers and should not be used directly.
/// Use <see cref="AsDictionary"/>.Add() instead.
/// <para />
/// Supports:
/// <code><![CDATA[
/// request.Document = new Document
/// {
/// {"foo", 42},
/// {"bar", 12},
/// {"baz", true}
/// };
/// ]]></code>
/// </summary>
/// <exception cref="InvalidDocumentTypeConversionException">Thrown if <see cref="Type"/> is not <see cref="DocumentType.Dictionary"/></exception>
public void Add(string key, Document value)
{
// special type case to support collection initializer
if (Type == DocumentType.Null)
{
_dataDictionary = new Dictionary<string, Document>();
Type = DocumentType.Dictionary;
}
AssertIsType(DocumentType.Dictionary);
_dataDictionary.Add(key, value);
}
#endregion
#region ToString
public override string ToString()
{
switch (Type)
{
case DocumentType.Bool:
return _dataBool.ToString();
case DocumentType.Dictionary:
return "Document dictionary";
case DocumentType.Double:
return _dataDouble.ToString(CultureInfo.CurrentCulture);
case DocumentType.Int:
return _dataInt.ToString();
case DocumentType.List:
return "Document list";
case DocumentType.Long:
return _dataLong.ToString();
case DocumentType.Null:
return "Document null value";
case DocumentType.String:
return _dataString;
}
return base.ToString();
}
#endregion
#region FromObject
/// <summary>
/// Convenience method for generating <see cref="Document"/> objects from a strongly typed
/// or anonymous object.
/// <example><code><![CDATA[
/// var document = Document.FromObject(new {
/// Hello = "World",
/// Nested = new {
/// Example = true,
/// Number = 42
/// }
/// });
/// ]]> </code></example>
/// This method uses reflection to analyze <paramref name="o"/> and is therefor not intended
/// for performance critical work. Additionally, if <paramref name="o"/> is a known primitive (ie <see cref="int"/>),
/// using a <see cref="Document"/> constructor directly will be more performant.
/// </summary>
public static Document FromObject(object o)
{
IJsonWrapper jsonData = JsonMapper.ToObject(JsonMapper.ToJson(o));
return FromObject(jsonData);
}
private static Document FromObject(IJsonWrapper jsonData)
{
switch (jsonData.GetJsonType())
{
case JsonType.None:
return new Document();
case JsonType.Boolean:
return new Document(jsonData.GetBoolean());
case JsonType.Double:
return new Document(jsonData.GetDouble());
case JsonType.Int:
return new Document(jsonData.GetInt());
case JsonType.Long:
return new Document(jsonData.GetLong());
case JsonType.String:
return new Document(jsonData.GetString());
case JsonType.Array:
return new Document(jsonData.Values.OfType<object>().Select(FromObject).ToArray());
case JsonType.Object:
var dictionary = new Dictionary<string, Document>();
Copy(jsonData, dictionary);
return new Document(dictionary);
}
throw new NotSupportedException($"Couldn't convert {jsonData.GetJsonType()}");
}
private static void Copy(IDictionary source, Dictionary<string, Document> target)
{
foreach (var key in source.Keys)
{
target[key.ToString()] = FromObject((IJsonWrapper)source[key]);
}
}
#endregion
}
}
| 457 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Documents
{
/// <summary>
/// Valid types for <see cref="Document" />
/// </summary>
public enum DocumentType
{
Null = 0,
Bool = 1,
Dictionary = 10,
Double = 100,
Int = 1000,
Long = 10000,
List = 100000,
String = 1000000
}
} | 32 |
aws-sdk-net | aws | C# | /*
* 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;
namespace Amazon.Runtime.Documents
{
/// <summary>
/// Thrown by <see cref="Document"/> AsX methods (ie <see cref="Document.AsBool"/>) if the
/// <see cref="Document.Type"/> does not match the requested conversion.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public class InvalidDocumentTypeConversionException : Exception
{
public InvalidDocumentTypeConversionException(DocumentType expected, DocumentType actual) :
base($"Cannot Convert DocumentType to {expected} because it is {actual}"){}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InvalidDocumentTypeConversionException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InvalidDocumentTypeConversionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 66 |
aws-sdk-net | aws | C# | /*
* 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 ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Documents.Internal.Transform
{
/// <summary>
/// Dedicated Json Marshaller for <see cref="Document"/>.
/// </summary>
public class DocumentMarshaller
{
public static DocumentMarshaller Instance { get; } = new DocumentMarshaller();
private DocumentMarshaller() { }
public void Write(JsonWriter writer, Document doc)
{
switch (doc.Type)
{
case DocumentType.Null:
// explicitly write null
writer.Write(null);
return;
case DocumentType.Bool:
writer.Write(doc.AsBool());
return;
case DocumentType.Double:
writer.Write(doc.AsDouble());
return;
case DocumentType.Int:
writer.Write(doc.AsInt());
return;
case DocumentType.String:
writer.Write(doc.AsString());
return;
case DocumentType.List:
writer.WriteArrayStart();
foreach (var item in doc.AsList())
Write(writer, item);
writer.WriteArrayEnd();
return;
case DocumentType.Long:
writer.Write(doc.AsLong());
return;
case DocumentType.Dictionary:
writer.WriteObjectStart();
foreach (var kvp in doc.AsDictionary())
{
writer.WritePropertyName(kvp.Key);
Write(writer, kvp.Value);
}
writer.WriteObjectEnd();
return;
default:
throw new ArgumentException($"Unknown Document Type: {doc.Type}");
}
}
}
} | 73 |
aws-sdk-net | aws | C# | /*
* 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.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Amazon.Runtime.Internal.Transform;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Documents.Internal.Transform
{
/// <summary>
/// Dedicated <see cref="IUnmarshaller{T,R}"/> for <see cref="Document"/>.
/// </summary>
/// <remarks>
/// Per the Document Spec, Xml is not supported.
/// </remarks>
public class DocumentUnmarshaller : IUnmarshaller<Document, JsonUnmarshallerContext>, IUnmarshaller<Document, XmlUnmarshallerContext>
{
public static DocumentUnmarshaller Instance { get; } = new DocumentUnmarshaller();
private DocumentUnmarshaller() { }
public Document Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
switch (context.CurrentTokenType)
{
case JsonToken.Null:
case JsonToken.None:
return new Document();
case JsonToken.Boolean:
return new Document(bool.Parse(context.ReadText()));
case JsonToken.Double:
return new Document(double.Parse(context.ReadText()));
case JsonToken.Int:
return new Document(int.Parse(context.ReadText()));
case JsonToken.Long:
return new Document(long.Parse(context.ReadText()));
case JsonToken.String:
return new Document(context.ReadText());
case JsonToken.ArrayStart:
var list = new List<Document>();
while (!context.Peek(JsonToken.ArrayEnd))
list.Add(Unmarshall(context));
context.Read(); // Read ArrayEnd
return new Document(list);
case JsonToken.ObjectStart:
var dict = new Dictionary<string, Document>();
while (!context.Peek(JsonToken.ObjectEnd))
{
// Only supported Object is Dictionary<string, Document>
var key = StringUnmarshaller.Instance.Unmarshall(context);
var value = Unmarshall(context);
dict.Add(key, value);
}
context.Read(); // Read ObjectEnd
return new Document(dict);
default:
throw new ArgumentException($"Unknown JSON type: {context.CurrentTokenType}");
}
}
/// <remarks>
/// Document Types does not support xml. However, Generic Type constraints for
/// <see cref="ListUnmarshaller{I,IUnmarshaller}"/> require implementing both
/// json and xml unmarshalling support.
/// </remarks>
Document IUnmarshaller<Document, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext input)
{
throw new NotImplementedException("Document is not supported in Xml Protocol");
}
}
} | 94 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Endpoints
{
/// <summary>
/// Endpoint to be used when calling service operation.
/// </summary>
public class Endpoint
{
/// <summary>
/// Constructor used by custorm EndpointProvider
/// </summary>
public Endpoint(string url) : this(url, null, null)
{
}
/// <summary>
/// Constructor used by code-generated EndpointProvider
/// </summary>
public Endpoint(string url, string attributesJson, string headersJson)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
URL = url;
if (!string.IsNullOrEmpty(attributesJson))
{
var attributes = JsonMapper.ToObject(attributesJson);
Attributes = PropertyBag.FromJsonData(attributes);
}
if (!string.IsNullOrEmpty(headersJson))
{
var headers = JsonMapper.ToObject(headersJson);
Headers = new Dictionary<string, IList<string>>();
foreach (var key in headers.PropertyNames)
{
var headerValues = new List<string>();
var values = headers[key];
if (values != null && values.IsArray)
{
foreach (JsonData value in values)
{
headerValues.Add((string)value);
}
}
Headers.Add(key, headerValues);
}
}
}
/// <summary>
/// Endpoint's url
/// </summary>
public string URL { get; set; }
/// <summary>
/// Custom endpoint attributes
/// </summary>
public IPropertyBag Attributes { get; set; }
/// <summary>
/// Custom endpoint headers
/// </summary>
public IDictionary<string, IList<string>> Headers { get; set; }
}
}
| 87 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Endpoints
{
/// <summary>
/// Base class for endpoint parameters.
/// Used for endpoint resolution.
/// </summary>
public class EndpointParameters : PropertyBag
{
}
}
| 25 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Endpoints
{
/// <summary>
/// Global endpoints resolution provider.
/// Can be used to override endpoints resolution for all services.
/// </summary>
public static class GlobalEndpoints
{
public static IGlobalEndpointProvider Provider { get; set; }
}
}
| 26 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Endpoints
{
/// <summary>
/// Interface to be implemented by service specific EndpointProviders.
/// </summary>
public interface IEndpointProvider
{
/// <summary>
/// Resolves service endpoint based on EndpointParameters
/// </summary>
Endpoint ResolveEndpoint(EndpointParameters parameters);
}
}
| 28 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Endpoints
{
public interface IGlobalEndpointProvider
{
/// <summary>
/// Defines logic to globally resolve service's endpoint.
/// based on serviceId and EndpointParameters.
/// </summary>
Endpoint ResolveEndpoint(string serviceId, EndpointParameters parameters);
}
}
| 26 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Endpoints
{
/// <summary>
/// Property bag interface.
/// </summary>
public interface IPropertyBag
{
/// <summary>
/// Indexer to access property value by name
/// </summary>
/// <param name="propertyName">Name of the property</param>
/// <returns></returns>
object this[string propertyName]
{
get;
set;
}
}
}
| 34 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Endpoints
{
/// <summary>
///
/// Property bag implementation.
///
/// Can store arbitrary data accessed by parameter/property name.
/// Use [] indexer to store/retrieve data.
/// e.g. bag["parameter"] = value;
/// If property is not defined returns null.
/// </summary>
public class PropertyBag : IPropertyBag
{
private Dictionary<string, object> properties = new Dictionary<string, object>();
public object this[string propertyName]
{
get
{
object result;
if (properties.TryGetValue(propertyName, out result))
{
return result;
}
return null;
}
set
{
properties[propertyName] = value;
}
}
/// <summary>
/// Creates PropertyBag based object tree from JsonData
/// </summary>
internal static PropertyBag FromJsonData(JsonData jsonData)
{
var result = new PropertyBag();
foreach (string name in jsonData.PropertyNames)
{
var node = jsonData[name];
result[name] = NodeToValue(node);
}
return result;
}
/// <summary>
/// Return a value from a JsonData node
/// Node value can be simple/final i.e. String, Int etc.
/// or it can be complex i.e. Object, Array
/// Translates Object json node to PropertyBag
/// Translates Array json node to List
/// </summary>
private static object NodeToValue(JsonData node)
{
if (node.IsString)
{
return (string)node;
}
if (node.IsBoolean)
{
return (bool)node;
}
if (node.IsInt)
{
return (int)node;
}
if (node.IsLong)
{
return (long)node;
}
if (node.IsDouble)
{
return (double)node;
}
if (node.IsUInt)
{
return (uint)node;
}
if (node.IsULong)
{
return (ulong)node;
}
if (node.IsObject)
{
return FromJsonData(node);
}
if (node.IsArray)
{
var list = new List<object>();
foreach (JsonData item in node)
{
list.Add(NodeToValue(item));
}
return list;
}
// we should never get here as we covered all JsonData possible types,
// but we still need to satisfy compiler with
// "all code paths must return a value"
throw new ArgumentException("Unsupported node type.");
}
}
}
| 121 |
aws-sdk-net | aws | C# | /*
* 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;
namespace Amazon.Runtime.Endpoints
{
/// <summary>
/// Static endpoint provider.
/// Use to resolve an endpoint to a given url.
/// </summary>
public class StaticEndpointProvider : IEndpointProvider
{
private readonly string _url;
public StaticEndpointProvider(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
_url = url;
}
public Endpoint ResolveEndpoint(EndpointParameters parameters)
{
return new Endpoint(_url);
}
}
} | 41 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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 Amazon.Runtime.EventStreams.Internal;
namespace Amazon.Runtime.EventStreams
{
/// <summary>
/// Superclass for Exceptions that come over the event stream, or to wrap other kinds of generic exceptions.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public sealed class EventStreamErrorCodeException : EventStreamException
{
/// <summary>
/// The numeric code identifier for the type of error.
/// </summary>
public int ErrorCode
{
get { return (int) Data[nameof(ErrorCode)]; }
private set { Data[nameof(ErrorCode)] = value; }
}
/// <summary>
/// Constructs an EventStreamError.
/// </summary>
public EventStreamErrorCodeException(int errorCode) : this(errorCode, null)
{
}
/// <summary>
/// Constructs an EventStreamError.
/// </summary>
/// <param name="errorCode">The error code.</param>
/// <param name="message">The error message.</param>
public EventStreamErrorCodeException(int errorCode, string message) : base(message)
{
ErrorCode = errorCode;
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the EventStreamErrorCodeException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
private EventStreamErrorCodeException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 76 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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.Diagnostics.CodeAnalysis;
using Amazon.Runtime.EventStreams.Internal;
namespace Amazon.Runtime.EventStreams
{
/// <summary>
/// Event args that contain an <see cref="IEventStreamEvent"/>.
/// </summary>
/// <typeparam name="T">The <see cref="IEventStreamEvent"/></typeparam>
[SuppressMessage("Microsoft.Naming", "CA1710", Justification =
"The suffix of 'EventArgs' makes the name have 3 'Event' declarations.' Since the second 'Event' has the same syntactic meaning, adding a another is unnecessarily verbose.")]
public class EventStreamEventReceivedArgs<T> : EventArgs where T : IEventStreamEvent
{
/// <summary>
/// The EventStream Event.
/// </summary>
public T EventStreamEvent { get; }
/// <summary>
/// Constructs an EventStreamEventReceivedArgs.
/// </summary>
/// <param name="eventStreamEvent">The EventStream Event.</param>
public EventStreamEventReceivedArgs(T eventStreamEvent)
{
EventStreamEvent = eventStreamEvent;
}
}
} | 50 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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.Diagnostics.CodeAnalysis;
using Amazon.Runtime.EventStreams.Internal;
namespace Amazon.Runtime.EventStreams
{
/// <summary>
/// Event args that contain an <see cref="EventStreamException"/>.
/// </summary>
/// <typeparam name="T">The <see cref="EventStreamException"/>.</typeparam>
[SuppressMessage("Microsoft.Naming", "CA1710", Justification =
"The suffix of 'EventArgs' makes the name have 3 equivalent 'Event' declarations.' Since 'Exception' in this case has the same syntactic meaning as 'event'" +
", adding another is unnecessarily verbose.")]
public class EventStreamExceptionReceivedArgs<T> : EventArgs where T : EventStreamException
{
/// <summary>
/// The EventStream Exception.
/// </summary>
public T EventStreamException { get; }
/// <summary>
/// Constructs an EventStreamExceptionReceivedArgs.
/// </summary>
/// <param name="eventStreamException">The EventStream Exception.</param>
public EventStreamExceptionReceivedArgs(T eventStreamException)
{
EventStreamException = eventStreamException;
}
}
} | 51 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using System.Text;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.EventStreams
{
#region headerParser
/// <summary>
/// Supported Header types for vnd.amazon.event-stream
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1028", Justification = "Low-level memory usage")]
public enum EventStreamHeaderType : byte
{
BoolTrue = 0,
BoolFalse,
Byte,
Int16,
Int32,
Int64,
ByteBuf,
String,
Timestamp,
UUID
}
public interface IEventStreamHeader
{
/// <summary>
/// Name for the Header. Maximum of 255 bytes.
/// </summary>
string Name { get; }
/// <summary>
/// Header type id
/// </summary>
EventStreamHeaderType HeaderType { get; }
/// <summary>
/// Computes the amount of memory neccesary to serialize this Header.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024", Justification = "Method can throw an exception.")]
int GetWireSize();
/// <summary>
/// Writes this Header to buffer starting at offset
/// Keep in mind, this API assumes buffer is large enough
/// for the operation.
/// </summary>
/// <param name="buffer">buffer to serialize this Header to</param>
/// <param name="offset">offset to begin writing at.</param>
/// <returns>
/// the new offset.
/// </returns>
int WriteToBuffer(byte[] buffer, int offset);
/// <summary>
/// Returns the current value as a bool
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1720", Justification = "Current name is most descriptive.")]
bool AsBool();
/// <summary>
/// Sets the current value
/// </summary>
void SetBool(bool value);
/// <summary>
/// Returns the current value as a byte
/// </summary>
Byte AsByte();
/// <summary>
/// Sets the current value
/// </summary>
void SetByte(Byte value);
/// <summary>
/// Gets the current value as a 16 bit integer. (Host Order).
/// </summary>
/// <returns></returns>
Int16 AsInt16();
/// <summary>
/// Sets the current value. (Host Order)
/// </summary>
void SetInt16(Int16 value);
/// <summary>
/// Returns the current value as a 32 bit integer. (Host Order)
/// </summary>
Int32 AsInt32();
/// <summary>
/// Sets the current value
/// </summary>
void SetInt32(Int32 value);
/// <summary>
/// returns the current value as a 64-bit integer. (Host Order)
/// </summary>
Int64 AsInt64();
/// <summary>
/// Sets the current value. (Host Order)
/// </summary>
void SetInt64(Int64 value);
/// <summary>
/// Returns the current value as a byte buffer.
/// </summary>
/// <returns></returns>
byte[] AsByteBuf();
/// <summary>
/// Sets the current value. Max length is 2^15 - 1
/// </summary>
void SetByteBuf(byte[] value);
/// <summary>
/// Returns the current value as a utf-8 string.
/// </summary>
string AsString();
/// <summary>
/// Sets the current value. Utf-8 encoded. Max byte size is 2^16 - 1
/// </summary>
void SetString(string value);
/// <summary>
/// Gets the current value as a DateTime.
/// Note: You do not need to compensate for unix epoch on this API.
/// </summary>
/// <returns></returns>
DateTime AsTimestamp();
/// <summary>
/// Sets the current value.
/// Note: You do not need to compensate for unix epoch on this API.
/// </summary>
void SetTimestamp(DateTime value);
/// <summary>
/// Returns the current value as a Guid (UUID)
/// </summary>
Guid AsUUID();
/// <summary>
/// Sets the current value
/// </summary>
void SetUUID(Guid value);
}
/// <summary>
/// Header Data for an EventStreamMessage
///
/// Each header is of format:
/// [name len] (1) | [utf-8 name] (v)
/// [type (1)]
/// [value (v)]
/// </summary>
public class EventStreamHeader : IEventStreamHeader
{
private static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private const int _sizeOfByte = 1;
private const int _sizeOfInt16 = 2;
private const int _sizeOfInt32 = 4;
private const int _sizeOfInt64 = 8;
private const int _sizeOfGuid = 16;
/// <summary>
/// Name for the Header. Maximum of 255 bytes.
/// </summary>
public string Name { get; }
/// <summary>
/// Header type id
/// </summary>
public EventStreamHeaderType HeaderType { get; set; }
private Object HeaderValue { get; set; }
/// <summary>
/// Initializes this Header with name.
/// </summary>
/// <param name="name">utf-8 string, max length is 255</param>
public EventStreamHeader(string name)
{
this.Name = name;
}
/// <summary>
/// Deserializes the header in buffer.
/// </summary>
/// <param buffer="buffer">buffer constaining the header</param>
/// <param offset="offset">index to start from in the buffer.</param>
/// <param offset="newOffset">updated offset with new value for offset</param>
[SuppressMessage("Microsoft.Design", "CA1045", Justification = "Performance and Cross-Runtime compatability.")]
public static EventStreamHeader FromBuffer(byte[] buffer, int offset, ref int newOffset)
{
newOffset = offset;
byte nameLength = buffer[newOffset++];
var header = new EventStreamHeader(Encoding.UTF8.GetString(buffer, newOffset, nameLength));
newOffset += nameLength;
header.HeaderType = (EventStreamHeaderType)buffer[newOffset++];
Int16 valueLength = 0;
switch (header.HeaderType)
{
case EventStreamHeaderType.BoolTrue:
header.HeaderValue = true;
break;
case EventStreamHeaderType.BoolFalse:
header.HeaderValue = false;
break;
case EventStreamHeaderType.Byte:
header.HeaderValue = buffer[newOffset];
newOffset += _sizeOfByte;
break;
case EventStreamHeaderType.Int16:
header.HeaderValue = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, newOffset));
newOffset += _sizeOfInt16;
break;
case EventStreamHeaderType.Int32:
header.HeaderValue = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, newOffset));
newOffset += _sizeOfInt32;
break;
case EventStreamHeaderType.Int64:
header.HeaderValue = IPAddress.NetworkToHostOrder(BitConverter.ToInt64(buffer, newOffset));
newOffset += _sizeOfInt64;
break;
case EventStreamHeaderType.ByteBuf:
valueLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, newOffset));
newOffset += _sizeOfInt16;
header.HeaderValue = new byte[valueLength];
Buffer.BlockCopy(buffer, newOffset, header.HeaderValue as byte[], 0, valueLength);
newOffset += valueLength;
break;
case EventStreamHeaderType.String:
valueLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, newOffset));
newOffset += _sizeOfInt16;
header.HeaderValue = Encoding.UTF8.GetString(buffer, newOffset, valueLength);
newOffset += valueLength;
break;
case EventStreamHeaderType.Timestamp:
Int64 tempValue = IPAddress.NetworkToHostOrder(BitConverter.ToInt64(buffer, newOffset));
newOffset += _sizeOfInt64;
//keep in mind on the windows APIs (and hence NetStandard as well) the epoch is 1/1/1900,
//and we're using unix epoch. So we compensate here.
header.HeaderValue = _unixEpoch.AddMilliseconds(tempValue);
break;
case EventStreamHeaderType.UUID:
var guidCpy = new byte[16];
valueLength = _sizeOfGuid;
Buffer.BlockCopy(buffer, newOffset, guidCpy, 0, valueLength);
newOffset += valueLength;
header.HeaderValue = new Guid(guidCpy);
break;
default:
throw new EventStreamParseException(string.Format(CultureInfo.InvariantCulture, "Header Type: {0} is an unknown type.", header.HeaderType));
}
return header;
}
/// <summary>
/// Writes this Header to buffer starting at offset
/// Keep in mind, this API assumes buffer is large enough
/// for the operation.
/// </summary>
/// <param name="buffer">buffer to serialize this Header to</param>
/// <param name="offset">offset to begin writing at.</param>
/// <returns>
/// the new offset.
/// </returns>
public int WriteToBuffer(byte[] buffer, int offset)
{
var newOffset = offset;
buffer[newOffset++] = (byte)Name.Length;
var nameBytes = Encoding.UTF8.GetBytes(Name);
Buffer.BlockCopy(nameBytes, 0, buffer, newOffset, Name.Length);
newOffset += Name.Length;
buffer[newOffset++] = (byte)HeaderType;
byte[] serializedBytes = null;
int valueLength = 0;
switch (HeaderType)
{
case EventStreamHeaderType.BoolTrue:
case EventStreamHeaderType.BoolFalse:
break;
case EventStreamHeaderType.Byte:
buffer[newOffset++] = (byte)HeaderValue;
break;
case EventStreamHeaderType.Int16:
serializedBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int16)HeaderValue));
Buffer.BlockCopy(serializedBytes, 0, buffer, newOffset, 2);
newOffset += _sizeOfInt16;
break;
case EventStreamHeaderType.Int32:
serializedBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int32)HeaderValue));
Buffer.BlockCopy(serializedBytes, 0, buffer, newOffset, 4);
newOffset += _sizeOfInt32;
break;
case EventStreamHeaderType.Int64:
serializedBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int64)HeaderValue));
Buffer.BlockCopy(serializedBytes, 0, buffer, newOffset, 8);
newOffset += _sizeOfInt64;
break;
case EventStreamHeaderType.ByteBuf:
serializedBytes = HeaderValue as byte[];
valueLength = serializedBytes.Length;
Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int16)valueLength)), 0,
buffer, newOffset, 2);
newOffset += _sizeOfInt16;
Buffer.BlockCopy(serializedBytes, 0, buffer, newOffset, valueLength);
newOffset += valueLength;
break;
case EventStreamHeaderType.String:
serializedBytes = Encoding.UTF8.GetBytes(HeaderValue as string);
valueLength = serializedBytes.Length;
Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int16)valueLength)), 0,
buffer, newOffset, 2);
newOffset += _sizeOfInt16;
Buffer.BlockCopy(serializedBytes, 0, buffer, newOffset, valueLength);
newOffset += valueLength;
break;
case EventStreamHeaderType.Timestamp:
var tempValue = (Int64)((DateTime)HeaderValue).Subtract(_unixEpoch).TotalMilliseconds;
serializedBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(tempValue));
Buffer.BlockCopy(serializedBytes, 0, buffer, newOffset, 8);
newOffset += _sizeOfInt64;
break;
case EventStreamHeaderType.UUID:
serializedBytes = ((Guid)HeaderValue).ToByteArray();
Buffer.BlockCopy(serializedBytes, 0, buffer, newOffset, serializedBytes.Length);
newOffset += serializedBytes.Length;
break;
default:
throw new EventStreamParseException(string.Format(CultureInfo.InvariantCulture, "Header Type: {0} is an unknown type.", HeaderType));
}
return newOffset;
}
/// <summary>
/// Computes the amount of memory neccesary to serialize this Header.
/// </summary>
public int GetWireSize()
{
//each header is of format:
// [name len] (1) | [utf-8 name] (v)
// [type (1)]
// [value (v)]
var len = _sizeOfByte + Name.Length + _sizeOfByte;
switch (HeaderType)
{
case EventStreamHeaderType.BoolTrue:
case EventStreamHeaderType.BoolFalse:
break;
case EventStreamHeaderType.Byte:
len += _sizeOfByte;
break;
case EventStreamHeaderType.Int16:
len += _sizeOfInt16;
break;
case EventStreamHeaderType.Int32:
len += _sizeOfInt32;
break;
case EventStreamHeaderType.Int64:
len += _sizeOfInt64;
break;
case EventStreamHeaderType.ByteBuf:
var bbuf = HeaderValue as byte[];
len += _sizeOfInt16 + bbuf.Length; //2 byte len | buffer
break;
case EventStreamHeaderType.String:
var strLen = Encoding.UTF8.GetBytes(HeaderValue as string).Length;
len += _sizeOfInt16 + strLen; //2 byte len | utf-8 buffer
break;
case EventStreamHeaderType.Timestamp:
len += _sizeOfInt64;
break;
case EventStreamHeaderType.UUID:
len += _sizeOfGuid;
break;
default:
throw new EventStreamParseException(string.Format(CultureInfo.InvariantCulture, "Header Type: {0} is an unknown type.", HeaderType));
}
return len;
}
/// <summary>
/// Returns the current value as a bool
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1720", Justification = "Current name is most descriptive.")]
public bool AsBool()
{
return HeaderType == EventStreamHeaderType.BoolTrue;
}
/// <summary>
/// Sets the current value
/// </summary>
public void SetBool(bool value)
{
HeaderValue = value;
HeaderType = value ? EventStreamHeaderType.BoolTrue : EventStreamHeaderType.BoolFalse;
}
/// <summary>
/// Returns the current value as a byte
/// </summary>
public Byte AsByte()
{
return (Byte)HeaderValue;
}
/// <summary>
/// Sets the current value
/// </summary>
public void SetByte(Byte value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.Byte;
}
/// <summary>
/// Gets the current value as a 16 bit integer. (Host Order).
/// </summary>
/// <returns></returns>
public Int16 AsInt16()
{
return (Int16)HeaderValue;
}
/// <summary>
/// Sets the current value. (Host Order)
/// </summary>
public void SetInt16(Int16 value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.Int16;
}
/// <summary>
/// Returns the current value as a 32 bit integer. (Host Order)
/// </summary>
public Int32 AsInt32()
{
return (Int32)HeaderValue;
}
/// <summary>
/// Sets the current value
/// </summary>
public void SetInt32(Int32 value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.Int32;
}
/// <summary>
/// returns the current value as a 64-bit integer. (Host Order)
/// </summary>
public Int64 AsInt64()
{
return (Int64)HeaderValue;
}
/// <summary>
/// Sets the current value. (Host Order)
/// </summary>
public void SetInt64(Int64 value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.Int64;
}
/// <summary>
/// Returns the current value as a byte buffer.
/// </summary>
/// <returns></returns>
public byte[] AsByteBuf()
{
return HeaderValue as byte[];
}
/// <summary>
/// Sets the current value. Max length is 2^15 - 1
/// </summary>
public void SetByteBuf(byte[] value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.ByteBuf;
}
/// <summary>
/// Returns the current value as a utf-8 string.
/// </summary>
public string AsString()
{
return HeaderValue as string;
}
/// <summary>
/// Sets the current value. Utf-8 encoded. Max byte size is 2^16 - 1
/// </summary>
public void SetString(string value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.String;
}
/// <summary>
/// Gets the current value as a DateTime.
/// Note: You do not need to compensate for unix epoch on this API.
/// </summary>
/// <returns></returns>
public DateTime AsTimestamp()
{
return (DateTime)HeaderValue;
}
/// <summary>
/// Sets the current value.
/// Note: You do not need to compensate for unix epoch on this API.
/// </summary>
public void SetTimestamp(DateTime value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.Timestamp;
}
/// <summary>
/// Returns the current value as a Guid (UUID)
/// </summary>
public Guid AsUUID()
{
return (Guid)HeaderValue;
}
/// <summary>
/// Sets the current value
/// </summary>
public void SetUUID(Guid value)
{
HeaderValue = value;
HeaderType = EventStreamHeaderType.UUID;
}
}
#endregion
}
| 579 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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.Globalization;
using System.Net;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Ionic.Zlib;
namespace Amazon.Runtime.EventStreams
{
#region exceptions
#if !NETSTANDARD
[Serializable]
#endif
public class EventStreamParseException : Exception
{
public EventStreamParseException(string message) : base(message)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the EventStreamParseException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected EventStreamParseException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
#if !NETSTANDARD
[Serializable]
#endif
public class EventStreamChecksumFailureException : Exception
{
public EventStreamChecksumFailureException(string message) : base(message)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the EventStreamChecksumFailureException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected EventStreamChecksumFailureException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
#endregion
#region messageImplementation
public interface IEventStreamMessage
{
/// <summary>
/// Headers for the message. Can be null.
/// </summary>
Dictionary<string, IEventStreamHeader> Headers { get; set; }
/// <summary>
/// Payload for the message. Can be null.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "This needs to be a byte[], and it makes the most sense as a property.")]
byte[] Payload { get; set; }
/// <summary>
/// Converts a message into a byte buffer (usually for network transmission).
/// </summary>
byte[] ToByteArray();
}
/// <summary>
/// Message is a single datagram. The format is as follows:
/// [ total length (4) ] | [ headers_length (4)] | [ prelude crc(4)]
/// [ headers (v)]
/// [ payload (v)}
/// [ trailing crc ]
///
/// CRCs use the CRC32 algorithm.
/// </summary>
public class EventStreamMessage : IEventStreamMessage
{
internal const int SizeOfInt32 = 4;
internal const int PreludeLen = SizeOfInt32 * 3;
internal const int TrailerLen = SizeOfInt32;
internal const int FramingSize = PreludeLen + TrailerLen;
/// <summary>
/// Content type for EventStreams.
/// </summary>
public const string ContentType = "vnd.amazon.eventstream";
/// <summary>
/// Headers for the message. Can be null.
/// </summary>
public Dictionary<string, IEventStreamHeader> Headers { get; set; }
/// <summary>
/// Payload for the message. Can be null.
/// </summary>
public byte[] Payload { get; set; }
private EventStreamMessage() { }
/// <summary>
/// Initialize a message with headers and a payload.
/// </summary>
/// <param name="headers">list of headers for the message, can be null.</param>
/// <param name="payload">payload for the message, can be null.</param>
public EventStreamMessage(List<IEventStreamHeader> headers, byte[] payload)
{
Headers = new Dictionary<string, IEventStreamHeader>(headers.Count, StringComparer.Ordinal);
foreach (var header in headers)
{
Headers.Add(header.Name, header);
}
Payload = payload;
}
/// <summary>
/// Builds a message from buffer.
/// </summary>
/// <param name="buffer">buffer to read</param>
/// <param name="offset">offset to start reading</param>
/// <param name="length">buffer length.</param>
/// <returns>
/// parsed instance of EventStreamMessage. Doesn't return null,
/// does throw if CRCs don't match.
/// </returns>
public static EventStreamMessage FromBuffer(byte[] buffer, int offset, int length)
{
var currentOffset = offset;
//get the total length of the message
var totalLength = BitConverter.ToInt32(buffer, currentOffset);
//endianness conversion
totalLength = IPAddress.NetworkToHostOrder(totalLength);
currentOffset += SizeOfInt32;
//get the length of the headers block.
var headersLength = BitConverter.ToInt32(buffer, currentOffset);
//endianness conversion
headersLength = IPAddress.NetworkToHostOrder(headersLength);
currentOffset += SizeOfInt32;
//get the prelude crc
var preludeCrc = BitConverter.ToInt32(buffer, currentOffset);
//endianness conversion
preludeCrc = IPAddress.NetworkToHostOrder(preludeCrc);
var message = new EventStreamMessage();
message.Headers = new Dictionary<string, IEventStreamHeader>(StringComparer.Ordinal);
using (var nullStream = new NullStream())
using (var runningChecksum = new CrcCalculatorStream(nullStream))
{
//write up to the prelude crc to the checksum stream
runningChecksum.Write(buffer, offset, currentOffset - offset);
//compare the current crc to the prelude crc and make sure they match.
if (preludeCrc != runningChecksum.Crc32)
{
throw new EventStreamChecksumFailureException(string.Format(CultureInfo.InvariantCulture, "Message Prelude Checksum failure. Expected {0} but was {1}", preludeCrc, runningChecksum.Crc32));
}
//if the data length passed isn't enough for the total length, that's an error condition.
if (totalLength != length)
{
throw new EventStreamChecksumFailureException(
string.Format(CultureInfo.InvariantCulture, "Message Total Length didn't match the passed in length. Expected {0} but was {1}", length, totalLength));
}
//now write the prelude crc to the checksum stream
runningChecksum.Write(buffer, currentOffset, SizeOfInt32);
currentOffset += SizeOfInt32;
//prelude length is total message, minus framing and headers size.
var payloadLength = totalLength - headersLength - FramingSize;
//if we have headers, then loop over each one and parse them out.
if (headersLength > 0)
{
int preOpOffset = currentOffset;
while (currentOffset - PreludeLen < headersLength)
{
EventStreamHeader header = EventStreamHeader.FromBuffer(buffer, currentOffset, ref currentOffset);
message.Headers.Add(header.Name, header);
}
//after parsing the header remember to write that data to the checksum stream
runningChecksum.Write(buffer, preOpOffset, currentOffset - preOpOffset);
}
// now we're on the payload
message.Payload = new byte[payloadLength];
Buffer.BlockCopy(buffer, currentOffset, message.Payload, 0, message.Payload.Length);
runningChecksum.Write(buffer, currentOffset, message.Payload.Length);
currentOffset += message.Payload.Length;
//after reading the payload, get the message crc and make sure it matches.
var trailingCrc = BitConverter.ToInt32(buffer, currentOffset);
//endianness conversion.
trailingCrc = IPAddress.NetworkToHostOrder(trailingCrc);
if (trailingCrc != runningChecksum.Crc32)
{
throw new EventStreamChecksumFailureException(
string.Format(CultureInfo.InvariantCulture, "Message Checksum failure. Expected {0} but was {1}", trailingCrc, runningChecksum.Crc32));
}
}
return message;
}
/// <summary>
/// Converts a message into a byte buffer (usually for network transmission).
/// </summary>
public byte[] ToByteArray()
{
int headersWireLength = 0;
//first we need to figure out how much space the headers will take up.
if (Headers != null)
{
foreach (var header in Headers)
{
headersWireLength += header.Value.GetWireSize();
}
}
var payloadLength = Payload?.Length ?? 0;
//total message length is the framing size + the payload size + the headers wire size.
var totalLength = headersWireLength + payloadLength + FramingSize;
var messageBuffer = new byte[totalLength];
//now write the total length and the headers length to the message. make sure to handle endianness conversions
var offset = 0;
Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(totalLength)), 0,
messageBuffer, offset, SizeOfInt32);
offset += SizeOfInt32;
Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(headersWireLength)), 0,
messageBuffer, offset, SizeOfInt32);
offset += SizeOfInt32;
using (var nullStream = new NullStream())
using (var runningChecksum = new CrcCalculatorStream(nullStream))
{
//write the total length and headers length to the checksum stream.
runningChecksum.Write(messageBuffer, 0, offset);
//take the current checksum and write it to the message.
Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(runningChecksum.Crc32)), 0,
messageBuffer, offset, SizeOfInt32);
//now take the current checksum and write it to the checksum stream.
runningChecksum.Write(messageBuffer, offset, SizeOfInt32);
offset += SizeOfInt32;
//loop over the headers and write them out to the message.
if (Headers != null)
{
foreach (var header in Headers)
{
offset = header.Value.WriteToBuffer(messageBuffer, offset);
}
//make sure to add the header bytes to the checksum stream.
runningChecksum.Write(messageBuffer, PreludeLen, offset - PreludeLen);
}
//write the payload to the message.
if (Payload != null)
{
Buffer.BlockCopy(Payload, 0, messageBuffer, offset, Payload.Length);
//update the checksum
runningChecksum.Write(messageBuffer, offset, Payload.Length);
offset += Payload.Length;
}
//take the final checksum and add it to the end of the message.
Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(runningChecksum.Crc32)), 0,
messageBuffer, offset, SizeOfInt32);
}
return messageBuffer;
}
}
#endregion
} | 319 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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;
namespace Amazon.Runtime.EventStreams
{
/// <summary>
/// Defines exceptions that arise from an <see cref="EventStreamMessage"/> not conforming to specification.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public sealed class EventStreamValidationException : Exception
{
/// <summary>
/// Constructs an EventStreamValidationException.
/// </summary>
public EventStreamValidationException()
{
}
/// <summary>
/// Constructs an EventStreamValidationException.
/// </summary>
/// <param name="message">The exception message.</param>
public EventStreamValidationException(string message) : base(message)
{
}
/// <summary>
/// Constructs an EventStreamValidationException.
/// </summary>
/// <param name="message">The exception message.</param>
/// <param name="innerException">The inner exception.</param>
public EventStreamValidationException(string message, Exception innerException) : base(message, innerException)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the EventStreamValidationException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
private EventStreamValidationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 75 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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 Amazon.Runtime.EventStreams.Internal;
namespace Amazon.Runtime.EventStreams
{
/// <summary>
/// This exception is thrown if an exception is retrieved from the event stream and should be modeled,
/// but a generator function for the strongly-typed exception is not defined.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public sealed class UnknownEventStreamException : EventStreamException
{
/// <summary>
/// The exception type.
/// </summary>
public string ExceptionType
{
get { return Data[nameof(ExceptionType)].ToString(); }
private set { Data[nameof(ExceptionType)] = value; }
}
/// <summary>
/// Constructs an EventStreamException.
/// </summary>
/// <param name="exceptionType">The exception type.</param>
public UnknownEventStreamException(string exceptionType)
{
ExceptionType = exceptionType;
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the UnknownEventStreamException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
private UnknownEventStreamException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 68 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace Amazon.Runtime.EventStreams.Internal
{
/// <summary>
/// The contract for the <see cref="EnumerableEventStream{T,TE}"/>.
/// </summary>
/// <typeparam name="T">An implementation of IEventStreamEvent (e.g. IS3Event).</typeparam>
/// <typeparam name="TE">An implementation of EventStreamException (e.g. S3EventStreamException).</typeparam>
[SuppressMessage("Microsoft.Naming", "CA1710", Justification = "IEventStreamCollection is not descriptive.")]
public interface IEnumerableEventStream<T, TE> : IEventStream<T, TE>, IEnumerable<T> where T : IEventStreamEvent where TE : EventStreamException, new()
{
}
/// <summary>
/// A subclass of <see cref="EventStream{T,TE}" /> that enables an enumerable interface for interacting with Events.
/// </summary>
/// <typeparam name="T">An implementation of IEventStreamEvent (e.g. IS3Event).</typeparam>
/// <typeparam name="TE">An implementation of EventStreamException (e.g. S3EventStreamException).</typeparam>
[SuppressMessage("Microsoft.Naming", "CA1710", Justification = "EventStreamCollection is not descriptive.")]
[SuppressMessage("Microsoft.Design", "CA1063", Justification = "IDisposable is a transient interface from IEventStream. Users need to be able to call Dispose.")]
public abstract class EnumerableEventStream<T, TE> : EventStream<T, TE>, IEnumerableEventStream<T, TE> where T : IEventStreamEvent where TE : EventStreamException, new()
{
private const string MutuallyExclusiveExceptionMessage = "Stream has already begun processing. Event-driven and Enumerable traversals of the stream are mutually exclusive. " +
"You can either use the event driven or enumerable interface, but not both.";
/// <summary>
/// Flag if the stream was chosen to be enumerated.
/// </summary>
protected bool IsEnumerated { get; set; }
/// <summary>
/// A Stream of Events. Events can be retrieved from this stream by either
/// <list type="bullet">
/// <item><description>attaching handlers to listen events, and then call StartProcessing <i>or</i></description></item>
/// <item><description>enumerating over the events.</description></item>
/// </list>
/// <para></para>
/// These options should be treated as mutually exclusive.
/// </summary>
protected EnumerableEventStream(Stream stream) : this(stream, null)
{
}
/// <summary>
/// A Stream of Events. Events can be retrieved from this stream by either
/// <list type="bullet">
/// <item><description>attaching handlers to listen events, and then call StartProcessing <i>or</i></description></item>
/// <item><description>enumerating over the events.</description></item>
/// </list>
/// <para></para>
/// These options should be treated as mutually exclusive.
/// </summary>
protected EnumerableEventStream(Stream stream, IEventStreamDecoder eventStreamDecoder) : base(stream, eventStreamDecoder)
{
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<T> GetEnumerator()
{
if (IsProcessing)
{
// If the queue has already begun processing, refuse to enumerate.
throw new InvalidOperationException(MutuallyExclusiveExceptionMessage);
}
// There could be more than 1 message created per decoder cycle.
var events = new Queue<T>();
// Opting out of events - letting the enumeration handle everything.
IsEnumerated = true;
IsProcessing = true;
// Enumeration is just magic over the event driven mechanism.
EventReceived += (sender, args) => events.Enqueue(args.EventStreamEvent);
var buffer = new byte[BufferSize];
while (IsProcessing)
{
// If there are already events ready to be served, do not ask for more.
if (events.Count > 0)
{
var ev = events.Dequeue();
// Enumeration handles terminal events on behalf of the user.
if (ev is IEventStreamTerminalEvent)
{
IsProcessing = false;
Dispose();
}
yield return ev;
}
else
{
try
{
ReadFromStream(buffer);
}
catch (Exception ex)
{
IsProcessing = false;
Dispose();
// Wrap exceptions as needed to match event-driven behavior.
throw WrapException(ex);
}
}
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Starts the background thread to start reading events from the network stream.
/// </summary>
public override void StartProcessing()
{
// If they are/have enumerated, the event-driven mode should be disabled
if (IsEnumerated) throw new InvalidOperationException(MutuallyExclusiveExceptionMessage);
base.StartProcessing();
}
}
} | 161 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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.IO;
#if AWS_ASYNC_API
using System.Threading.Tasks;
#else
using System.Threading;
#endif
namespace Amazon.Runtime.EventStreams.Internal
{
/// <summary>
/// The contract for the <see cref="EventStream{T,TE}"/>.
/// </summary>
/// <typeparam name="T">An implementation of IEventStreamEvent (e.g. IS3Event).</typeparam>
/// <typeparam name="TE">An implementation of EventStreamException (e.g. S3EventStreamException).</typeparam>
public interface IEventStream<T, TE> : IDisposable where T : IEventStreamEvent where TE : EventStreamException, new()
{
/// <summary>
/// The size of the buffer for reading from the network stream.
/// </summary>
int BufferSize { get; set; }
/// <summary>
/// Fires when an event is received.
/// </summary>
event EventHandler<EventStreamEventReceivedArgs<T>> EventReceived;
/// <summary>
/// Fired when an exception or error is raised.
/// </summary>
event EventHandler<EventStreamExceptionReceivedArgs<TE>> ExceptionReceived;
/// <summary>
/// Starts the background thread to start reading events from the network stream.
/// </summary>
void StartProcessing();
}
/// <summary>
/// The superclass for all EventStreams. It contains the common processing logic needed to retreive events from a network Stream. It
/// also contains the mechanisms needed to have a background loop raise events.
/// </summary>
/// <typeparam name="T">An implementation of IEventStreamEvent (e.g. IS3Event).</typeparam>
/// <typeparam name="TE">An implementation of EventStreamException (e.g. S3EventStreamException).</typeparam>
public abstract class EventStream<T, TE> : IEventStream<T, TE> where T : IEventStreamEvent where TE : EventStreamException, new()
{
/// <summary>
/// "Unique" key for unknown event lookup.
/// </summary>
protected const string UnknownEventKey = "===UNKNOWN===";
/// <summary>
/// Header key for message type.
/// </summary>
private const string HeaderMessageType = ":message-type";
/// <summary>
/// Header key for event type.
/// </summary>
private const string HeaderEventType = ":event-type";
/// <summary>
/// Header key for exception type.
/// </summary>
private const string HeaderExceptionType = ":exception-type";
/// <summary>
/// Header key for error code.
/// </summary>
private const string HeaderErrorCode = ":error-code";
/// <summary>
/// Header key for error message.
/// </summary>
private const string HeaderErrorMessage = ":error-message";
/// <summary>
/// Value of <see cref="HeaderMessageType"/> when the message is an event.
/// </summary>
private const string EventHeaderMessageTypeValue = "event";
/// <summary>
/// Value of <see cref="HeaderMessageType"/> when the message is an exception.
/// </summary>
private const string ExceptionHeaderMessageTypeValue = "exception";
/// <summary>
/// Value of <see cref="HeaderMessageType"/> when the message is an error.
/// </summary>
private const string ErrorHeaderMessageTypeValue = "error";
private const string WrappedErrorMessage = "Error.";
/// <summary>
/// The size of the buffer for reading from the network stream.
/// Default is 8192.
/// </summary>
public int BufferSize { get; set; } = 8192;
/// <summary>
/// The underlying stream to read events from.
/// </summary>
protected Stream NetworkStream { get; }
/// <summary>
/// Responsible for decoding events from sequences of bytes.
/// </summary>
protected IEventStreamDecoder Decoder { get; }
/// <summary>
/// Fires when an event is recieved.
/// </summary>
public virtual event EventHandler<EventStreamEventReceivedArgs<T>> EventReceived;
/// <summary>
/// Fired when an exception or error is raised.
/// </summary>
public virtual event EventHandler<EventStreamExceptionReceivedArgs<TE>> ExceptionReceived;
/// <summary>
/// The mapping of event message to a generator function to construct the matching Event Stream event.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1006",
Justification = "Mapping of string to generic generator function is clear to the reader. This property is not exposed to the end user.")]
protected abstract IDictionary<string, Func<IEventStreamMessage, T>> EventMapping { get; }
/// <summary>
/// The mapping of event message to a generator function to construct the matching Event Stream exception.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1006",
Justification = "Mapping of string to generic generator function is clear to the reader. This property is not exposed to the end user.")]
protected abstract IDictionary<string, Func<IEventStreamMessage, TE>> ExceptionMapping { get; }
/// <summary>
/// Whether the Stream is currently being processed.
/// </summary>
// This is true is StartProcessing is called, or if enumeration has started.
protected abstract bool IsProcessing { get; set; }
/// <summary>
/// A Stream of Events. Events can be retrieved from this stream by attaching handlers to listen events, and then calling StartProcessing.
/// </summary>
protected EventStream(Stream stream) : this(stream, null)
{
}
/// <summary>
/// A Stream of Events. Events can be retrieved from this stream by attaching handlers to listen events, and then calling StartProcessing.
/// </summary>
protected EventStream(Stream stream, IEventStreamDecoder eventStreamDecoder)
{
NetworkStream = stream;
Decoder = eventStreamDecoder ?? new EventStreamDecoder();
}
/// <summary>
/// Converts an EventStreamMessage to an event.
/// </summary>
/// <param name="eventStreamMessage">The event stream message to be converted.</param>
/// <returns>The event</returns>
protected T ConvertMessageToEvent(EventStreamMessage eventStreamMessage)
{
var eventStreamMessageHeaders = eventStreamMessage.Headers;
string eventStreamMessageType;
try
{
// Message type can be an event, an exception, or an error. This information is stored in the :message-type header.
eventStreamMessageType = eventStreamMessageHeaders[HeaderMessageType].AsString();
}
catch (KeyNotFoundException ex)
{
throw new EventStreamValidationException("Message type missing from event stream message.", ex);
}
switch (eventStreamMessageType)
{
case EventHeaderMessageTypeValue:
string eventTypeKey;
try
{
eventTypeKey = eventStreamMessageHeaders[HeaderEventType].AsString();
}
catch (KeyNotFoundException ex)
{
throw new EventStreamValidationException("Event Type not defined for event.", ex);
}
try
{
return EventMapping[eventTypeKey](eventStreamMessage);
}
catch (KeyNotFoundException)
{
return EventMapping[UnknownEventKey](eventStreamMessage);
}
case ExceptionHeaderMessageTypeValue:
string exceptionTypeKey;
try
{
exceptionTypeKey = eventStreamMessageHeaders[HeaderExceptionType].AsString();
}
catch (KeyNotFoundException ex)
{
throw new EventStreamValidationException("Exception Type not defined for exception.", ex);
}
try
{
throw ExceptionMapping[exceptionTypeKey](eventStreamMessage);
}
catch (KeyNotFoundException)
{
throw new UnknownEventStreamException(exceptionTypeKey);
}
case ErrorHeaderMessageTypeValue:
int errorCode;
try
{
errorCode = eventStreamMessageHeaders[HeaderErrorCode].AsInt32();
}
catch (KeyNotFoundException ex)
{
throw new EventStreamValidationException("Error Code not defined for error.", ex);
}
// Error message is not required for errors. Errors do not have payloads.
IEventStreamHeader errorMessage = null;
var hasErrorMessage = eventStreamMessageHeaders.TryGetValue(HeaderErrorMessage, out errorMessage);
throw new EventStreamErrorCodeException(errorCode, hasErrorMessage ? errorMessage.AsString() : string.Empty);
default:
// Unknown message type. Swallow the message to enable future message types without breaking existing clients.
throw new UnknownEventStreamMessageTypeException();
}
}
/// <summary>
/// Abstraction for cross-framework initiation of the background thread.
/// </summary>
protected void Process()
{
#if AWS_ASYNC_API
// Task only exists in framework 4.5 and up, and Standard.
Task.Run(() => ProcessLoop());
#else
// ThreadPool only exists in 3.5 and below. These implementations do not have the Task library.
ThreadPool.QueueUserWorkItem(ProcessLoop);
#endif
}
/// <summary>
/// The background thread main loop. It will constantly read from the network stream until IsProcessing is false, or an error occurs.
/// <para></para>
/// This stub exists due to FXCop.
/// </summary>
private void ProcessLoop()
{
ProcessLoop(null);
}
/// <summary>
/// The background thread main loop. It will constantly read from the network stream until IsProcessing is false, or an error occurs.
/// </summary>
/// <param name="state">Needed for 3.5 support. Not used.</param>
[SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Needed for .NET 3.5 (ThreadPool.QueueUserWorkItem)")]
private void ProcessLoop(object state)
{
var buffer = new byte[BufferSize];
try
{
while (IsProcessing)
{
ReadFromStream(buffer);
}
}
// These exceptions are raised on the background thread. They are fired as events for visibility.
catch (Exception ex)
{
IsProcessing = false;
// surfaceException means what is surfaced to the user. For example, in S3Select, that would be a S3EventStreamException.
var surfaceException = WrapException(ex);
// Raise the exception as an event.
ExceptionReceived?.Invoke(this,
new EventStreamExceptionReceivedArgs<TE>(surfaceException));
}
}
/// <summary>
/// Reads from the stream into the buffer. It then passes the buffer to the decoder, which raises an event for
/// each message it decodes.
/// </summary>
/// <param name="buffer">The buffer to store the read bytes from the stream.</param>
protected void ReadFromStream(byte[] buffer)
{
var bytesRead = NetworkStream.Read(buffer, 0, buffer.Length);
if (NetworkStream.CanRead)
{
if (bytesRead > 0)
{
// Decoder raises MessageReceived for every message it encounters.
Decoder.ProcessData(buffer, 0, bytesRead);
}
}
else
{
IsProcessing = false;
}
}
/// <summary>
/// Wraps exceptions in an outer exception so they can be passed to event handlers. If the Exception is already of a compatable type,
/// the method returns what it was given.
/// </summary>
/// <param name="ex">The exception to wrap.</param>
/// <returns>An exception of type TE</returns>
protected TE WrapException(Exception ex)
{
var teEx = ex as TE;
if (teEx != null)
{
return teEx;
}
// Types of exception that would not already be of type TE would be DecoderExceptions, EventStreamValidationExceptions,
// and EventStreamErrorCodeExceptions.
// We want to wrap the exception in the generic type so we can give it to the exception event handler.
// Only one exception should fire, since the background thread dies on the exception. Therefore, the reflection
// used here is not a preformance concern, and lets us abstract this method to the superclass.
var exArgs = new object[] {WrappedErrorMessage, ex};
return (TE) Activator.CreateInstance(typeof(TE), exArgs);
}
/// <summary>
/// Starts the background thread to start reading events from the network stream.
/// </summary>
public virtual void StartProcessing()
{
if (IsProcessing) return;
IsProcessing = true;
Process();
}
#region Dispose Pattern
private bool _disposed;
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the resources of this stream.
/// </summary>
/// <param name="disposing">Should dispose of unmanged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
IsProcessing = false;
NetworkStream?.Dispose();
Decoder?.Dispose();
}
_disposed = true;
}
#endregion
}
} | 393 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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.Globalization;
using System.Net;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Ionic.Zlib;
namespace Amazon.Runtime.EventStreams.Internal
{
#region streamingDecoder
/// <summary>
/// Event Arguments for EventStreamDecoder.MessageReceived.
/// </summary>
public class EventStreamMessageReceivedEventArgs : EventArgs
{
/// <summary>
/// Received message.
/// </summary>
public EventStreamMessage Message { get; private set; }
/// <summary>
/// Additional object context
/// </summary>
public Object Context { get; private set; }
/// <summary>
/// Initialize this with message
/// </summary>
public EventStreamMessageReceivedEventArgs(EventStreamMessage message)
{
Message = message;
}
/// <summary>
/// Initialize this with message and object conetext
/// </summary>
public EventStreamMessageReceivedEventArgs(EventStreamMessage message, Object context)
{
Message = message;
Context = context;
}
}
/// <summary>
/// Exception thrown when a request is made of the Decoder, but the internal state
/// machine is an invalid state. This is usually the result of an interanl exception
/// being thrown during parsing of the network stream.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public class EventStreamDecoderIllegalStateException : Exception
{
public EventStreamDecoderIllegalStateException(string message) : base(message)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the EventStreamDecoderIllegalStateException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected EventStreamDecoderIllegalStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
/// <summary>
/// Contract for EventStreamDecoder
/// </summary>
public interface IEventStreamDecoder : IDisposable
{
/// <summary>
/// Invoked anytime an EventStreamMessage is found.
/// </summary>
event EventHandler<EventStreamMessageReceivedEventArgs> MessageReceived;
/// <summary>
/// Processes data starting at offset up to length.
/// Invokes MessageRecieved for each message encountered.
/// If an exception is thrown, this object is not safe for reuse.
/// </summary>
/// <param name="data">buffer to read</param>
/// <param name="offset">offset in buffer to start reading.</param>
/// <param name="length">length of data.</param>
void ProcessData(byte[] data, int offset, int length);
}
/// <summary>
/// Streaming decoder for listening for incoming EventStreamMessage datagrams.
/// </summary>
public class EventStreamDecoder : IEventStreamDecoder
{
/// <summary>
/// Invoked anytime an EventStreamMessage is found.
/// </summary>
public event EventHandler<EventStreamMessageReceivedEventArgs> MessageReceived;
/// <summary>
/// Object data (optional) that can be passed to the event handler for MessageReceived.
/// </summary>
public object MessageReceivedContext { get; set; }
private delegate int ProcessRead(byte[] data, int offset, int length);
private enum DecoderState
{
Start = 0,
ReadPrelude,
ProcessPrelude,
ReadMessage,
Error
}
private ProcessRead[] _stateFns = null;
private DecoderState _state;
private int _currentMessageLength;
private int _amountBytesRead;
private byte[] _workingMessage;
private byte[] _workingBuffer;
private CrcCalculatorStream _runningChecksumStream;
/// <summary>
/// Default constructor. Initializes internal _state machine.
/// </summary>
public EventStreamDecoder()
{
_workingBuffer = new byte[EventStreamMessage.PreludeLen];
_stateFns = new ProcessRead[] { Start, ReadPrelude, ProcessPrelude, ReadMessage, Error };
_state = DecoderState.Start;
}
#region StreamingDecoderStateMachine
private int Start(byte[] data, int offset, int length)
{
_workingMessage = null;
_amountBytesRead = 0;
if (_runningChecksumStream != null)
{
_runningChecksumStream.Dispose();
}
_runningChecksumStream = new CrcCalculatorStream(new NullStream());
_currentMessageLength = 0;
_state = DecoderState.ReadPrelude;
return 0;
}
private int ReadPrelude(byte[] data, int offset, int length)
{
var read = 0;
if (_amountBytesRead < EventStreamMessage.PreludeLen)
{
read = Math.Min(length - offset, EventStreamMessage.PreludeLen - _amountBytesRead);
Buffer.BlockCopy(data, offset, _workingBuffer, _amountBytesRead, read);
_amountBytesRead += read;
}
if (_amountBytesRead == EventStreamMessage.PreludeLen)
{
_state = DecoderState.ProcessPrelude;
}
return read;
}
private int ProcessPrelude(byte[] data, int offset, int length)
{
/* this is absolutely redundant, but since the totalLength field will result
in a potentially huge allocation, we want to fail fast before even attempting to continue
if the totalLength field has been corrupted. */
_runningChecksumStream.Write(_workingBuffer, 0, EventStreamMessage.PreludeLen - EventStreamMessage.SizeOfInt32);
var preludeChecksum = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(_workingBuffer,
EventStreamMessage.PreludeLen - EventStreamMessage.SizeOfInt32));
if (preludeChecksum != _runningChecksumStream.Crc32)
{
_state = DecoderState.Error;
throw new EventStreamChecksumFailureException(
string.Format(CultureInfo.InvariantCulture, "Message Prelude Checksum failure. Expected {0} but was {1}", preludeChecksum, _runningChecksumStream.Crc32));
}
_runningChecksumStream.Write(_workingBuffer, EventStreamMessage.PreludeLen - 4, EventStreamMessage.SizeOfInt32);
_currentMessageLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(_workingBuffer, 0));
/* It's entirely possible to change this to not do this potentially large allocation
but it complicates the API a bit and is most likely unnecessary. For now, just allocate
the entire message buffer. It will be released after each message is processed. */
_workingMessage = new byte[_currentMessageLength];
Buffer.BlockCopy(_workingBuffer, 0, _workingMessage, 0, EventStreamMessage.PreludeLen);
_state = DecoderState.ReadMessage;
return 0;
}
private int ReadMessage(byte[] data, int offset, int length)
{
var read = 0;
if (_amountBytesRead < _currentMessageLength)
{
read = Math.Min(length - offset, _currentMessageLength - _amountBytesRead);
Buffer.BlockCopy(data, offset, _workingMessage, _amountBytesRead, read);
_amountBytesRead += read;
}
if (_amountBytesRead == _currentMessageLength)
{
ProcessMessage();
}
return read;
}
private void ProcessMessage()
{
try
{
var message = EventStreamMessage.FromBuffer(_workingMessage, 0, _currentMessageLength);
MessageReceived?.Invoke(this, new EventStreamMessageReceivedEventArgs(message, MessageReceivedContext));
_state = DecoderState.Start;
}
catch(Exception)
{
_state = DecoderState.Error;
throw;
}
}
private int Error(byte[] data, int offset, int length)
{
throw new EventStreamDecoderIllegalStateException("Event stream decoder is in an error state. Create a new instance, and use a new stream to continue");
}
#endregion
/// <summary>
/// Processes data starting at offset up to length.
/// Invokes MessageRecieved for each message encountered.
/// If an exception is thrown, this object is not safe for reuse.
/// </summary>
/// <param name="data">buffer to read</param>
/// <param name="offset">offset in buffer to start reading.</param>
/// <param name="length">length of data.</param>
public void ProcessData(byte[] data, int offset, int length)
{
var available = length - offset;
while (offset < available)
{
offset += _stateFns[(int)_state](data, offset, length);
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_runningChecksumStream.Dispose();
_workingMessage = null;
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
#endregion
}
| 307 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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;
namespace Amazon.Runtime.EventStreams.Internal
{
/// <summary>
/// Superclass for Exceptions that come over the event stream, or to wrap other kinds of generic exceptions.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public abstract class EventStreamException : Exception
{
/// <summary>
/// Constructs an EventStreamException.
/// </summary>
protected EventStreamException()
{
}
/// <summary>
/// Constructs an EventStreamException.
/// </summary>
/// <param name="message">The exception message.</param>
protected EventStreamException(string message) : base(message)
{
}
/// <summary>
/// Constructs an EventStreamException.
/// </summary>
/// <param name="message">The exception message.</param>
/// <param name="innerException">The inner exception.</param>
protected EventStreamException(string message, Exception innerException) : base(message, innerException)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the EventStreamException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected EventStreamException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 72 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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.Diagnostics.CodeAnalysis;
namespace Amazon.Runtime.EventStreams.Internal
{
/// <summary>
/// The contract for EventStream events.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1040", Justification = "This interface exists to categorize events, and provide future extensibility.")]
public interface IEventStreamEvent
{
}
} | 33 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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.Diagnostics.CodeAnalysis;
namespace Amazon.Runtime.EventStreams.Internal
{
/// <summary>
/// The contract for EventStream terminal events.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1040", Justification = "This interface exists to categorize terminal events, and provide future extensibility.")]
public interface IEventStreamTerminalEvent : IEventStreamEvent
{
}
} | 33 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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.EventStreams;
namespace Amazon.Runtime.EventStreams.Internal
{
/// <summary>
/// This Event is returned if an event is retrieved from the event stream, but a generator function
/// for the event is not defined. This can occur if the SDK is not updated after a new event type is introduced.
/// </summary>
public class UnknownEventStreamEvent : IEventStreamEvent
{
/// <summary>
/// The Message recieved from the event stream before conversion.
/// </summary>
public IEventStreamMessage ReceivedMessage { get; set; }
/// <summary>
/// The event type.
/// </summary>
public string EventType { get; set; }
/// <summary>
/// Constructs an UnknownEventStreamEvent.
/// </summary>
public UnknownEventStreamEvent()
{
}
/// <summary>
/// Constructs an UnknownEventStreamEvent.
/// </summary>
/// <param name="receivedMessage">The Message recieved from the event stream before conversion.</param>
/// <param name="eventType">The event type.</param>
public UnknownEventStreamEvent(IEventStreamMessage receivedMessage, string eventType)
{
ReceivedMessage = receivedMessage;
EventType = eventType;
}
}
} | 59 |
aws-sdk-net | aws | C# | // /*******************************************************************************
// * 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;
namespace Amazon.Runtime.EventStreams
{
/// <summary>
/// Signals that an an <see cref="EventStreamMessage"/> has an unknown message type. These exceptions whould be
/// swallowed to allow future expansion of the EventStream specification without breaking existing clients.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public sealed class UnknownEventStreamMessageTypeException : Exception
{
/// <summary>
/// Constructs an UnknownEventStreamMessageTypeException.
/// </summary>
public UnknownEventStreamMessageTypeException()
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the UnknownEventStreamMessageTypeException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
private UnknownEventStreamMessageTypeException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 56 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
namespace Amazon.Runtime
{
public abstract partial class AmazonWebServiceRequest : IAmazonWebServiceRequest
{
/// <summary>
/// This flag specifies if SigV4 will be used for the current request.
/// </summary>
[Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")]
bool IAmazonWebServiceRequest.UseSigV4
{
get { return UseSigV4; }
set { UseSigV4 = value; }
}
/// <summary>
/// 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.
/// </summary>
[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; }
}
/// <summary>
/// Specifies which signature version will be used for the current request.
/// </summary>
SignatureVersion IAmazonWebServiceRequest.SignatureVersion
{
get;
set;
}
/// <summary>
/// Gets or Sets a value indicating if "Expect: 100-continue" HTTP header will be
/// sent by the client for this request. The default value is false.
/// </summary>
protected virtual bool Expect100Continue
{
get { return false; }
}
internal bool GetExpect100Continue()
{
return this.Expect100Continue;
}
protected virtual bool IncludeSHA256Header
{
get { return true; }
}
internal bool GetIncludeSHA256Header()
{
return this.IncludeSHA256Header;
}
/// <summary>
/// Gets the signer to use for this request.
/// A null return value indicates to use the configured
/// signer for the service that this request is part of.
/// </summary>
/// <returns>A signer for this request, or null.</returns>
protected virtual AbstractAWSSigner CreateSigner()
{
return null;
}
internal AbstractAWSSigner GetSigner()
{
return CreateSigner();
}
/// <summary>
/// Checksum validation behavior for validating the integrity of this request's response
/// </summary>
protected internal virtual CoreChecksumResponseBehavior CoreChecksumMode => CoreChecksumResponseBehavior.DISABLED;
/// <summary>
/// Checksum algorithms that are supported for validating the integrity of this request's response
/// </summary>
protected internal virtual ReadOnlyCollection<CoreChecksumAlgorithm> ChecksumResponseAlgorithms => new List<CoreChecksumAlgorithm>(0).AsReadOnly();
}
}
| 109 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
#if !NETSTANDARD
using System.Runtime.Serialization;
#endif
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Collection used to indicate if the property was initialized by the SDK.
/// </summary>
/// <typeparam name="T"></typeparam>
public class AutoConstructedList<T> : List<T>
{
}
/// <summary>
/// Collection used to indicate if the property was initialized by the SDK.
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="V"></typeparam>
#if !NETSTANDARD
[Serializable]
#endif
public class AutoConstructedDictionary<K, V> : Dictionary<K, V>
{
#if !NETSTANDARD
protected AutoConstructedDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 51 |
aws-sdk-net | aws | C# | using System;
namespace Amazon.Runtime.Internal
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class AWSPropertyAttribute : Attribute
{
private long min;
private long max;
public bool Sensitive { get; set; }
public bool Required { get; set; }
public bool IsMinSet { get; private set; }
public long Min
{
get
{
return IsMinSet ? min : long.MinValue;
}
set
{
IsMinSet = true;
min = value;
}
}
public bool IsMaxSet { get; private set; }
public long Max
{
get
{
return IsMaxSet ? max : long.MaxValue;
}
set
{
IsMaxSet = true;
max = value;
}
}
}
}
| 41 |
aws-sdk-net | aws | C# | using System;
namespace Amazon.Runtime.Internal
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AWSSignerTypeAttribute : Attribute
{
public AWSSignerTypeAttribute(string signerType)
{
SignerType = signerType;
}
public string SignerType { get; }
}
}
| 16 |
aws-sdk-net | aws | C# | /*
* 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 Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using Amazon.Util.Internal;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Resolves <see cref="DefaultConfigurationMode.Auto"/> into the correct <see cref="DefaultConfigurationMode"/> given
/// the current operating environment.
/// </summary>
public interface IDefaultConfigurationAutoModeResolver
{
/// <summary>
/// Resolves <see cref="DefaultConfigurationMode.Auto"/> into the correct <see cref="DefaultConfigurationMode"/> given
/// the current operating environment.
///<para />
/// Auto resolution is heuristic based and does not guarantee 100% accuracy.
/// If you are unsure about the behavior, use a <see cref="DefaultConfigurationMode"/> other
/// than <see cref="DefaultConfigurationMode.Auto"/>.
/// </summary>
/// <param name="clientRegion">The <see cref="RegionEndpoint"/> configured in <see cref="IClientConfig.RegionEndpoint"/>.</param>
/// <param name="imdsRegion">
/// IMDS region provided by <see cref="EC2InstanceMetadata.Region"/>.
/// Func allows to defer the check until the point of use.
/// </param>
/// <returns>The resolved <see cref="DefaultConfigurationMode"/> for the current operating environment.</returns>
DefaultConfigurationMode Resolve(RegionEndpoint clientRegion, Func<RegionEndpoint> imdsRegion);
}
/// <inheritdoc />
public class DefaultConfigurationAutoModeResolver : IDefaultConfigurationAutoModeResolver
{
private readonly IRuntimeInformationProvider _runtimeInformationProvider;
private readonly IEnvironmentVariableRetriever _environmentVariableRetriever;
public DefaultConfigurationAutoModeResolver(IRuntimeInformationProvider runtimeInformationProvider,
IEnvironmentVariableRetriever environmentVariableRetriever)
{
_runtimeInformationProvider = runtimeInformationProvider;
_environmentVariableRetriever = environmentVariableRetriever;
}
/// <inheritdoc />
public DefaultConfigurationMode Resolve(RegionEndpoint clientRegion, Func<RegionEndpoint> imdsRegion)
{
var defaultConfigurationMode = ResolveInternal(clientRegion, imdsRegion);
Logger
.GetLogger(GetType())
.InfoFormat($"Resolved {nameof(DefaultConfigurationMode)} for {nameof(RegionEndpoint)} [{clientRegion?.SystemName}] to [{defaultConfigurationMode}].");
return defaultConfigurationMode;
}
private DefaultConfigurationMode ResolveInternal(RegionEndpoint clientRegion, Func<RegionEndpoint> imdsRegion)
{
if (_runtimeInformationProvider.IsMobile())
{
return DefaultConfigurationMode.Mobile;
}
// We're not on mobile (best we can tell). See if we can determine whether we're an in-region or cross-region client.
string currentRegion = null;
if (!string.IsNullOrEmpty(_environmentVariableRetriever.GetEnvironmentVariable(InternalSDKUtils.EXECUTION_ENVIRONMENT_ENVVAR)))
{
currentRegion = _environmentVariableRetriever.GetEnvironmentVariable(EnvironmentVariableAWSRegion.ENVIRONMENT_VARIABLE_REGION);
if (string.IsNullOrEmpty(currentRegion))
{
currentRegion = _environmentVariableRetriever.GetEnvironmentVariable(EnvironmentVariableAWSRegion.ENVIRONMENT_VARIABLE_DEFAULT_REGION);
}
}
if (string.IsNullOrEmpty(currentRegion))
{
// We couldn't figure out the region from environment variables. Check IMDSv2
// There is no need to check AWS_EC2_METADATA_DISABLED env var, because EC2InstanceMetadata handles it internally.
currentRegion = imdsRegion()?.SystemName;
}
if (!string.IsNullOrEmpty(currentRegion))
{
if (clientRegion.SystemName == currentRegion)
{
return DefaultConfigurationMode.InRegion;
}
else
{
return DefaultConfigurationMode.CrossRegion;
}
}
// We don't seem to be mobile, and we couldn't determine whether we're running within an AWS region. Fall back to standard.
return DefaultConfigurationMode.Standard;
}
}
} | 114 |
aws-sdk-net | aws | C# | /* * 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.Collections.Generic;
using System.Linq;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using Amazon.Util.Internal;
namespace Amazon.Runtime.Internal
{
/// <inheritdoc cref="GetDefaultConfiguration"/>
public interface IDefaultConfigurationProvider
{
/// <summary>
/// Determines the correct <see cref="DefaultConfiguration"/> to use.
/// <para />
/// Implementations of <see cref="IDefaultConfigurationProvider"/> are responsible for storing a reference to
/// all valid <see cref="DefaultConfiguration"/>s for a given context. Because the default values in a <see cref="DefaultConfiguration"/>
/// can differ between Services, it's important to not use <see cref="IDefaultConfigurationProvider"/>s in a different
/// Service Client.
/// <para />
/// The <see cref="DefaultConfiguration"/> is selected as follows:
/// <list type="number">
/// <item>Mode matching <paramref name="requestedConfigurationMode"/>. This should be set via <see cref="ClientConfig.DefaultConfigurationMode"/></item>
/// <item>The Environment Variable <see cref="DefaultConfigurationProvider.AWS_DEFAULTS_MODE_ENVIRONMENT_VARIABLE"/></item>
/// <item>Shared config/credential file via <see cref="FallbackInternalConfigurationFactory.DefaultConfigurationModeName"/></item>
/// <item><see cref="DefaultConfigurationMode.Legacy"/></item>
/// </list>
/// </summary>
/// <remarks>
/// <see cref="IDefaultConfiguration"/> is not cached. It will be re-resolved on every call.
/// </remarks>
IDefaultConfiguration GetDefaultConfiguration(RegionEndpoint clientRegion, DefaultConfigurationMode? requestedConfigurationMode = null);
}
/// <inheritdoc cref="IDefaultConfigurationProvider"/>
public class DefaultConfigurationProvider : IDefaultConfigurationProvider
{
private const string AWS_DEFAULTS_MODE_ENVIRONMENT_VARIABLE = "AWS_DEFAULTS_MODE";
private readonly IEnvironmentVariableRetriever _environmentVariableRetriever;
private readonly IDefaultConfigurationAutoModeResolver _defaultConfigurationAutoModeResolver;
private readonly IDefaultConfiguration[] _availableConfigurations;
/// <inheritdoc cref="IDefaultConfigurationProvider"/>
public DefaultConfigurationProvider(IEnumerable<IDefaultConfiguration> availableConfigurations)
: this(EnvironmentVariableSource.Instance.EnvironmentVariableRetriever,
new DefaultConfigurationAutoModeResolver(
new RuntimeInformationProvider(),
EnvironmentVariableSource.Instance.EnvironmentVariableRetriever),
availableConfigurations) { }
/// <inheritdoc cref="IDefaultConfigurationProvider"/>
public DefaultConfigurationProvider(
IEnvironmentVariableRetriever environmentVariableRetriever,
IDefaultConfigurationAutoModeResolver defaultConfigurationAutoModeResolver,
IEnumerable<IDefaultConfiguration> availableConfigurations)
: this (environmentVariableRetriever, defaultConfigurationAutoModeResolver, availableConfigurations.ToArray()) { }
/// <inheritdoc cref="IDefaultConfigurationProvider"/>
public DefaultConfigurationProvider(
IEnvironmentVariableRetriever environmentVariableRetriever,
IDefaultConfigurationAutoModeResolver defaultConfigurationAutoModeResolver,
params IDefaultConfiguration[] availableConfigurations)
{
if (availableConfigurations?.Any() != true)
throw new ArgumentException(
"Must provide at least one Default Configuration",
nameof(availableConfigurations));
_environmentVariableRetriever = environmentVariableRetriever;
_defaultConfigurationAutoModeResolver = defaultConfigurationAutoModeResolver;
_availableConfigurations = availableConfigurations;
}
/// <inheritdoc cref="IDefaultConfigurationProvider"/>
public IDefaultConfiguration GetDefaultConfiguration(
RegionEndpoint clientRegion,
DefaultConfigurationMode? requestedConfigurationMode = null)
{
var defaultConfigurationModeName =
// 1) requested mode
requestedConfigurationMode?.ToString() ??
// 2) try to get from environment variable
_environmentVariableRetriever.GetEnvironmentVariable(AWS_DEFAULTS_MODE_ENVIRONMENT_VARIABLE) ??
// 3) try to get from shared config/credential file
FallbackInternalConfigurationFactory.DefaultConfigurationModeName ??
// 4) fallback to 'Legacy'
DefaultConfigurationMode.Legacy.ToString();
Logger
.GetLogger(GetType())
.InfoFormat(
$"Resolved {nameof(DefaultConfigurationMode)} for {nameof(RegionEndpoint)} [{clientRegion?.SystemName}] to [{defaultConfigurationModeName}].");
try
{
var mode =
(DefaultConfigurationMode)
Enum.Parse(typeof(DefaultConfigurationMode), defaultConfigurationModeName, ignoreCase: true);
if (mode == DefaultConfigurationMode.Auto)
mode = _defaultConfigurationAutoModeResolver.Resolve(clientRegion, () => EC2InstanceMetadata.Region);
// save resolved values to cache
return _availableConfigurations.First(x => x.Name == mode);
}
catch (Exception)
{
throw new AmazonClientException(
$"Failed to find requested Default Configuration Mode '{defaultConfigurationModeName}'. " +
$"Valid values are {string.Join(",", Enum.GetNames(typeof(DefaultConfigurationMode)))}");
}
}
}
} | 130 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
using Amazon.Runtime.Internal.Auth;
using Amazon.Util;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Default implementation of the IRequest interface.
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public class DefaultRequest : IRequest
{
readonly ParameterCollection parametersCollection;
readonly IDictionary<string,string> parametersFacade;
readonly IDictionary<string, string> headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
readonly IDictionary<string, string> trailingHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
readonly IDictionary<string, string> subResources = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
readonly IDictionary<string, string> pathResources = new Dictionary<string, string>(StringComparer.Ordinal);
Uri endpoint;
string resourcePath;
string serviceName;
readonly AmazonWebServiceRequest originalRequest;
byte[] content;
Stream contentStream;
string contentStreamHash;
string httpMethod = "POST";
bool useQueryString = false;
string requestName;
string canonicalResource;
RegionEndpoint alternateRegion;
long originalStreamLength;
int marshallerVersion = 2; //2 is the default version and must be used whenever a version is not specified in the marshaller.
/// <summary>
/// Constructs a new DefaultRequest with the specified service name and the
/// original, user facing request object.
/// </summary>
/// <param name="request">The orignal request that is being wrapped</param>
/// <param name="serviceName">The service name</param>
public DefaultRequest(AmazonWebServiceRequest request, String serviceName)
{
if (request == null) throw new ArgumentNullException("request");
if (string.IsNullOrEmpty(serviceName)) throw new ArgumentNullException("serviceName");
this.serviceName = serviceName;
this.originalRequest = request;
this.requestName = this.originalRequest.GetType().Name;
this.UseSigV4 = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)this.originalRequest).UseSigV4;
this.SignatureVersion = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)this.originalRequest).SignatureVersion;
this.HostPrefix = string.Empty;
parametersCollection = new ParameterCollection();
parametersFacade = new ParametersDictionaryFacade(parametersCollection);
}
/// <summary>
/// The name of the request
/// </summary>
public string RequestName
{
get { return this.requestName; }
}
/// <summary>
/// Gets and sets the type of http request to make, whether it should be POST,GET or DELETE
/// </summary>
public string HttpMethod
{
get
{
return this.httpMethod;
}
set
{
this.httpMethod = value;
}
}
/// <summary>
/// Gets and sets a flag that indicates whether the request is sent as a query string instead of the request body.
/// </summary>
public bool UseQueryString
{
get
{
if (this.HttpMethod == "GET")
return true;
return this.useQueryString;
}
set
{
this.useQueryString = value;
}
}
/// <summary>
/// Returns the original, user facing request object which this internal
/// request object is representing.
/// </summary>
public AmazonWebServiceRequest OriginalRequest
{
get
{
return originalRequest;
}
}
/// <summary>
/// Returns a dictionary of the headers included in this request.
/// </summary>
public IDictionary<string, string> Headers
{
get
{
return this.headers;
}
}
/// <summary>
/// Returns a dictionary of the parameters included in this request.
/// </summary>
public IDictionary<string, string> Parameters
{
get
{
return this.parametersFacade;
}
}
/// <summary>
/// Collection of parameters included in this request.
/// </summary>
public ParameterCollection ParameterCollection
{
get
{
return this.parametersCollection;
}
}
/// <summary>
/// Returns the subresources that should be appended to the resource path.
/// This is used primarily for Amazon S3, where object keys can contain '?'
/// characters, making string-splitting of a resource path potentially
/// hazardous.
/// </summary>
public IDictionary<string, string> SubResources
{
get
{
return this.subResources;
}
}
/// <summary>
/// Adds a new null entry to the SubResources collection for the request
/// </summary>
/// <param name="subResource">The name of the subresource</param>
public void AddSubResource(string subResource)
{
AddSubResource(subResource, null);
}
/// <summary>
/// Adds a new entry to the SubResources collection for the request
/// </summary>
/// <param name="subResource">The name of the subresource</param>
/// <param name="value">Value of the entry</param>
public void AddSubResource(string subResource, string value)
{
SubResources.Add(subResource, value);
}
/// <summary>
/// Gets and Sets the endpoint for this request.
/// </summary>
public Uri Endpoint
{
get
{
return this.endpoint;
}
set
{
this.endpoint = value;
}
}
/// <summary>
/// Gets and Sets the resource path added on to the endpoint.
/// </summary>
public string ResourcePath
{
get
{
return this.resourcePath;
}
set
{
this.resourcePath = value;
}
}
/// <summary>
/// Returns the path resources that should be used within the resource path.
/// This is used for services where path keys can contain '/'
/// characters, making string-splitting of a resource path potentially
/// hazardous.
/// </summary>
public IDictionary<string, string> PathResources
{
get
{
return this.pathResources;
}
}
/// <summary>
/// Adds a new entry to the PathResources collection for the request
/// </summary>
/// <param name="key">The name of the pathresource with potential greedy syntax: {key+}</param>
/// <param name="value">Value of the entry</param>
public void AddPathResource(string key, string value)
{
PathResources.Add(key, value);
}
/// <summary>
/// Gets and Sets the version number for the marshaller used to create this request. The version number
/// is used to support backward compatible changes that would otherwise be breaking changes when a
/// newer core is used with an older service assembly.
/// Versions:
/// 1 - Legacy version (no longer supported)
/// 2 - Default version. Support for path segments
/// </summary>
public int MarshallerVersion
{
get
{
return this.marshallerVersion;
}
set
{
this.marshallerVersion = value;
}
}
public string CanonicalResource
{
get
{
return this.canonicalResource;
}
set
{
this.canonicalResource = value;
}
}
/// <summary>
/// Gets and Sets the content for this request.
/// </summary>
public byte[] Content
{
get
{
return this.content;
}
set
{
this.content = value;
}
}
/// <summary>
/// Flag that signals that Content was and should be set
/// from the Parameters collection.
/// </summary>
public bool SetContentFromParameters { get; set; }
/// <summary>
/// Gets and sets the content stream.
/// </summary>
public Stream ContentStream
{
get { return this.contentStream; }
set
{
this.contentStream = value;
OriginalStreamPosition = -1;
if (this.contentStream != null)
{
Stream baseStream = HashStream.GetNonWrapperBaseStream(this.contentStream);
if (baseStream.CanSeek)
OriginalStreamPosition = baseStream.Position;
}
}
}
/// <summary>
/// Gets and sets the original stream position.
/// If ContentStream is null or does not support seek, this propery
/// should be equal to -1.
/// </summary>
public long OriginalStreamPosition
{
get { return this.originalStreamLength; }
set { this.originalStreamLength = value; }
}
/// <summary>
/// Computes the SHA 256 hash of the content stream. If the stream is not
/// seekable, it searches the parent stream hierarchy to find a seekable
/// stream prior to computation. Once computed, the hash is cached for future
/// use. If a suitable stream cannot be found to use, null is returned.
/// </summary>
public string ComputeContentStreamHash()
{
if (this.contentStream == null)
return null;
if (this.contentStreamHash == null)
{
var seekableStream = WrapperStream.SearchWrappedStream(this.contentStream, s => s.CanSeek);
if (seekableStream != null)
{
var position = seekableStream.Position;
byte[] payloadHashBytes = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(seekableStream);
this.contentStreamHash = AWSSDKUtils.ToHex(payloadHashBytes, true);
seekableStream.Seek(position, SeekOrigin.Begin);
}
}
return this.contentStreamHash;
}
/// <summary>
/// The name of the service to which this request is being sent.
/// </summary>
public string ServiceName
{
get
{
return this.serviceName;
}
}
/// <summary>
/// Alternate endpoint to use for this request, if any.
/// </summary>
public RegionEndpoint AlternateEndpoint
{
get
{
return this.alternateRegion;
}
set
{
this.alternateRegion = value;
}
}
/// <summary>
/// Host prefix value to prepend to the endpoint for this request, if any.
/// </summary>
public string HostPrefix { get; set; }
/// <summary>
/// Gets and sets the Suppress404Exceptions property. If true then 404s return back from AWS will not cause an exception and
/// an empty response object will be returned.
/// </summary>
public bool Suppress404Exceptions
{
get;
set;
}
/// <summary>
/// If using AWS4 signing protocol, contains the resultant parts of the
/// signature that we may need to make use of if we elect to do a chunked
/// encoding upload.
/// </summary>
public AWS4SigningResult AWS4SignerResult { get; set; }
/// <summary>
/// <para><b>WARNING: Setting DisablePayloadSigning to true disables the SigV4 payload signing
/// data integrity check on this request.</b></para>
/// <para>If using SigV4, the DisablePayloadSigning flag controls if the payload should be
/// signed on a request by request basis. By default this flag is null which will use the
/// default client behavior. The default client behavior is to sign the payload. When
/// DisablePayloadSigning is true, the request will be signed with an UNSIGNED-PAYLOAD value.
/// Setting DisablePayloadSigning to true requires that the request is sent over a HTTPS
/// connection.</para>
/// <para>Under certain circumstances, such as uploading to S3 while using MD5 hashing, it may
/// be desireable to use UNSIGNED-PAYLOAD to decrease signing CPU usage. This flag only applies
/// to Amazon S3 PutObject and UploadPart requests.</para>
/// <para>MD5Stream, SigV4 payload signing, and HTTPS each provide some data integrity
/// verification. If DisableMD5Stream is true and DisablePayloadSigning is true, then the
/// possibility of data corruption is completely dependant on HTTPS being the only remaining
/// source of data integrity verification.</para>
/// </summary>
public bool? DisablePayloadSigning { get; set; }
/// <summary>
/// If using SigV4a signing protocol, contains the resultant parts of the
/// signature that we may need to make use of if we elect to do a chunked
/// encoding upload.
/// </summary>
public AWS4aSigningResult AWS4aSignerResult { get; set; }
/// <summary>
/// Determine whether to use a chunked encoding upload for the request
/// (applies to Amazon S3 PutObject and UploadPart requests only). If
/// DisablePayloadSigning is true, UseChunkEncoding will be automatically
/// set to false.
/// </summary>
public bool UseChunkEncoding { get; set; }
/// <summary>
/// Determine whether to use double encoding for request's signer.
/// Propagated from the endpoint's authSchemes.
/// Default value is "true".
/// Currently only S3 and S3 Control will disable double encoding.
/// </summary>
public bool UseDoubleEncoding { get; set; } = true;
/// <summary>
/// Used for Amazon S3 requests where the bucket name is removed from
/// the marshalled resource path into the host header. To comply with
/// AWS2 signature calculation, we need to recover the bucket name
/// and include it in the resource canonicalization, which we do using
/// this field.
/// </summary>
public string CanonicalResourcePrefix
{
get;
set;
}
/// <summary>
/// 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.
/// </summary>
[Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")]
public bool UseSigV4
{
get { return SignatureVersion == SignatureVersion.SigV4; }
set { this.SignatureVersion = value ? SignatureVersion.SigV4 : SignatureVersion.SigV2; }
}
/// <summary>
/// Specifies which signature version shall be used for the current request.
/// </summary>
public SignatureVersion SignatureVersion { get; set; }
/// <summary>
/// The authentication region to use for the request.
/// Set from Config.AuthenticationRegion.
/// </summary>
public string AuthenticationRegion { get; set; }
/// <summary>
/// The region in which the service request was signed.
/// </summary>
public string DeterminedSigningRegion { get ; set; }
/// <summary>
/// If the request needs to be signed with a different service name
/// than the client config AuthenticationServiceName, set it here to override
/// the result of DetermineService in AWS4Signer
/// </summary>
public string OverrideSigningServiceName { get; set; }
/// <summary>
/// The checksum algorithm that was selected to validate this request's integrity
/// </summary>
public CoreChecksumAlgorithm SelectedChecksum { get; set; }
/// <summary>
/// Returns a dictionary of the trailing headers included
/// after this request's content.
/// </summary>
public IDictionary<string, string> TrailingHeaders => this.trailingHeaders;
/// <summary>
/// Checks if the request stream can be rewinded.
/// </summary>
/// <returns>Returns true if the request stream can be rewinded ,
/// else false.</returns>
public bool IsRequestStreamRewindable()
{
var stream = this.ContentStream;
// Retries may not be possible with a stream
if (stream != null)
{
// Pull out the underlying non-wrapper stream
stream = WrapperStream.GetNonWrapperBaseStream(stream);
// Retry is possible if stream is seekable
return stream.CanSeek;
}
return true;
}
/// <summary>
/// Returns true if the request can contain a request body, else false.
/// </summary>
/// <returns>Returns true if the currect request can contain a request body, else false.</returns>
public bool MayContainRequestBody()
{
return
(this.HttpMethod == "POST" ||
this.HttpMethod == "PUT" ||
this.HttpMethod == "PATCH");
}
/// <summary>
/// Returns true if the request has a body, else false.
/// </summary>
/// <returns>Returns true if the request has a body, else false.</returns>
public bool HasRequestBody()
{
var isPutPost = (this.HttpMethod == "POST" || this.HttpMethod == "PUT" || this.HttpMethod == "PATCH");
var hasContent = this.HasRequestData();
return (isPutPost && hasContent);
}
public string GetHeaderValue(string headerName)
{
string headerValue;
if (headers.TryGetValue(headerName, out headerValue))
return headerValue;
return string.Empty;
}
}
}
| 568 |
aws-sdk-net | aws | C# | /*
* 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.Diagnostics.CodeAnalysis;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Class containing the data for one endpoint returned from a endpoint discovery request
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public abstract class DiscoveryEndpointBase
{
private DateTime _createdOn;
private string _address;
private long _cachePeriodInMinutes;
private object objectExtendLock = new object();
/// <summary>
/// Constructs a new DiscoveryEndpoint
/// </summary>
/// <param name="address">The address of the endpoint</param>
/// <param name="cachePeriodInMinutes">The cache period for the endpoint in minutes</param>
[SuppressMessage("AwsSdkRules", "CR1003:PreventDateTimeNowUseRule",
Justification = "The DateTime value is never used on the server.")]
protected DiscoveryEndpointBase(string address, long cachePeriodInMinutes)
{
Address = address;
CachePeriodInMinutes = cachePeriodInMinutes;
_createdOn = DateTime.UtcNow;
}
/// <summary>
/// The address of the endpoint.
/// </summary>
public string Address
{
get { return _address; }
protected set
{
var address = value;
// A null endpoint is allowed when endpoint discovery is not required.
if (address != null)
{
// Only http schemes are allowed, and we assume that if it does not start with an http scheme,
// it should be defaulted to https.
if (!address.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
address = "https://" + address;
}
}
_address = address;
}
}
/// <summary>
/// The cache period for the endpoint in minutes
/// </summary>
public long CachePeriodInMinutes
{
get { return _cachePeriodInMinutes; }
protected set { _cachePeriodInMinutes = value; }
}
/// <summary>
/// Calculates if this endpoint has expired
/// </summary>
/// <returns>A boolean value indicating if the cache period has expired</returns>
[SuppressMessage("AwsSdkRules", "CR1003:PreventDateTimeNowUseRule",
Justification = "The DateTime value is never used on the server.")]
public bool HasExpired()
{
TimeSpan timespan = DateTime.UtcNow - _createdOn;
return timespan.TotalMinutes > CachePeriodInMinutes ? true : false;
}
/// <summary>
/// Extends the endpoint expiration by the specified number of minutes from now.
/// </summary>
[SuppressMessage("AwsSdkRules", "CR1003:PreventDateTimeNowUseRule",
Justification = "The DateTime value is never used on the server.")]
public void ExtendExpiration(long minutes)
{
//Lock for this instance of the object against multiple extends
lock (objectExtendLock)
{
CachePeriodInMinutes = minutes;
_createdOn = DateTime.UtcNow;
}
}
}
/// <summary>
/// Class containing the data for one endpoint returned from a endpoint discovery request
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public class DiscoveryEndpoint : DiscoveryEndpointBase
{
public DiscoveryEndpoint(string address, long cachePeriodInMinutes) : base(address, cachePeriodInMinutes)
{
}
}
} | 125 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.IO;
using System.Text;
using Amazon.Runtime.Internal.Auth;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Class containing the data to use with endpoint discovery
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public abstract class EndpointDiscoveryDataBase
{
private bool _required;
private SortedDictionary<string, string> _identifiers;
protected EndpointDiscoveryDataBase(bool required)
{
_required = required;
_identifiers = new SortedDictionary<string, string>();
}
/// <summary>
/// Gets/sets and flag indicating if endpoint discovery is required for the request.
/// </summary>
public virtual bool Required
{
get
{
return _required;
}
protected set
{
_required = value;
}
}
/// <summary>
/// Sorted dictionary of the identifiers that must be sent with the endpoint discovery request. These
/// identifiers are used to construct the cache key for the cache that stores discovered endpoints. A
/// sorted dictionary is used instead of a dictionary to ensure the cache key comes out in the same order
/// each time it is constructed.
/// </summary>
public virtual SortedDictionary<string, string> Identifiers
{
get
{
return _identifiers;
}
protected set
{
_identifiers = value;
}
}
}
/// <summary>
/// Represents the data to be used with endpoint discovery operations
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public class EndpointDiscoveryData : EndpointDiscoveryDataBase
{
public EndpointDiscoveryData(bool required) : base(required) { }
}
}
| 87 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Class used to resolve endpoints using Endpoint Discovery.
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public abstract class EndpointDiscoveryResolverBase
{
private IClientConfig _config;
private Logger _logger;
private LruCache<string, IList<DiscoveryEndpointBase>> _cache;
private object objectCacheLock = new object();
private const int _cacheKeyValidityInSeconds = 3600;
protected EndpointDiscoveryResolverBase(IClientConfig config, Logger logger)
{
_config = config;
_logger = logger;
_cache = new LruCache<string, IList<DiscoveryEndpointBase>>(config.EndpointDiscoveryCacheLimit);
}
/// <summary>
/// Method that performs endpoint discovery for the current operation
/// </summary>
/// <param name="context">Context information used in calculations for endpoint discovery</param>
/// <param name="InvokeEndpointOperation">The operation to fetch endpoints from the server</param>
/// <returns></returns>
public virtual IEnumerable<DiscoveryEndpointBase> ResolveEndpoints(EndpointOperationContextBase context, Func<IList<DiscoveryEndpointBase>> InvokeEndpointOperation)
{
//Build the cacheKey
var cacheKey = BuildEndpointDiscoveryCacheKey(context);
//Evict cache keys that more than 1 hour old.
_cache.EvictExpiredLRUListItems(_cacheKeyValidityInSeconds);
//Check / cleanup the cache
var refreshCache = false;
IEnumerable<DiscoveryEndpointBase> endpoints = ProcessEndpointCache(cacheKey, context.EvictCacheKey, context.EvictUri, out refreshCache);
if (endpoints != null)
{
if (refreshCache)
{
//Async fetch new endpoints because one or more of the endpoints in the cache have expired.
#if AWS_ASYNC_API
// Task only exists in framework 4.5 and up, and Standard.
System.Threading.Tasks.Task.Run(() =>
{
ProcessInvokeEndpointOperation(cacheKey, InvokeEndpointOperation, false);
});
#else
// ThreadPool only exists in 3.5 and below. These implementations do not have the Task library.
System.Threading.ThreadPool.QueueUserWorkItem((state) =>
{
ProcessInvokeEndpointOperation(cacheKey, InvokeEndpointOperation, false);
});
#endif
}
return endpoints;
}
if (context.EvictCacheKey)
{
return null;
}
//Determine if we are required to get an endpoint or if we can defer it to an async call
if (context.EndpointDiscoveryData.Required)
{
//Must find an endpoint or error for this operation
endpoints = ProcessInvokeEndpointOperation(cacheKey, InvokeEndpointOperation, true);
}
else if (_config.EndpointDiscoveryEnabled)
{
//Optionally find and endpoint for this supported operation async
#if AWS_ASYNC_API
// Task only exists in framework 4.5 and up, and Standard.
System.Threading.Tasks.Task.Run(() =>
{
ProcessInvokeEndpointOperation(cacheKey, InvokeEndpointOperation, false);
});
#else
// ThreadPool only exists in 3.5 and below. These implementations do not have the Task library.
System.Threading.ThreadPool.QueueUserWorkItem((state) =>
{
ProcessInvokeEndpointOperation(cacheKey, InvokeEndpointOperation, false);
});
#endif
return null;
}
//else not required or endpoint discovery has been disabled so fall through to normal regional endpoint
return endpoints;
}
private IEnumerable<DiscoveryEndpointBase> ProcessInvokeEndpointOperation(string cacheKey, Func<IList<DiscoveryEndpointBase>> InvokeEndpointOperation, bool endpointRequired)
{
IList<DiscoveryEndpointBase> endpoints = null;
try
{
endpoints = InvokeEndpointOperation();
if (endpoints != null && endpoints.Count > 0)
{
_cache.AddOrUpdate(cacheKey, endpoints);
}
else
{
endpoints = null;
if (!endpointRequired)
{
//Since it is not required that endpoint discovery is used for this operation, cache
//a null endpoint with an expiration time of 60 seconds so that requests are not
//excessively sent.
var cacheEndpoints = new List<DiscoveryEndpointBase>();
cacheEndpoints.Add(new DiscoveryEndpoint(null, 1));
_cache.AddOrUpdate(cacheKey, cacheEndpoints);
}
_logger.InfoFormat("The request to discover endpoints did not return any endpoints.");
}
}
catch (Exception exception)
{
_logger.Error(exception, "An unhandled exception occurred while trying to discover endpoints.");
}
if (endpoints == null && endpointRequired)
{
throw new AmazonClientException("Failed to discover the endpoint for the request. Requests will not succeed until an endpoint can be retrieved or an endpoint is manually specified.");
}
return endpoints;
}
public virtual IList<DiscoveryEndpointBase> GetDiscoveryEndpointsFromCache(string cacheKey)
{
IList<DiscoveryEndpointBase> endpoints = null;
if (!_cache.TryGetValue(cacheKey, out endpoints))
{
return null;
}
return endpoints;
}
/// <summary>
/// Gets the number of cache keys in the cache
/// </summary>
public virtual int CacheCount
{
get
{
return _cache.Count;
}
}
private IEnumerable<DiscoveryEndpointBase> ProcessEndpointCache(string cacheKey, bool evictCacheKey, Uri evictUri, out bool refreshCache)
{
refreshCache = false;
IList<DiscoveryEndpointBase> endpoints = GetDiscoveryEndpointsFromCache(cacheKey);
if (evictCacheKey && endpoints != null)
{
//Force eviction of the evictUri endpoint but keep the rest to use. This only happens if an
//Invalid Endpoint Exception was processed against the cached endpoint data.
var testAddress = evictUri.ToString();
lock (objectCacheLock)
{
for (var i = 0; i < endpoints.Count; i++)
{
var endpoint = endpoints[i];
if (endpoint.Address != null && endpoint.Address.Equals(testAddress, StringComparison.OrdinalIgnoreCase))
{
endpoints.RemoveAt(i);
break;
}
}
}
if (endpoints.Count == 0)
{
_cache.Evict(cacheKey);
return null;
}
}
//Check to see if we have cached endpoints
if (endpoints != null)
{
//If any endpoints have expired we need to async get new endpoints while continuing to use
//the existing endpoints in the cache. They must not be evicted if they expired until new
//endpoints are obtained.
foreach (var endpoint in endpoints)
{
if (endpoint.HasExpired())
{
refreshCache = true;
//Add 1 minute to the expiration so we don't retry again until 1 minute from now if
//the refresh fails. If the refresh succeeds all the extended endpoints will be replaced
//before the extended 1 minute expiration.
endpoint.ExtendExpiration(1);
}
}
return endpoints;
}
return null;
}
private static string BuildEndpointDiscoveryCacheKey(EndpointOperationContextBase context)
{
var cacheKeyBuilder = new StringBuilder();
cacheKeyBuilder.Append(context.CustomerCredentials);
var identifiers = context.EndpointDiscoveryData.Identifiers;
if (identifiers != null && identifiers.Count > 0)
{
cacheKeyBuilder.Append(string.Format(CultureInfo.InvariantCulture, ".{0}", context.OperationName));
foreach (var identifier in identifiers)
{
cacheKeyBuilder.Append(string.Format(CultureInfo.InvariantCulture, ".{0}", identifier.Value));
}
}
return cacheKeyBuilder.ToString();
}
}
/// <summary>
/// Class used to resolve endpoints using Endpoint Discovery.
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public class EndpointDiscoveryResolver : EndpointDiscoveryResolverBase
{
public EndpointDiscoveryResolver(IClientConfig config, Logger logger) : base(config, logger)
{
}
}
}
| 270 |
aws-sdk-net | aws | C# | /*
* 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.Auth;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Class containing context information to use with endpoint discovery
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public abstract class EndpointOperationContextBase
{
private string _customerCredentials;
private string _operationName;
private EndpointDiscoveryDataBase _endpointDiscoveryData;
private bool _evictCacheKey;
private Uri _evictUri;
protected EndpointOperationContextBase(string customerCredentials, string operationName, EndpointDiscoveryDataBase endpointDiscoveryData, bool evictCacheKey, Uri evictUri)
{
if (string.IsNullOrEmpty(customerCredentials))
{
throw new ArgumentNullException("customerCredentials");
}
_customerCredentials = customerCredentials;
_operationName = operationName;
_endpointDiscoveryData = endpointDiscoveryData;
_evictCacheKey = evictCacheKey;
_evictUri = evictUri;
}
/// <summary>
/// Gets the customer credential information.
/// </summary>
public virtual string CustomerCredentials
{
get
{
return _customerCredentials;
}
protected set
{
_customerCredentials = value;
}
}
/// <summary>
/// Gets the operation name.
/// </summary>
public virtual string OperationName
{
get
{
return _operationName;
}
protected set
{
_operationName = value;
}
}
/// <summary>
/// Gets the current marshalled endpoint discovery data.
/// </summary>
public virtual EndpointDiscoveryDataBase EndpointDiscoveryData
{
get
{
return _endpointDiscoveryData;
}
protected set
{
_endpointDiscoveryData = value;
}
}
/// <summary>
/// Gets the flag indicating if the specified key should be evicted from the cache.
/// </summary>
public virtual bool EvictCacheKey
{
get
{
return _evictCacheKey;
}
protected set
{
_evictCacheKey = value;
}
}
/// <summary>
/// Gets the Uri that should be evicted if EvictCacheKey is set to true.
/// </summary>
public virtual Uri EvictUri
{
get
{
return _evictUri;
}
protected set
{
_evictUri = value;
}
}
}
/// <summary>
/// Class containing context information to use with endpoint discovery
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public class EndpointOperationContext : EndpointOperationContextBase
{
public EndpointOperationContext(string customerCredentials, string operationName, EndpointDiscoveryDataBase endpointDiscoveryData, bool evictCacheKey, Uri evictUri)
: base(customerCredentials, operationName, endpointDiscoveryData, evictCacheKey, evictUri)
{
}
}
}
| 146 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.IO;
using System.Net;
namespace Amazon.Runtime.Internal
{
public class ErrorResponse
{
/// <summary>
/// Error type, one of Sender, Receiver, Unknown
/// Only applies to XML-based services.
/// </summary>
public ErrorType Type { get; set; }
/// <summary>
/// Name of the exception class to return
/// </summary>
public string Code { get; set; }
/// <summary>
/// Error message
/// </summary>
public string Message { get; set; }
/// <summary>
/// RequestId of the error.
/// Only applies to XML-based services.
/// </summary>
public string RequestId { get; set; }
public Exception InnerException { get; set; }
public HttpStatusCode StatusCode { get; set; }
}
}
| 52 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.Runtime.Internal
{
public interface IAmazonWebServiceRequest
{
EventHandler<StreamTransferProgressArgs> StreamUploadProgressCallback { get; set; }
void AddBeforeRequestHandler(RequestEventHandler handler);
void RemoveBeforeRequestHandler(RequestEventHandler handler);
Dictionary<string, object> RequestState { get; }
[Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")]
bool UseSigV4 { get; set; }
SignatureVersion SignatureVersion { get; set; }
}
}
| 24 |
aws-sdk-net | aws | C# | /*
* 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;
#if BCL || NETSTANDARD
using Amazon.Runtime.CredentialManagement;
#endif
using System.ComponentModel;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// InternalConfiguration holds the cached SDK configuration values
/// obtained from the environment and profile configuration
/// factories. These configuration values are loaded internally and
/// are not the same as user exposed AWSConfigs.
/// </summary>
public class InternalConfiguration
{
/// <summary>
/// Flag indicating if Endpoint Discovery is enabled.
/// </summary>
public bool? EndpointDiscoveryEnabled { get; set; }
/// <summary>
/// The retry mode to use: Legacy, Standard, or Adaptive.
/// </summary>
public RequestRetryMode? RetryMode { get; set; }
/// <summary>
/// The max number of request attempts.
/// </summary>
public int? MaxAttempts { get; set; }
/// <summary>
/// Endpoint of the EC2 Instance Metadata Service
/// </summary>
public string EC2MetadataServiceEndpoint { get; set; }
/// <summary>
/// Internet protocol version to be used for communicating with the EC2 Instance Metadata Service
/// </summary>
public EC2MetadataServiceEndpointMode? EC2MetadataServiceEndpointMode { get; set; }
/// <inheritdoc cref="CredentialProfile.DefaultConfigurationModeName"/>
public string DefaultConfigurationModeName { get; set; }
/// <summary>
/// Configures the endpoint calculation for a service to go to a dual stack (ipv6 enabled) endpoint
/// for the configured region.
/// </summary>
public bool? UseDualstackEndpoint { get; set; }
/// <summary>
/// Configures the endpoint calculation to go to a FIPS (https://aws.amazon.com/compliance/fips/) endpoint
/// for the configured region.
/// </summary>
public bool? UseFIPSEndpoint { get; set; }
}
#if BCL || NETSTANDARD
/// <summary>
/// Determines the configuration values based on environment variables. If
/// no values is found for a configuration the value will be set to null.
/// </summary>
public class EnvironmentVariableInternalConfiguration : InternalConfiguration
{
private Logger _logger = Logger.GetLogger(typeof(EnvironmentVariableInternalConfiguration));
public const string ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY = "AWS_ENABLE_ENDPOINT_DISCOVERY";
public const string ENVIRONMENT_VARIABLE_AWS_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
public const string ENVIRONMENT_VARIABLE_AWS_RETRY_MODE = "AWS_RETRY_MODE";
public const string ENVIRONMENT_VARIABLE_AWS_EC2_METADATA_SERVICE_ENDPOINT = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
public const string ENVIRONMENT_VARIABLE_AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
public const string ENVIRONMENT_VARIABLE_AWS_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
public const string ENVIRONMENT_VARIABLE_AWS_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
/// <summary>
/// Attempts to construct a configuration instance of configuration environment
/// variables. If an environment variable value isn't found then the individual value
/// for that environment variable will be null. If unable to obtain a value converter
/// to convert a configuration string to the appropriate type a InvalidOperationException
/// is thrown.
/// </summary>
public EnvironmentVariableInternalConfiguration()
{
EndpointDiscoveryEnabled = GetEnvironmentVariable<bool>(ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY);
MaxAttempts = GetEnvironmentVariable<int>(ENVIRONMENT_VARIABLE_AWS_MAX_ATTEMPTS);
RetryMode = GetEnvironmentVariable<RequestRetryMode>(ENVIRONMENT_VARIABLE_AWS_RETRY_MODE);
EC2MetadataServiceEndpoint = GetEC2MetadataEndpointEnvironmentVariable();
EC2MetadataServiceEndpointMode = GetEnvironmentVariable<EC2MetadataServiceEndpointMode>(ENVIRONMENT_VARIABLE_AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE);
UseDualstackEndpoint = GetEnvironmentVariable<bool>(ENVIRONMENT_VARIABLE_AWS_USE_DUALSTACK_ENDPOINT);
UseFIPSEndpoint = GetEnvironmentVariable<bool>(ENVIRONMENT_VARIABLE_AWS_USE_FIPS_ENDPOINT);
}
private bool TryGetEnvironmentVariable(string environmentVariableName, out string value)
{
value = Environment.GetEnvironmentVariable(environmentVariableName);
if (string.IsNullOrEmpty(value))
{
_logger.InfoFormat($"The environment variable {environmentVariableName} was not set with a value.");
value = null;
return false;
}
return true;
}
private T? GetEnvironmentVariable<T>(string name) where T : struct
{
if (!TryGetEnvironmentVariable(name, out var value))
{
return null;
}
var converter = TypeDescriptor.GetConverter(typeof(T?));
if (converter == null)
{
throw new InvalidOperationException($"Unable to obtain type converter for type {typeof(T?)} " +
$"to convert environment variable {name}.");
}
try
{
return (T?)converter.ConvertFromString(value);
}
catch (Exception e)
{
_logger.Error(e, $"The environment variable {name} was set with value {value}, but it could not be parsed as a valid value.");
}
return null;
}
/// <summary>
/// Loads the EC2 Instance Metadata endpoint from the environment variable, and validates it is a well-formed uri
/// </summary>
/// <returns>Override EC2 instance metadata endpoint if valid, else an empty string</returns>
private string GetEC2MetadataEndpointEnvironmentVariable()
{
if (!TryGetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_EC2_METADATA_SERVICE_ENDPOINT, out var rawValue))
{
return null;
}
if (!Uri.IsWellFormedUriString(rawValue, UriKind.Absolute))
{
throw new AmazonClientException($"The environment variable {ENVIRONMENT_VARIABLE_AWS_EC2_METADATA_SERVICE_ENDPOINT} was set with value " +
$"{rawValue}, but it could not be parsed as a well-formed Uri.");
}
return rawValue;
}
}
/// <summary>
/// Determines configuration values based on a <see cref="CredentialProfile"/> stored in an <see cref="ICredentialProfileSource"/>.
/// If the profile doesn't exist, the status will be logged and no value will be set in the configuration.
/// </summary>
public class ProfileInternalConfiguration : InternalConfiguration
{
private Logger _logger = Logger.GetLogger(typeof(ProfileInternalConfiguration));
/// <summary>
/// Attempts to construct an instance of <see cref="ProfileInternalConfiguration"/>.
/// 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 status will be logged and no value will be set in the configuration.
/// </summary>
/// <param name="source">The ICredentialProfileSource to read the profile from.</param>
public ProfileInternalConfiguration(ICredentialProfileSource source)
{
var profileName = FallbackCredentialsFactory.GetProfileName();
Setup(source, profileName);
}
/// <summary>
/// Attempts to construct an instance of <see cref="ProfileInternalConfiguration"/>.
/// If the profile doesn't exist status will be logged and no value will be set in the configuration.
/// </summary>
/// <param name="source">The ICredentialProfileSource to read the profile from.</param>
/// <param name="profileName">The name of the profile.</param>
public ProfileInternalConfiguration(ICredentialProfileSource source, string profileName)
{
Setup(source, profileName);
}
private void Setup(ICredentialProfileSource source, string profileName)
{
CredentialProfile profile;
if (source.TryGetProfile(profileName, out profile))
{
DefaultConfigurationModeName = profile.DefaultConfigurationModeName;
EndpointDiscoveryEnabled = profile.EndpointDiscoveryEnabled;
RetryMode = profile.RetryMode;
MaxAttempts = profile.MaxAttempts;
EC2MetadataServiceEndpoint = profile.EC2MetadataServiceEndpoint;
EC2MetadataServiceEndpointMode = profile.EC2MetadataServiceEndpointMode;
UseDualstackEndpoint = profile.UseDualstackEndpoint;
UseFIPSEndpoint = profile.UseFIPSEndpoint;
}
else
{
_logger.InfoFormat("Unable to find a profile named '" + profileName + "' in store " + source.GetType());
return;
}
var items = new KeyValuePair<string, object>[]
{
new KeyValuePair<string, object>("defaults_mode", profile.DefaultConfigurationModeName),
new KeyValuePair<string, object>("endpoint_discovery_enabled", profile.EndpointDiscoveryEnabled),
new KeyValuePair<string, object>("retry_mode", profile.RetryMode),
new KeyValuePair<string, object>("max_attempts", profile.MaxAttempts),
new KeyValuePair<string, object>("ec2_metadata_service_endpoint", profile.EC2MetadataServiceEndpoint),
new KeyValuePair<string, object>("ec2_metadata_service_endpoint_mode", profile.EC2MetadataServiceEndpointMode),
new KeyValuePair<string, object>("use_dualstack_endpoint", profile.UseDualstackEndpoint),
new KeyValuePair<string, object>("use_fips_endpoint", profile.UseFIPSEndpoint)
};
foreach(var item in items)
{
_logger.InfoFormat(item.Value == null
? $"There is no {item.Key} set in the profile named '{profileName}' in store {source.GetType()}"
: $"{item.Key} found in profile '{profileName}' in store {source.GetType()}"
);
}
}
}
#endif
/// <summary>
/// Probing mechanism to determine the configuration values from various sources.
/// </summary>
public static class FallbackInternalConfigurationFactory
{
#if BCL || NETSTANDARD
private static CredentialProfileStoreChain _credentialProfileChain = new CredentialProfileStoreChain();
#endif
private static InternalConfiguration _cachedConfiguration;
static FallbackInternalConfigurationFactory()
{
Reset();
}
private delegate InternalConfiguration ConfigGenerator();
/// <summary>
/// Resets all the configuration values reloading as needed. This method will use
/// the AWS_PROFILE environment variable if set to construct the instance. Otherwise
/// the default profile will be used.
/// </summary>
public static void Reset()
{
#if BCL || NETSTANDARD
//Preload configurations that are fast or pull all the values at the same time. Slower configurations
//should be called for specific values dynamically.
InternalConfiguration environmentVariablesConfiguration = new EnvironmentVariableInternalConfiguration();
InternalConfiguration profileConfiguration = new ProfileInternalConfiguration(_credentialProfileChain);
#endif
_cachedConfiguration = new InternalConfiguration();
var standardGenerators = new List<ConfigGenerator>
{
#if BCL || NETSTANDARD
() => environmentVariablesConfiguration,
() => profileConfiguration,
#endif
};
//Find the priority first ordered config value for each property
_cachedConfiguration.DefaultConfigurationModeName = SeekString(standardGenerators, c => c.DefaultConfigurationModeName, defaultValue: null);
_cachedConfiguration.EndpointDiscoveryEnabled = SeekValue(standardGenerators, (c) => c.EndpointDiscoveryEnabled);
_cachedConfiguration.RetryMode = SeekValue(standardGenerators, (c) => c.RetryMode);
_cachedConfiguration.MaxAttempts = SeekValue(standardGenerators, (c) => c.MaxAttempts);
_cachedConfiguration.EC2MetadataServiceEndpoint = SeekString(standardGenerators, (c) => c.EC2MetadataServiceEndpoint);
_cachedConfiguration.EC2MetadataServiceEndpointMode = SeekValue(standardGenerators, (c) => c.EC2MetadataServiceEndpointMode);
_cachedConfiguration.UseDualstackEndpoint = SeekValue(standardGenerators, (c) => c.UseDualstackEndpoint);
_cachedConfiguration.UseFIPSEndpoint = SeekValue(standardGenerators, (c) => c.UseFIPSEndpoint);
}
private static T? SeekValue<T>(List<ConfigGenerator> generators, Func<InternalConfiguration, T?> getValue) where T : struct
{
//Look for the configuration value stopping at the first generator that returns the expected value.
foreach (var generator in generators)
{
var configuration = generator();
T? value = getValue(configuration);
if (value.HasValue)
{
return value;
}
}
return null;
}
private static string SeekString(List<ConfigGenerator> generators, Func<InternalConfiguration, string> getValue, string defaultValue = "")
{
//Look for the configuration value stopping at the first generator that returns the expected value.
foreach (var generator in generators)
{
var configuration = generator();
string value = getValue(configuration);
if (!string.IsNullOrEmpty(value))
{
return value;
}
}
return defaultValue;
}
/// <summary>
/// Flag that specifies if endpoint discovery is enabled, disabled,
/// or not set.
/// </summary>
public static bool? EndpointDiscoveryEnabled
{
get
{
return _cachedConfiguration.EndpointDiscoveryEnabled;
}
}
/// <summary>
/// Flag that specifies which retry mode to use or if retry mode has
/// not been set.
/// </summary>
public static RequestRetryMode? RetryMode
{
get
{
return _cachedConfiguration.RetryMode;
}
}
/// <summary>
/// Flag that specifies the max number of request attempts or if max
/// attempts has not been set.
/// </summary>
public static int? MaxAttempts
{
get
{
return _cachedConfiguration.MaxAttempts;
}
}
/// <summary>
/// Endpoint of the EC2 Instance Metadata Service
/// </summary>
public static string EC2MetadataServiceEndpoint
{
get
{
return _cachedConfiguration.EC2MetadataServiceEndpoint;
}
}
/// <summary>
/// Internet protocol version to be used for communicating with the EC2 Instance Metadata Service
/// </summary>
public static EC2MetadataServiceEndpointMode? EC2MetadataServiceEndpointMode
{
get
{
return _cachedConfiguration.EC2MetadataServiceEndpointMode;
}
}
/// <inheritdoc cref="InternalConfiguration.DefaultConfigurationModeName"/>
public static string DefaultConfigurationModeName
{
get
{
return _cachedConfiguration.DefaultConfigurationModeName;
}
}
/// <summary>
/// Configures the endpoint calculation to go to a dual stack (ipv6 enabled) endpoint
/// for the configured region.
/// </summary>
public static bool? UseDualStackEndpoint
{
get
{
return _cachedConfiguration.UseDualstackEndpoint;
}
}
/// <summary>
/// Configures the endpoint calculation to go to a FIPS (https://aws.amazon.com/compliance/fips/) endpoint
/// for the configured region.
/// </summary>
public static bool? UseFIPSEndpoint
{
get
{
return _cachedConfiguration.UseFIPSEndpoint;
}
}
}
}
| 425 |
aws-sdk-net | aws | C# | /*
* 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.Transform;
using System.Collections.Generic;
namespace Amazon.Runtime.Internal
{
public delegate IEnumerable<DiscoveryEndpointBase> EndpointOperationDelegate(EndpointOperationContextBase context);
/// <summary>
/// Class containing the members used to invoke service calls
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public abstract class InvokeOptionsBase
{
private IMarshaller<IRequest, AmazonWebServiceRequest> _requestMarshaller;
private ResponseUnmarshaller _responseUnmarshaller;
private IMarshaller<EndpointDiscoveryDataBase, AmazonWebServiceRequest> _endpointDiscoveryMarshaller;
private EndpointOperationDelegate _endpointOperation;
protected InvokeOptionsBase()
{
}
#region Standard Marshaller/Unmarshaller
public virtual IMarshaller<IRequest, AmazonWebServiceRequest> RequestMarshaller
{
get
{
return _requestMarshaller;
}
set
{
_requestMarshaller = value;
}
}
public virtual ResponseUnmarshaller ResponseUnmarshaller
{
get
{
return _responseUnmarshaller;
}
set
{
_responseUnmarshaller = value;
}
}
#endregion
#region EndpointDiscovery
public virtual IMarshaller<EndpointDiscoveryDataBase, AmazonWebServiceRequest> EndpointDiscoveryMarshaller
{
get
{
return _endpointDiscoveryMarshaller;
}
set
{
_endpointDiscoveryMarshaller = value;
}
}
public virtual EndpointOperationDelegate EndpointOperation
{
get
{
return _endpointOperation;
}
set
{
_endpointOperation = value;
}
}
#endregion
}
/// <summary>
/// Class containing the members used to invoke service calls
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public class InvokeOptions : InvokeOptionsBase
{
public InvokeOptions() : base()
{
}
}
} | 112 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.IO;
using System.Text;
using Amazon.Runtime.Internal.Auth;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Represents a request being sent to an Amazon Web Service, including the
/// parameters being sent as part of the request, the endpoint to which the
/// request should be sent, etc.
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public interface IRequest
{
/// <summary>
/// The name of the request
/// </summary>
string RequestName
{
get;
}
/// <summary>
/// Returns a dictionary of the headers included in this request.
/// </summary>
IDictionary<string, string> Headers
{
get;
}
/// <summary>
/// Gets and sets a flag that indicates whether the request is sent as a query string instead of the request body.
/// </summary>
bool UseQueryString
{
get;
set;
}
/// <summary>
/// Returns a dictionary of the parameters included in this request.
/// </summary>
IDictionary<String, String> Parameters
{
get;
}
/// <summary>
/// Collection of parameters included in this request.
/// </summary>
ParameterCollection ParameterCollection
{
get;
}
/// <summary>
/// Returns the subresources that should be appended to the resource path.
/// This is used primarily for Amazon S3, where object keys can contain '?'
/// characters, making string-splitting of a resource path potentially
/// hazardous.
/// </summary>
IDictionary<string, string> SubResources
{
get;
}
/// <summary>
/// Adds a new null entry to the SubResources collection for the request
/// </summary>
/// <param name="subResource">The name of the subresource</param>
void AddSubResource(string subResource);
/// <summary>
/// Adds a new entry to the SubResources collection for the request
/// </summary>
/// <param name="subResource">The name of the subresource</param>
/// <param name="value">Value of the entry</param>
void AddSubResource(string subResource, string value);
/// <summary>
/// Gets and sets the type of http request to make, whether it should be POST,GET or DELETE
/// </summary>
string HttpMethod
{
get;
set;
}
/// <summary>
/// Gets and Sets the endpoint for this request.
/// </summary>
Uri Endpoint
{
get;
set;
}
/// <summary>
/// Gets and Sets the resource path added on to the endpoint.
/// </summary>
string ResourcePath
{
get;
set;
}
/// <summary>
/// Returns the path resources that should be used within the resource path.
/// This is used for services where path keys can contain '/'
/// characters, making string-splitting of a resource path potentially
/// hazardous.
/// </summary>
IDictionary<string, string> PathResources
{
get;
}
/// <summary>
/// Adds a new entry to the PathResources collection for the request
/// </summary>
/// <param name="key">The name of the pathresource with potential greedy syntax: {key+}</param>
/// <param name="value">Value of the entry</param>
void AddPathResource(string key, string value);
/// <summary>
/// Gets and Sets the version number for the marshaller used to create this request. The version number
/// is used to support backward compatible changes that would otherwise be breaking changes when a
/// newer core is used with an older service assembly.
/// </summary>
int MarshallerVersion
{
get;
set;
}
/// <summary>
/// Gets and Sets the content for this request.
/// </summary>
byte[] Content
{
get;
set;
}
/// <summary>
/// Gets the header value from the request.
/// </summary>
string GetHeaderValue(string headerName);
/// <summary>
/// Flag that signals that Content was and should be set
/// from the Parameters collection.
/// </summary>
bool SetContentFromParameters { get; set; }
/// <summary>
/// Gets and sets the content stream.
/// </summary>
Stream ContentStream
{
get;
set;
}
/// <summary>
/// Gets and sets the original stream position.
/// If ContentStream is null or does not support seek, this propery
/// should be equal to -1.
/// </summary>
long OriginalStreamPosition
{
get;
set;
}
/// <summary>
/// Computes the SHA 256 hash of the content stream. If the stream is not
/// seekable, it searches the parent stream hierarchy to find a seekable
/// stream prior to computation. Once computed, the hash is cached for future
/// use.
/// </summary>
string ComputeContentStreamHash();
/// <summary>
/// If the request needs to be signed with a different service name
/// than the client config AuthenticationServiceName, set it here to override
/// the result of DetermineService in AWS4Signer
/// </summary>
string OverrideSigningServiceName { get; set; }
/// <summary>
/// The name of the service to which this request is being sent.
/// </summary>
string ServiceName
{
get;
}
/// <summary>
/// Returns the original, user facing request object which this internal
/// request object is representing.
/// </summary>
AmazonWebServiceRequest OriginalRequest
{
get;
}
/// <summary>
/// Alternate endpoint to use for this request, if any.
/// </summary>
RegionEndpoint AlternateEndpoint
{
get;
set;
}
/// <summary>
/// Host prefix value to prepend to the endpoint for this request, if any.
/// </summary>
string HostPrefix
{
get;
set;
}
/// <summary>
/// Gets and sets the Suppress404Exceptions property. If true then 404s return back from AWS will not cause an exception and
/// an empty response object will be returned.
/// </summary>
bool Suppress404Exceptions
{
get;
set;
}
/// <summary>
/// If using AWS4 signing protocol, contains the resultant parts of the
/// signature that we may need to make use of if we elect to do a chunked
/// encoding upload.
/// </summary>
AWS4SigningResult AWS4SignerResult
{
get;
set;
}
/// <summary>
/// <para><b>WARNING: Setting DisablePayloadSigning to true disables the SigV4 payload signing
/// data integrity check on this request.</b></para>
/// <para>If using SigV4, the DisablePayloadSigning flag controls if the payload should be
/// signed on a request by request basis. By default this flag is null which will use the
/// default client behavior. The default client behavior is to sign the payload. When
/// DisablePayloadSigning is true, the request will be signed with an UNSIGNED-PAYLOAD value.
/// Setting DisablePayloadSigning to true requires that the request is sent over a HTTPS
/// connection.</para>
/// <para>Under certain circumstances, such as uploading to S3 while using MD5 hashing, it may
/// be desireable to use UNSIGNED-PAYLOAD to decrease signing CPU usage. This flag only applies
/// to Amazon S3 PutObject and UploadPart requests.</para>
/// <para>MD5Stream, SigV4 payload signing, and HTTPS each provide some data integrity
/// verification. If DisableMD5Stream is true and DisablePayloadSigning is true, then the
/// possibility of data corruption is completely dependant on HTTPS being the only remaining
/// source of data integrity verification.</para>
/// </summary>
bool? DisablePayloadSigning
{
get;
set;
}
/// <summary>
/// If using SigV4a signing protocol, contains the resultant parts of the
/// signature that we may need to make use of if we elect to do a chunked
/// encoding upload.
/// </summary>
AWS4aSigningResult AWS4aSignerResult
{
get;
set;
}
/// <summary>
/// Determine whether to use a chunked encoding upload for the request
/// (applies to Amazon S3 PutObject and UploadPart requests only). If
/// DisablePayloadSigning is true, UseChunkEncoding will be automatically
/// set to false.
/// </summary>
bool UseChunkEncoding
{
get;
set;
}
/// <summary>
/// Used for Amazon S3 requests where the bucket name is removed from
/// the marshalled resource path into the host header. To comply with
/// AWS2 signature calculation, we need to recover the bucket name
/// and include it in the resource canonicalization, which we do using
/// this field.
/// </summary>
string CanonicalResourcePrefix
{
get;
set;
}
/// <summary>
/// This flag specifies if SigV4 is required for the current request.
/// </summary>
[Obsolete("UseSigV4 is deprecated. Use SignatureVersion directly instead.")]
bool UseSigV4 { get; set; }
/// <summary>
/// Specifies which signature version shall be used for the current request.
/// </summary>
SignatureVersion SignatureVersion { get; set; }
/// <summary>
/// The authentication region to use for the request.
/// Set from Config.AuthenticationRegion.
/// </summary>
string AuthenticationRegion { get; set; }
/// <summary>
/// The region in which the service request was signed.
/// </summary>
string DeterminedSigningRegion { get; set; }
/// <summary>
/// Checks if the request stream can be rewinded.
/// </summary>
/// <returns>Returns true if the request stream can be rewinded ,
/// else false.</returns>
bool IsRequestStreamRewindable();
/// <summary>
/// Returns true if the request can contain a request body, else false.
/// </summary>
/// <returns>Returns true if the currect request can contain a request body, else false.</returns>
bool MayContainRequestBody();
/// <summary>
/// Returns true if the request has a body, else false.
/// </summary>
/// <returns>Returns true if the request has a body, else false.</returns>
bool HasRequestBody();
/// <summary>
/// The checksum algorithm that was selected to validate this request's integrity
/// </summary>
CoreChecksumAlgorithm SelectedChecksum { get; set; }
/// <summary>
/// Returns a dictionary of the trailing headers included
/// after this request's content.
/// </summary>
IDictionary<string, string> TrailingHeaders { get; }
/// <summary>
/// Determine whether to use double encoding for request's signer.
/// </summary>
bool UseDoubleEncoding { get; set; }
}
}
| 383 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal
{
public interface IRequestData
{
ResponseUnmarshaller Unmarshaller { get; }
RequestMetrics Metrics { get; }
IRequest Request { get; }
AbstractAWSSigner Signer { get; }
int RetriesAttempt { get; }
}
}
| 35 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Internal
{
public interface IServiceMetadata
{
/// <summary>
/// Gets the value of the Service Id.
/// </summary>
string ServiceId { get; }
/// <summary>
/// Gets the dictionary that gives mapping of renamed operations
/// </summary>
System.Collections.Generic.IDictionary<string, string> OperationNameMapping { get; }
}
} | 30 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
using Amazon.Runtime.Internal.Auth;
using Amazon.Util;
using System.Collections;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// IDictionary{String, String} access to ParameterCollection.
/// TODO: remove this class in version 3.4 of the SDK.
/// </summary>
public class ParametersDictionaryFacade : IDictionary<String, String>
{
private readonly ParameterCollection _parameterCollection;
/// <summary>
/// Constructs ParametersDictionaryFacade for a ParameterCollection
/// </summary>
/// <param name="collection"></param>
public ParametersDictionaryFacade(ParameterCollection collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
_parameterCollection = collection;
}
// Converts ParameterValue to a string representation
private static string ParameterValueToString(ParameterValue pv)
{
if (pv == null)
throw new ArgumentNullException("pv");
var spv = pv as StringParameterValue;
var slpv = pv as StringListParameterValue;
if (spv != null)
return spv.Value;
else if (slpv != null)
{
var json = ThirdParty.Json.LitJson.JsonMapper.ToJson(slpv.Value);
return json;
}
else
throw new AmazonClientException("Unexpected parameter value type " + pv.GetType().FullName);
}
// Update a ParameterValue with a string representation of its value
private static void UpdateParameterValue(ParameterValue pv, string newValue)
{
if (pv == null)
throw new ArgumentNullException("pv");
var spv = pv as StringParameterValue;
var slpv = pv as StringListParameterValue;
if (spv != null)
{
spv.Value = newValue;
}
else if (slpv != null)
{
var stringList = ThirdParty.Json.LitJson.JsonMapper.ToObject<List<string>>(newValue);
slpv.Value = stringList;
}
else
{
throw new AmazonClientException("Unexpected parameter value type " + pv.GetType().FullName);
}
}
#region IDictionary<String, String> methods
public void Add(string key, string value)
{
_parameterCollection.Add(key, value);
}
public int Count
{
get { return _parameterCollection.Count; }
}
public bool ContainsKey(string key)
{
return _parameterCollection.ContainsKey(key);
}
public bool Remove(string key)
{
return _parameterCollection.Remove(key);
}
public string this[string key]
{
get
{
var pv = _parameterCollection[key];
var s = ParameterValueToString(pv);
return s;
}
set
{
ParameterValue pv;
if (_parameterCollection.TryGetValue(key, out pv))
{
UpdateParameterValue(pv, value);
}
else
{
// if not updating existing ParameterValue, we only
// support creating StringParameterValue
pv = new StringParameterValue(value);
}
_parameterCollection[key] = pv;
}
}
public ICollection<string> Keys
{
get { return _parameterCollection.Keys; }
}
public bool TryGetValue(string key, out string value)
{
ParameterValue pv;
if (_parameterCollection.TryGetValue(key, out pv))
{
value = ParameterValueToString(pv);
return true;
}
else
{
value = null;
return false;
}
}
public bool Remove(KeyValuePair<string, string> item)
{
if (this.Contains(item))
return _parameterCollection.Remove(item.Key);
else
return false;
}
public ICollection<string> Values
{
get
{
var values = new List<string>();
foreach(var kvp in _parameterCollection)
{
var stringValue = ParameterValueToString(kvp.Value);
values.Add(stringValue);
}
return values;
}
}
public void Add(KeyValuePair<string, string> item)
{
// when not updating existing ParameterValue, we only
// support creating StringParameterValue
var pv = new StringParameterValue(item.Value);
_parameterCollection.Add(item.Key, pv);
}
public bool Contains(KeyValuePair<string, string> item)
{
var key = item.Key;
var value = item.Value;
ParameterValue pv;
if (_parameterCollection.TryGetValue(key, out pv))
{
var expectedValue = ParameterValueToString(pv);
return string.Equals(expectedValue, value, StringComparison.Ordinal);
}
else
return false;
}
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException("arrayIndex");
}
if (array.Length - arrayIndex < _parameterCollection.Count)
{
throw new ArgumentOutOfRangeException("arrayIndex", "Not enough space in target array");
}
foreach(var kvp in this)
{
array[arrayIndex++] = kvp;
}
}
public bool IsReadOnly
{
get { return (_parameterCollection as IDictionary).IsReadOnly; }
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
foreach (var kvp in _parameterCollection)
{
var key = kvp.Key;
var stringValue = ParameterValueToString(kvp.Value);
var result = new KeyValuePair<string, string>(key, stringValue);
yield return result;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Clear()
{
_parameterCollection.Clear();
}
#endregion
}
}
| 254 |
aws-sdk-net | aws | C# | /*
* 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.Linq;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Provides information about the current runtime environment.
/// </summary>
public interface IRuntimeInformationProvider
{
/// <summary>
/// Indicates whether the current application is running on Mobile.
/// </summary>
/// <returns>true if the current application is running on Mobile; otherwise, false.</returns>
bool IsMobile();
}
/// <inheritdoc />
public class RuntimeInformationProvider : IRuntimeInformationProvider
{
/// <inheritdoc/>
/// <remarks>
/// SDK does not do intelligent checks like checking package references or reflection to determine whether
/// the current project is a mobile project because of performance reasons. Moving forward, when .NET 6 support is added,
/// it should use OperatingSystem.IsAndroid <see href="https://docs.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroid"/>
/// or OperatingSystem.IsIOS <see href="https://docs.microsoft.com/en-us/dotnet/api/system.operatingsystem.isios"/> to determine
/// whether the current application is running on Mobile or not.
/// </remarks>
public bool IsMobile()
{
return false;
}
}
} | 49 |
aws-sdk-net | aws | C# | using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// A registry of object that will manipulate the runtime pipeline used by service clients.
/// </summary>
public class RuntimePipelineCustomizerRegistry : IDisposable
{
public static RuntimePipelineCustomizerRegistry Instance { get; } = new RuntimePipelineCustomizerRegistry();
private RuntimePipelineCustomizerRegistry()
{
}
Logger _logger = Logger.GetLogger(typeof(RuntimePipelineCustomizerRegistry));
ReaderWriterLockSlim _rwlock = new ReaderWriterLockSlim();
// List is used instead of a dictionary to maintain order
IList<IRuntimePipelineCustomizer> _customizers = new List<IRuntimePipelineCustomizer>();
/// <summary>
/// Registers a customizer that will be applied for all service clients created. Each customizer has a unique name associated with it. If a customizer is registered more
/// than once with the same unique name then the calls after the first will be ignored.
/// </summary>
/// <param name="customizer"></param>
public void Register(IRuntimePipelineCustomizer customizer)
{
_rwlock.EnterWriteLock();
try
{
// If the customizer is already registered then skip adding it again. This could happen if 2 separate libraries are added
// to a project and they both one to turn on a third party customizer
if (_customizers.FirstOrDefault(x => string.Equals(x.UniqueName, customizer.UniqueName)) != null)
{
_logger.InfoFormat("Skipping registration because runtime pipeline customizer {0} already registered", customizer.UniqueName);
return;
}
_logger.InfoFormat("Registering runtime pipeline customizer {0}", customizer.UniqueName);
_customizers.Add(customizer);
}
finally
{
_rwlock.ExitWriteLock();
}
}
/// <summary>
/// Deregistered the runtime pipeline customizer
/// </summary>
/// <param name="customizer"></param>
public void Deregister(IRuntimePipelineCustomizer customizer)
{
Deregister(customizer.UniqueName);
}
/// <summary>
/// Deregistered the runtime pipeline customizer
/// </summary>
/// <param name="uniqueName"></param>
public void Deregister(string uniqueName)
{
_rwlock.EnterWriteLock();
try
{
int pos = -1;
for(int i = 0; i < _customizers.Count; i++)
{
if(string.Equals(uniqueName, _customizers[i].UniqueName, StringComparison.Ordinal))
{
pos = i;
break;
}
}
if(pos != -1)
{
_logger.InfoFormat("Deregistering runtime pipeline customizer {0}", uniqueName);
_customizers.RemoveAt(pos);
}
else
{
_logger.InfoFormat("Runtime pipeline customizer {0} not found to deregister", uniqueName);
}
}
finally
{
_rwlock.ExitWriteLock();
}
}
/// <summary>
/// Applies all of the registered customizers on the runtime pipeline
/// </summary>
/// <param name="pipeline">The service clients runtime pipeline.</param>
/// <param name="type">Type object for the service client being created</param>
internal void ApplyCustomizations(Type type, RuntimePipeline pipeline)
{
_rwlock.EnterReadLock();
try
{
foreach (var customizer in _customizers)
{
_logger.InfoFormat("Applying runtime pipeline customization {0}", customizer.UniqueName);
customizer.Customize(type, pipeline);
}
}
finally
{
_rwlock.ExitReadLock();
}
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_rwlock != null)
{
_rwlock.Dispose();
_rwlock = null;
}
}
}
#endregion
}
/// <summary>
/// Interface for objects that will customize the runtime pipleine for newly created service clients.
/// </summary>
public interface IRuntimePipelineCustomizer
{
/// <summary>
/// The unique name for the customizer that identifies the customizer in the registry. The name is also used to identify the customizer on the SDK logs.
/// </summary>
string UniqueName { get; }
/// <summary>
/// Called on service clients as they are being constructed to customize their runtime pipeline.
/// </summary>
/// <param name="pipeline"></param>
/// <param name="type">Type object for the service client being created</param>
void Customize(Type type, RuntimePipeline pipeline);
}
}
| 162 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.CompilerServices;
using Amazon.Util.Internal;
namespace Amazon.Runtime.Internal
{
public static class ServiceClientHelpers
{
public const string S3_ASSEMBLY_NAME = "AWSSDK.S3";
public const string S3_SERVICE_CLASS_NAME = "Amazon.S3.AmazonS3Client";
public const string SSO_ASSEMBLY_NAME = "AWSSDK.SSO";
public const string SSO_SERVICE_CLASS_NAME = "Amazon.SSO.AmazonSSOClient";
public const string SSO_SERVICE_CONFIG_NAME = "Amazon.SSO.AmazonSSOConfig";
public const string SSO_OIDC_ASSEMBLY_NAME = "AWSSDK.SSOOIDC";
public const string SSO_OIDC_SERVICE_CLASS_NAME = "Amazon.SSOOIDC.AmazonSSOOIDCClient";
public const string SSO_OIDC_SERVICE_CONFIG_NAME = "Amazon.SSOOIDC.AmazonSSOOIDCConfig";
public const string STS_ASSEMBLY_NAME = "AWSSDK.SecurityToken";
public const string STS_SERVICE_CLASS_NAME = "Amazon.SecurityToken.AmazonSecurityTokenServiceClient";
public const string STS_SERVICE_CONFIG_NAME = "Amazon.SecurityToken.AmazonSecurityTokenServiceConfig";
public const string KMS_ASSEMBLY_NAME = "AWSSDK.KeyManagementService";
public const string KMS_SERVICE_CLASS_NAME = "Amazon.KeyManagementService.AmazonKeyManagementServiceClient";
public static TClient CreateServiceFromAnother<TClient, TConfig>(AmazonServiceClient originalServiceClient)
where TConfig : ClientConfig, new ()
where TClient : AmazonServiceClient
{
var credentials = originalServiceClient.Credentials;
var newConfig = originalServiceClient.CloneConfig<TConfig>();
var newServiceClientTypeInfo = TypeFactory.GetTypeInfo(typeof(TClient));
var constructor = newServiceClientTypeInfo.GetConstructor(new ITypeInfo[]
{
TypeFactory.GetTypeInfo(typeof(AWSCredentials)),
TypeFactory.GetTypeInfo(newConfig.GetType())
});
var newServiceClient = constructor.Invoke(new object[] { credentials, newConfig }) as TClient;
return newServiceClient;
}
public static TClient CreateServiceFromAssembly<TClient>(string assemblyName, string serviceClientClassName,
RegionEndpoint region)
where TClient : class
{
var serviceClientTypeInfo = LoadServiceClientType(assemblyName, serviceClientClassName);
var constructor = serviceClientTypeInfo.GetConstructor(new ITypeInfo[]
{
TypeFactory.GetTypeInfo(typeof(RegionEndpoint))
});
var newServiceClient = constructor.Invoke(new object[] { region }) as TClient;
return newServiceClient;
}
public static TClient CreateServiceFromAssembly<TClient>(string assemblyName, string serviceClientClassName,
AWSCredentials credentials, RegionEndpoint region)
where TClient : class
{
var serviceClientTypeInfo = LoadServiceClientType(assemblyName, serviceClientClassName);
var constructor = serviceClientTypeInfo.GetConstructor(new ITypeInfo[]
{
TypeFactory.GetTypeInfo(typeof(AWSCredentials)),
TypeFactory.GetTypeInfo(typeof(RegionEndpoint))
});
var newServiceClient = constructor.Invoke(new object[] { credentials, region }) as TClient;
return newServiceClient;
}
public static TClient CreateServiceFromAssembly<TClient>(string assemblyName, string serviceClientClassName,
AWSCredentials credentials, ClientConfig config)
where TClient : class
{
var serviceClientTypeInfo = LoadServiceClientType(assemblyName, serviceClientClassName);
var constructor = serviceClientTypeInfo.GetConstructor(new ITypeInfo[]
{
TypeFactory.GetTypeInfo(typeof(AWSCredentials)),
TypeFactory.GetTypeInfo(config.GetType())
});
var newServiceClient = constructor.Invoke(new object[] { credentials, config }) as TClient;
return newServiceClient;
}
public static TClient CreateServiceFromAssembly<TClient>(string assemblyName, string serviceClientClassName, AmazonServiceClient originalServiceClient)
where TClient : class
{
var serviceClientTypeInfo = LoadServiceClientType(assemblyName, serviceClientClassName);
var config = CreateServiceConfig(assemblyName, serviceClientClassName.Replace("Client", "Config"));
originalServiceClient.CloneConfig(config);
var constructor = serviceClientTypeInfo.GetConstructor(new ITypeInfo[]
{
TypeFactory.GetTypeInfo(typeof(AWSCredentials)),
TypeFactory.GetTypeInfo(config.GetType())
});
var newServiceClient = constructor.Invoke(new object[] { originalServiceClient.Credentials, config }) as TClient;
return newServiceClient;
}
public static ClientConfig CreateServiceConfig(string assemblyName, string serviceConfigClassName)
{
var typeInfo = LoadServiceConfigType(assemblyName, serviceConfigClassName);
var ci = typeInfo.GetConstructor(new ITypeInfo[0]);
var config = ci.Invoke(new object[0]);
return config as ClientConfig;
}
private static ITypeInfo LoadServiceClientType(string assemblyName, string serviceClientClassName)
{
return LoadTypeFromAssembly(assemblyName, serviceClientClassName);
}
private static ITypeInfo LoadServiceConfigType(string assemblyName, string serviceConfigClassName)
{
return LoadTypeFromAssembly(assemblyName, serviceConfigClassName);
}
internal static ITypeInfo LoadTypeFromAssembly(string assemblyName, string className)
{
var assembly = GetSDKAssembly(assemblyName);
var type = assembly.GetType(className);
return TypeFactory.GetTypeInfo(type);
}
private static Assembly GetSDKAssembly(string assemblyName)
{
return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => string.Equals(x.GetName().Name, assemblyName, StringComparison.Ordinal))
?? Assembly.Load(new AssemblyName(assemblyName))
?? throw new AmazonClientException($"Failed to load assembly. Be sure to include a reference to {assemblyName}.");
}
}
}
| 156 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using Amazon.Runtime.Internal;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Default ServiceMetadata implementation.
/// This implementation will be used if the service doesn't have a
/// IServiceMetadata implementation.
/// </summary>
internal class ServiceMetadata : IServiceMetadata
{
/// <summary>
/// Gets the value of the Service Id.
/// </summary>
public string ServiceId { get; }
/// <summary>
/// Gets the dictionary that gives mapping of renamed operations
/// </summary>
public IDictionary<string, string> OperationNameMapping { get; } = new Dictionary<string, string>();
}
} | 38 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon.Util;
namespace Amazon.Runtime.Internal
{
internal class StreamReadTracker
{
object sender;
EventHandler<StreamTransferProgressArgs> callback;
long contentLength;
long totalBytesRead;
long totalIncrementTransferred;
long progressUpdateInterval;
internal StreamReadTracker(object sender, EventHandler<StreamTransferProgressArgs> callback, long contentLength, long progressUpdateInterval)
{
this.sender = sender;
this.callback = callback;
this.contentLength = contentLength;
this.progressUpdateInterval = progressUpdateInterval;
}
public void ReadProgress(int bytesRead)
{
if (callback == null)
return;
// Invoke the progress callback only if bytes read > 0
if (bytesRead > 0)
{
totalBytesRead += bytesRead;
totalIncrementTransferred += bytesRead;
if (totalIncrementTransferred >= this.progressUpdateInterval ||
totalBytesRead == contentLength)
{
AWSSDKUtils.InvokeInBackground(
callback,
new StreamTransferProgressArgs(totalIncrementTransferred, totalBytesRead, contentLength),
sender);
totalIncrementTransferred = 0;
}
}
}
public void UpdateProgress(float progress)
{
int bytesRead = (int)((long)(progress * contentLength) - totalBytesRead);
ReadProgress(bytesRead);
}
}
}
| 72 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
using System.Net;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
using Amazon.Internal;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal.Auth
{
public enum ClientProtocol { QueryStringProtocol, RestProtocol, Unknown }
public abstract class AbstractAWSSigner
{
private AWS4Signer _aws4Signer;
private AWS4Signer AWS4SignerInstance
{
get
{
if (_aws4Signer == null)
{
lock (this)
{
if (_aws4Signer == null)
_aws4Signer = new AWS4Signer();
}
}
return _aws4Signer;
}
}
private AWS4aSignerCRTWrapper _aws4aSignerCRTWrapper;
private AWS4aSignerCRTWrapper AWS4aSignerCRTWrapperInstance
{
get
{
if (_aws4aSignerCRTWrapper == null)
{
lock (this)
{
if (_aws4aSignerCRTWrapper == null)
_aws4aSignerCRTWrapper = new AWS4aSignerCRTWrapper();
}
}
return _aws4aSignerCRTWrapper;
}
}
/// <summary>
/// Signals to the <see cref="Signer"/> Pipeline Handler
/// if a Signer requires valid <see cref="ImmutableCredentials"/> in order
/// to correctly <see cref="Sign(IRequest,IClientConfig,RequestMetrics,ImmutableCredentials)"/>.
/// </summary>
public virtual bool RequiresCredentials { get; } = true;
/// <summary>
/// Computes RFC 2104-compliant HMAC signature.
/// </summary>
protected static string ComputeHash(string data, string secretkey, SigningAlgorithm algorithm)
{
try
{
string signature = CryptoUtilFactory.CryptoInstance.HMACSign(data, secretkey, algorithm);
return signature;
}
catch (Exception e)
{
throw new Amazon.Runtime.SignatureException("Failed to generate signature: " + e.Message, e);
}
}
/// <summary>
/// Computes RFC 2104-compliant HMAC signature.
/// </summary>
protected static string ComputeHash(byte[] data, string secretkey, SigningAlgorithm algorithm)
{
try
{
string signature = CryptoUtilFactory.CryptoInstance.HMACSign(data, secretkey, algorithm);
return signature;
}
catch (Exception e)
{
throw new Amazon.Runtime.SignatureException("Failed to generate signature: " + e.Message, e);
}
}
public abstract void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey);
public virtual void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
{
Sign(request, clientConfig, metrics, credentials?.AccessKey, credentials?.SecretKey);
}
#if AWS_ASYNC_API
public virtual System.Threading.Tasks.Task SignAsync(
IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
ImmutableCredentials credentials,
CancellationToken token = default)
{
Sign(request, clientConfig, metrics, credentials);
#if NETSTANDARD
return Task.CompletedTask;
#else
return Task.FromResult(0);
#endif
}
#endif
public abstract ClientProtocol Protocol { get; }
/// <summary>
/// Inspects the supplied evidence to determine if sigv4 or sigv2 signing should be used
/// </summary>
/// <param name="useSigV4Setting">Global setting for the service</param>
/// <param name="request">The request.</param>
/// <param name="config">Configuration for the client</param>
/// <returns>True if signature v4 request signing should be used, false if v2 signing should be used</returns>
protected static bool UseV4Signing(bool useSigV4Setting, IRequest request, IClientConfig config)
{
if (request.SignatureVersion == SignatureVersion.SigV4 ||
config.SignatureVersion == "4" ||
(useSigV4Setting && config.SignatureVersion != "2"))
{
return true;
}
else
{
// do a cascading series of checks to try and arrive at whether we have
// a recognisable region; this is required to use the AWS4 signer
RegionEndpoint r = null;
if (!string.IsNullOrEmpty(request.AuthenticationRegion))
r = RegionEndpoint.GetBySystemName(request.AuthenticationRegion);
if (r == null && !string.IsNullOrEmpty(config.ServiceURL))
{
var parsedRegion = AWSSDKUtils.DetermineRegion(config.ServiceURL);
if (!string.IsNullOrEmpty(parsedRegion))
r = RegionEndpoint.GetBySystemName(parsedRegion);
}
if (r == null && config.RegionEndpoint != null)
r = config.RegionEndpoint;
if (r != null)
{
var endpoint = r.GetEndpointForService(config.RegionEndpointServiceName, config.ToGetEndpointForServiceOptions());
if (endpoint != null && (endpoint.SignatureVersionOverride == "4" || string.IsNullOrEmpty(endpoint.SignatureVersionOverride)))
return true;
}
return false;
}
}
protected AbstractAWSSigner SelectSigner(IRequest request, IClientConfig config)
{
return SelectSigner(this, useSigV4Setting: false, request: request, config: config);
}
protected AbstractAWSSigner SelectSigner(AbstractAWSSigner defaultSigner,bool useSigV4Setting,
IRequest request, IClientConfig config)
{
if (request.SignatureVersion == SignatureVersion.SigV4a)
return AWS4aSignerCRTWrapperInstance;
else if (UseV4Signing(useSigV4Setting, request, config))
return AWS4SignerInstance;
else
return defaultSigner;
}
}
}
| 197 |
aws-sdk-net | aws | C# | /*
* 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 Amazon.Runtime.SharedInterfaces;
using Amazon.Util.Internal;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// Asymmetric SigV4 signer using a the AWS Common Runtime implementation of SigV4a via AWSSDK.Extensions.CrtIntegration
/// </summary>
public class AWS4aSignerCRTWrapper : AbstractAWSSigner
{
private const string CRT_WRAPPER_ASSEMBLY_NAME = "AWSSDK.Extensions.CrtIntegration";
private const string CRT_WRAPPER_NUGET_PACKGE_NAME = "AWSSDK.Extensions.CrtIntegration";
private const string CRT_WRAPPER_CLASS_NAME = "Amazon.Extensions.CrtIntegration.CrtAWS4aSigner";
private static IAWSSigV4aProvider _awsSigV4AProvider;
private static object _lock = new object();
/// <summary>
/// Instantiates an SigV4a signer using CRT's SigV4a implementation
/// </summary>
public AWS4aSignerCRTWrapper() : this(true)
{
}
/// <summary>
/// Instantiates an SigV4a signer using CRT's SigV4a implementation
/// </summary>
/// <param name="signPayload">Whether to sign the request's payload</param>
public AWS4aSignerCRTWrapper(bool signPayload)
{
if (_awsSigV4AProvider == null)
{
lock(_lock)
{
if (_awsSigV4AProvider == null)
{
try
{
var crtWrapperTypeInfo = ServiceClientHelpers.LoadTypeFromAssembly(CRT_WRAPPER_ASSEMBLY_NAME, CRT_WRAPPER_CLASS_NAME);
var constructor = crtWrapperTypeInfo.GetConstructor(new ITypeInfo[]
{
TypeFactory.GetTypeInfo(typeof(bool))
});
_awsSigV4AProvider = constructor.Invoke(new object[] { signPayload }) as IAWSSigV4aProvider;
}
catch (FileNotFoundException)
{
throw new AWSCommonRuntimeException
(
string.Format(CultureInfo.InvariantCulture, "Attempting to make a request that requires an implementation of AWS Signature V4a. " +
$"Add a reference to the {CRT_WRAPPER_NUGET_PACKGE_NAME} NuGet package to your project to include the AWS Signature V4a signer.")
);
}
}
}
}
}
/// <summary>
/// Protocol for the requests being signed
/// </summary>
public override ClientProtocol Protocol
{
get { return _awsSigV4AProvider.Protocol; }
}
/// <summary>
/// Calculates and signs the specified request using the asymmetric Sigv4 (Sigv4a) signing protocol.
/// The resulting signature is added to the request headers as 'Authorization'. Parameters supplied in the request, either in
/// the resource path as a query string or in the Parameters collection must not have been
/// uri encoded. If they have, use the SignRequest method to obtain a signature.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4a protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Client configuration data encompassing the service call (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
{
_awsSigV4AProvider.Sign(request, clientConfig, metrics, credentials);
}
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
{
throw new AWSCommonRuntimeException("SigV4a signing with only an access key and secret is not supported. Call the Sign override with ImmutableCredentials instead.");
}
/// <summary>
/// Calculates and signs the specified request using the asymmetric Sigv4 (Sigv4a) signing protocol.
/// The resulting signature is added to the request headers as 'Authorization'. Parameters supplied in the request, either in
/// the resource path as a query string or in the Parameters collection must not have been
/// uri encoded. If they have, use the SignRequest method to obtain a signature.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4a protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Client configuration data encompassing the service call (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
/// <returns>AWS4a Signing Result</returns>
public AWS4aSigningResult SignRequest(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
ImmutableCredentials credentials)
{
return _awsSigV4AProvider.SignRequest(request, clientConfig, metrics, credentials);
}
/// <summary>
/// Calculates the asymmetric Sigv4 (Sigv4a) signature for a presigned url.
/// </summary>
/// <param name="request">
/// The request to compute the signature for.
/// </param>
/// <param name="clientConfig">
/// Adding supporting data for the service call required by the signer (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
/// <param name="service">
/// The service to sign for
/// </param>
/// <param name="overrideSigningRegion">
/// The region to sign to, if null then the region the client is configured for will be used.
/// </param>
/// <returns>AWS4a Signing Result</returns>
public AWS4aSigningResult Presign4a(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
ImmutableCredentials credentials,
string service,
string overrideSigningRegion)
{
return _awsSigV4AProvider.Presign4a(request, clientConfig, metrics, credentials, service, overrideSigningRegion);
}
/// <summary>
/// Calculates the signature for a single chunk of a chunked SigV4a request
/// </summary>
/// <param name="chunkBody">Content of the current chunk</param>
/// <param name="previousSignature">Signature of the previous chunk</param>
/// <param name="headerSigningResult">Signing result of the request's header</param>
/// <returns>Unpadded SigV4a signature of the given chunk</returns>
public string SignChunk(Stream chunkBody, string previousSignature, AWS4aSigningResult headerSigningResult)
{
return _awsSigV4AProvider.SignChunk(chunkBody, previousSignature, headerSigningResult);
}
/// <summary>
/// Signs the final chunk containing trailing headers
/// </summary>
/// <param name="trailingHeaders">Trailing header keys and values</param>
/// <param name="previousSignature">Signature of the previously signed chunk</param>
/// <param name="headerSigningResult">Signing result for the "seed" signature consisting of headers</param>
/// <returns>Signature of the trailing header chunk</returns>
public string SignTrailingHeaderChunk(IDictionary<string, string> trailingHeaders, string previousSignature, AWS4aSigningResult headerSigningResult)
{
return _awsSigV4AProvider.SignTrailingHeaderChunk(trailingHeaders, previousSignature, headerSigningResult);
}
}
}
| 203 |
aws-sdk-net | aws | C# | /*
* 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.Text;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// Encapsulates the various fields and eventual signing value that makes up
/// an AWS4a signature. This can be used to retrieve the required authorization string
/// or authorization query parameters for the final request as well as hold ongoing
/// signature computations for subsequent calls related to the initial signing.
/// </summary>
public class AWS4aSigningResult : AWSSigningResultBase
{
private readonly string _regionSet;
private readonly string _signature;
private readonly string _service;
private readonly string _presignedUri;
private readonly ImmutableCredentials _credentials;
/// <summary>
/// Constructs a new signing result instance for a computed signature
/// </summary>
/// <param name="awsAccessKeyId">The access key that was included in the signature</param>
/// <param name="signedAt">Date/time (UTC) that the signature was computed</param>
/// <param name="signedHeaders">The collection of headers names that were included in the signature</param>
/// <param name="scope">Formatted 'scope' value for signing (YYYYMMDD/region/service/aws4_request)</param>
/// <param name="regionSet">The set of AWS regions this signature is valid for</param>
/// <param name="signature">Computed signature</param>
/// <param name="service">Service the request was signed for</param>
/// <param name="presignedUri">Presigned Uri</param>
/// <param name="credentials">Credentials of the AWS account making the signed request</param>
public AWS4aSigningResult(string awsAccessKeyId,
DateTime signedAt,
string signedHeaders,
string scope,
string regionSet,
string signature,
string service,
string presignedUri,
ImmutableCredentials credentials) :
base(awsAccessKeyId, signedAt, signedHeaders, scope)
{
_regionSet = regionSet;
_signature = signature;
_service = service;
_presignedUri = presignedUri;
_credentials = credentials;
}
/// <summary>
/// Returns the hex string representing the signature
/// </summary>
public override string Signature
{
get { return _signature; }
}
/// <summary>
/// Returns the signature in a form usable as an 'Authorization' header value.
/// </summary>
public override string ForAuthorizationHeader
{
get
{
var authorizationHeader = new StringBuilder()
.Append(AWS4Signer.AWS4aAlgorithmTag)
.AppendFormat(" {0}={1}/{2},", AWS4Signer.Credential, AccessKeyId, Scope)
.AppendFormat(" {0}={1},", AWS4Signer.SignedHeaders, SignedHeaders)
.AppendFormat(" {0}={1}", AWS4Signer.Signature, Signature);
return authorizationHeader.ToString();
}
}
/// <summary>
/// Returns the set of regions this signature is valid for
/// </summary>
public string RegionSet
{
get { return _regionSet; }
}
/// <summary>
/// Returns the full presigned Uri
/// </summary>
public string PresignedUri
{
get { return _presignedUri; }
}
/// <summary>
/// Returns the service the request was signed for
/// </summary>
public string Service
{
get { return _service; }
}
/// <summary>
/// Returns the credentials of the AWS account making the signed request
/// </summary>
public ImmutableCredentials Credentials
{
get { return _credentials; }
}
}
}
| 124 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Amazon.Internal;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// AWS4 protocol signer for service calls that transmit authorization in the header field "Authorization".
/// </summary>
public class AWS4Signer : AbstractAWSSigner
{
public const string Scheme = "AWS4";
public const string Algorithm = "HMAC-SHA256";
public const string Sigv4aAlgorithm = "ECDSA-P256-SHA256";
public const string AWS4AlgorithmTag = Scheme + "-" + Algorithm;
public const string AWS4aAlgorithmTag = Scheme + "-" + Sigv4aAlgorithm;
public const string Terminator = "aws4_request";
public static readonly byte[] TerminatorBytes = Encoding.UTF8.GetBytes(Terminator);
public const string Credential = "Credential";
public const string SignedHeaders = "SignedHeaders";
public const string Signature = "Signature";
public const string EmptyBodySha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
public const string StreamingBodySha256 = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
public const string StreamingBodySha256WithTrailer = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER";
public const string V4aStreamingBodySha256 = "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD";
public const string V4aStreamingBodySha256WithTrailer = "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER";
public const string AWSChunkedEncoding = "aws-chunked";
public const string UnsignedPayload = "UNSIGNED-PAYLOAD";
public const string UnsignedPayloadWithTrailer = "STREAMING-UNSIGNED-PAYLOAD-TRAILER";
const SigningAlgorithm SignerAlgorithm = SigningAlgorithm.HmacSHA256;
private static IEnumerable<string> _headersToIgnoreWhenSigning = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
HeaderKeys.XAmznTraceIdHeader,
HeaderKeys.TransferEncodingHeader,
HeaderKeys.AmzSdkInvocationId,
HeaderKeys.AmzSdkRequest
};
public AWS4Signer()
: this(true)
{
}
public AWS4Signer(bool signPayload)
{
SignPayload = signPayload;
}
public bool SignPayload
{
get;
private set;
}
public override ClientProtocol Protocol
{
get { return ClientProtocol.RestProtocol; }
}
/// <summary>
/// Calculates and signs the specified request using the AWS4 signing protocol by using the
/// AWS account credentials given in the method parameters. The resulting signature is added
/// to the request headers as 'Authorization'. Parameters supplied in the request, either in
/// the resource path as a query string or in the Parameters collection must not have been
/// uri encoded. If they have, use the SignRequest method to obtain a signature.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Client configuration data encompassing the service call (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="awsAccessKeyId">
/// The AWS public key for the account making the service call.
/// </param>
/// <param name="awsSecretAccessKey">
/// The AWS secret key for the account making the call, in clear text.
/// </param>
/// <exception cref="Amazon.Runtime.SignatureException">
/// If any problems are encountered while signing the request.
/// </exception>
public override void Sign(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
string awsAccessKeyId,
string awsSecretAccessKey)
{
var signingResult = SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
}
/// <summary>
/// Calculates and signs the specified request using the AWS4 signing protocol by using the
/// AWS account credentials given in the method parameters. The resulting signature is added
/// to the request headers as 'Authorization'. Parameters supplied in the request, either in
/// the resource path as a query string or in the Parameters collection must not have been
/// uri encoded. If they have, use the SignRequest method to obtain a signature.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Client configuration data encompassing the service call (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
/// <exception cref="Amazon.Runtime.SignatureException">
/// If any problems are encountered while signing the request.
/// </exception>
public override void Sign(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
ImmutableCredentials credentials)
{
Sign(request, clientConfig, metrics, credentials.AccessKey, credentials.SecretKey);
}
/// <summary>
/// Calculates and signs the specified request using the AWS4 signing protocol by using the
/// AWS account credentials given in the method parameters.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Client configuration data encompassing the service call (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request.
/// </param>
/// <param name="awsAccessKeyId">
/// The AWS public key for the account making the service call.
/// </param>
/// <param name="awsSecretAccessKey">
/// The AWS secret key for the account making the call, in clear text.
/// </param>
/// <exception cref="Amazon.Runtime.SignatureException">
/// If any problems are encountered while signing the request.
/// </exception>
/// <remarks>
/// Parameters passed as part of the resource path should be uri-encoded prior to
/// entry to the signer. Parameters passed in the request.Parameters collection should
/// be not be encoded; encoding will be done for these parameters as part of the
/// construction of the canonical request.
/// </remarks>
public AWS4SigningResult SignRequest(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
string awsAccessKeyId,
string awsSecretAccessKey)
{
ValidateRequest(request);
var signedAt = InitializeHeaders(request.Headers, request.Endpoint);
var serviceSigningName = !string.IsNullOrEmpty(request.OverrideSigningServiceName) ? request.OverrideSigningServiceName : DetermineService(clientConfig);
if (serviceSigningName == "s3")
{
// Older versions of the S3 package can be used with newer versions of Core, this guarantees no double encoding will be used.
// The new behavior uses endpoint resolution rules, which are not present prior to 3.7.100
request.UseDoubleEncoding = false;
}
request.DeterminedSigningRegion = DetermineSigningRegion(clientConfig, clientConfig.RegionEndpointServiceName, request.AlternateEndpoint, request);
SetXAmzTrailerHeader(request.Headers, request.TrailingHeaders);
var parametersToCanonicalize = GetParametersToCanonicalize(request);
var canonicalParameters = CanonicalizeQueryParameters(parametersToCanonicalize);
// If the request should use a fixed x-amz-content-sha256 header value, determine the appropriate one
var bodySha = request.TrailingHeaders?.Count > 0
? StreamingBodySha256WithTrailer
: StreamingBodySha256;
var bodyHash = SetRequestBodyHash(request, SignPayload, bodySha, ChunkedUploadWrapperStream.V4_SIGNATURE_LENGTH);
var sortedHeaders = SortAndPruneHeaders(request.Headers);
var canonicalRequest = CanonicalizeRequest(request.Endpoint,
request.ResourcePath,
request.HttpMethod,
sortedHeaders,
canonicalParameters,
bodyHash,
request.PathResources,
request.UseDoubleEncoding);
if (metrics != null)
metrics.AddProperty(Metric.CanonicalRequest, canonicalRequest);
return ComputeSignature(awsAccessKeyId,
awsSecretAccessKey,
request.DeterminedSigningRegion,
signedAt,
serviceSigningName,
CanonicalizeHeaderNames(sortedHeaders),
canonicalRequest,
metrics);
}
#region Public Signing Helpers
/// <summary>
/// Sets the AWS4 mandated 'host' and 'x-amz-date' headers, returning the date/time that will
/// be used throughout the signing process in various elements and formats.
/// </summary>
/// <param name="headers">The current set of headers</param>
/// <param name="requestEndpoint"></param>
/// <returns>Date and time used for x-amz-date, in UTC</returns>
public static DateTime InitializeHeaders(IDictionary<string, string> headers, Uri requestEndpoint)
{
return InitializeHeaders(headers, requestEndpoint, CorrectClockSkew.GetCorrectedUtcNowForEndpoint(requestEndpoint.ToString()));
}
/// <summary>
/// Sets the AWS4 mandated 'host' and 'x-amz-date' headers, accepting and returning the date/time that will
/// be used throughout the signing process in various elements and formats.
/// </summary>
/// <param name="headers">The current set of headers</param>
/// <param name="requestEndpoint"></param>
/// <param name="requestDateTime"></param>
/// <returns>Date and time used for x-amz-date, in UTC</returns>
public static DateTime InitializeHeaders(IDictionary<string, string> headers, Uri requestEndpoint, DateTime requestDateTime)
{
// clean up any prior signature in the headers if resigning
CleanHeaders(headers);
if (!headers.ContainsKey(HeaderKeys.HostHeader))
{
var hostHeader = requestEndpoint.Host;
if (!requestEndpoint.IsDefaultPort)
hostHeader += ":" + requestEndpoint.Port;
headers.Add(HeaderKeys.HostHeader, hostHeader);
}
var dt = requestDateTime;
headers[HeaderKeys.XAmzDateHeader] = dt.ToUniversalTime().ToString(AWSSDKUtils.ISO8601BasicDateTimeFormat, CultureInfo.InvariantCulture);
return dt;
}
/// <summary>
/// Sets the x-amz-trailer header for the given set of trailing headers
/// </summary>
/// <param name="headers">request's headers</param>
/// <param name="trailingHeaders">request's trailing headers</param>
public static void SetXAmzTrailerHeader(IDictionary<string, string> headers, IDictionary<string, string> trailingHeaders)
{
if (trailingHeaders == null || trailingHeaders.Count == 0)
{
return;
}
// The x-amz-trailer HTTP header MUST be set with the value as comma-separated
// string consisting of trailing header names in the order they are written on the HTTP request.
headers[HeaderKeys.XAmzTrailerHeader] = string.Join(",", trailingHeaders.Keys.OrderBy(key => key).ToArray());
}
private static void CleanHeaders(IDictionary<string, string> headers)
{
headers.Remove(HeaderKeys.AuthorizationHeader);
headers.Remove(HeaderKeys.XAmzContentSha256Header);
if (headers.ContainsKey(HeaderKeys.XAmzDecodedContentLengthHeader))
{
headers[HeaderKeys.ContentLengthHeader] =
headers[HeaderKeys.XAmzDecodedContentLengthHeader];
headers.Remove(HeaderKeys.XAmzDecodedContentLengthHeader);
}
}
private static void ValidateRequest(IRequest request)
{
Uri url = request.Endpoint;
// Before we sign the request, we need to validate if the request is being
// sent over https when DisablePayloadSigning is true.
if((request.DisablePayloadSigning ?? false) && url.Scheme != "https")
{
throw new AmazonClientException("When DisablePayloadSigning is true, the request must be sent over HTTPS.");
}
}
/// <summary>
/// Computes and returns an AWS4 signature for the specified canonicalized request
/// </summary>
/// <param name="credentials"></param>
/// <param name="region"></param>
/// <param name="signedAt"></param>
/// <param name="service"></param>
/// <param name="signedHeaders"></param>
/// <param name="canonicalRequest"></param>
/// <returns></returns>
public static AWS4SigningResult ComputeSignature(ImmutableCredentials credentials,
string region,
DateTime signedAt,
string service,
string signedHeaders,
string canonicalRequest)
{
return ComputeSignature(credentials.AccessKey,
credentials.SecretKey,
region,
signedAt,
service,
signedHeaders,
canonicalRequest);
}
/// <summary>
/// Computes and returns an AWS4 signature for the specified canonicalized request
/// </summary>
/// <param name="awsAccessKey"></param>
/// <param name="awsSecretAccessKey"></param>
/// <param name="region"></param>
/// <param name="signedAt"></param>
/// <param name="service"></param>
/// <param name="signedHeaders"></param>
/// <param name="canonicalRequest"></param>
/// <returns></returns>
public static AWS4SigningResult ComputeSignature(string awsAccessKey,
string awsSecretAccessKey,
string region,
DateTime signedAt,
string service,
string signedHeaders,
string canonicalRequest)
{
return ComputeSignature(awsAccessKey, awsSecretAccessKey, region, signedAt, service, signedHeaders, canonicalRequest, null);
}
/// <summary>
/// Computes and returns an AWS4 signature for the specified canonicalized request
/// </summary>
/// <param name="awsAccessKey"></param>
/// <param name="awsSecretAccessKey"></param>
/// <param name="region"></param>
/// <param name="signedAt"></param>
/// <param name="service"></param>
/// <param name="signedHeaders"></param>
/// <param name="canonicalRequest"></param>
/// <param name="metrics"></param>
/// <returns></returns>
public static AWS4SigningResult ComputeSignature(string awsAccessKey,
string awsSecretAccessKey,
string region,
DateTime signedAt,
string service,
string signedHeaders,
string canonicalRequest,
RequestMetrics metrics)
{
var dateStamp = FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat);
var scope = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}", dateStamp, region, service, Terminator);
var stringToSignBuilder = new StringBuilder();
stringToSignBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}-{1}\n{2}\n{3}\n",
Scheme,
Algorithm,
FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateTimeFormat),
scope);
var canonicalRequestHashBytes = ComputeHash(canonicalRequest);
stringToSignBuilder.Append(AWSSDKUtils.ToHex(canonicalRequestHashBytes, true));
if (metrics != null)
metrics.AddProperty(Metric.StringToSign, stringToSignBuilder);
var key = ComposeSigningKey(awsSecretAccessKey,
region,
dateStamp,
service);
var stringToSign = stringToSignBuilder.ToString();
var signature = ComputeKeyedHash(SignerAlgorithm, key, stringToSign);
return new AWS4SigningResult(awsAccessKey, signedAt, signedHeaders, scope, key, signature);
}
/// <summary>
/// Formats the supplied date and time for use in AWS4 signing, where various formats are used.
/// </summary>
/// <param name="dt"></param>
/// <param name="formatString">The required format</param>
/// <returns>The UTC date/time in the requested format</returns>
public static string FormatDateTime(DateTime dt, string formatString)
{
return dt.ToUniversalTime().ToString(formatString, CultureInfo.InvariantCulture);
}
/// <summary>
/// Compute and return the multi-stage signing key for the request.
/// </summary>
/// <param name="awsSecretAccessKey">The clear-text AWS secret key, if not held in secureKey</param>
/// <param name="region">The region in which the service request will be processed</param>
/// <param name="date">Date of the request, in yyyyMMdd format</param>
/// <param name="service">The name of the service being called by the request</param>
/// <returns>Computed signing key</returns>
public static byte[] ComposeSigningKey(string awsSecretAccessKey, string region, string date, string service)
{
char[] ksecret = null;
try
{
ksecret = (Scheme + awsSecretAccessKey).ToCharArray();
var hashDate = ComputeKeyedHash(SignerAlgorithm, Encoding.UTF8.GetBytes(ksecret), Encoding.UTF8.GetBytes(date));
var hashRegion = ComputeKeyedHash(SignerAlgorithm, hashDate, Encoding.UTF8.GetBytes(region));
var hashService = ComputeKeyedHash(SignerAlgorithm, hashRegion, Encoding.UTF8.GetBytes(service));
return ComputeKeyedHash(SignerAlgorithm, hashService, TerminatorBytes);
}
finally
{
// clean up all secrets, regardless of how initially seeded (for simplicity)
if (ksecret != null)
Array.Clear(ksecret, 0, ksecret.Length);
}
}
/// <summary>
/// If the caller has already set the x-amz-content-sha256 header with a pre-computed
/// content hash, or it is present as ContentStreamHash on the request instance, return
/// the value to be used in request canonicalization.
/// If not set as a header or in the request, attempt to compute a hash based on
/// inspection of the style of the request content.
/// </summary>
/// <param name="request">Request to sign</param>
/// <param name="chunkedBodyHash">The fixed value to set for the x-amz-content-sha256 header for chunked requests</param>
/// <param name="signatureLength">Length of the signature for each chunk in a chuncked request, in bytes</param>
/// <returns>
/// The computed hash, whether already set in headers or computed here. Null
/// if we were not able to compute a hash.
/// </returns>
public static string SetRequestBodyHash(IRequest request, string chunkedBodyHash, int signatureLength)
{
return SetRequestBodyHash(request, true, chunkedBodyHash, signatureLength);
}
/// <summary>
/// If signPayload is false set the x-amz-content-sha256 header to
/// the UNSIGNED-PAYLOAD magic string and return it.
/// Otherwise, if the caller has already set the x-amz-content-sha256 header with a pre-computed
/// content hash, or it is present as ContentStreamHash on the request instance, return
/// the value to be used in request canonicalization.
/// If not set as a header or in the request, attempt to compute a hash based on
/// inspection of the style of the request content.
/// </summary>
/// <param name="request">Request to sign</param>
/// <param name="signPayload">Whether to sign the payload</param>
/// <param name="chunkedBodyHash">The fixed value to set for the x-amz-content-sha256 header for chunked requests</param>
/// <param name="signatureLength">Length of the signature for each chunk in a chuncked request, in bytes</param>
/// <returns>
/// The computed hash, whether already set in headers or computed here. Null
/// if we were not able to compute a hash.
/// </returns>
public static string SetRequestBodyHash(IRequest request, bool signPayload, string chunkedBodyHash, int signatureLength)
{
// If unsigned payload, set the appropriate magic string in the header and return it
if (request.DisablePayloadSigning != null ? request.DisablePayloadSigning.Value : !signPayload)
{
if (request.TrailingHeaders?.Count > 0)
{
// Set X-Amz-Decoded-Content-Length with the true size of the data
request.Headers[HeaderKeys.XAmzDecodedContentLengthHeader] = request.Headers[HeaderKeys.ContentLengthHeader];
// Substitute the originally declared content length with the inflated length due to trailing headers
var originalContentLength = long.Parse(request.Headers[HeaderKeys.ContentLengthHeader], CultureInfo.InvariantCulture);
request.Headers[HeaderKeys.ContentLengthHeader]
= TrailingHeadersWrapperStream.CalculateLength(request.TrailingHeaders, request.SelectedChecksum, originalContentLength).ToString(CultureInfo.InvariantCulture);
SetContentEncodingHeader(request);
return SetPayloadSignatureHeader(request, UnsignedPayloadWithTrailer);
}
else // request does not have trailing headers (and is still unsigned payload)
{
return SetPayloadSignatureHeader(request, UnsignedPayload);
}
}
// if the body hash has been precomputed and already placed in the header, just extract and return it
string computedContentHash;
var shaHeaderPresent = request.Headers.TryGetValue(HeaderKeys.XAmzContentSha256Header, out computedContentHash);
if (shaHeaderPresent && !request.UseChunkEncoding)
return computedContentHash;
// otherwise continue to calculate the hash and set it in the headers before returning
if (request.UseChunkEncoding)
{
computedContentHash = chunkedBodyHash;
if (request.Headers.ContainsKey(HeaderKeys.ContentLengthHeader))
{
// Set X-Amz-Decoded-Content-Length with the true size of the data
request.Headers[HeaderKeys.XAmzDecodedContentLengthHeader] = request.Headers[HeaderKeys.ContentLengthHeader];
// Substitute the originally declared content length with the inflated length due to chunking metadata and/or trailing headers
var originalContentLength = long.Parse(request.Headers[HeaderKeys.ContentLengthHeader], CultureInfo.InvariantCulture);
request.Headers[HeaderKeys.ContentLengthHeader]
= ChunkedUploadWrapperStream.ComputeChunkedContentLength(originalContentLength, signatureLength, request.TrailingHeaders, request.SelectedChecksum).ToString(CultureInfo.InvariantCulture);
}
SetContentEncodingHeader(request);
}
else
{
if (request.ContentStream != null)
computedContentHash = request.ComputeContentStreamHash();
else
{
byte[] payloadBytes = GetRequestPayloadBytes(request);
byte[] payloadHashBytes = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(payloadBytes);
computedContentHash = AWSSDKUtils.ToHex(payloadHashBytes, true);
}
}
// set the header if needed and return it
return SetPayloadSignatureHeader(request, computedContentHash ?? UnsignedPayload);
}
/// <summary>
/// Appends "aws-chunked" to the Content-Encoding header if it's already set
/// </summary>
/// <param name="request">Request to modify</param>
private static void SetContentEncodingHeader(IRequest request)
{
if (request.Headers.TryGetValue(HeaderKeys.ContentEncodingHeader, out var originalEncoding) &&
!originalEncoding.Contains(AWSChunkedEncoding))
{
request.Headers[HeaderKeys.ContentEncodingHeader] = $"{originalEncoding}, {AWSChunkedEncoding}";
}
}
/// <summary>
/// Returns the HMAC256 for an arbitrary blob using the specified key
/// </summary>
/// <param name="key"></param>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] SignBlob(byte[] key, string data)
{
return SignBlob(key, Encoding.UTF8.GetBytes(data));
}
/// <summary>
/// Returns the HMAC256 for an arbitrary blob using the specified key
/// </summary>
/// <param name="key"></param>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] SignBlob(byte[] key, byte[] data)
{
return CryptoUtilFactory.CryptoInstance.HMACSignBinary(data, key, SignerAlgorithm);
}
/// <summary>
/// Compute and return the hash of a data blob using the specified key
/// </summary>
/// <param name="algorithm">Algorithm to use for hashing</param>
/// <param name="key">Hash key</param>
/// <param name="data">Data blob</param>
/// <returns>Hash of the data</returns>
public static byte[] ComputeKeyedHash(SigningAlgorithm algorithm, byte[] key, string data)
{
return ComputeKeyedHash(algorithm, key, Encoding.UTF8.GetBytes(data));
}
/// <summary>
/// Compute and return the hash of a data blob using the specified key
/// </summary>
/// <param name="algorithm">Algorithm to use for hashing</param>
/// <param name="key">Hash key</param>
/// <param name="data">Data blob</param>
/// <returns>Hash of the data</returns>
public static byte[] ComputeKeyedHash(SigningAlgorithm algorithm, byte[] key, byte[] data)
{
return CryptoUtilFactory.CryptoInstance.HMACSignBinary(data, key, algorithm);
}
/// <summary>
/// Computes the non-keyed hash of the supplied data
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] ComputeHash(string data)
{
return ComputeHash(Encoding.UTF8.GetBytes(data));
}
/// <summary>
/// Computes the non-keyed hash of the supplied data
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] ComputeHash(byte[] data)
{
return CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(data);
}
#endregion
#region Private Signing Helpers
static string SetPayloadSignatureHeader(IRequest request, string payloadHash)
{
if (request.Headers.ContainsKey(HeaderKeys.XAmzContentSha256Header))
request.Headers[HeaderKeys.XAmzContentSha256Header] = payloadHash;
else
request.Headers.Add(HeaderKeys.XAmzContentSha256Header, payloadHash);
return payloadHash;
}
public static string DetermineSigningRegion(IClientConfig clientConfig,
string serviceName,
RegionEndpoint alternateEndpoint,
IRequest request)
{
// Alternate endpoint (IRequest.AlternateEndpoint) takes precedence over
// client config properties.
if (alternateEndpoint != null)
{
var serviceEndpoint = alternateEndpoint.GetEndpointForService(serviceName, clientConfig.ToGetEndpointForServiceOptions());
if (serviceEndpoint.AuthRegion != null)
return serviceEndpoint.AuthRegion;
return alternateEndpoint.SystemName;
}
string authenticationRegion = clientConfig.AuthenticationRegion;
// We always have request.AuthenticationRegion defined, as per
// Amazon.Runtime.Internal.BaseEndpointResolver implementation.
// request.AuthenticationRegion value is set either based on endpoint rules or
// overriden by clientConfig.AuthenticationRegion if defined.
// Normally, users should only override clientConfig.AuthenticationRegion value for non-AWS services
if (request != null && request.AuthenticationRegion != null)
authenticationRegion = request.AuthenticationRegion;
if (!string.IsNullOrEmpty(authenticationRegion))
return authenticationRegion.ToLowerInvariant();
if (!string.IsNullOrEmpty(clientConfig.ServiceURL))
{
var parsedRegion = AWSSDKUtils.DetermineRegion(clientConfig.ServiceURL);
if (!string.IsNullOrEmpty(parsedRegion))
return parsedRegion.ToLowerInvariant();
}
var endpoint = clientConfig.RegionEndpoint;
if (endpoint != null)
{
var serviceEndpoint = endpoint.GetEndpointForService(serviceName, clientConfig.ToGetEndpointForServiceOptions());
if (!string.IsNullOrEmpty(serviceEndpoint.AuthRegion))
return serviceEndpoint.AuthRegion;
// Check if the region is overridden in the endpoints.json file
var overrideRegion = RegionEndpoint.GetRegionEndpointOverride(endpoint);
if (overrideRegion != null)
return overrideRegion.SystemName;
return endpoint.SystemName;
}
return string.Empty;
}
public static string DetermineService(IClientConfig clientConfig)
{
return (!string.IsNullOrEmpty(clientConfig.AuthenticationServiceName))
? clientConfig.AuthenticationServiceName
: AWSSDKUtils.DetermineService(clientConfig.DetermineServiceURL());
}
/// <summary>
/// Computes and returns the canonical request
/// </summary>
/// <param name="endpoint">The endpoint URL</param>
/// <param name="resourcePath">the path of the resource being operated on</param>
/// <param name="httpMethod">The http method used for the request</param>
/// <param name="sortedHeaders">The full request headers, sorted into canonical order</param>
/// <param name="canonicalQueryString">The query parameters for the request</param>
/// <param name="precomputedBodyHash">
/// The hash of the binary request body if present. If not supplied, the routine
/// will look for the hash as a header on the request.
/// </param>
/// <returns>Canonicalised request as a string</returns>
protected static string CanonicalizeRequest(Uri endpoint,
string resourcePath,
string httpMethod,
IDictionary<string, string> sortedHeaders,
string canonicalQueryString,
string precomputedBodyHash)
{
return CanonicalizeRequest(endpoint, resourcePath, httpMethod, sortedHeaders, canonicalQueryString, precomputedBodyHash, null);
}
/// <summary>
/// Computes and returns the canonical request
/// </summary>
/// <param name="endpoint">The endpoint URL</param>
/// <param name="resourcePath">the path of the resource being operated on</param>
/// <param name="httpMethod">The http method used for the request</param>
/// <param name="sortedHeaders">The full request headers, sorted into canonical order</param>
/// <param name="canonicalQueryString">The query parameters for the request</param>
/// <param name="precomputedBodyHash">
/// <param name="pathResources">The path resource values lookup to use to replace the keys within resourcePath</param>
/// The hash of the binary request body if present. If not supplied, the routine
/// will look for the hash as a header on the request.
/// </param>
/// <returns>Canonicalised request as a string</returns>
protected static string CanonicalizeRequest(Uri endpoint,
string resourcePath,
string httpMethod,
IDictionary<string, string> sortedHeaders,
string canonicalQueryString,
string precomputedBodyHash,
IDictionary<string, string> pathResources)
{
return CanonicalizeRequestHelper(endpoint,
resourcePath,
httpMethod,
sortedHeaders,
canonicalQueryString,
precomputedBodyHash,
pathResources,
true);
}
/// <summary>
/// Computes and returns the canonical request
/// </summary>
/// <param name="endpoint">The endpoint URL</param>
/// <param name="resourcePath">the path of the resource being operated on</param>
/// <param name="httpMethod">The http method used for the request</param>
/// <param name="sortedHeaders">The full request headers, sorted into canonical order</param>
/// <param name="canonicalQueryString">The query parameters for the request</param>
/// <param name="precomputedBodyHash">
/// <param name="pathResources">The path resource values lookup to use to replace the keys within resourcePath</param>
/// The hash of the binary request body if present. If not supplied, the routine
/// will look for the hash as a header on the request.
/// </param>
/// <param name="doubleEncode">Encode "/" when canonicalize resource path</param>
/// <returns>Canonicalised request as a string</returns>
protected static string CanonicalizeRequest(Uri endpoint,
string resourcePath,
string httpMethod,
IDictionary<string, string> sortedHeaders,
string canonicalQueryString,
string precomputedBodyHash,
IDictionary<string, string> pathResources,
bool doubleEncode)
{
return CanonicalizeRequestHelper(endpoint,
resourcePath,
httpMethod,
sortedHeaders,
canonicalQueryString,
precomputedBodyHash,
pathResources,
doubleEncode);
}
private static string CanonicalizeRequestHelper(Uri endpoint,
string resourcePath,
string httpMethod,
IDictionary<string, string> sortedHeaders,
string canonicalQueryString,
string precomputedBodyHash,
IDictionary<string, string> pathResources,
bool doubleEncode)
{
var canonicalRequest = new StringBuilder();
canonicalRequest.AppendFormat("{0}\n", httpMethod);
canonicalRequest.AppendFormat("{0}\n", AWSSDKUtils.CanonicalizeResourcePathV2(endpoint, resourcePath, doubleEncode, pathResources));
canonicalRequest.AppendFormat("{0}\n", canonicalQueryString);
canonicalRequest.AppendFormat("{0}\n", CanonicalizeHeaders(sortedHeaders));
canonicalRequest.AppendFormat("{0}\n", CanonicalizeHeaderNames(sortedHeaders));
if (precomputedBodyHash != null)
{
canonicalRequest.Append(precomputedBodyHash);
}
else
{
string contentHash;
if (sortedHeaders.TryGetValue(HeaderKeys.XAmzContentSha256Header, out contentHash))
canonicalRequest.Append(contentHash);
}
return canonicalRequest.ToString();
}
/// <summary>
/// Reorders the headers for the request for canonicalization.
/// </summary>
/// <param name="requestHeaders">The set of proposed headers for the request</param>
/// <returns>List of headers that must be included in the signature</returns>
/// <remarks>For AWS4 signing, all headers are considered viable for inclusion</remarks>
protected internal static IDictionary<string, string> SortAndPruneHeaders(IEnumerable<KeyValuePair<string, string>> requestHeaders)
{
// Refer https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html. (Step #4: "Build the canonical headers list by sorting the (lowercase) headers by character code"). StringComparer.OrdinalIgnoreCase incorrectly places '_' after lowercase chracters.
var sortedHeaders = new SortedDictionary<string, string>(StringComparer.Ordinal);
foreach (var header in requestHeaders)
{
if (_headersToIgnoreWhenSigning.Contains(header.Key))
{
continue;
}
sortedHeaders.Add(header.Key.ToLowerInvariant(), header.Value);
}
return sortedHeaders;
}
/// <summary>
/// Computes the canonical headers with values for the request. Only headers included in the signature
/// are included in the canonicalization process.
/// </summary>
/// <param name="sortedHeaders">All request headers, sorted into canonical order</param>
/// <returns>Canonicalized string of headers, with the header names in lower case.</returns>
protected internal static string CanonicalizeHeaders(IEnumerable<KeyValuePair<string, string>> sortedHeaders)
{
if (sortedHeaders == null || sortedHeaders.Count() == 0)
return string.Empty;
var builder = new StringBuilder();
foreach (var entry in sortedHeaders)
{
// Refer https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html. (Step #4: "To create the canonical headers list, convert all header names to lowercase and remove leading spaces and trailing spaces. Convert sequential spaces in the header value to a single space.").
builder.Append(entry.Key.ToLowerInvariant());
builder.Append(":");
builder.Append(AWSSDKUtils.CompressSpaces(entry.Value)?.Trim());
builder.Append("\n");
}
return builder.ToString();
}
/// <summary>
/// Returns the set of headers included in the signature as a flattened, ;-delimited string
/// </summary>
/// <param name="sortedHeaders">The headers included in the signature</param>
/// <returns>Formatted string of header names</returns>
protected static string CanonicalizeHeaderNames(IEnumerable<KeyValuePair<string, string>> sortedHeaders)
{
var builder = new StringBuilder();
foreach (var header in sortedHeaders)
{
if (builder.Length > 0)
builder.Append(";");
builder.Append(header.Key.ToLowerInvariant());
}
return builder.ToString();
}
/// <summary>
/// Collects the subresource and query string parameters into one collection
/// ready for canonicalization
/// </summary>
/// <param name="request">The in-flight request being signed</param>
/// <returns>The fused set of parameters</returns>
protected static List<KeyValuePair<string, string>> GetParametersToCanonicalize(IRequest request)
{
var parametersToCanonicalize = new List<KeyValuePair<string, string>>();
if (request.SubResources != null && request.SubResources.Count > 0)
{
foreach (var subResource in request.SubResources)
{
parametersToCanonicalize.Add(new KeyValuePair<string,string>(subResource.Key, subResource.Value));
}
}
if (request.UseQueryString && request.Parameters != null && request.Parameters.Count > 0)
{
var requestParameters = request.ParameterCollection.GetSortedParametersList();
foreach (var queryParameter in requestParameters.Where(queryParameter => queryParameter.Value != null))
{
parametersToCanonicalize.Add(new KeyValuePair<string,string>(queryParameter.Key, queryParameter.Value));
}
}
return parametersToCanonicalize;
}
protected static string CanonicalizeQueryParameters(string queryString)
{
return CanonicalizeQueryParameters(queryString, true);
}
/// <summary>
/// Computes and returns the canonicalized query string, if query parameters have been supplied.
/// Parameters with no value will be canonicalized as 'param='. The expectation is that parameters
/// have not already been url encoded prior to canonicalization.
/// </summary>
/// <param name="queryString">The set of parameters being passed on the uri</param>
/// <param name="uriEncodeParameters">
/// Parameters must be uri encoded into the canonical request and by default the signer expects
/// that the supplied collection contains non-encoded data. Set this to false if the encoding was
/// done prior to signer entry.
/// </param>
/// <returns>The uri encoded query string parameters in canonical ordering</returns>
protected static string CanonicalizeQueryParameters(string queryString, bool uriEncodeParameters)
{
if (string.IsNullOrEmpty(queryString))
return string.Empty;
var queryParams = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var queryParamsStart = queryString.IndexOf('?');
var qs = queryString.Substring(++queryParamsStart);
var subStringPos = 0;
var index = qs.IndexOfAny(new char[] { '&', ';' }, 0);
if (index == -1 && subStringPos < qs.Length)
index = qs.Length;
while (index != -1)
{
var token = qs.Substring(subStringPos, index - subStringPos);
// If the next character is a space then this isn't the end of query string value
// Content Disposition is an example of this.
if (!(index + 1 < qs.Length && qs[index + 1] == ' '))
{
var equalPos = token.IndexOf('=');
if (equalPos == -1)
queryParams.Add(token, null);
else
queryParams.Add(token.Substring(0, equalPos), token.Substring(equalPos + 1));
subStringPos = index + 1;
}
if (qs.Length <= index + 1)
break;
index = qs.IndexOfAny(new char[] { '&', ';' }, index + 1);
if (index == -1 && subStringPos < qs.Length)
index = qs.Length;
}
return CanonicalizeQueryParameters(queryParams, uriEncodeParameters: uriEncodeParameters);
}
protected static string CanonicalizeQueryParameters(IEnumerable<KeyValuePair<string, string>> parameters)
{
return CanonicalizeQueryParameters(parameters, true);
}
/// <summary>
/// Computes and returns the canonicalized query string, if query parameters have been supplied.
/// Parameters with no value will be canonicalized as 'param='. The expectation is that parameters
/// have not already been url encoded prior to canonicalization.
/// </summary>
/// <param name="parameters">The set of parameters to be encoded in the query string</param>
/// <param name="uriEncodeParameters">
/// Parameters must be uri encoded into the canonical request and by default the signer expects
/// that the supplied collection contains non-encoded data. Set this to false if the encoding was
/// done prior to signer entry.
/// </param>
/// <returns>The uri encoded query string parameters in canonical ordering</returns>
protected static string CanonicalizeQueryParameters(
IEnumerable<KeyValuePair<string, string>> parameters,
bool uriEncodeParameters)
{
if (parameters == null)
return string.Empty;
var sortedParameters = parameters.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).ToList();
var canonicalQueryString = new StringBuilder();
foreach (var param in sortedParameters)
{
var key = param.Key;
var value = param.Value;
if (canonicalQueryString.Length > 0)
canonicalQueryString.Append("&");
if (uriEncodeParameters)
{
if (string.IsNullOrEmpty(value))
canonicalQueryString.AppendFormat("{0}=", AWSSDKUtils.UrlEncode(key, false));
else
canonicalQueryString.AppendFormat("{0}={1}", AWSSDKUtils.UrlEncode(key, false), AWSSDKUtils.UrlEncode(value, false));
}
else
{
if (string.IsNullOrEmpty(value))
canonicalQueryString.AppendFormat("{0}=", key);
else
canonicalQueryString.AppendFormat("{0}={1}", key, value);
}
}
return canonicalQueryString.ToString();
}
/// <summary>
/// Returns the request parameters in the form of a query string.
/// </summary>
/// <param name="request">The request instance</param>
/// <returns>Request parameters in query string format</returns>
static byte[] GetRequestPayloadBytes(IRequest request)
{
if (request.Content != null)
return request.Content;
var content = request.UseQueryString ? string.Empty : AWSSDKUtils.GetParametersAsString(request);
return Encoding.UTF8.GetBytes(content);
}
#endregion
}
/// <summary>
/// AWS4 protocol signer for Amazon S3 presigned urls.
/// </summary>
public class AWS4PreSignedUrlSigner : AWS4Signer
{
// 7 days is the maximum period for presigned url expiry with AWS4
public const Int64 MaxAWS4PreSignedUrlExpiry = 7 * 24 * 60 * 60;
public static readonly IEnumerable<string> ServicesUsingUnsignedPayload = new HashSet<string>()
{
"s3",
"s3-object-lambda",
"s3-outposts"
};
/// <summary>
/// Calculates and signs the specified request using the AWS4 signing protocol by using the
/// AWS account credentials given in the method parameters. The resulting signature is added
/// to the request headers as 'Authorization'.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Adding supporting data for the service call required by the signer (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="awsAccessKeyId">
/// The AWS public key for the account making the service call.
/// </param>
/// <param name="awsSecretAccessKey">
/// The AWS secret key for the account making the call, in clear text
/// </param>
/// <exception cref="Amazon.Runtime.SignatureException">
/// If any problems are encountered while signing the request.
/// </exception>
public override void Sign(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
string awsAccessKeyId,
string awsSecretAccessKey)
{
throw new InvalidOperationException("PreSignedUrl signature computation is not supported by this method; use SignRequest instead.");
}
/// <summary>
/// Calculates and signs the specified request using the AWS4 signing protocol by using the
/// AWS account credentials given in the method parameters. The resulting signature is added
/// to the request headers as 'Authorization'.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Adding supporting data for the service call required by the signer (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
/// <exception cref="Amazon.Runtime.SignatureException">
/// If any problems are encountered while signing the request.
/// </exception>
public override void Sign(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
ImmutableCredentials credentials)
{
throw new InvalidOperationException("PreSignedUrl signature computation is not supported by this method; use SignRequest instead.");
}
/// <summary>
/// Calculates the AWS4 signature for a presigned url.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
/// ('host' and 'x-amz-date') will be added to the request before signing. If the Expires parameter
/// is present, it is renamed to 'X-Amz-Expires' before signing.
/// </param>
/// <param name="clientConfig">
/// Adding supporting data for the service call required by the signer (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="awsAccessKeyId">
/// The AWS public key for the account making the service call.
/// </param>
/// <param name="awsSecretAccessKey">
/// The AWS secret key for the account making the call, in clear text
/// </param>
/// <exception cref="Amazon.Runtime.SignatureException">
/// If any problems are encountered while signing the request.
/// </exception>
/// <remarks>
/// Parameters passed as part of the resource path should be uri-encoded prior to
/// entry to the signer. Parameters passed in the request.Parameters collection should
/// be not be encoded; encoding will be done for these parameters as part of the
/// construction of the canonical request.
/// </remarks>
public new AWS4SigningResult SignRequest(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
string awsAccessKeyId,
string awsSecretAccessKey)
{
var service = "s3";
if (!string.IsNullOrEmpty(request.OverrideSigningServiceName))
service = request.OverrideSigningServiceName;
return SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey, service, null);
}
/// <summary>
/// Calculates the AWS4 signature for a presigned url.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
/// ('host' and 'x-amz-date') will be added to the request before signing. If the Expires parameter
/// is present, it is renamed to 'X-Amz-Expires' before signing.
/// </param>
/// <param name="clientConfig">
/// Adding supporting data for the service call required by the signer (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="awsAccessKeyId">
/// The AWS public key for the account making the service call.
/// </param>
/// <param name="awsSecretAccessKey">
/// The AWS secret key for the account making the call, in clear text
/// </param>
/// <param name="service">
/// The service to sign for
/// </param>
/// <param name="overrideSigningRegion">
/// The region to sign to, if null then the region the client is configured for will be used.
/// </param>
/// <exception cref="Amazon.Runtime.SignatureException">
/// If any problems are encountered while signing the request.
/// </exception>
/// <remarks>
/// Parameters passed as part of the resource path should be uri-encoded prior to
/// entry to the signer. Parameters passed in the request.Parameters collection should
/// be not be encoded; encoding will be done for these parameters as part of the
/// construction of the canonical request.
///
/// The X-Amz-Content-SHA256 is cleared out of the request.
/// If the request is for S3 then the UNSIGNED_PAYLOAD value is used to generate the canonical request.
/// If the request isn't for S3 then the empty body SHA is used to generate the canonical request.
/// </remarks>
public static AWS4SigningResult SignRequest(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
string awsAccessKeyId,
string awsSecretAccessKey,
string service,
string overrideSigningRegion)
{
if (service == "s3")
{
// Older versions of the S3 package can be used with newer versions of Core, this guarantees no double encoding will be used.
// The new behavior uses endpoint resolution rules, which are not present prior to 3.7.100
request.UseDoubleEncoding = false;
}
// clean up any prior signature in the headers if resigning
request.Headers.Remove(HeaderKeys.AuthorizationHeader);
if (!request.Headers.ContainsKey(HeaderKeys.HostHeader))
{
var hostHeader = request.Endpoint.Host;
if (!request.Endpoint.IsDefaultPort)
hostHeader += ":" + request.Endpoint.Port;
request.Headers.Add(HeaderKeys.HostHeader, hostHeader);
}
var signedAt = CorrectClockSkew.GetCorrectedUtcNowForEndpoint(request.Endpoint.ToString());
var region = overrideSigningRegion ?? DetermineSigningRegion(clientConfig, clientConfig.RegionEndpointServiceName, request.AlternateEndpoint, request);
// AWS4 presigned urls got S3 are expected to contain a 'UNSIGNED-PAYLOAD' magic string
// during signing (other services use the empty-body sha)
if (request.Headers.ContainsKey(HeaderKeys.XAmzContentSha256Header))
request.Headers.Remove(HeaderKeys.XAmzContentSha256Header);
var sortedHeaders = SortAndPruneHeaders(request.Headers);
var canonicalizedHeaderNames = CanonicalizeHeaderNames(sortedHeaders);
var parametersToCanonicalize = GetParametersToCanonicalize(request);
parametersToCanonicalize.Add(new KeyValuePair<string,string>(HeaderKeys.XAmzAlgorithm, AWS4AlgorithmTag));
var xAmzCredentialValue = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}/{4}",
awsAccessKeyId,
FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat),
region,
service,
Terminator);
parametersToCanonicalize.Add(new KeyValuePair<string,string>(HeaderKeys.XAmzCredential, xAmzCredentialValue));
parametersToCanonicalize.Add(new KeyValuePair<string,string>(HeaderKeys.XAmzDateHeader, FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateTimeFormat)));
parametersToCanonicalize.Add(new KeyValuePair<string,string>(HeaderKeys.XAmzSignedHeadersHeader, canonicalizedHeaderNames));
var canonicalQueryParams = CanonicalizeQueryParameters(parametersToCanonicalize);
var canonicalRequest = CanonicalizeRequest(request.Endpoint,
request.ResourcePath,
request.HttpMethod,
sortedHeaders,
canonicalQueryParams,
ServicesUsingUnsignedPayload.Contains(service) ? UnsignedPayload : EmptyBodySha256,
request.PathResources,
request.UseDoubleEncoding);
if (metrics != null)
metrics.AddProperty(Metric.CanonicalRequest, canonicalRequest);
return ComputeSignature(awsAccessKeyId,
awsSecretAccessKey,
region,
signedAt,
service,
canonicalizedHeaderNames,
canonicalRequest,
metrics);
}
}
}
| 1,284 |
aws-sdk-net | aws | C# | /*
* 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 System;
using System.Globalization;
using System.Text;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// Encapsulates the various fields and eventual signing value that makes up
/// an AWS4 signature. This can be used to retrieve the required authorization string
/// or authorization query parameters for the final request as well as hold ongoing
/// signature computations for subsequent calls related to the initial signing.
/// </summary>
public class AWS4SigningResult : AWSSigningResultBase
{
private readonly byte[] _signingKey;
private readonly byte[] _signature;
/// <summary>
/// Constructs a new signing result instance for a computed signature
/// </summary>
/// <param name="awsAccessKeyId">The access key that was included in the signature</param>
/// <param name="signedAt">Date/time (UTC) that the signature was computed</param>
/// <param name="signedHeaders">The collection of headers names that were included in the signature</param>
/// <param name="scope">Formatted 'scope' value for signing (YYYYMMDD/region/service/aws4_request)</param>
/// <param name="signingKey">Returns the key that was used to compute the signature</param>
/// <param name="signature">Computed signature</param>
public AWS4SigningResult(string awsAccessKeyId,
DateTime signedAt,
string signedHeaders,
string scope,
byte[] signingKey,
byte[] signature) :
base(awsAccessKeyId, signedAt, signedHeaders, scope)
{
_signingKey = signingKey;
_signature = signature;
}
/// <summary>
/// Returns a copy of the key that was used to compute the signature
/// </summary>
public byte[] GetSigningKey()
{
var kSigningCopy = new byte[_signingKey.Length];
_signingKey.CopyTo(kSigningCopy, 0);
return kSigningCopy;
}
/// <summary>
/// Returns the hex string representing the signature
/// </summary>
public override string Signature
{
get { return AWSSDKUtils.ToHex(_signature, true); }
}
/// <summary>
/// Returns the signature in a form usable as an 'Authorization' header value.
/// </summary>
public override string ForAuthorizationHeader
{
get
{
var authorizationHeader = new StringBuilder()
.Append(AWS4Signer.AWS4AlgorithmTag)
.AppendFormat(" {0}={1}/{2},", AWS4Signer.Credential, AccessKeyId, Scope)
.AppendFormat(" {0}={1},", AWS4Signer.SignedHeaders, SignedHeaders)
.AppendFormat(" {0}={1}", AWS4Signer.Signature, Signature);
return authorizationHeader.ToString();
}
}
/// <summary>
/// Returns the signature in a form usable as a set of query string parameters.
/// </summary>
public string ForQueryParameters
{
get
{
var authParams = new StringBuilder()
.AppendFormat("{0}={1}", HeaderKeys.XAmzAlgorithm, AWS4Signer.AWS4AlgorithmTag)
.AppendFormat("&{0}={1}", HeaderKeys.XAmzCredential, string.Format(CultureInfo.InvariantCulture, "{0}/{1}", AccessKeyId, Scope))
.AppendFormat("&{0}={1}", HeaderKeys.XAmzDateHeader, ISO8601DateTime)
.AppendFormat("&{0}={1}", HeaderKeys.XAmzSignedHeadersHeader, SignedHeaders)
.AppendFormat("&{0}={1}", HeaderKeys.XAmzSignature, Signature);
return authParams.ToString();
}
}
}
}
| 109 |
aws-sdk-net | aws | C# | /*
* 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 System;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// Base class for the various fields and eventual signing value
/// that make up an AWS request signature.
/// </summary>
public abstract class AWSSigningResultBase
{
private readonly string _awsAccessKeyId;
private readonly DateTime _originalDateTime;
private readonly string _signedHeaders;
private readonly string _scope;
/// <summary>
/// Constructs a new signing result instance for a computed signature
/// </summary>
/// <param name="awsAccessKeyId">The access key that was included in the signature</param>
/// <param name="signedAt">Date/time (UTC) that the signature was computed</param>
/// <param name="signedHeaders">The collection of headers names that were included in the signature</param>
/// <param name="scope">Formatted 'scope' value for signing (YYYYMMDD/region/service/aws4_request)</param>
public AWSSigningResultBase(string awsAccessKeyId,
DateTime signedAt,
string signedHeaders,
string scope)
{
_awsAccessKeyId = awsAccessKeyId;
_originalDateTime = signedAt;
_signedHeaders = signedHeaders;
_scope = scope;
}
/// <summary>
/// The access key that was used in signature computation.
/// </summary>
public string AccessKeyId
{
get { return _awsAccessKeyId; }
}
/// <summary>
/// ISO8601 formatted date/time that the signature was computed
/// </summary>
public string ISO8601DateTime
{
get { return AWS4Signer.FormatDateTime(_originalDateTime, AWSSDKUtils.ISO8601BasicDateTimeFormat); }
}
/// <summary>
/// ISO8601 formatted date that the signature was computed
/// </summary>
public string ISO8601Date
{
get { return AWS4Signer.FormatDateTime(_originalDateTime, AWSSDKUtils.ISO8601BasicDateFormat); }
}
/// <summary>
/// Original date/time that the signature was computed
/// </summary>
public DateTime DateTime
{
get { return _originalDateTime; }
}
/// <summary>
/// The ;-delimited collection of header names that were included in the signature computation
/// </summary>
public string SignedHeaders
{
get { return _signedHeaders; }
}
/// <summary>
/// Formatted 'scope' value for signing (YYYYMMDD/region/service/aws4_request)
/// </summary>
public string Scope
{
get { return _scope; }
}
public abstract string Signature { get; }
public abstract string ForAuthorizationHeader { get; }
}
}
| 103 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Security;
using System.Text;
using Amazon.Util;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
using System.Globalization;
namespace Amazon.Runtime.Internal.Auth
{
public class CloudFrontSigner : AbstractAWSSigner
{
public override ClientProtocol Protocol
{
get { return ClientProtocol.RestProtocol; }
}
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
{
if (String.IsNullOrEmpty(awsAccessKeyId))
{
throw new ArgumentOutOfRangeException("awsAccessKeyId", "The AWS Access Key ID cannot be NULL or a Zero length string");
}
string dateTime = AWSSDKUtils.GetFormattedTimestampRFC822(0);
request.Headers.Add(HeaderKeys.XAmzDateHeader, dateTime);
string signature = ComputeHash(dateTime, awsSecretAccessKey, SigningAlgorithm.HmacSHA1);
request.Headers.Add(HeaderKeys.AuthorizationHeader, "AWS " + awsAccessKeyId + ":" + signature);
}
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
{
Sign(request, clientConfig, metrics, credentials.AccessKey, credentials.SecretKey);
}
}
}
| 56 |
aws-sdk-net | aws | C# | /*
* 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.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// AWS4/AWS4a protocol signer for service calls that transmit authorization in the header field "Authorization".
/// Specific for EventBridge
/// </summary>
public class EventBridgeSigner : AbstractAWSSigner
{
public override ClientProtocol Protocol
{
get { return ClientProtocol.RestProtocol; }
}
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
{
Sign(request, clientConfig, metrics, new ImmutableCredentials(awsAccessKeyId, awsSecretAccessKey, ""));
}
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
{
var useSigV4 = request.SignatureVersion == SignatureVersion.SigV4;
var signer = SelectSigner(this, useSigV4, request, clientConfig);
var aws4aSigner = signer as AWS4aSignerCRTWrapper;
var aws4Signer = signer as AWS4Signer;
var useV4a = aws4aSigner != null;
var useV4 = aws4Signer != null;
AWSSigningResultBase signingResult;
if (useV4a)
{
signingResult = aws4aSigner.SignRequest(request, clientConfig, metrics, credentials);
}
else if(useV4)
{
signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, credentials.AccessKey, credentials.SecretKey);
}
else
{
throw new AmazonClientException("EventBridge supports only SigV4 and SigV4a signature versions");
}
request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
}
}
}
| 65 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// Null Signer which does a no-op.
/// </summary>
public class NullSigner : AbstractAWSSigner
{
public override void Sign(IRequest request, IClientConfig clientConfig, Util.RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
{
// This is a null signer which a does no-op
return;
}
public override void Sign(IRequest request, IClientConfig clientConfig, Util.RequestMetrics metrics, ImmutableCredentials credentials)
{
// This is a null signer which does no-op
return;
}
public override ClientProtocol Protocol
{
get { return ClientProtocol.Unknown; }
}
}
}
| 46 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Security;
using System.Text;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
namespace Amazon.Runtime.Internal.Auth
{
public class QueryStringSigner : AbstractAWSSigner
{
private const string SignatureVersion2 = "2";
public QueryStringSigner()
{
}
public override ClientProtocol Protocol
{
get { return ClientProtocol.QueryStringProtocol; }
}
/// <summary>
/// Signs the specified request with the AWS2 signing protocol by using the
/// AWS account credentials given in the method parameters.
/// </summary>
/// <param name="awsAccessKeyId">The AWS public key</param>
/// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
/// <param name="metrics">Request metrics</param>
/// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
/// <param name="request">The request to have the signature compute for</param>
/// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
{
if (String.IsNullOrEmpty(awsAccessKeyId))
{
throw new ArgumentOutOfRangeException("awsAccessKeyId", "The AWS Access Key ID cannot be NULL or a Zero length string");
}
request.Parameters["AWSAccessKeyId"] = awsAccessKeyId;
request.Parameters["SignatureVersion"] = SignatureVersion2;
request.Parameters["SignatureMethod"] = clientConfig.SignatureMethod.ToString();
request.Parameters["Timestamp"] = AWSSDKUtils.GetFormattedTimestampISO8601(clientConfig);
// remove Signature parameter, in case this is a retry
request.Parameters.Remove("Signature");
string toSign = AWSSDKUtils.CalculateStringToSignV2(request.ParameterCollection, request.Endpoint.AbsoluteUri);
metrics.AddProperty(Metric.StringToSign, toSign);
string auth = ComputeHash(toSign, awsSecretAccessKey, clientConfig.SignatureMethod);
request.Parameters["Signature"] = auth;
}
/// <summary>
/// Signs the specified request with the AWS2 signing protocol by using the
/// AWS account credentials given in the method parameters.
/// </summary>
/// <param name="request">The request to have the signature compute for</param>
/// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
/// <param name="metrics">Request metrics</param>
/// <param name="credentials">AWS credentials for the account making the request</param>
/// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
{
Sign(request, clientConfig, metrics, credentials.AccessKey, credentials.SecretKey);
}
}
}
| 84 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
using System.Linq;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
#pragma warning disable 1591
namespace Amazon.Runtime.Internal.Auth
{
public class S3Signer : AbstractAWSSigner
{
public delegate void RegionDetectionUpdater(IRequest request);
private readonly bool _useSigV4;
private readonly RegionDetectionUpdater _regionDetector;
/// <summary>
/// S3 signer constructor
/// </summary>
public S3Signer() :
this(true, null)
{
}
/// <summary>
/// S3 signer constructor
/// </summary>
public S3Signer(bool useSigV4, RegionDetectionUpdater regionDetector)
{
_useSigV4 = useSigV4;
_regionDetector = regionDetector;
}
public override ClientProtocol Protocol
{
get { return ClientProtocol.RestProtocol; }
}
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
{
Sign(request, clientConfig, metrics, new ImmutableCredentials(awsAccessKeyId, awsSecretAccessKey, ""));
}
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
{
var signer = SelectSigner(this, _useSigV4, request, clientConfig);
var aws4Signer = signer as AWS4Signer;
var aws4aSigner = signer as AWS4aSignerCRTWrapper;
var useV4 = aws4Signer != null;
var useV4a = aws4aSigner != null;
if (useV4a)
{
var signingResult = aws4aSigner.SignRequest(request, clientConfig, metrics, credentials);
if (request.UseChunkEncoding)
{
request.AWS4aSignerResult = signingResult;
}
}
else if (useV4)
{
_regionDetector?.Invoke(request);
var signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, credentials.AccessKey, credentials.SecretKey);
request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
if (request.UseChunkEncoding)
request.AWS4SignerResult = signingResult;
}
else
{
SignRequest(request, metrics, credentials.AccessKey, credentials.SecretKey);
}
}
public static void SignRequest(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
{
request.Headers[HeaderKeys.XAmzDateHeader] = AWSSDKUtils.FormattedCurrentTimestampRFC822;
var stringToSign = BuildStringToSign(request);
metrics.AddProperty(Metric.StringToSign, stringToSign);
var auth = CryptoUtilFactory.CryptoInstance.HMACSign(stringToSign, awsSecretAccessKey, SigningAlgorithm.HmacSHA1);
var authorization = string.Concat("AWS ", awsAccessKeyId, ":", auth);
request.Headers[HeaderKeys.AuthorizationHeader] = authorization;
}
static string BuildStringToSign(IRequest request)
{
var sb = new StringBuilder("", 256);
sb.Append(request.HttpMethod);
sb.Append("\n");
var headers = request.Headers;
var parameters = request.Parameters;
if (headers != null)
{
string value = null;
if (headers.ContainsKey(HeaderKeys.ContentMD5Header) && !String.IsNullOrEmpty(value = headers[HeaderKeys.ContentMD5Header]))
{
sb.Append(value);
}
sb.Append("\n");
if (parameters.ContainsKey("ContentType"))
{
sb.Append(parameters["ContentType"]);
}
else if (headers.ContainsKey(HeaderKeys.ContentTypeHeader))
{
sb.Append(headers[HeaderKeys.ContentTypeHeader]);
}
sb.Append("\n");
}
else
{
// The headers are null, but we still need to append
// the 2 newlines that are required by S3.
// Without these, S3 rejects the signature.
sb.Append("\n\n");
}
if (parameters.ContainsKey("Expires"))
{
sb.Append(parameters["Expires"]);
if (headers != null)
headers.Remove(HeaderKeys.XAmzDateHeader);
}
IDictionary<string, string> headersAndParameters = new Dictionary<string, string>(headers);
foreach (var pair in parameters)
{
// If there's a key that's both a header and a parameter then the header will take precedence.
if (!headersAndParameters.ContainsKey(pair.Key))
headersAndParameters.Add(pair.Key, pair.Value);
}
sb.Append("\n");
sb.Append(BuildCanonicalizedHeaders(headersAndParameters));
var canonicalizedResource = BuildCanonicalizedResource(request);
if (!string.IsNullOrEmpty(canonicalizedResource))
{
sb.Append(canonicalizedResource);
}
return sb.ToString();
}
static string BuildCanonicalizedHeaders(IDictionary<string, string> headers)
{
// Refer "Constructing the CanonicalizedAmzHeaders element" section at https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html.
var sb = new StringBuilder(256);
// Steps 1 and Steps 2 requires all headers to be in lowercase and lexicographically sorted by header name. StringComparer.OrdinalIgnoreCase incorrectly places '_' after lowercase chracters.
foreach (var key in headers.Keys.OrderBy(x => x.ToLowerInvariant(), StringComparer.Ordinal))
{
var lowerKey = key.ToLowerInvariant();
if (!lowerKey.StartsWith("x-amz-", StringComparison.Ordinal))
continue;
// Step 5: Trim any spaces around the colon in the header (based on testing spaces at the end of value also needs to be removed).
sb.Append(String.Concat(lowerKey, ":", headers[key]?.Trim(), "\n"));
}
return sb.ToString();
}
private static readonly HashSet<string> SignableParameters = new HashSet<string>
(
new[]
{
"response-content-type",
"response-content-language",
"response-expires",
"response-cache-control",
"response-content-disposition",
"response-content-encoding"
},
StringComparer.OrdinalIgnoreCase
);
//This is a list of sub resources that S3 does not expect to be signed
//and thus have to be excluded from the signer. This is only applicable to S3SigV2 signer
//id:- subresource belongs to analytics,inventory and metrics S3 APIs
private static readonly HashSet<string> SubResourcesSigningExclusion = new HashSet<string>
(
new[]
{
"id"
},
StringComparer.OrdinalIgnoreCase
);
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);
sb.Append(!string.IsNullOrEmpty(request.ResourcePath)
? AWSSDKUtils.ResolveResourcePath(request.ResourcePath, request.PathResources)
: "/");
// 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
// canonicalization
var resourcesToSign = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (request.SubResources.Count > 0)
{
foreach (var subResource in request.SubResources)
{
if (!SubResourcesSigningExclusion.Contains(subResource.Key))
{
resourcesToSign.Add(subResource.Key, subResource.Value);
}
}
}
if (request.Parameters.Count > 0)
{
var parameters = request.ParameterCollection.GetSortedParametersList();
foreach (var parameter in parameters)
{
if (parameter.Value != null && SignableParameters.Contains(parameter.Key))
{
resourcesToSign.Add(parameter.Key, parameter.Value);
}
}
}
var delim = "?";
List<KeyValuePair<string, string>> resources = new List<KeyValuePair<string, string>>();
foreach (var kvp in resourcesToSign)
{
resources.Add(kvp);
}
resources.Sort((firstPair, nextPair) =>
{
return string.CompareOrdinal(firstPair.Key, nextPair.Key);
});
foreach (var resourceToSign in resources)
{
sb.AppendFormat("{0}{1}", delim, resourceToSign.Key);
if (resourceToSign.Value != null)
sb.AppendFormat("={0}", resourceToSign.Value);
delim = "&";
}
return sb.ToString();
}
}
}
| 269 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
namespace Amazon.Runtime.Internal.Auth
{
/// <summary>
/// This exception is thrown if there are problems signing the request.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public class SignatureException : Exception
{
public SignatureException(string message)
: base(message)
{
}
public SignatureException(string message, Exception innerException)
: base(message, innerException)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the SignatureException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected SignatureException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 54 |
aws-sdk-net | aws | C# | /*
* 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.Endpoints;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Internal implementation of ARN (Amazon Resource Name).
/// Used by standard library functions to parse and validate ARNs.
/// </summary>
public class Arn : PropertyBag
{
/// <summary>
/// ARN partition
/// </summary>
public string partition
{
get { return (string)this["partition"]; }
set { this["partition"] = value; }
}
/// <summary>
/// ARN service
/// </summary>
public string service
{
get { return (string)this["service"]; }
set { this["service"] = value; }
}
/// <summary>
/// ARN region
/// </summary>
public string region
{
get { return (string)this["region"]; }
set { this["region"] = value; }
}
/// <summary>
/// ARN accountId
/// </summary>
public string accountId
{
get { return (string)this["accountId"]; }
set { this["accountId"] = value; }
}
/// <summary>
/// ARN list of ResourceIDs
/// </summary>
public List<string> resourceId
{
get { return (List<string>)this["resourceId"]; }
set { this["resourceId"] = value; }
}
/// <summary>
/// Check if input string is a valid ARN
/// </summary>
public static bool IsArn(string arn)
{
return arn != null && arn.StartsWith("arn:");
}
/// <summary>
/// Parses the string into an ARN object.
/// </summary>
/// <param name="arnString">String to parse into an ARN.</param>
/// <param name="arn">The out parameter for the ARN object created by TryParse.</param>
/// <returns>True if the string was parsed into an ARN object.</returns>
public static bool TryParse(string arnString, out Arn arn)
{
try
{
if (IsArn(arnString))
{
arn = Parse(arnString);
return true;
}
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception) { }
#pragma warning restore CA1031 // Do not catch general exception types
arn = null;
return false;
}
/// <summary>
/// Parses the string into an ARN object.
/// </summary>
/// <param name="arnString">String to parse into an Arn.</param>
/// <returns>The Arn object created from the passed in string.</returns>
/// <exception cref="ArgumentNullException">Thrown if arnString is null.</exception>
/// <exception cref="ArgumentException">Thrown if the string passed in not valid ARN.</exception>
public static Arn Parse(string arnString)
{
if (arnString == null)
{
throw new ArgumentNullException(nameof(arnString));
}
const string malformedErrorMessage = "ARN is in incorrect format. ARN format is: arn:<partition>:<service>:<region>:<account-id>:<resource>";
var tokens = arnString.Split(new char[] { ':' }, 6);
if (tokens.Length != 6)
{
throw new ArgumentException(malformedErrorMessage);
}
if (tokens[0] != "arn")
{
throw new ArgumentException(malformedErrorMessage);
}
string partition = tokens[1];
if (string.IsNullOrEmpty(partition))
{
throw new ArgumentException("Malformed ARN - no partition specified");
}
string service = tokens[2];
if (string.IsNullOrEmpty(service))
{
throw new ArgumentException("Malformed ARN - no service specified");
}
string region = tokens[3];
string accountId = tokens[4];
string resource = tokens[5];
if (string.IsNullOrEmpty(resource))
{
throw new ArgumentException("Malformed ARN - no resource specified");
}
return new Arn
{
partition = partition,
service = service,
region = region,
accountId = accountId,
resourceId = resource.Split(new[] { ':', '/' }).ToList()
};
}
}
}
| 161 |
aws-sdk-net | aws | C# | /*
* 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.Endpoints;
using Amazon.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Set of internal functions supported by ruleset conditions.
/// </summary>
public static class Fn
{
/// <summary>
/// Evaluates whether a value (such as an endpoint parameter) is set
/// </summary>
public static bool IsSet(object value)
{
return value != null;
}
/// <summary>
/// Extracts part of given object graph by path
///
/// Example: Given the input object {"Thing1": "foo", "Thing2": ["index0", "index1"], "Thing3": {"SubThing": 42}}
/// GetAttr(object, "Thing1") returns "foo"
/// path "Thing2[0]" returns "index0"
/// path "Thing3.SubThing" returns 42
/// Given the input IList list = {"foo", "bar"}
/// GetAttr(list, "[0]") returns "foo"
///
/// Every path segment must resolve to IPropertyBag
/// Every path segment with indexer must resolve to IList
/// Indexers must be at the very end of the path
/// </summary>
public static object GetAttr(object value, string path)
{
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
var parts = path.Split('.');
var propertyValue = value;
for (int i = 0; i < parts.Length; i++)
{
var part = parts[i];
// indexer is always at the end of path e.g. "Part1.Part2[3]"
if (i == parts.Length - 1)
{
var indexerStart = part.LastIndexOf('[');
var indexerEnd = part.Length - 1;
// indexer detected
if (indexerStart >= 0)
{
var propertyPath = part.Substring(0, indexerStart);
var index = int.Parse(part.Substring(indexerStart + 1, indexerEnd - indexerStart - 1));
// indexer can be passed directly as a path e.g. "[1]"
if (indexerStart > 0)
{
propertyValue = ((IPropertyBag)propertyValue)[propertyPath];
}
if (!(propertyValue is IList)) throw new ArgumentException("Object addressing by pathing segment '{part}' with indexer must be IList");
var list = (IList)propertyValue;
if (index < 0 || index > list.Count - 1)
{
return null;
}
return list[index];
}
}
if (!(propertyValue is IPropertyBag)) throw new ArgumentException("Object addressing by pathing segment '{part}' must be IPropertyBag");
propertyValue = ((IPropertyBag)propertyValue)[part];
}
return propertyValue;
}
/// <summary>
/// Returns partition data for a region
/// </summary>
public static Partition Partition(string region)
{
return StandardLibrary.Partition.GetPartitionByRegion(region);
}
/// <summary>
/// Evaluates a string ARN value, and returns an object containing details about the parsed ARN.
/// If the input was not a valid ARN, the function returns null.
/// </summary>
public static Arn ParseArn(string arn)
{
Arn parsedArn;
if (!Arn.TryParse(arn, out parsedArn))
{
return null;
}
return parsedArn;
}
/// <summary>
/// Evaluates whether one or more string values are valid host labels per RFC 1123.
/// https://www.rfc-editor.org/rfc/rfc1123#page-13
/// Each host label must be between [1, 63] characters, start with a number or letter, and only contain numbers, letters, or hyphens.
/// Host label can't end with a hyphen.
/// If allowSubDomains is true, then the provided value may be zero or more dotted subdomains which are each validated per RFC 1123.
/// </summary>
public static bool IsValidHostLabel(string hostLabel, bool allowSubDomains)
{
var hosts = new List<string>();
if (allowSubDomains)
{
hosts.AddRange(hostLabel.Split('.'));
}
else
{
hosts.Add(hostLabel);
}
foreach (var host in hosts)
{
if (!IsVirtualHostableName(host))
{
return false;
}
}
return true;
}
private static bool IsVirtualHostableName(string name)
{
if (string.IsNullOrEmpty(name) || name.Length < 1 || name.Length > 63)
{
return false;
}
if (!char.IsLetterOrDigit(name[0]) || !char.IsLetterOrDigit(name.Last()))
{
return false;
}
for (int i = 1; i < name.Length - 1; i++)
{
if (!char.IsLetterOrDigit(name[i]) && name[i] != '-')
{
return false;
}
}
return true;
}
/// <summary>
/// In addition to the restrictions defined in RFC 1123 and isValidHostLabel,
/// validates that the bucket name is between [3,63] characters,
/// does not contain upper case characters, and is not formatted as an IP4 address.
/// Host label can't end with a hyphen.
/// </summary>
public static bool IsVirtualHostableS3Bucket(string hostLabel, bool allowSubDomains)
{
if (IsIpV4Address(hostLabel))
{
return false;
}
var hosts = new List<string>();
if (allowSubDomains)
{
hosts.AddRange(hostLabel.Split('.'));
}
else
{
hosts.Add(hostLabel);
}
foreach (var host in hosts)
{
if (!IsVirtualHostableS3Name(host))
{
return false;
}
}
return true;
}
private static bool IsVirtualHostableS3Name(string name)
{
if (string.IsNullOrEmpty(name) || name.Length < 3 || name.Length > 63)
{
return false;
}
if (char.IsUpper(name[0]) || !char.IsLetterOrDigit(name[0]) || !char.IsLetterOrDigit(name.Last()))
{
return false;
}
for (int i = 1; i < name.Length - 1; i++)
{
if (char.IsUpper(name[i]) || (!char.IsLetterOrDigit(name[i]) && name[i] != '-'))
{
return false;
}
}
return true;
}
private static bool IsIpV4Address(string name)
{
const byte IpV4AddressPartsCount = 4;
var parts = name.Split('.');
if (parts.Length != IpV4AddressPartsCount)
{
return false;
}
foreach (var part in parts)
{
byte result;
if (!byte.TryParse(part, out result))
{
return false;
}
}
return true;
}
#pragma warning disable CA1055 // Uri return values should not be strings
/// <summary>
/// Given a string the function will perform uri percent-encoding
/// </summary>
public static string UriEncode(string value)
#pragma warning restore CA1055 // Uri return values should not be strings
{
return AWSSDKUtils.UrlEncode(value, false);
}
private static string[] SupportedSchemas = new string[] { "http", "https", "wss" };
/// <summary>
/// Parses url string into URL object.
/// Given a string the function will attempt to parse the string into it’s URL components.
/// If the string can not be parsed into a valid URL then the function will return a null.
/// If the URL given contains a query portion, the URL MUST be rejected and the function MUST return null.
/// We only support "http" and "https" schemas at the moment.
/// </summary>
public static URL ParseURL(string url)
{
Uri uri;
Uri.TryCreate(url, UriKind.Absolute, out uri);
if (uri == null || uri.Query?.Length > 0 || !SupportedSchemas.Contains(uri.Scheme))
{
return null;
}
var result = new URL
{
scheme = uri.Scheme,
authority = uri.Authority,
path = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped)
};
if (result.path.Length > 0)
{
result.path = "/" + result.path;
}
result.normalizedPath = uri.PathAndQuery;
if (result.normalizedPath.Length > 1)
{
result.normalizedPath += "/";
}
var hostNameType = Uri.CheckHostName(uri.Host);
result.isIp = hostNameType == UriHostNameType.IPv4 || hostNameType == UriHostNameType.IPv6;
return result;
}
/// <summary>
/// Interpolate template placeholders with values from "refs" dictionary.
///
/// e.g. Template "My url scheme is {url#scheme} for {region}",
/// where "url" and "region" are keys in refs dictionary and "scheme" is property of object refs["url"].
/// Uses GetAttr() to resolve {} placeholders, i.e. {object#prop1.prop2[3]} -> GetAttr(refs["object"], "prop1.prop2[3]").
/// {{ and }} are considered as escape sequences to allow rule authors to output a literal { and } respectively.
/// Throws ArgumentException if template is not well formed.
/// </summary>
public static string Interpolate(string template, Dictionary<string, object> refs)
{
const char OpenBracket = '{';
const char CloseBracket = '}';
var result = new StringBuilder();
for (int i = 0; i < template.Length; i++)
{
var currentChar = template[i];
char nextChar = (i < template.Length - 1) ? template[i + 1] : default(char);
// translate {{ -> { and }} -> }
if (currentChar == OpenBracket && nextChar == OpenBracket)
{
result.Append(OpenBracket);
i++;
continue;
}
if (currentChar == CloseBracket && nextChar == CloseBracket)
{
result.Append(CloseBracket);
i++;
continue;
}
// translate {object#path} -> value
if (currentChar == OpenBracket)
{
var placeholder = new StringBuilder();
while (i < template.Length - 1 && template[i + 1] != CloseBracket)
{
i++;
placeholder.Append(template[i]);
}
if (i == template.Length - 1)
{
throw new ArgumentException("template is missing closing }");
}
i++;
var refParts = placeholder.ToString().Split('#');
var refName = refParts[0];
if (refParts.Length > 1) // has path after #
{
result.Append(GetAttr(refs[refName], refParts[1]).ToString());
}
else
{
result.Append(refs[refName].ToString());
}
}
else if (currentChar == CloseBracket)
{
throw new ArgumentException("template has non-matching closing bracket, use }} to output }");
}
else
{
result.Append(currentChar);
}
}
return result.ToString();
}
/// <summary>
/// Interpolate all templates in all string nodes for given json
/// </summary>
public static string InterpolateJson(string json, Dictionary<string, object> refs)
{
var jsonObject = JsonMapper.ToObject(json);
InterpolateJson(jsonObject, refs);
return jsonObject.ToJson();
}
private static void InterpolateJson(JsonData json, Dictionary<string, object> refs)
{
if (json.IsString)
{
var jsonWrapper = (IJsonWrapper)json;
jsonWrapper.SetString(Interpolate(jsonWrapper.GetString(), refs));
}
if (json.IsObject)
{
foreach (var key in json.PropertyNames)
{
InterpolateJson(json[key], refs);
}
}
if (json.IsArray)
{
foreach (JsonData item in json)
{
InterpolateJson(item, refs);
}
}
}
/// <summary>
/// Computes the substring of a given string, conditionally indexing from the end of the string.
/// When the string is long enough to fully include the substring, return the substring.
/// Otherwise, return null. The start index is inclusive and the stop index is exclusive.
/// The length of the returned string will always be stop-start.
/// Substring MUST return null when the input contains non-ascii (>127) characters.
/// </summary>
public static string Substring(string input, int start, int stop, bool reverse)
{
var str = (string)input;
if (start >= stop || str.Length < stop)
{
return null;
}
if (str.Any(c => c > 127))
{
return null;
}
if (!reverse)
{
return str.Substring(start, stop - start);
}
var r_start = str.Length - stop;
var r_stop = str.Length - start;
return str.Substring(r_start, r_stop - r_start);
}
}
}
| 425 |
aws-sdk-net | aws | C# | /*
* 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.Endpoints;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Internal implementation of partition related data.
/// Used by standard library functions to access partition related data.
/// </summary>
public partial class Partition : PropertyBag
{
/// <summary>
/// Partition Name
/// </summary>
public string name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
/// <summary>
/// Partition DNS suffix
/// </summary>
public string dnsSuffix
{
get { return (string)this["dnsSuffix"]; }
set { this["dnsSuffix"] = value; }
}
/// <summary>
/// Partition IPv6 DNS suffix
/// </summary>
public string dualStackDnsSuffix
{
get { return (string)this["dualStackDnsSuffix"]; }
set { this["dualStackDnsSuffix"] = value; }
}
/// <summary>
/// Partition supports FIPS
/// </summary>
public bool supportsFIPS
{
get { return (bool)this["supportsFIPS"]; }
set { this["supportsFIPS"] = value; }
}
/// <summary>
/// Partition supports IPv6
/// </summary>
public bool supportsDualStack
{
get { return (bool)this["supportsDualStack"]; }
set { this["supportsDualStack"] = value; }
}
/// <summary>
/// Builds Partition from PartitionAttributesShape
/// </summary>
internal static Partition FromPartitionData(PartitionAttributesShape data)
{
return new Partition
{
name = data.name,
dnsSuffix = data.dnsSuffix,
dualStackDnsSuffix = data.dualStackDnsSuffix,
supportsFIPS = data.supportsFIPS,
supportsDualStack = data.supportsDualStack
};
}
private static readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();
private static Dictionary<string, PartitionAttributesShape> _partitionsByRegionName = new Dictionary<string, PartitionAttributesShape>();
private static Dictionary<string, PartitionAttributesShape> _partitionsByRegex = new Dictionary<string, PartitionAttributesShape>();
private static PartitionAttributesShape _defaultPartition;
/// <summary>
/// Override partitions data from json file
/// </summary>
public static void LoadPartitions(string partitionsFile)
{
if (!File.Exists(partitionsFile))
{
throw new AmazonClientException($"Can't find partitions file: {partitionsFile}");
}
_locker.EnterWriteLock();
try
{
var json = File.ReadAllText(partitionsFile);
var partitions = JsonMapper.ToObject<PartitionFunctionShape>(json);
_partitionsByRegionName.Clear();
_partitionsByRegex.Clear();
_defaultPartition = null;
foreach (var partition in partitions.partitions)
{
if (partition.id == "aws")
{
_defaultPartition = partition.outputs;
}
_partitionsByRegex.Add(partition.regionRegex, partition.outputs);
foreach (var region in partition.regions.Keys)
{
_partitionsByRegionName.Add(region, partition.outputs);
}
}
}
finally
{
_locker.ExitWriteLock();
}
}
internal static Partition GetPartitionByRegion(string region)
{
_locker.EnterReadLock();
try
{
PartitionAttributesShape partition;
// direct match
if (_partitionsByRegionName.TryGetValue(region, out partition))
{
return FromPartitionData(partition);
}
// regex match
foreach (var regex in _partitionsByRegex.Keys)
{
if (Regex.IsMatch(region, regex))
{
return FromPartitionData(_partitionsByRegex[regex]);
}
}
return FromPartitionData(_defaultPartition);
}
finally
{
_locker.ExitReadLock();
}
}
}
}
| 159 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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
*
*/
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Generated implementation of partition-specific data.
/// Based on the data from partitions.json
/// </summary>
public partial class Partition
{
static Partition()
{
var aws = new PartitionAttributesShape
{
name = "aws",
dnsSuffix = "amazonaws.com",
dualStackDnsSuffix = "api.aws",
supportsFIPS = true,
supportsDualStack = true
};
_partitionsByRegex.Add(@"^(us|eu|ap|sa|ca|me|af)\-\w+\-\d+$", aws);
_partitionsByRegionName.Add("af-south-1", aws);
_partitionsByRegionName.Add("ap-east-1", aws);
_partitionsByRegionName.Add("ap-northeast-1", aws);
_partitionsByRegionName.Add("ap-northeast-2", aws);
_partitionsByRegionName.Add("ap-northeast-3", aws);
_partitionsByRegionName.Add("ap-south-1", aws);
_partitionsByRegionName.Add("ap-south-2", aws);
_partitionsByRegionName.Add("ap-southeast-1", aws);
_partitionsByRegionName.Add("ap-southeast-2", aws);
_partitionsByRegionName.Add("ap-southeast-3", aws);
_partitionsByRegionName.Add("ap-southeast-4", aws);
_partitionsByRegionName.Add("aws-global", aws);
_partitionsByRegionName.Add("ca-central-1", aws);
_partitionsByRegionName.Add("eu-central-1", aws);
_partitionsByRegionName.Add("eu-central-2", aws);
_partitionsByRegionName.Add("eu-north-1", aws);
_partitionsByRegionName.Add("eu-south-1", aws);
_partitionsByRegionName.Add("eu-south-2", aws);
_partitionsByRegionName.Add("eu-west-1", aws);
_partitionsByRegionName.Add("eu-west-2", aws);
_partitionsByRegionName.Add("eu-west-3", aws);
_partitionsByRegionName.Add("me-central-1", aws);
_partitionsByRegionName.Add("me-south-1", aws);
_partitionsByRegionName.Add("sa-east-1", aws);
_partitionsByRegionName.Add("us-east-1", aws);
_partitionsByRegionName.Add("us-east-2", aws);
_partitionsByRegionName.Add("us-west-1", aws);
_partitionsByRegionName.Add("us-west-2", aws);
var aws_cn = new PartitionAttributesShape
{
name = "aws-cn",
dnsSuffix = "amazonaws.com.cn",
dualStackDnsSuffix = "api.amazonwebservices.com.cn",
supportsFIPS = true,
supportsDualStack = true
};
_partitionsByRegex.Add(@"^cn\-\w+\-\d+$", aws_cn);
_partitionsByRegionName.Add("aws-cn-global", aws_cn);
_partitionsByRegionName.Add("cn-north-1", aws_cn);
_partitionsByRegionName.Add("cn-northwest-1", aws_cn);
var aws_us_gov = new PartitionAttributesShape
{
name = "aws-us-gov",
dnsSuffix = "amazonaws.com",
dualStackDnsSuffix = "api.aws",
supportsFIPS = true,
supportsDualStack = true
};
_partitionsByRegex.Add(@"^us\-gov\-\w+\-\d+$", aws_us_gov);
_partitionsByRegionName.Add("aws-us-gov-global", aws_us_gov);
_partitionsByRegionName.Add("us-gov-east-1", aws_us_gov);
_partitionsByRegionName.Add("us-gov-west-1", aws_us_gov);
var aws_iso = new PartitionAttributesShape
{
name = "aws-iso",
dnsSuffix = "c2s.ic.gov",
dualStackDnsSuffix = "c2s.ic.gov",
supportsFIPS = true,
supportsDualStack = false
};
_partitionsByRegex.Add(@"^us\-iso\-\w+\-\d+$", aws_iso);
_partitionsByRegionName.Add("aws-iso-global", aws_iso);
_partitionsByRegionName.Add("us-iso-east-1", aws_iso);
_partitionsByRegionName.Add("us-iso-west-1", aws_iso);
var aws_iso_b = new PartitionAttributesShape
{
name = "aws-iso-b",
dnsSuffix = "sc2s.sgov.gov",
dualStackDnsSuffix = "sc2s.sgov.gov",
supportsFIPS = true,
supportsDualStack = false
};
_partitionsByRegex.Add(@"^us\-isob\-\w+\-\d+$", aws_iso_b);
_partitionsByRegionName.Add("aws-iso-b-global", aws_iso_b);
_partitionsByRegionName.Add("us-isob-east-1", aws_iso_b);
var aws_iso_e = new PartitionAttributesShape
{
name = "aws-iso-e",
dnsSuffix = "cloud.adc-e.uk",
dualStackDnsSuffix = "cloud.adc-e.uk",
supportsFIPS = true,
supportsDualStack = false
};
_partitionsByRegex.Add(@"^eu\-isoe\-\w+\-\d+$", aws_iso_e);
var aws_iso_f = new PartitionAttributesShape
{
name = "aws-iso-f",
dnsSuffix = "csp.hci.ic.gov",
dualStackDnsSuffix = "csp.hci.ic.gov",
supportsFIPS = true,
supportsDualStack = false
};
_partitionsByRegex.Add(@"^us\-isof\-\w+\-\d+$", aws_iso_f);
_defaultPartition = aws;
}
}
} | 143 |
aws-sdk-net | aws | C# | /*
* 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.
*/
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Object model for json partition data.
/// </summary>
public class PartitionAttributesShape
{
public string name { get; set; }
public string dnsSuffix { get; set; }
public string dualStackDnsSuffix { get; set; }
public bool supportsFIPS { get; set; }
public bool supportsDualStack { get; set; }
}
} | 28 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Object model for json partition function data.
/// </summary>
public class PartitionFunctionShape
{
public string version { get; set; }
public List<PartitionShape> partitions { get; set; }
}
}
| 28 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Object model for json partition.
/// </summary>
public class PartitionShape
{
public string id { get; set; }
public string regionRegex { get; set; }
public Dictionary<string, JsonData> regions { get; set; }
public PartitionAttributesShape outputs { get; set; }
}
} | 30 |
aws-sdk-net | aws | C# | /*
* 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.Endpoints;
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Internal implementation of URL.
/// Used by standard library functions to parse and validate URLs.
/// </summary>
public class URL : PropertyBag
{
/// <summary>
/// URL scheme
/// </summary>
public string scheme
{
get { return (string)this["scheme"]; }
set { this["scheme"] = value; }
}
/// <summary>
/// URL authority
/// </summary>
public string authority
{
get { return (string)this["authority"]; }
set { this["authority"] = value; }
}
/// <summary>
/// URL path
/// </summary>
public string path
{
get { return (string)this["path"]; }
set { this["path"] = value; }
}
/// <summary>
/// URL normalized path
/// </summary>
public string normalizedPath
{
get { return (string)this["normalizedPath"]; }
set { this["normalizedPath"] = value; }
}
/// <summary>
/// URL is IP address
/// </summary>
public bool isIp
{
get { return (bool)this["isIp"]; }
set { this["isIp"] = value; }
}
}
}
| 71 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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.Internal.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Settings
{
public interface IPersistenceManager
{
SettingsCollection GetSettings(string type);
void SaveSettings(string type, SettingsCollection settings);
}
public class InMemoryPersistenceManager: IPersistenceManager
{
private readonly Dictionary<string, SettingsCollection> _settingsDictionary = new Dictionary<string, SettingsCollection>();
public SettingsCollection GetSettings(string type)
{
if (_settingsDictionary.ContainsKey(type))
return _settingsDictionary[type];
return new SettingsCollection();
}
public void SaveSettings(string type, SettingsCollection settings)
{
_settingsDictionary[type] = settings;
}
}
public class PersistenceManager: IPersistenceManager
{
#region Private members
static readonly HashSet<string> ENCRYPTEDKEYS = new HashSet<string>
{
SettingsConstants.AccessKeyField,
SettingsConstants.SecretKeyField,
SettingsConstants.SessionTokenField,
SettingsConstants.ExternalIDField,
SettingsConstants.MfaSerialField,
SettingsConstants.SecretKeyRepository,
SettingsConstants.EC2InstanceUserName,
SettingsConstants.EC2InstancePassword,
SettingsConstants.ProxyUsernameEncrypted,
SettingsConstants.ProxyPasswordEncrypted,
SettingsConstants.UserIdentityField,
SettingsConstants.RoleSession
};
static readonly Logger _logger;
readonly Dictionary<string, SettingsWatcher> _watchers = new Dictionary<string, SettingsWatcher>();
// static but not readonly - allows for unit testing
static string SettingsStoreFolder = null;
#endregion
#region Constructor
static PersistenceManager()
{
_logger = Logger.GetLogger(typeof(PersistenceManager));
try
{
#if BCL
SettingsStoreFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) + "/AWSToolkit";
#else
SettingsStoreFolder = System.Environment.GetEnvironmentVariable("HOME");
if (string.IsNullOrEmpty(SettingsStoreFolder))
SettingsStoreFolder = System.Environment.GetEnvironmentVariable("USERPROFILE");
SettingsStoreFolder = Path.Combine(SettingsStoreFolder, "AppData/Local/AWSToolkit");
#endif
if (!Directory.Exists(SettingsStoreFolder))
Directory.CreateDirectory(SettingsStoreFolder);
Instance = new PersistenceManager();
}
catch (UnauthorizedAccessException ex)
{
_logger.Error(ex, $"Unable to initialize '{nameof(PersistenceManager)}'. Falling back to '{nameof(InMemoryPersistenceManager)}'.");
Instance = new InMemoryPersistenceManager();
}
}
#endregion
#region Public methods
public static IPersistenceManager Instance { get; set; }
public SettingsCollection GetSettings(string type)
{
return loadSettingsType(type);
}
public void SaveSettings(string type, SettingsCollection settings)
{
saveSettingsType(type, settings);
}
public string GetSetting(string key)
{
var sc = GetSettings(SettingsConstants.MiscSettings);
var oc = sc[SettingsConstants.MiscSettings];
var value = oc[key];
return value;
}
public void SetSetting(string key, string value)
{
var sc = GetSettings(SettingsConstants.MiscSettings);
var oc = sc[SettingsConstants.MiscSettings];
oc[key] = value;
SaveSettings(SettingsConstants.MiscSettings, sc);
}
public static string GetSettingsStoreFolder()
{
return SettingsStoreFolder;
}
public SettingsWatcher Watch(string type)
{
SettingsWatcher sw = new SettingsWatcher(getFileFromType(type), type);
this._watchers[type] = sw;
return sw;
}
void enableWatcher(string type)
{
SettingsWatcher sw = null;
if (this._watchers.TryGetValue(type, out sw))
{
sw.Enable = true;
}
}
void disableWatcher(string type)
{
SettingsWatcher sw = null;
if (this._watchers.TryGetValue(type, out sw))
{
sw.Enable = false;
}
}
internal static bool IsEncrypted(string key)
{
return ENCRYPTEDKEYS.Contains(key);
}
#endregion
#region Private methods
void saveSettingsType(string type, SettingsCollection settings)
{
this.disableWatcher(type);
try
{
var filePath = getFileFromType(type);
if (settings == null || settings.Count == 0)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
return;
}
// Cover the case where the file still has a lock on it from a previous IO access and needs time to let go.
var retryAttempt = 0;
while(true)
{
try
{
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(stream))
{
settings.Persist(writer);
break;
}
}
catch (Exception)
{
if (retryAttempt < 5)
{
Thread.Sleep(1000);
retryAttempt++;
}
else
throw;
}
}
}
finally
{
this.enableWatcher(type);
}
}
SettingsCollection loadSettingsType(string type)
{
var filePath = getFileFromType(type);
if(!File.Exists(filePath))
{
return new SettingsCollection();
}
// cover case where SDK in another process might be writing to settings file,
// yielding IO contention exceptons
var retryAttempt = 0;
while (true)
{
try
{
string content;
using (var stream = File.OpenRead(filePath))
using (var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
var settings = JsonMapper.ToObject<Dictionary<string, Dictionary<string, object>>>(content);
if (settings == null)
settings = new Dictionary<string, Dictionary<string, object>>();
DecryptAnyEncryptedValues(settings);
return new SettingsCollection(settings);
}
catch
{
if (retryAttempt < 5)
{
Thread.Sleep(1000);
retryAttempt++;
}
else
return new SettingsCollection(); // give up
}
}
}
static void DecryptAnyEncryptedValues(Dictionary<string, Dictionary<string, object>> settings)
{
foreach (var kvp in settings)
{
string settingsKey = kvp.Key;
var objectCollection = kvp.Value;
foreach (string key in new List<string>(objectCollection.Keys))
{
if (IsEncrypted(key) || IsEncrypted(settingsKey))
{
string value = objectCollection[key] as string;
if (value != null)
{
try
{
objectCollection[key] = UserCrypto.Decrypt(value);
}
catch (Exception e)
{
objectCollection.Remove(key);
var logger = Logger.GetLogger(typeof(PersistenceManager));
logger.Error(e, "Exception decrypting value for key {0}/{1}", settingsKey, key);
}
}
}
}
}
}
private static string getFileFromType(string type)
{
return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}.json", GetSettingsStoreFolder(), type);
}
#endregion
}
public class SettingsWatcher : IDisposable
{
#region Private members
#if BCL
private static ICollection<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
private FileSystemWatcher watcher;
#endif
private string type;
#endregion
#region Constructors
private SettingsWatcher()
{
throw new NotSupportedException();
}
internal SettingsWatcher(string filePath, string type)
{
string dirPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
this.type = type;
#if BCL
this.watcher = new FileSystemWatcher(dirPath, fileName)
{
EnableRaisingEvents = true
};
this.watcher.Changed += new FileSystemEventHandler(SettingsFileChanged);
this.watcher.Created += new FileSystemEventHandler(SettingsFileChanged);
watchers.Add(watcher);
#endif
}
#endregion
#region Public methods
public SettingsCollection GetSettings()
{
return PersistenceManager.Instance.GetSettings(this.type);
}
public bool Enable
{
#if BCL
get { return this.watcher.EnableRaisingEvents; }
set { this.watcher.EnableRaisingEvents = value; }
#else
get; set;
#endif
}
#endregion
#region Events
public event EventHandler SettingsChanged;
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
#if BCL
if (watcher != null)
{
watchers.Remove(watcher);
watcher = null;
}
#endif
}
}
#endregion
#region Private methods
#if BCL
private void SettingsFileChanged(object sender, FileSystemEventArgs e)
{
if (SettingsChanged != null)
SettingsChanged(this, null);
}
#endif
#endregion
}
}
| 424 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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.IO;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Settings
{
public class SettingsCollection : IEnumerable<SettingsCollection.ObjectSettings>
{
Dictionary<string, Dictionary<string, object>> _values;
public SettingsCollection()
{
this._values = new Dictionary<string, Dictionary<string, object>>();
this.InitializedEmpty = true;
}
public SettingsCollection(Dictionary<string, Dictionary<string, object>> values)
{
this._values = values;
this.InitializedEmpty = false;
}
public int Count
{
get { return this._values.Count; }
}
public bool InitializedEmpty { get; private set; }
internal void Persist(StreamWriter writer)
{
JsonWriter jsonWriter = new JsonWriter();
jsonWriter.PrettyPrint = true;
jsonWriter.WriteObjectStart();
foreach (var key in this._values.Keys)
{
ObjectSettings os = this[key];
jsonWriter.WritePropertyName(key);
os.WriteToJson(jsonWriter);
}
jsonWriter.WriteObjectEnd();
string content = jsonWriter.ToString();
writer.Write(content);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<SettingsCollection.ObjectSettings> GetEnumerator()
{
foreach (var key in this._values.Keys)
{
ObjectSettings os = this[key];
yield return os;
}
}
public ObjectSettings this[string key]
{
get
{
Dictionary<string, object> values;
if (!this._values.TryGetValue(key, out values))
{
return NewObjectSettings(key);
}
return new ObjectSettings(key, values);
}
}
public ObjectSettings NewObjectSettings()
{
string uniqueKey = Guid.NewGuid().ToString();
return NewObjectSettings(uniqueKey);
}
public ObjectSettings NewObjectSettings(string uniqueKey)
{
Dictionary<string, object> backStore = new Dictionary<string, object>();
ObjectSettings settings = new ObjectSettings(uniqueKey, backStore);
this._values[uniqueKey] = backStore;
return settings;
}
public void Remove(string uniqueKey)
{
this._values.Remove(uniqueKey);
}
public void Clear()
{
this._values.Clear();
}
public class ObjectSettings
{
string _uniqueKey;
Dictionary<string, object> _values;
internal ObjectSettings(string uniqueKey, Dictionary<string, object> values)
{
this._uniqueKey = uniqueKey;
this._values = values;
}
public string UniqueKey
{
get { return this._uniqueKey; }
}
public string this[string key]
{
get
{
object o;
this._values.TryGetValue(key, out o);
return o as string;
}
set { this._values[key] = value; }
}
public string GetValueOrDefault(string key, string defaultValue)
{
var value = this[key];
if (value == null)
return defaultValue;
return value;
}
public void Remove(string key)
{
this._values.Remove(key);
}
public void Clear()
{
this._values.Clear();
}
public bool IsEmpty
{
get { return this._values == null || this._values.Count == 0; }
}
public IEnumerable<string> Keys
{
get
{
Dictionary<string, object>.KeyCollection keys = this._values.Keys;
string[] k = new string[keys.Count];
this._values.Keys.CopyTo(k,0);
return k;
}
}
internal void WriteToJson(JsonWriter writer)
{
writer.WriteObjectStart();
foreach (var kvp in this._values)
{
string value = kvp.Value as string;
if (value == null)
continue;
writer.WritePropertyName(kvp.Key);
if (PersistenceManager.IsEncrypted(kvp.Key) || PersistenceManager.IsEncrypted(this._uniqueKey))
value = UserCrypto.Encrypt(value);
writer.Write(value);
}
writer.WriteObjectEnd();
}
}
}
}
| 202 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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
*/
namespace Amazon.Runtime.Internal.Settings
{
public static class SettingsConstants
{
public const string UserPreferences = "UserPreferences";
public const string MiscSettings = "MiscSettings";
public const string RegisteredProfiles = "RegisteredAccounts";
public const string RegisteredSAMLEndpoints = "SAMLEndpoints";
public const string RegisteredRoleSessions = "RoleSessions";
public const string RecentUsages = "RecentUsages";
public const string ProfileTypeField = "ProfileType";
public const string DisplayNameField = "DisplayName";
public const string AccountNumberField = "AccountNumber";
public const string Restrictions = "Restrictions";
// present in profiles for AWS credentials
// some keys are used for multiple types of profiles
public const string AccessKeyField = "AWSAccessKey";
public const string SecretKeyField = "AWSSecretKey";
public const string SessionTokenField = "SessionToken";
public const string ExternalIDField = "ExternalId";
public const string MfaSerialField = "MfaSerial";
public const string EndpointNameField = "EndpointName";
public const string RoleArnField = "RoleArn";
public const string RoleSessionName = "RoleSessionName";
public const string UserIdentityField = "UserIdentity";
public const string Region = "Region";
public const string AuthenticationTypeField = "AuthenticationType";
public const string SourceProfileField = "SourceProfile";
public const string CredentialSourceField = "CredentialSource";
public const string CredentialProcess = "credential_process";
public const string WebIdentityTokenFile = "WebIdentityTokenFile";
// present in endpoint definitions in SAMLEndpoints.json file
public const string EndpointField = "Endpoint";
// session data for a role profile, persisted in RoleSessions.json file.
public const string RoleSession = "RoleSession";
public const string SecretKeyRepository = "SecretKeyRepository";
public const string LastAcountSelectedKey = "LastAcountSelectedKey";
public const string VersionCheck = "VersionCheck";
public const string LastVersionDoNotRemindMe = "LastVersionDoNotRemindMe";
public const string HostedFilesLocation = "HostedFilesLocation";
public const string EC2ConnectSettings = "EC2ConnectSettings";
public const string EC2InstanceUseKeyPair = "EC2RDPUseKeyPair";
public const string EC2InstanceMapDrives = "EC2RDPMapDrives";
public const string EC2InstanceSaveCredentials = "EC2InstanceSaveCredentials";
public const string EC2InstanceUserName = "EC2InstanceUserName";
public const string EC2InstancePassword = "EC2InstancePassword";
public const string ProxySettings = "ProxySettings";
public const string ProxyHost = "ProxyHost";
public const string ProxyPort = "ProxyPort";
public const string ProxyUsernameObsolete = "ProxyUsername";
public const string ProxyPasswordObsolete = "ProxyPassword";
public const string ProxyUsernameEncrypted = "ProxyUsernameEncrypted";
public const string ProxyPasswordEncrypted = "ProxyPasswordEncrypted";
}
}
| 94 |
aws-sdk-net | aws | C# | /*******************************************************************************
* 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.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal.Settings
{
public static class UserCrypto
{
public static string Decrypt(string encrypted)
{
List<Byte> dataIn = new List<byte>();
for (int i = 0; i < encrypted.Length; i = i + 2)
{
byte data = Convert.ToByte(encrypted.Substring(i, 2), 16);
dataIn.Add(data);
}
CryptProtectFlags flags = CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN;
DATA_BLOB encryptedBlob = ConvertData(dataIn.ToArray());
DATA_BLOB unencryptedBlob = new DATA_BLOB();
DATA_BLOB dataOption = new DATA_BLOB();
try
{
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
if (!CryptUnprotectData(ref encryptedBlob, "psw", ref dataOption, IntPtr.Zero, ref prompt, flags, ref unencryptedBlob))
{
int errCode = Marshal.GetLastWin32Error();
throw new AmazonClientException("CryptProtectData failed. Error Code: " + errCode);
}
byte[] outData = new byte[unencryptedBlob.cbData];
Marshal.Copy(unencryptedBlob.pbData, outData, 0, outData.Length);
string unencrypted = Encoding.Unicode.GetString(outData);
return unencrypted;
}
finally
{
if (encryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(encryptedBlob.pbData);
if (unencryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(unencryptedBlob.pbData);
}
}
public static string Encrypt(string unencrypted)
{
CryptProtectFlags flags = CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN;
DATA_BLOB unencryptedBlob = ConvertData(Encoding.Unicode.GetBytes(unencrypted));
DATA_BLOB encryptedBlob = new DATA_BLOB();
DATA_BLOB dataOption = new DATA_BLOB();
try
{
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
if (!CryptProtectData(ref unencryptedBlob, "psw", ref dataOption, IntPtr.Zero, ref prompt, flags, ref encryptedBlob))
{
int errCode = Marshal.GetLastWin32Error();
throw new AmazonClientException("CryptProtectData failed. Error Code: " + errCode);
}
byte[] outData = new byte[encryptedBlob.cbData];
Marshal.Copy(encryptedBlob.pbData, outData, 0, outData.Length);
StringBuilder encrypted = new StringBuilder();
for (int i = 0; i <= outData.Length - 1; i++)
{
encrypted.Append(
Convert.ToString(outData[i], 16).PadLeft(2, '0').ToUpper(CultureInfo.InvariantCulture));
}
string encryptedPassword = encrypted.ToString().ToUpper(CultureInfo.InvariantCulture);
return encryptedPassword;
}
finally
{
if (unencryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(unencryptedBlob.pbData);
if (encryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(encryptedBlob.pbData);
}
}
static DATA_BLOB ConvertData(byte[] data)
{
DATA_BLOB blob = new DATA_BLOB();
blob.pbData = Marshal.AllocHGlobal(data.Length);
blob.cbData = data.Length;
Marshal.Copy(data, 0, blob.pbData, data.Length);
return blob;
}
#region PInvoke Declarations
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DATA_BLOB
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct CRYPTPROTECT_PROMPTSTRUCT
{
public int cbSize;
public CryptProtectPromptFlags dwPromptFlags;
public IntPtr hwndApp;
public String szPrompt;
}
[Flags]
private enum CryptProtectPromptFlags
{
// prompt on unprotect
CRYPTPROTECT_PROMPT_ON_UNPROTECT = 0x1,
// prompt on protect
CRYPTPROTECT_PROMPT_ON_PROTECT = 0x2
}
[Flags]
private enum CryptProtectFlags
{
// for remote-access situations where ui is not an option
// if UI was specified on protect or unprotect operation, the call
// will fail and GetLastError() will indicate ERROR_PASSWORD_RESTRICTION
CRYPTPROTECT_UI_FORBIDDEN = 0x1,
// per machine protected data -- any user on machine where CryptProtectData
// took place may CryptUnprotectData
CRYPTPROTECT_LOCAL_MACHINE = 0x4,
// force credential synchronize during CryptProtectData()
// Synchronize is only operation that occurs during this operation
CRYPTPROTECT_CRED_SYNC = 0x8,
// Generate an Audit on protect and unprotect operations
CRYPTPROTECT_AUDIT = 0x10,
// Protect data with a non-recoverable key
CRYPTPROTECT_NO_RECOVERY = 0x20,
// Verify the protection of a protected blob
CRYPTPROTECT_VERIFY_PROTECTION = 0x40
}
[DllImport("Crypt32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CryptProtectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct,
CryptProtectFlags dwFlags,
ref DATA_BLOB pDataOut
);
[DllImport("Crypt32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CryptUnprotectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct,
CryptProtectFlags dwFlags,
ref DATA_BLOB pDataOut
);
static bool? _isUserCryptAvailable;
public static bool IsUserCryptAvailable
{
get
{
if(!_isUserCryptAvailable.HasValue)
{
try
{
Encrypt("test");
_isUserCryptAvailable = true;
}
catch(Exception e)
{
var logger = Logger.GetLogger(typeof(UserCrypto));
logger.InfoFormat("UserCrypto is not supported. This may be due to use of a non-Windows operating system or Windows Nano Server, or the current user account may not have its profile loaded. {0}", e.Message);
_isUserCryptAvailable = false;
}
}
return _isUserCryptAvailable.Value;
}
}
#endregion
}
}
| 228 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.Runtime.Internal.Transform
{
public static class CustomMarshallTransformations
{
public static long ConvertDateTimeToEpochMilliseconds(DateTime dateTime)
{
TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - Amazon.Util.AWSSDKUtils.EPOCH_START.Ticks);
return (long)ts.TotalMilliseconds;
}
}
}
| 17 |
aws-sdk-net | aws | C# | /*
* 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 System;
using System.Xml;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// Response Unmarshaller for all Errors
/// </summary>
public class ErrorResponseUnmarshaller : IUnmarshaller<ErrorResponse, XmlUnmarshallerContext>
{
/// <summary>
/// Build an ErrorResponse from XML
/// </summary>
/// <param name="context">The XML parsing context.
/// Usually an <c>Amazon.Runtime.Internal.UnmarshallerContext</c>.</param>
/// <returns>An <c>ErrorResponse</c> object.</returns>
public ErrorResponse Unmarshall(XmlUnmarshallerContext context)
{
var response = new ErrorResponse()
{
// this default value will get overwritten if it's included in the XML
Type = ErrorType.Unknown
};
PopulateErrorResponseFromXmlIfPossible(context, response);
// if it wasn't possible to get a message from the XML then set a useful message here
if (string.IsNullOrEmpty(response.Message))
{
if (string.IsNullOrEmpty(response.Code))
{
if (string.IsNullOrEmpty(context.ResponseBody))
response.Message = "The service returned an error. See inner exception for details.";
else
response.Message = "The service returned an error with HTTP Body: " + context.ResponseBody;
}
else
{
response.Message = "The service returned an error with Error Code " + response.Code + " and HTTP Body: " + context.ResponseBody;
}
}
return response;
}
private static void PopulateErrorResponseFromXmlIfPossible(XmlUnmarshallerContext context, ErrorResponse response)
{
while (TryReadContext(context))
{
if (context.IsStartElement)
{
if (context.TestExpression("Error/Type"))
{
try
{
response.Type = (ErrorType)Enum.Parse(typeof(ErrorType), StringUnmarshaller.GetInstance().Unmarshall(context), true);
}
catch (ArgumentException)
{
response.Type = ErrorType.Unknown;
}
continue;
}
if (context.TestExpression("Error/Code"))
{
response.Code = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Error/Message"))
{
response.Message = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("RequestId"))
{
response.RequestId = StringUnmarshaller.GetInstance().Unmarshall(context);
}
}
}
}
private static bool TryReadContext(XmlUnmarshallerContext context)
{
try
{
return context.Read();
}
catch (XmlException)
{
return false;
}
}
private static ErrorResponseUnmarshaller instance;
/// <summary>
/// Return an instance of and ErrorResponseUnmarshaller.
/// </summary>
/// <returns></returns>
public static ErrorResponseUnmarshaller GetInstance()
{
if (instance == null)
instance = new ErrorResponseUnmarshaller();
return instance;
}
}
}
| 126 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
using Amazon.Util;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// Interface for unmarshallers which unmarshall objects from response data.
/// The Unmarshallers are stateless, and only encode the rules for what data
/// in the XML stream goes into what members of an object.
/// </summary>
/// <typeparam name="TUnmarshaller">The type of object the unmarshaller returns</typeparam>
/// <typeparam name="TUnmarshalleContext">The type of the XML unmashaller context, which contains the
/// state during parsing of the XML stream. Usually an instance of
/// <c>Amazon.Runtime.Internal.Transform.UnmarshallerContext</c>.</typeparam>
public interface IErrorResponseUnmarshaller<TUnmarshaller, TUnmarshalleContext> : IUnmarshaller<TUnmarshaller, TUnmarshalleContext>
{
/// <summary>
/// Given the current position in the XML stream, extract a T.
/// </summary>
/// <param name="input">The XML parsing context</param>
/// <returns>An object of type T populated with data from the XML stream.</returns>
TUnmarshaller Unmarshall(TUnmarshalleContext input, ErrorResponse errorResponse);
}
} | 44 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
namespace Amazon.Runtime.Internal.Transform
{
public interface IMarshaller<T, R>
{
T Marshall(R input);
}
}
| 26 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
using System.Xml;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Transform
{
public interface IRequestMarshaller<R, T>
where T : MarshallerContext
{
void Marshall(R requestObject, T context);
}
public abstract class MarshallerContext
{
public IRequest Request { get; private set; }
protected MarshallerContext(IRequest request)
{
Request = request;
}
}
public class XmlMarshallerContext : MarshallerContext
{
public XmlWriter Writer { get; private set; }
public XmlMarshallerContext(IRequest request, XmlWriter writer)
: base(request)
{
Writer = writer;
}
}
public class JsonMarshallerContext : MarshallerContext
{
public JsonWriter Writer { get; private set; }
public JsonMarshallerContext(IRequest request, JsonWriter writer)
: base(request)
{
Writer = writer;
}
}
}
| 61 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Net;
using System.Text;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// Interface for unmarshallers which unmarshall service responses.
/// The Unmarshallers are stateless, and only encode the rules for what data
/// in the XML stream goes into what members of an object.
/// </summary>
/// <typeparam name="T">The type of object the unmarshaller returns</typeparam>
/// <typeparam name="R">The type of the XML unmashaller context, which contains the
/// state of parsing the XML stream. Uaually an instance of
/// <c>Amazon.Runtime.Internal.Transform.UnmarshallerContext</c>.</typeparam>
public interface IResponseUnmarshaller<T, R> : IUnmarshaller<T, R>
{
/// <summary>
/// Extracts an exeption with data from an ErrorResponse.
/// </summary>
/// <param name="input">The XML parsing context.</param>
/// <param name="innerException">An inner exception to be included with the returned exception</param>
/// <param name="statusCode">The HttpStatusCode from the ErrorResponse</param>
/// <returns>Either an exception based on the ErrorCode from the ErrorResponse, or the
/// general service exception for the service in question.</returns>
AmazonServiceException UnmarshallException(R input, Exception innerException, HttpStatusCode statusCode);
}
}
| 45 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
using Amazon.Util;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// Interface for unmarshallers which unmarshall objects from response data.
/// The Unmarshallers are stateless, and only encode the rules for what data
/// in the XML stream goes into what members of an object.
/// </summary>
/// <typeparam name="T">The type of object the unmarshaller returns</typeparam>
/// <typeparam name="R">The type of the XML unmashaller context, which contains the
/// state during parsing of the XML stream. Usually an instance of
/// <c>Amazon.Runtime.Internal.Transform.UnmarshallerContext</c>.</typeparam>
public interface IUnmarshaller<T, R>
{
/// <summary>
/// Given the current position in the XML stream, extract a T.
/// </summary>
/// <param name="input">The XML parsing context</param>
/// <returns>An object of type T populated with data from the XML stream.</returns>
T Unmarshall(R input);
}
}
| 45 |
aws-sdk-net | aws | C# | /*
* 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace Amazon.Runtime.Internal.Transform
{
public interface IWebResponseData
{
long ContentLength { get; }
string ContentType { get; }
HttpStatusCode StatusCode { get; }
bool IsSuccessStatusCode { get; }
string[] GetHeaderNames();
bool IsHeaderPresent(string headerName);
string GetHeaderValue(string headerName);
IHttpResponseBody ResponseBody { get; }
}
public interface IHttpResponseBody : IDisposable
{
Stream OpenResponse();
#if AWS_ASYNC_API
System.Threading.Tasks.Task<Stream> OpenResponseAsync();
#endif
}
}
| 46 |
aws-sdk-net | aws | C# | /*
* 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 System;
using Amazon.Util;
using System.Xml;
using ThirdParty.Json.LitJson;
using System.Text;
using System.IO;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// First-pass unmarshaller for all errors
/// </summary>
public class JsonErrorResponseUnmarshaller : IUnmarshaller<ErrorResponse, JsonUnmarshallerContext>
{
/// <summary>
/// Build an ErrorResponse from json
/// </summary>
/// <param name="context">The json parsing context.
/// Usually an <c>Amazon.Runtime.Internal.JsonUnmarshallerContext</c>.</param>
/// <returns>An <c>ErrorResponse</c> object.</returns>
public ErrorResponse Unmarshall(JsonUnmarshallerContext context)
{
ErrorResponse response;
if (context.Peek() == 60) //starts with '<' so assuming XML.
{
ErrorResponseUnmarshaller xmlUnmarshaller = new ErrorResponseUnmarshaller();
using (var stream = new MemoryStream(context.GetResponseBodyBytes()))
{
XmlUnmarshallerContext xmlContext = new XmlUnmarshallerContext(stream, false, null);
response = xmlUnmarshaller.Unmarshall(xmlContext);
}
}
else
{
string type;
string message;
string code;
string requestId = null;
GetValuesFromJsonIfPossible(context, out type, out message, out code);
// If an error code was not found, check for the x-amzn-ErrorType header.
// This header is returned by rest-json services.
if (string.IsNullOrEmpty(type) &&
context.ResponseData.IsHeaderPresent(HeaderKeys.XAmzErrorType))
{
var errorType = context.ResponseData.GetHeaderValue(HeaderKeys.XAmzErrorType);
if (!string.IsNullOrEmpty(errorType))
{
// The error type can contain additional information, with ":" as a delimiter
// We are only interested in the initial part which is the error type
var index = errorType.IndexOf(":", StringComparison.Ordinal);
if(index != -1)
{
errorType = errorType.Substring(0, index);
}
type = errorType;
}
}
// Check for the x-amzn-error-message header. This header is returned by rest-json services.
// If the header is present it is preferred over any value provided in the response body.
if (context.ResponseData.IsHeaderPresent(HeaderKeys.XAmznErrorMessage))
{
var errorMessage = context.ResponseData.GetHeaderValue(HeaderKeys.XAmznErrorMessage);
if (!string.IsNullOrEmpty(errorMessage))
message = errorMessage;
}
// if both "__type" and HeaderKeys.XAmzErrorType were not specified, use "code" as type
// this impacts Glacier
if (string.IsNullOrEmpty(type) &&
!string.IsNullOrEmpty(code))
{
type = code;
}
// strip extra data from type, leaving only the exception type name
type = type == null ? null : type.Substring(type.LastIndexOf("#", StringComparison.Ordinal) + 1);
// if no message was found create a generic message
if (string.IsNullOrEmpty(message))
{
if (string.IsNullOrEmpty(type))
{
if (string.IsNullOrEmpty(context.ResponseBody))
message = "The service returned an error. See inner exception for details.";
else
message = "The service returned an error with HTTP Body: " + context.ResponseBody;
}
else
{
if (string.IsNullOrEmpty(context.ResponseBody))
message = "The service returned an error with Error Code " + type + ".";
else
message = "The service returned an error with Error Code " + type + " and HTTP Body: " + context.ResponseBody;
}
}
// Check for the x-amzn-RequestId header. This header is returned by rest-json services.
// If the header is present it is preferred over any value provided in the response body.
if (context.ResponseData.IsHeaderPresent(HeaderKeys.RequestIdHeader))
{
requestId = context.ResponseData.GetHeaderValue(HeaderKeys.RequestIdHeader);
}
response = new ErrorResponse
{
Code = type,
Message = message,
// type is not applicable to JSON services, setting to Unknown
Type = ErrorType.Unknown,
RequestId = requestId
};
}
return response;
}
private static void GetValuesFromJsonIfPossible(JsonUnmarshallerContext context, out string type, out string message, out string code)
{
code = null;
type = null;
message = null;
while (TryReadContext(context))
{
if (context.TestExpression("__type"))
{
type = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("message"))
{
message = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("code"))
{
code = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
}
}
private static bool TryReadContext(JsonUnmarshallerContext context)
{
try
{
return context.Read();
}
catch (JsonException)
{
return false;
}
}
private static JsonErrorResponseUnmarshaller instance;
/// <summary>
/// Return an instance of JsonErrorResponseUnmarshaller.
/// </summary>
/// <returns></returns>
public static JsonErrorResponseUnmarshaller GetInstance()
{
if (instance == null)
instance = new JsonErrorResponseUnmarshaller();
return instance;
}
}
}
| 189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.