protected static bool UseV4Signing(bool useSigV4Setting, IRequest request, IClientConfig config)
        {
            if (useSigV4Setting || request.UseSigV4 || config.SignatureVersion == "4")
            {
                return(true);
            }
            RegionEndpoint regionEndpoint = null;

            if (!string.IsNullOrEmpty(request.AuthenticationRegion))
            {
                regionEndpoint = RegionEndpoint.GetBySystemName(request.AuthenticationRegion);
            }
            if (regionEndpoint == null && !string.IsNullOrEmpty(config.ServiceURL))
            {
                string text = AWSSDKUtils.DetermineRegion(config.ServiceURL);
                if (!string.IsNullOrEmpty(text))
                {
                    regionEndpoint = RegionEndpoint.GetBySystemName(text);
                }
            }
            if (regionEndpoint == null && config.RegionEndpoint != null)
            {
                regionEndpoint = config.RegionEndpoint;
            }
            if (regionEndpoint != null)
            {
                RegionEndpoint.Endpoint endpointForService = regionEndpoint.GetEndpointForService(config.RegionEndpointServiceName, config.UseDualstackEndpoint);
                if (endpointForService != null && (endpointForService.SignatureVersionOverride == "4" || string.IsNullOrEmpty(endpointForService.SignatureVersionOverride)))
                {
                    return(true);
                }
            }
            return(false);
        }
        /// <summary>
        /// Generate a presigned URL based on a <see cref="SynthesizeSpeechRequest"/>.
        /// </summary>
        /// <param name="credentials">The credentials to use in the presigned URL.</param>
        /// <param name="region">The region for the URL.</param>
        /// <param name="request">The request to base the presigned URL on.</param>
        /// <returns></returns>
        public static string GeneratePresignedUrl(AWSCredentials credentials, RegionEndpoint region, SynthesizeSpeechRequest request)
        {
            if (credentials == null)
                throw new ArgumentNullException("credentials");

            if (region == null)
                throw new ArgumentNullException("region");

            if (request == null)
                throw new ArgumentNullException("request");

            // Marshall this request and prepare it to be signed
            var marshaller = new SynthesizeSpeechRequestMarshaller();
            var iRequest = marshaller.Marshall(request);
            iRequest.UseQueryString = true;
            iRequest.HttpMethod = HTTPGet;
            iRequest.Endpoint = new UriBuilder(HTTPS, region.GetEndpointForService(PollyServiceName).Hostname).Uri;
            iRequest.Parameters[XAmzExpires] = ((int)FifteenMinutes.TotalSeconds).ToString(CultureInfo.InvariantCulture);

            if (request.IsSetLexiconNames())
            {
                var sortedLexiconNames = new List<string>(request.LexiconNames);
                sortedLexiconNames.Sort(StringComparer.Ordinal);
                iRequest.Parameters[LexiconNamesParameter] = JsonMapper.ToJson(sortedLexiconNames);
            }

            if (request.IsSetOutputFormat())
                iRequest.Parameters["OutputFormat"] = request.OutputFormat.ToString();

            if (request.IsSetSampleRate())
                iRequest.Parameters["SampleRate"] = request.SampleRate.ToString();

            if (request.IsSetText())
                iRequest.Parameters["Text"] = request.Text;

            if (request.IsSetTextType())
                iRequest.Parameters["TextType"] = request.TextType.ToString();

            if (request.IsSetVoiceId())
                iRequest.Parameters["VoiceId"] = request.VoiceId;

            var immutableCredentials = credentials.GetCredentials();
            if (immutableCredentials.UseToken)
            {
                // Don't use HeaderKeys.XAmzSecurityTokenHeader because Polly treats this as case-sensitive
                iRequest.Parameters["X-Amz-Security-Token"] = immutableCredentials.Token;
            }

            // Only the host header should be signed, and the signer adds that.
            // So clear out headers.
            iRequest.Headers.Clear();

            // Create presigned URL and assign it
            var signingResult = SynthesizeSpeechPresignedUrlSigner.SignSynthesizeSpeechRequest(iRequest, new RequestMetrics(),
                immutableCredentials.AccessKey, immutableCredentials.SecretKey, PollyServiceName, region.SystemName);

            var authorization = "&" + signingResult.ForQueryParameters;

            return ComposeUrl(iRequest).AbsoluteUri + authorization;
        }
Exemple #3
0
 public AmazonS3Region(RegionEndpoint region)
 {
     Name         = region.DisplayName;
     Identifier   = region.SystemName;
     AmazonRegion = region;
     Hostname     = region.GetEndpointForService("s3").Hostname;
 }
        internal static string GetUrl(RegionEndpoint regionEndpoint, string regionEndpointServiceName, bool useHttp, bool useDualStack)
        {
            var    endpoint = regionEndpoint.GetEndpointForService(regionEndpointServiceName, useDualStack);
            string url      = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", useHttp ? "http://" : "https://", endpoint.Hostname)).AbsoluteUri;

            return(url);
        }
Exemple #5
0
        internal static string GetUrl(IClientConfig config, RegionEndpoint regionEndpoint)
        {
            var endpoint = regionEndpoint.GetEndpointForService(config);

            string url = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", config.UseHttp ? "http://" : "https://", endpoint.Hostname)).AbsoluteUri;

            return(url);
        }
Exemple #6
0
        /// <summary>
        /// Creates a <see cref="Uri"/> for a queue in the current account with name specified with <see cref="queueName"/>.
        /// </summary>
        /// <param name="queueName">The queue name.</param>
        /// <returns>The <see cref="Uri"/> for this queue.</returns>
        public Uri GetQueueUri(string queueName)
        {
            var hostname = _regionEndpoint.GetEndpointForService("sqs").Hostname;

            return(new UriBuilder("https", hostname)
            {
                Path = $"{_accountId}/{queueName}"
            }.Uri);
        }
        /// <summary>
        /// Inspects the supplied evidence to return the signer appropriate for the operation
        /// </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</returns>
        protected static bool UseV4Signing(bool useSigV4Setting, IRequest request, IClientConfig config)
        {
            if (request.UseSigV4 ||
                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.UseDualstackEndpoint);
                    if (endpoint != null && (endpoint.SignatureVersionOverride == "4" || string.IsNullOrEmpty(endpoint.SignatureVersionOverride)))
                    {
                        return(true);
                    }
                }

                return(false);
            }
        }
Exemple #8
0
        public static string DetermineSigningRegion(IClientConfig clientConfig, string serviceName, RegionEndpoint alternateEndpoint, IRequest request)
        {
            if (alternateEndpoint != null)
            {
                RegionEndpoint.Endpoint endpointForService = alternateEndpoint.GetEndpointForService(serviceName, clientConfig.UseDualstackEndpoint);
                if (endpointForService.AuthRegion != null)
                {
                    return(endpointForService.AuthRegion);
                }
                return(alternateEndpoint.SystemName);
            }
            string authenticationRegion = clientConfig.AuthenticationRegion;

            if (request != null && request.AuthenticationRegion != null)
            {
                authenticationRegion = request.AuthenticationRegion;
            }
            if (!string.IsNullOrEmpty(authenticationRegion))
            {
                return(authenticationRegion.ToLowerInvariant());
            }
            if (!string.IsNullOrEmpty(clientConfig.ServiceURL))
            {
                string text = AWSSDKUtils.DetermineRegion(clientConfig.ServiceURL);
                if (!string.IsNullOrEmpty(text))
                {
                    return(text.ToLowerInvariant());
                }
            }
            RegionEndpoint regionEndpoint = clientConfig.RegionEndpoint;

            if (regionEndpoint != null)
            {
                RegionEndpoint.Endpoint endpointForService2 = regionEndpoint.GetEndpointForService(serviceName, clientConfig.UseDualstackEndpoint);
                if (!string.IsNullOrEmpty(endpointForService2.AuthRegion))
                {
                    return(endpointForService2.AuthRegion);
                }
                return(regionEndpoint.SystemName);
            }
            return(string.Empty);
        }
        internal static string GetUrl(RegionEndpoint regionEndpoint, string regionEndpointServiceName, bool useHttp)
        {
            var  endpoint = regionEndpoint.GetEndpointForService(regionEndpointServiceName);
            bool shouldUseHttp;

            if (endpoint.HTTP && endpoint.HTTPS)    // if both are supported, go with user preference
            {
                shouldUseHttp = useHttp;
            }
            else if (endpoint.HTTPS)                // if HTTPS is supported, go with HTTPS
            {
                shouldUseHttp = false;
            }
            else                                    // if HTTP is supported, go with HTTP
            {
                shouldUseHttp = true;
            }

            string url = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", shouldUseHttp ? "http://" : "https://", endpoint.Hostname)).AbsoluteUri;

            return(url);
        }
Exemple #10
0
        /// <summary>
        /// Create a signed URL allowing access to a resource that would
        /// usually require authentication.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When using query string authentication you create a query,
        /// specify an expiration time for the query, sign it with your
        /// signature, place the data in an HTTP request, and distribute
        /// the request to a user or embed the request in a web page.
        /// </para>
        /// <para>
        /// A PreSigned URL can be generated for GET, PUT, DELETE and HEAD
        /// operations on your bucketName, keys, and versions.
        /// </para>
        /// </remarks>
        /// <param name="request">The GetPreSignedUrlRequest that defines the
        /// parameters of the operation.</param>
        /// <param name="useSigV2Fallback">determines if signing will fall back to SigV2 if the
        /// signing region is us-east-1
        /// <returns>A string that is the signed http request.</returns>
        /// <exception cref="T:System.ArgumentException" />
        /// <exception cref="T:System.ArgumentNullException" />
        internal string GetPreSignedURLInternal(GetPreSignedUrlRequest request, bool useSigV2Fallback = true)
        {
            if (Credentials == null)
            {
                throw new AmazonS3Exception("Credentials must be specified, cannot call method anonymously");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request", "The PreSignedUrlRequest specified is null!");
            }

            if (!request.IsSetExpires())
            {
                throw new InvalidOperationException("The Expires specified is null!");
            }

            var aws4Signing = AWSConfigsS3.UseSignatureVersion4;
            var region      = AWS4Signer.DetermineSigningRegion(Config, "s3", alternateEndpoint: null, request: null);

            if (aws4Signing && string.IsNullOrEmpty(region))
            {
                throw new InvalidOperationException("To use AWS4 signing, a region must be specified in the client configuration using the AuthenticationRegion or Region properties, or be determinable from the service URL.");
            }

            RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(region);

            if (endpoint.GetEndpointForService("s3").SignatureVersionOverride == "4" || endpoint.GetEndpointForService("s3").SignatureVersionOverride == null)
            {
                aws4Signing = true;
            }

            var fallbackToSigV2 = useSigV2Fallback && !AWSConfigsS3.UseSigV4SetExplicitly;

            if (endpoint == RegionEndpoint.USEast1 && fallbackToSigV2)
            {
                aws4Signing = false;
            }

            // If the expiration is longer than SigV4 will allow then automatically use SigV2 instead.
            // But only if the region we're signing for allows SigV2.
            if (aws4Signing)
            {
                var secondsUntilExpiration = GetSecondsUntilExpiration(request, aws4Signing);

                if (secondsUntilExpiration > AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry &&
                    endpoint.GetEndpointForService("s3").SignatureVersionOverride == "2")
                {
                    aws4Signing = false;
                }
            }

            var immutableCredentials = Credentials.GetCredentials();
            var irequest             = Marshall(request, immutableCredentials.AccessKey, immutableCredentials.Token, aws4Signing);

            irequest.Endpoint = EndpointResolver.DetermineEndpoint(this.Config, irequest);

            var context = new Amazon.Runtime.Internal.ExecutionContext(new Amazon.Runtime.Internal.RequestContext(true)
            {
                Request = irequest, ClientConfig = this.Config
            }, null);

            AmazonS3PostMarshallHandler.ProcessRequestHandlers(context);

            var metrics = new RequestMetrics();

            string authorization;

            if (aws4Signing)
            {
                var aws4Signer    = new AWS4PreSignedUrlSigner();
                var signingResult = aws4Signer.SignRequest(irequest,
                                                           this.Config,
                                                           metrics,
                                                           immutableCredentials.AccessKey,
                                                           immutableCredentials.SecretKey);
                authorization = "&" + signingResult.ForQueryParameters;
            }
            else
            {
                S3Signer.SignRequest(irequest, metrics, immutableCredentials.AccessKey, immutableCredentials.SecretKey);
                authorization = irequest.Headers[HeaderKeys.AuthorizationHeader];
                authorization = authorization.Substring(authorization.IndexOf(":", StringComparison.Ordinal) + 1);
                authorization = "&Signature=" + AmazonS3Util.UrlEncode(authorization, false);
            }

            Uri    url    = AmazonServiceClient.ComposeUrl(irequest);
            string result = url.AbsoluteUri + authorization;

            Protocol protocol = DetermineProtocol();

            if (request.Protocol != protocol)
            {
                switch (protocol)
                {
                case Protocol.HTTP:
                    result = result.Replace("http://", "https://");
                    break;

                case Protocol.HTTPS:
                    result = result.Replace("https://", "http://");
                    break;
                }
            }
            return(result);
        }
Exemple #11
0
        /// <summary>
        /// Create a signed URL allowing access to a resource that would
        /// usually require authentication.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When using query string authentication you create a query,
        /// specify an expiration time for the query, sign it with your
        /// signature, place the data in an HTTP request, and distribute
        /// the request to a user or embed the request in a web page.
        /// </para>
        /// <para>
        /// A PreSigned URL can be generated for GET, PUT, DELETE and HEAD
        /// operations on your bucketName, keys, and versions.
        /// </para>
        /// </remarks>
        /// <param name="request">The GetPreSignedUrlRequest that defines the
        /// parameters of the operation.</param>
        /// <returns>A string that is the signed http request.</returns>
        /// <exception cref="T:System.ArgumentException" />
        /// <exception cref="T:System.ArgumentNullException" />
        public string GetPreSignedURL(GetPreSignedUrlRequest request)
        {
            if (Credentials == null)
            {
                throw new AmazonS3Exception("Credentials must be specified, cannot call method anonymously");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request", "The PreSignedUrlRequest specified is null!");
            }

            if (!request.IsSetExpires())
            {
                throw new InvalidOperationException("The Expires specified is null!");
            }

            var aws4Signing = AWSConfigs.S3Config.UseSignatureVersion4;
            var region      = AWS4Signer.DetermineSigningRegion(Config, "s3", alternateEndpoint: null);

            if (aws4Signing && string.IsNullOrEmpty(region))
            {
                throw new InvalidOperationException("To use AWS4 signing, a region must be specified in the client configuration using the AuthenticationRegion or Region properties, or be determinable from the service URL.");
            }

            RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(region);

            if (endpoint.GetEndpointForService("s3").SignatureVersionOverride == "4")
            {
                aws4Signing = true;
            }

            var immutableCredentials = Credentials.GetCredentials();
            var irequest             = Marshall(request, immutableCredentials.AccessKey, immutableCredentials.Token, aws4Signing);

            irequest.Endpoint = DetermineEndpoint(irequest);
            ProcessRequestHandlers(irequest);
            var metrics = new RequestMetrics();

            string authorization;

            if (aws4Signing)
            {
                var aws4Signer    = new AWS4PreSignedUrlSigner();
                var signingResult = aws4Signer.SignRequest(irequest,
                                                           this.Config,
                                                           metrics,
                                                           immutableCredentials.AccessKey,
                                                           immutableCredentials.SecretKey);
                authorization = "&" + signingResult.ForQueryParameters;
            }
            else
            {
                signer.SignRequest(irequest, metrics, immutableCredentials.AccessKey, immutableCredentials.SecretKey);
                authorization = irequest.Headers[HeaderKeys.AuthorizationHeader];
                authorization = authorization.Substring(authorization.IndexOf(":", StringComparison.Ordinal) + 1);
                authorization = "&Signature=" + AmazonS3Util.UrlEncode(authorization, false);
            }

            Uri    url    = ComposeUrl(irequest, irequest.Endpoint);
            string result = url.AbsoluteUri + authorization;

            Protocol protocol = DetermineProtocol();

            if (request.Protocol != protocol)
            {
                switch (protocol)
                {
                case Protocol.HTTP:
                    result = result.Replace("http://", "https://");
                    break;

                case Protocol.HTTPS:
                    result = result.Replace("https://", "http://");
                    break;
                }
            }
            return(result);
        }
Exemple #12
0
        /// <summary>
        /// Create a signed URL allowing access to a resource that would
        /// usually require authentication.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When using query string authentication you create a query,
        /// specify an expiration time for the query, sign it with your
        /// signature, place the data in an HTTP request, and distribute
        /// the request to a user or embed the request in a web page.
        /// </para>
        /// <para>
        /// A PreSigned URL can be generated for GET, PUT, DELETE and HEAD
        /// operations on your bucketName, keys, and versions.
        /// </para>
        /// </remarks>
        /// <param name="request">The GetPreSignedUrlRequest that defines the
        /// parameters of the operation.</param>
        /// <param name="useSigV2Fallback">determines if signing will fall back to SigV2 if the
        /// signing region is us-east-1</param>
        /// <returns>A string that is the signed http request.</returns>
        /// <exception cref="T:System.ArgumentException" />
        /// <exception cref="T:System.ArgumentNullException" />
        internal string GetPreSignedURLInternal(GetPreSignedUrlRequest request, bool useSigV2Fallback = true)
        {
            if (Credentials == null)
            {
                throw new AmazonS3Exception("Credentials must be specified, cannot call method anonymously");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request", "The PreSignedUrlRequest specified is null!");
            }

            if (!request.IsSetExpires())
            {
                throw new InvalidOperationException("The Expires specified is null!");
            }

            var signatureVersionToUse = AWSConfigsS3.UseSignatureVersion4 ? SignatureVersion.SigV4 : SignatureVersion.SigV2;

            Arn    arn;
            string accessPoint;

            if (Arn.TryParse(request.BucketName, out arn) &&
                (arn.TryParseAccessPoint(out accessPoint) || arn.IsOutpostArn()))
            {
                signatureVersionToUse = SignatureVersion.SigV4;

                if (arn.IsMRAPArn())
                {
                    signatureVersionToUse = SignatureVersion.SigV4a;
                }
            }
            else
            {
                var region = AWS4Signer.DetermineSigningRegion(Config, "s3", alternateEndpoint: null, request: null);
                if (signatureVersionToUse == SignatureVersion.SigV4 && string.IsNullOrEmpty(region))
                {
                    throw new InvalidOperationException("To use AWS4 signing, a region must be specified in the client configuration using the AuthenticationRegion or Region properties, or be determinable from the service URL.");
                }

                RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(region);
                var            s3SignatureVersionOverride = endpoint.GetEndpointForService("s3", Config.ToGetEndpointForServiceOptions()).SignatureVersionOverride;
                if (s3SignatureVersionOverride == "4" || s3SignatureVersionOverride == null)
                {
                    signatureVersionToUse = SignatureVersion.SigV4;
                }

                var fallbackToSigV2 = useSigV2Fallback && !AWSConfigsS3.UseSigV4SetExplicitly;
                if (endpoint?.SystemName == RegionEndpoint.USEast1.SystemName && fallbackToSigV2)
                {
                    signatureVersionToUse = SignatureVersion.SigV2;
                }

                // If the expiration is longer than SigV4 will allow then automatically use SigV2 instead.
                // But only if the region we're signing for allows SigV2.
                if (signatureVersionToUse == SignatureVersion.SigV4)
                {
                    var secondsUntilExpiration = GetSecondsUntilExpiration(this.Config, request, signatureVersionToUse);

                    if (secondsUntilExpiration > AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry &&
                        s3SignatureVersionOverride == "2")
                    {
                        signatureVersionToUse = SignatureVersion.SigV2;
                    }
                }
            }


            var immutableCredentials = Credentials.GetCredentials();
            var irequest             = Marshall(this.Config, request, immutableCredentials.AccessKey, immutableCredentials.Token, signatureVersionToUse);

            irequest.Endpoint = EndpointResolver.DetermineEndpoint(this.Config, irequest);

            var context = new Amazon.Runtime.Internal.ExecutionContext(new Amazon.Runtime.Internal.RequestContext(true, new NullSigner())
            {
                Request = irequest, ClientConfig = this.Config
            }, null);

            AmazonS3PostMarshallHandler.ProcessRequestHandlers(context);

            var    metrics = new RequestMetrics();
            string result;
            string authorization;

            switch (signatureVersionToUse)
            {
            case SignatureVersion.SigV4a:
                var aws4aSigner     = new AWS4aSignerCRTWrapper();
                var signingResult4a = aws4aSigner.Presign4a(irequest,
                                                            Config,
                                                            metrics,
                                                            immutableCredentials,
                                                            "s3",
                                                            arn.IsMRAPArn() ? "*" : "");
                result = signingResult4a.PresignedUri;
                break;

            case SignatureVersion.SigV4:
                var aws4Signer     = new AWS4PreSignedUrlSigner();
                var signingResult4 = aws4Signer.SignRequest(irequest,
                                                            Config,
                                                            metrics,
                                                            immutableCredentials.AccessKey,
                                                            immutableCredentials.SecretKey);
                authorization = "&" + signingResult4.ForQueryParameters;
                result        = ComposeUrl(irequest).AbsoluteUri + authorization;
                break;

            default:     // SigV2
                Amazon.S3.Internal.S3Signer.SignRequest(irequest, metrics, immutableCredentials.AccessKey, immutableCredentials.SecretKey);
                authorization = irequest.Headers[HeaderKeys.AuthorizationHeader];
                authorization = authorization.Substring(authorization.IndexOf(":", StringComparison.Ordinal) + 1);
                authorization = "&Signature=" + AmazonS3Util.UrlEncode(authorization, false);
                result        = ComposeUrl(irequest).AbsoluteUri + authorization;
                break;
            }

            Protocol protocol = DetermineProtocol();

            if (request.Protocol != protocol)
            {
                switch (protocol)
                {
                case Protocol.HTTP:
                    result = result.Replace("http://", "https://");
                    break;

                case Protocol.HTTPS:
                    result = result.Replace("https://", "http://");
                    break;
                }
            }
            return(result);
        }
        /// <summary>
        /// Generate a presigned URL based on a <see cref="SynthesizeSpeechRequest"/>.
        /// </summary>
        /// <param name="credentials">The credentials to use in the presigned URL.</param>
        /// <param name="region">The region for the URL.</param>
        /// <param name="request">The request to base the presigned URL on.</param>
        /// <returns></returns>
        public static string GeneratePresignedUrl(AWSCredentials credentials, RegionEndpoint region, SynthesizeSpeechRequest request)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }

            if (region == null)
            {
                throw new ArgumentNullException("region");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // Marshall this request and prepare it to be signed
            var marshaller = new SynthesizeSpeechRequestMarshaller();
            var iRequest   = marshaller.Marshall(request);

            iRequest.UseQueryString          = true;
            iRequest.HttpMethod              = HTTPGet;
            iRequest.Endpoint                = new UriBuilder(HTTPS, region.GetEndpointForService(PollyServiceName).Hostname).Uri;
            iRequest.Parameters[XAmzExpires] = ((int)FifteenMinutes.TotalSeconds).ToString(CultureInfo.InvariantCulture);

            if (request.IsSetLexiconNames())
            {
                iRequest.ParameterCollection.Add("LexiconNames", request.LexiconNames);
            }

            if (request.IsSetOutputFormat())
            {
                iRequest.Parameters["OutputFormat"] = request.OutputFormat.ToString();
            }

            if (request.IsSetSampleRate())
            {
                iRequest.Parameters["SampleRate"] = request.SampleRate.ToString();
            }

            if (request.IsSetText())
            {
                iRequest.Parameters["Text"] = request.Text;
            }

            if (request.IsSetTextType())
            {
                iRequest.Parameters["TextType"] = request.TextType.ToString();
            }

            if (request.IsSetVoiceId())
            {
                iRequest.Parameters["VoiceId"] = request.VoiceId;
            }

            if (request.IsSetSpeechMarkTypes())
            {
                iRequest.ParameterCollection.Add("SpeechMarkTypes", request.SpeechMarkTypes);
            }

            if (request.IsSetLanguageCode())
            {
                iRequest.ParameterCollection.Add("LanguageCode", request.LanguageCode);
            }

            var immutableCredentials = credentials.GetCredentials();

            if (immutableCredentials.UseToken)
            {
                // Don't use HeaderKeys.XAmzSecurityTokenHeader because Polly treats this as case-sensitive
                iRequest.Parameters["X-Amz-Security-Token"] = immutableCredentials.Token;
            }

            // Only the host header should be signed, and the signer adds that.
            // So clear out headers.
            iRequest.Headers.Clear();

            // Create presigned URL and assign it
            var signingResult = AWS4PreSignedUrlSigner.SignRequest(iRequest, null, new RequestMetrics(),
                                                                   immutableCredentials.AccessKey, immutableCredentials.SecretKey, PollyServiceName, region.SystemName);

            var authorization = "&" + signingResult.ForQueryParameters;

            return(AmazonServiceClient.ComposeUrl(iRequest).AbsoluteUri + authorization);
        }
Exemple #14
0
        public static string DetermineSigningRegion(IClientConfig clientConfig, 
                                                    string serviceName, 
                                                    RegionEndpoint alternateEndpoint,
                                                    IRequest request)
        {
            // Alternate endpoint (IRequest.AlternateEndopoint) takes precedence over
            // client config properties.
            if (alternateEndpoint != null)
            {
                var serviceEndpoint = alternateEndpoint.GetEndpointForService(serviceName, clientConfig.UseDualstackEndpoint);
                if (serviceEndpoint.AuthRegion != null)
                    return serviceEndpoint.AuthRegion;

                return alternateEndpoint.SystemName;
            }

            string authenticationRegion = clientConfig.AuthenticationRegion;
            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.UseDualstackEndpoint);
                if (!string.IsNullOrEmpty(serviceEndpoint.AuthRegion))
                    return serviceEndpoint.AuthRegion;

                return endpoint.SystemName; 
            }

            return string.Empty;
        }
Exemple #15
0
 public static RegionEndpoint.Endpoint GetEndpointForService(this RegionEndpoint endpoint, IClientConfig config)
 {
     return(endpoint.GetEndpointForService(config.RegionEndpointServiceName, config.ToGetEndpointForServiceOptions()));
 }
Exemple #16
0
 internal static string GetUrl(RegionEndpoint regionEndpoint, string regionEndpointServiceName, bool useHttp, bool useDualStack)
 {
     var endpoint = regionEndpoint.GetEndpointForService(regionEndpointServiceName, useDualStack);
     string url = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", useHttp ? "http://" : "https://", endpoint.Hostname)).AbsoluteUri;
     return url;
 }
Exemple #17
0
        /// <summary>
        /// Given this client configuration, return a DNS suffix for service endpoint url.
        /// </summary>
        public virtual string DetermineDnsSuffix()
        {
            var endpoint = regionEndpoint.GetEndpointForService(this);

            return(endpoint.DnsSuffix);
        }