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 System; using System.Collections.Generic; using System.Text; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for AWS Marketplace Management Portal. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class MarketplaceManagementPortalActionIdentifiers { public static readonly ActionIdentifier AllMarketplaceManagementPortalActions = new ActionIdentifier("aws-marketplace-management:*"); public static readonly ActionIdentifier uploadFiles = new ActionIdentifier("aws-marketplace-management:uploadFiles"); public static readonly ActionIdentifier viewMarketing = new ActionIdentifier("aws-marketplace-management:viewMarketing"); public static readonly ActionIdentifier viewReports = new ActionIdentifier("aws-marketplace-management:viewReports"); public static readonly ActionIdentifier viewSupport = new ActionIdentifier("aws-marketplace-management:viewSupport"); } }
39
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon Mobile Analytics. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class MobileAnalyticsActionIdentifiers { public static readonly ActionIdentifier AllMobileAnalyticsActions = new ActionIdentifier("mobileanalytics:*"); public static readonly ActionIdentifier PutEvents = new ActionIdentifier("mobileanalytics:PutEvents"); public static readonly ActionIdentifier GetReports = new ActionIdentifier("mobileanalytics:GetReports"); public static readonly ActionIdentifier GetFinancialReports = new ActionIdentifier("mobileanalytics:GetFinancialReports"); } }
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.Text; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for AWS OpsWorks. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class OpsWorksActionIdentifiers { public static readonly ActionIdentifier AllOpsWorksActions = new ActionIdentifier("opsworks:*"); public static readonly ActionIdentifier AssignVolume = new ActionIdentifier("opsworks:AssignVolume"); public static readonly ActionIdentifier AssociateElasticIp = new ActionIdentifier("opsworks:AssociateElasticIp"); public static readonly ActionIdentifier AttachElasticLoadBalancer = new ActionIdentifier("opsworks:AttachElasticLoadBalancer"); public static readonly ActionIdentifier CloneStack = new ActionIdentifier("opsworks:CloneStack"); public static readonly ActionIdentifier CreateApp = new ActionIdentifier("opsworks:CreateApp"); public static readonly ActionIdentifier CreateDeployment = new ActionIdentifier("opsworks:CreateDeployment"); public static readonly ActionIdentifier CreateInstance = new ActionIdentifier("opsworks:CreateInstance"); public static readonly ActionIdentifier CreateLayer = new ActionIdentifier("opsworks:CreateLayer"); public static readonly ActionIdentifier CreateStack = new ActionIdentifier("opsworks:CreateStack"); public static readonly ActionIdentifier CreateUserProfile = new ActionIdentifier("opsworks:CreateUserProfile"); public static readonly ActionIdentifier DeleteApp = new ActionIdentifier("opsworks:DeleteApp"); public static readonly ActionIdentifier DeleteInstance = new ActionIdentifier("opsworks:DeleteInstance"); public static readonly ActionIdentifier DeleteLayer = new ActionIdentifier("opsworks:DeleteLayer"); public static readonly ActionIdentifier DeleteStack = new ActionIdentifier("opsworks:DeleteStack"); public static readonly ActionIdentifier DeleteUserProfile = new ActionIdentifier("opsworks:DeleteUserProfile"); public static readonly ActionIdentifier DeregisterElasticIp = new ActionIdentifier("opsworks:DeregisterElasticIp"); public static readonly ActionIdentifier DeregisterVolume = new ActionIdentifier("opsworks:DeregisterVolume"); public static readonly ActionIdentifier DescribeApps = new ActionIdentifier("opsworks:DescribeApps"); public static readonly ActionIdentifier DescribeCommands = new ActionIdentifier("opsworks:DescribeCommands"); public static readonly ActionIdentifier DescribeDeployments = new ActionIdentifier("opsworks:DescribeDeployments"); public static readonly ActionIdentifier DescribeElasticIps = new ActionIdentifier("opsworks:DescribeElasticIps"); public static readonly ActionIdentifier DescribeElasticLoadBalancers = new ActionIdentifier("opsworks:DescribeElasticLoadBalancers"); public static readonly ActionIdentifier DescribeInstances = new ActionIdentifier("opsworks:DescribeInstances"); public static readonly ActionIdentifier DescribeLayers = new ActionIdentifier("opsworks:DescribeLayers"); public static readonly ActionIdentifier DescribeLoadBasedAutoScaling = new ActionIdentifier("opsworks:DescribeLoadBasedAutoScaling"); public static readonly ActionIdentifier DescribePermissions = new ActionIdentifier("opsworks:DescribePermissions"); public static readonly ActionIdentifier DescribeRaidArrays = new ActionIdentifier("opsworks:DescribeRaidArrays"); public static readonly ActionIdentifier DescribeServiceErrors = new ActionIdentifier("opsworks:DescribeServiceErrors"); public static readonly ActionIdentifier DescribeStacks = new ActionIdentifier("opsworks:DescribeStacks"); public static readonly ActionIdentifier DescribeTimeBasedAutoScaling = new ActionIdentifier("opsworks:DescribeTimeBasedAutoScaling"); public static readonly ActionIdentifier DescribeUserProfiles = new ActionIdentifier("opsworks:DescribeUserProfiles"); public static readonly ActionIdentifier DescribeVolumes = new ActionIdentifier("opsworks:DescribeVolumes"); public static readonly ActionIdentifier DetachElasticLoadBalancer = new ActionIdentifier("opsworks:DetachElasticLoadBalancer"); public static readonly ActionIdentifier DisassociateElasticIp = new ActionIdentifier("opsworks:DisassociateElasticIp"); public static readonly ActionIdentifier GetHostnameSuggestion = new ActionIdentifier("opsworks:GetHostnameSuggestion"); public static readonly ActionIdentifier RebootInstance = new ActionIdentifier("opsworks:RebootInstance"); public static readonly ActionIdentifier RegisterElasticIp = new ActionIdentifier("opsworks:RegisterElasticIp"); public static readonly ActionIdentifier RegisterVolume = new ActionIdentifier("opsworks:RegisterVolume"); public static readonly ActionIdentifier SetLoadBasedAutoScaling = new ActionIdentifier("opsworks:SetLoadBasedAutoScaling"); public static readonly ActionIdentifier SetPermission = new ActionIdentifier("opsworks:SetPermission"); public static readonly ActionIdentifier SetTimeBasedAutoScaling = new ActionIdentifier("opsworks:SetTimeBasedAutoScaling"); public static readonly ActionIdentifier StartInstance = new ActionIdentifier("opsworks:StartInstance"); public static readonly ActionIdentifier StartStack = new ActionIdentifier("opsworks:StartStack"); public static readonly ActionIdentifier StopInstance = new ActionIdentifier("opsworks:StopInstance"); public static readonly ActionIdentifier StopStack = new ActionIdentifier("opsworks:StopStack"); public static readonly ActionIdentifier UnassignVolume = new ActionIdentifier("opsworks:UnassignVolume"); public static readonly ActionIdentifier UpdateApp = new ActionIdentifier("opsworks:UpdateApp"); public static readonly ActionIdentifier UpdateElasticIp = new ActionIdentifier("opsworks:UpdateElasticIp"); public static readonly ActionIdentifier UpdateInstance = new ActionIdentifier("opsworks:UpdateInstance"); public static readonly ActionIdentifier UpdateLayer = new ActionIdentifier("opsworks:UpdateLayer"); public static readonly ActionIdentifier UpdateStack = new ActionIdentifier("opsworks:UpdateStack"); public static readonly ActionIdentifier UpdateUserProfile = new ActionIdentifier("opsworks:UpdateUserProfile"); public static readonly ActionIdentifier UpdateVolume = new ActionIdentifier("opsworks:UpdateVolume"); } }
88
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon RDS. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class RDSActionIdentifiers { public static readonly ActionIdentifier AllRDSActions = new ActionIdentifier("rds:*"); public static readonly ActionIdentifier AuthorizeDBSecurityGroupIngress = new ActionIdentifier("rds:AuthorizeDBSecurityGroupIngress"); public static readonly ActionIdentifier AddTagsToResource = new ActionIdentifier("rds:AddTagsToResource"); public static readonly ActionIdentifier AddSourceIdentifierToSubscription = new ActionIdentifier("rds:AddSourceIdentifierToSubscription"); public static readonly ActionIdentifier CopyDBSnapshot = new ActionIdentifier("rds:CopyDBSnapshot"); public static readonly ActionIdentifier CreateDBInstance = new ActionIdentifier("rds:CreateDBInstance"); public static readonly ActionIdentifier CreateDBInstanceReadReplica = new ActionIdentifier("rds:CreateDBInstanceReadReplica"); public static readonly ActionIdentifier CreateDBParameterGroup = new ActionIdentifier("rds:CreateDBParameterGroup"); public static readonly ActionIdentifier CreateDBSecurityGroup = new ActionIdentifier("rds:CreateDBSecurityGroup"); public static readonly ActionIdentifier CreateDBSnapshot = new ActionIdentifier("rds:CreateDBSnapshot"); public static readonly ActionIdentifier CreateDBSubnetGroup = new ActionIdentifier("rds:CreateDBSubnetGroup"); public static readonly ActionIdentifier CreateEventSubscription = new ActionIdentifier("rds:CreateEventSubscription"); public static readonly ActionIdentifier CreateOptionGroup = new ActionIdentifier("rds:CreateOptionGroup"); public static readonly ActionIdentifier DeleteDBInstance = new ActionIdentifier("rds:DeleteDBInstance"); public static readonly ActionIdentifier DeleteDBParameterGroup = new ActionIdentifier("rds:DeleteDBParameterGroup"); public static readonly ActionIdentifier DeleteDBSecurityGroup = new ActionIdentifier("rds:DeleteDBSecurityGroup"); public static readonly ActionIdentifier DeleteDBSnapshot = new ActionIdentifier("rds:DeleteDBSnapshot"); public static readonly ActionIdentifier DeleteDBSubnetGroup = new ActionIdentifier("rds:DeleteDBSubnetGroup"); public static readonly ActionIdentifier DeleteEventSubscription = new ActionIdentifier("rds:DeleteEventSubscription"); public static readonly ActionIdentifier DeleteOptionGroup = new ActionIdentifier("rds:DeleteOptionGroup"); public static readonly ActionIdentifier DescribeEngineDefaultParameters = new ActionIdentifier("rds:DescribeEngineDefaultParameters"); public static readonly ActionIdentifier DescribeDBInstances = new ActionIdentifier("rds:DescribeDBInstances"); public static readonly ActionIdentifier DescribeDBLogFiles = new ActionIdentifier("rds:DescribeDBLogFiles"); public static readonly ActionIdentifier DescribeDBParameterGroups = new ActionIdentifier("rds:DescribeDBParameterGroups"); public static readonly ActionIdentifier DescribeDBParameters = new ActionIdentifier("rds:DescribeDBParameters"); public static readonly ActionIdentifier DescribeDBSecurityGroups = new ActionIdentifier("rds:DescribeDBSecurityGroups"); public static readonly ActionIdentifier DescribeDBSnapshots = new ActionIdentifier("rds:DescribeDBSnapshots"); public static readonly ActionIdentifier DescribeDBEngineVersions = new ActionIdentifier("rds:DescribeDBEngineVersions"); public static readonly ActionIdentifier DescribeDBSubnetGroups = new ActionIdentifier("rds:DescribeDBSubnetGroups"); public static readonly ActionIdentifier DescribeEventCategories = new ActionIdentifier("rds:DescribeEventCategories"); public static readonly ActionIdentifier DescribeEvents = new ActionIdentifier("rds:DescribeEvents"); public static readonly ActionIdentifier DescribeEventSubscriptions = new ActionIdentifier("rds:DescribeEventSubscriptions"); public static readonly ActionIdentifier DescribeOptionGroups = new ActionIdentifier("rds:DescribeOptionGroups"); public static readonly ActionIdentifier DescribeOptionGroupOptions = new ActionIdentifier("rds:DescribeOptionGroupOptions"); public static readonly ActionIdentifier DescribeOrderableDBInstanceOptions = new ActionIdentifier("rds:DescribeOrderableDBInstanceOptions"); public static readonly ActionIdentifier DescribeReservedDBInstances = new ActionIdentifier("rds:DescribeReservedDBInstances"); public static readonly ActionIdentifier DescribeReservedDBInstancesOfferings = new ActionIdentifier("rds:DescribeReservedDBInstancesOfferings"); public static readonly ActionIdentifier DownloadDBLogFilePortion = new ActionIdentifier("rds:DownloadDBLogFilePortion"); public static readonly ActionIdentifier ListTagsForResource = new ActionIdentifier("rds:ListTagsForResource"); public static readonly ActionIdentifier ModifyDBInstance = new ActionIdentifier("rds:ModifyDBInstance"); public static readonly ActionIdentifier ModifyDBParameterGroup = new ActionIdentifier("rds:ModifyDBParameterGroup"); public static readonly ActionIdentifier ModifyDBSubnetGroup = new ActionIdentifier("rds:ModifyDBSubnetGroup"); public static readonly ActionIdentifier ModifyEventSubscription = new ActionIdentifier("rds:ModifyEventSubscription"); public static readonly ActionIdentifier ModifyOptionGroup = new ActionIdentifier("rds:ModifyOptionGroup"); public static readonly ActionIdentifier PromoteReadReplica = new ActionIdentifier("rds:PromoteReadReplica"); public static readonly ActionIdentifier PurchaseReservedDBInstancesOffering = new ActionIdentifier("rds:PurchaseReservedDBInstancesOffering"); public static readonly ActionIdentifier RebootDBInstance = new ActionIdentifier("rds:RebootDBInstance"); public static readonly ActionIdentifier RemoveSourceIdentifierFromSubscription = new ActionIdentifier("rds:RemoveSourceIdentifierFromSubscription"); public static readonly ActionIdentifier RemoveTagsFromResource = new ActionIdentifier("rds:RemoveTagsFromResource"); public static readonly ActionIdentifier RestoreDBInstanceFromDBSnapshot = new ActionIdentifier("rds:RestoreDBInstanceFromDBSnapshot"); public static readonly ActionIdentifier RestoreDBInstanceToPointInTime = new ActionIdentifier("rds:RestoreDBInstanceToPointInTime"); public static readonly ActionIdentifier ResetDBParameterGroup = new ActionIdentifier("rds:ResetDBParameterGroup"); public static readonly ActionIdentifier RevokeDBSecurityGroupIngress = new ActionIdentifier("rds:RevokeDBSecurityGroupIngress"); } }
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.Text; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon Redshift. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class RedshiftActionIdentifiers { public static readonly ActionIdentifier AllRedshiftActions = new ActionIdentifier("redshift:*"); public static readonly ActionIdentifier AuthorizeClusterSecurityGroupIngress = new ActionIdentifier("redshift:AuthorizeClusterSecurityGroupIngress"); public static readonly ActionIdentifier AuthorizeSnapshotAccess = new ActionIdentifier("redshift:AuthorizeSnapshotAccess"); public static readonly ActionIdentifier CopyClusterSnapshot = new ActionIdentifier("redshift:CopyClusterSnapshot"); public static readonly ActionIdentifier CreateCluster = new ActionIdentifier("redshift:CreateCluster"); public static readonly ActionIdentifier CreateClusterParameterGroup = new ActionIdentifier("redshift:CreateClusterParameterGroup"); public static readonly ActionIdentifier CreateClusterSecurityGroup = new ActionIdentifier("redshift:CreateClusterSecurityGroup"); public static readonly ActionIdentifier CreateClusterSnapshot = new ActionIdentifier("redshift:CreateClusterSnapshot"); public static readonly ActionIdentifier CreateClusterSubnetGroup = new ActionIdentifier("redshift:CreateClusterSubnetGroup"); public static readonly ActionIdentifier CreateEventSubscription = new ActionIdentifier("redshift:CreateEventSubscription"); public static readonly ActionIdentifier CreateHsmClientCertificate = new ActionIdentifier("redshift:CreateHsmClientCertificate"); public static readonly ActionIdentifier CreateHsmConfiguration = new ActionIdentifier("redshift:CreateHsmConfiguration"); public static readonly ActionIdentifier DeleteCluster = new ActionIdentifier("redshift:DeleteCluster"); public static readonly ActionIdentifier DeleteClusterParameterGroup = new ActionIdentifier("redshift:DeleteClusterParameterGroup"); public static readonly ActionIdentifier DeleteClusterSecurityGroup = new ActionIdentifier("redshift:DeleteClusterSecurityGroup"); public static readonly ActionIdentifier DeleteClusterSnapshot = new ActionIdentifier("redshift:DeleteClusterSnapshot"); public static readonly ActionIdentifier DeleteClusterSubnetGroup = new ActionIdentifier("redshift:DeleteClusterSubnetGroup"); public static readonly ActionIdentifier DeleteEventSubscription = new ActionIdentifier("redshift:DeleteEventSubscription"); public static readonly ActionIdentifier DeleteHsmClientCertificate = new ActionIdentifier("redshift:DeleteHsmClientCertificate"); public static readonly ActionIdentifier DeleteHsmConfiguration = new ActionIdentifier("redshift:DeleteHsmConfiguration"); public static readonly ActionIdentifier DescribeClusterParameterGroups = new ActionIdentifier("redshift:DescribeClusterParameterGroups"); public static readonly ActionIdentifier DescribeClusterParameters = new ActionIdentifier("redshift:DescribeClusterParameters"); public static readonly ActionIdentifier DescribeClusterSecurityGroups = new ActionIdentifier("redshift:DescribeClusterSecurityGroups"); public static readonly ActionIdentifier DescribeClusterSnapshots = new ActionIdentifier("redshift:DescribeClusterSnapshots"); public static readonly ActionIdentifier DescribeClusterSubnetGroups = new ActionIdentifier("redshift:DescribeClusterSubnetGroups"); public static readonly ActionIdentifier DescribeClusterVersions = new ActionIdentifier("redshift:DescribeClusterVersions"); public static readonly ActionIdentifier DescribeClusters = new ActionIdentifier("redshift:DescribeClusters"); public static readonly ActionIdentifier DescribeDefaultClusterParameters = new ActionIdentifier("redshift:DescribeDefaultClusterParameters"); public static readonly ActionIdentifier DescribeEventCategories = new ActionIdentifier("redshift:DescribeEventCategories"); public static readonly ActionIdentifier DescribeEventSubscriptions = new ActionIdentifier("redshift:DescribeEventSubscriptions"); public static readonly ActionIdentifier DescribeEvents = new ActionIdentifier("redshift:DescribeEvents"); public static readonly ActionIdentifier DescribeHsmClientCertificates = new ActionIdentifier("redshift:DescribeHsmClientCertificates"); public static readonly ActionIdentifier DescribeHsmConfigurations = new ActionIdentifier("redshift:DescribeHsmConfigurations"); public static readonly ActionIdentifier DescribeLoggingStatus = new ActionIdentifier("redshift:DescribeLoggingStatus"); public static readonly ActionIdentifier DescribeOrderableClusterOptions = new ActionIdentifier("redshift:DescribeOrderableClusterOptions"); public static readonly ActionIdentifier DescribeReservedNodeOfferings = new ActionIdentifier("redshift:DescribeReservedNodeOfferings"); public static readonly ActionIdentifier DescribeReservedNodes = new ActionIdentifier("redshift:DescribeReservedNodes"); public static readonly ActionIdentifier DescribeResize = new ActionIdentifier("redshift:DescribeResize"); public static readonly ActionIdentifier DisableLogging = new ActionIdentifier("redshift:DisableLogging"); public static readonly ActionIdentifier DisableSnapshotCopy = new ActionIdentifier("redshift:DisableSnapshotCopy"); public static readonly ActionIdentifier EnableLogging = new ActionIdentifier("redshift:EnableLogging"); public static readonly ActionIdentifier EnableSnapshotCopy = new ActionIdentifier("redshift:EnableSnapshotCopy"); public static readonly ActionIdentifier ModifyCluster = new ActionIdentifier("redshift:ModifyCluster"); public static readonly ActionIdentifier ModifyClusterParameterGroup = new ActionIdentifier("redshift:ModifyClusterParameterGroup"); public static readonly ActionIdentifier ModifyClusterSubnetGroup = new ActionIdentifier("redshift:ModifyClusterSubnetGroup"); public static readonly ActionIdentifier ModifyEventSubscription = new ActionIdentifier("redshift:ModifyEventSubscription"); public static readonly ActionIdentifier ModifySnapshotCopyRetentionPeriod = new ActionIdentifier("redshift:ModifySnapshotCopyRetentionPeriod"); public static readonly ActionIdentifier PurchaseReservedNodeOffering = new ActionIdentifier("redshift:PurchaseReservedNodeOffering"); public static readonly ActionIdentifier RebootCluster = new ActionIdentifier("redshift:RebootCluster"); public static readonly ActionIdentifier ResetClusterParameterGroup = new ActionIdentifier("redshift:ResetClusterParameterGroup"); public static readonly ActionIdentifier RestoreFromClusterSnapshot = new ActionIdentifier("redshift:RestoreFromClusterSnapshot"); public static readonly ActionIdentifier RevokeClusterSecurityGroupIngress = new ActionIdentifier("redshift:RevokeClusterSecurityGroupIngress"); public static readonly ActionIdentifier RevokeSnapshotAccess = new ActionIdentifier("redshift:RevokeSnapshotAccess"); public static readonly ActionIdentifier RotateEncryptionKey = new ActionIdentifier("redshift:RotateEncryptionKey"); public static readonly ActionIdentifier ViewQueriesInConsole = new ActionIdentifier("redshift:ViewQueriesInConsole"); } }
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; using System.Collections.Generic; using System.Text; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon Route 53. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class Route53ActionIdentifiers { public static readonly ActionIdentifier AllRoute53Actions = new ActionIdentifier("route53:*"); public static readonly ActionIdentifier ChangeResourceRecordSets = new ActionIdentifier("route53:ChangeResourceRecordSets"); public static readonly ActionIdentifier CreateHostedZone = new ActionIdentifier("route53:CreateHostedZone"); public static readonly ActionIdentifier DeleteHostedZone = new ActionIdentifier("route53:DeleteHostedZone"); public static readonly ActionIdentifier GetChange = new ActionIdentifier("route53:GetChange"); public static readonly ActionIdentifier GetHostedZone = new ActionIdentifier("route53:GetHostedZone"); public static readonly ActionIdentifier ListHostedZones = new ActionIdentifier("route53:ListHostedZones"); public static readonly ActionIdentifier ListResourceRecordSets = new ActionIdentifier("route53:ListResourceRecordSets"); } }
42
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon S3. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class S3ActionIdentifiers { public static readonly ActionIdentifier AllS3Actions = new ActionIdentifier("s3:*"); public static readonly ActionIdentifier AbortMultipartUpload = new ActionIdentifier("s3:AbortMultipartUpload"); public static readonly ActionIdentifier CreateBucket = new ActionIdentifier("s3:CreateBucket"); public static readonly ActionIdentifier DeleteBucket = new ActionIdentifier("s3:DeleteBucket"); public static readonly ActionIdentifier DeleteBucketPolicy = new ActionIdentifier("s3:DeleteBucketPolicy"); public static readonly ActionIdentifier DeleteBucketWebsite = new ActionIdentifier("s3:DeleteBucketWebsite"); public static readonly ActionIdentifier DeleteObject = new ActionIdentifier("s3:DeleteObject"); public static readonly ActionIdentifier DeleteObjectVersion = new ActionIdentifier("s3:DeleteObjectVersion"); public static readonly ActionIdentifier GetBucketAcl = new ActionIdentifier("s3:GetBucketAcl"); public static readonly ActionIdentifier GetBucketCORS = new ActionIdentifier("s3:GetBucketCORS"); public static readonly ActionIdentifier GetBucketLocation = new ActionIdentifier("s3:GetBucketLocation"); public static readonly ActionIdentifier GetBucketLogging = new ActionIdentifier("s3:GetBucketLogging"); public static readonly ActionIdentifier GetBucketNotification = new ActionIdentifier("s3:GetBucketNotification"); public static readonly ActionIdentifier GetBucketPolicy = new ActionIdentifier("s3:GetBucketPolicy"); public static readonly ActionIdentifier GetBucketRequestPayment = new ActionIdentifier("s3:GetBucketRequestPayment"); public static readonly ActionIdentifier GetBucketTagging = new ActionIdentifier("s3:GetBucketTagging"); public static readonly ActionIdentifier GetBucketVersioning = new ActionIdentifier("s3:GetBucketVersioning"); public static readonly ActionIdentifier GetBucketWebsite = new ActionIdentifier("s3:GetBucketWebsite"); public static readonly ActionIdentifier GetLifecycleConfiguration = new ActionIdentifier("s3:GetLifecycleConfiguration"); public static readonly ActionIdentifier GetObject = new ActionIdentifier("s3:GetObject"); public static readonly ActionIdentifier GetObjectAcl = new ActionIdentifier("s3:GetObjectAcl"); public static readonly ActionIdentifier GetObjectTorrent = new ActionIdentifier("s3:GetObjectTorrent"); public static readonly ActionIdentifier GetObjectVersion = new ActionIdentifier("s3:GetObjectVersion"); public static readonly ActionIdentifier GetObjectVersionAcl = new ActionIdentifier("s3:GetObjectVersionAcl"); public static readonly ActionIdentifier GetObjectVersionTorrent = new ActionIdentifier("s3:GetObjectVersionTorrent"); public static readonly ActionIdentifier ListAllMyBuckets = new ActionIdentifier("s3:ListAllMyBuckets"); public static readonly ActionIdentifier ListBucket = new ActionIdentifier("s3:ListBucket"); public static readonly ActionIdentifier ListBucketMultipartUploads = new ActionIdentifier("s3:ListBucketMultipartUploads"); public static readonly ActionIdentifier ListBucketVersions = new ActionIdentifier("s3:ListBucketVersions"); public static readonly ActionIdentifier ListMultipartUploadParts = new ActionIdentifier("s3:ListMultipartUploadParts"); public static readonly ActionIdentifier PutBucketAcl = new ActionIdentifier("s3:PutBucketAcl"); public static readonly ActionIdentifier PutBucketCORS = new ActionIdentifier("s3:PutBucketCORS"); public static readonly ActionIdentifier PutBucketLogging = new ActionIdentifier("s3:PutBucketLogging"); public static readonly ActionIdentifier PutBucketNotification = new ActionIdentifier("s3:PutBucketNotification"); public static readonly ActionIdentifier PutBucketPolicy = new ActionIdentifier("s3:PutBucketPolicy"); public static readonly ActionIdentifier PutBucketRequestPayment = new ActionIdentifier("s3:PutBucketRequestPayment"); public static readonly ActionIdentifier PutBucketTagging = new ActionIdentifier("s3:PutBucketTagging"); public static readonly ActionIdentifier PutBucketVersioning = new ActionIdentifier("s3:PutBucketVersioning"); public static readonly ActionIdentifier PutBucketWebsite = new ActionIdentifier("s3:PutBucketWebsite"); public static readonly ActionIdentifier PutLifecycleConfiguration = new ActionIdentifier("s3:PutLifecycleConfiguration"); public static readonly ActionIdentifier PutObject = new ActionIdentifier("s3:PutObject"); public static readonly ActionIdentifier PutObjectAcl = new ActionIdentifier("s3:PutObjectAcl"); public static readonly ActionIdentifier PutObjectVersionAcl = new ActionIdentifier("s3:PutObjectVersionAcl"); public static readonly ActionIdentifier RestoreObject = new ActionIdentifier("s3:RestoreObject"); } }
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.Text; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for AWS Security Token Service. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class SecurityTokenServiceActionIdentifiers { public static readonly ActionIdentifier AllSecurityTokenServiceActions = new ActionIdentifier("sts:*"); public static readonly ActionIdentifier GetFederationToken = new ActionIdentifier("sts:GetFederationToken"); public static readonly ActionIdentifier AssumeRole = new ActionIdentifier("sts:AssumeRole"); } }
37
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon SES. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class SESActionIdentifiers { public static readonly ActionIdentifier AllSESActions = new ActionIdentifier("ses:*"); public static readonly ActionIdentifier DeleteIdentity = new ActionIdentifier("ses:DeleteIdentity"); public static readonly ActionIdentifier DeleteVerifiedEmailAddress = new ActionIdentifier("ses:DeleteVerifiedEmailAddress"); public static readonly ActionIdentifier GetIdentityDkimAttributes = new ActionIdentifier("ses:GetIdentityDkimAttributes"); public static readonly ActionIdentifier GetIdentityNotificationAttributes = new ActionIdentifier("ses:GetIdentityNotificationAttributes"); public static readonly ActionIdentifier GetIdentityVerificationAttributes = new ActionIdentifier("ses:GetIdentityVerificationAttributes"); public static readonly ActionIdentifier GetSendQuota = new ActionIdentifier("ses:GetSendQuota"); public static readonly ActionIdentifier GetSendStatistics = new ActionIdentifier("ses:GetSendStatistics"); public static readonly ActionIdentifier ListIdentities = new ActionIdentifier("ses:ListIdentities"); public static readonly ActionIdentifier ListVerifiedEmailAddresses = new ActionIdentifier("ses:ListVerifiedEmailAddresses"); public static readonly ActionIdentifier SendEmail = new ActionIdentifier("ses:SendEmail"); public static readonly ActionIdentifier SendRawEmail = new ActionIdentifier("ses:SendRawEmail"); public static readonly ActionIdentifier SetIdentityDkimEnabled = new ActionIdentifier("ses:SetIdentityDkimEnabled"); public static readonly ActionIdentifier SetIdentityNotificationTopic = new ActionIdentifier("ses:SetIdentityNotificationTopic"); public static readonly ActionIdentifier SetIdentityFeedbackForwardingEnabled = new ActionIdentifier("ses:SetIdentityFeedbackForwardingEnabled"); public static readonly ActionIdentifier VerifyDomainDkim = new ActionIdentifier("ses:VerifyDomainDkim"); public static readonly ActionIdentifier VerifyDomainIdentity = new ActionIdentifier("ses:VerifyDomainIdentity"); public static readonly ActionIdentifier VerifyEmailAddress = new ActionIdentifier("ses:VerifyEmailAddress"); public static readonly ActionIdentifier VerifyEmailIdentity = new ActionIdentifier("ses:VerifyEmailIdentity"); } }
53
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon SimpleDB. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class SimpleDBActionIdentifiers { public static readonly ActionIdentifier AllSimpleDBActions = new ActionIdentifier("sdb:*"); public static readonly ActionIdentifier BatchDeleteAttributes = new ActionIdentifier("sdb:BatchDeleteAttributes"); public static readonly ActionIdentifier BatchPutAttributes = new ActionIdentifier("sdb:BatchPutAttributes"); public static readonly ActionIdentifier CreateDomain = new ActionIdentifier("sdb:CreateDomain"); public static readonly ActionIdentifier DeleteAttributes = new ActionIdentifier("sdb:DeleteAttributes"); public static readonly ActionIdentifier DeleteDomain = new ActionIdentifier("sdb:DeleteDomain"); public static readonly ActionIdentifier DomainMetadata = new ActionIdentifier("sdb:DomainMetadata"); public static readonly ActionIdentifier GetAttributes = new ActionIdentifier("sdb:GetAttributes"); public static readonly ActionIdentifier ListDomains = new ActionIdentifier("sdb:ListDomains"); public static readonly ActionIdentifier PutAttributes = new ActionIdentifier("sdb:PutAttributes"); public static readonly ActionIdentifier Select = new ActionIdentifier("sdb:Select"); } }
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; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon Simple Workflow Service. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class SimpleWorkflowServiceActionIdentifiers { public static readonly ActionIdentifier AllSimpleWorkflowServiceActions = new ActionIdentifier("swf:*"); public static readonly ActionIdentifier CancelTimer = new ActionIdentifier("swf:CancelTimer"); public static readonly ActionIdentifier CancelWorkflowExecution = new ActionIdentifier("swf:CancelWorkflowExecution"); public static readonly ActionIdentifier CompleteWorkflowExecution = new ActionIdentifier("swf:CompleteWorkflowExecution"); public static readonly ActionIdentifier ContinueAsNewWorkflowExecution = new ActionIdentifier("swf:ContinueAsNewWorkflowExecution"); public static readonly ActionIdentifier CountClosedWorkflowExecutions = new ActionIdentifier("swf:CountClosedWorkflowExecutions"); public static readonly ActionIdentifier CountOpenWorkflowExecutions = new ActionIdentifier("swf:CountOpenWorkflowExecutions"); public static readonly ActionIdentifier CountPendingActivityTasks = new ActionIdentifier("swf:CountPendingActivityTasks"); public static readonly ActionIdentifier CountPendingDecisionTasks = new ActionIdentifier("swf:CountPendingDecisionTasks"); public static readonly ActionIdentifier DeprecateActivityType = new ActionIdentifier("swf:DeprecateActivityType"); public static readonly ActionIdentifier DeprecateDomain = new ActionIdentifier("swf:DeprecateDomain"); public static readonly ActionIdentifier DeprecateWorkflowType = new ActionIdentifier("swf:DeprecateWorkflowType"); public static readonly ActionIdentifier DescribeActivityType = new ActionIdentifier("swf:DescribeActivityType"); public static readonly ActionIdentifier DescribeDomain = new ActionIdentifier("swf:DescribeDomain"); public static readonly ActionIdentifier DescribeWorkflowExecution = new ActionIdentifier("swf:DescribeWorkflowExecution"); public static readonly ActionIdentifier DescribeWorkflowType = new ActionIdentifier("swf:DescribeWorkflowType"); public static readonly ActionIdentifier FailWorkflowExecution = new ActionIdentifier("swf:FailWorkflowExecution"); public static readonly ActionIdentifier GetWorkflowExecutionHistory = new ActionIdentifier("swf:GetWorkflowExecutionHistory"); public static readonly ActionIdentifier ListActivityTypes = new ActionIdentifier("swf:ListActivityTypes"); public static readonly ActionIdentifier ListClosedWorkflowExecutions = new ActionIdentifier("swf:ListClosedWorkflowExecutions"); public static readonly ActionIdentifier ListDomains = new ActionIdentifier("swf:ListDomains"); public static readonly ActionIdentifier ListOpenWorkflowExecutions = new ActionIdentifier("swf:ListOpenWorkflowExecutions"); public static readonly ActionIdentifier ListWorkflowTypes = new ActionIdentifier("swf:ListWorkflowTypes"); public static readonly ActionIdentifier PollForActivityTask = new ActionIdentifier("swf:PollForActivityTask"); public static readonly ActionIdentifier PollForDecisionTask = new ActionIdentifier("swf:PollForDecisionTask"); public static readonly ActionIdentifier RecordActivityTaskHeartbeat = new ActionIdentifier("swf:RecordActivityTaskHeartbeat"); public static readonly ActionIdentifier RecordMarker = new ActionIdentifier("swf:RecordMarker"); public static readonly ActionIdentifier RegisterActivityType = new ActionIdentifier("swf:RegisterActivityType"); public static readonly ActionIdentifier RegisterDomain = new ActionIdentifier("swf:RegisterDomain"); public static readonly ActionIdentifier RegisterWorkflowType = new ActionIdentifier("swf:RegisterWorkflowType"); public static readonly ActionIdentifier RequestCancelActivityTask = new ActionIdentifier("swf:RequestCancelActivityTask"); public static readonly ActionIdentifier RequestCancelExternalWorkflowExecution = new ActionIdentifier("swf:RequestCancelExternalWorkflowExecution"); public static readonly ActionIdentifier RequestCancelWorkflowExecution = new ActionIdentifier("swf:RequestCancelWorkflowExecution"); public static readonly ActionIdentifier RespondActivityTaskCanceled = new ActionIdentifier("swf:RespondActivityTaskCanceled"); public static readonly ActionIdentifier RespondActivityTaskCompleted = new ActionIdentifier("swf:RespondActivityTaskCompleted"); public static readonly ActionIdentifier RespondActivityTaskFailed = new ActionIdentifier("swf:RespondActivityTaskFailed"); public static readonly ActionIdentifier RespondDecisionTaskCompleted = new ActionIdentifier("swf:RespondDecisionTaskCompleted"); public static readonly ActionIdentifier ScheduleActivityTask = new ActionIdentifier("swf:ScheduleActivityTask"); public static readonly ActionIdentifier SignalExternalWorkflowExecution = new ActionIdentifier("swf:SignalExternalWorkflowExecution"); public static readonly ActionIdentifier SignalWorkflowExecution = new ActionIdentifier("swf:SignalWorkflowExecution"); public static readonly ActionIdentifier StartChildWorkflowExecution = new ActionIdentifier("swf:StartChildWorkflowExecution"); public static readonly ActionIdentifier StartTimer = new ActionIdentifier("swf:StartTimer"); public static readonly ActionIdentifier StartWorkflowExecution = new ActionIdentifier("swf:StartWorkflowExecution"); public static readonly ActionIdentifier TerminateWorkflowExecution = new ActionIdentifier("swf:TerminateWorkflowExecution"); } }
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.Text; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon SNS. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class SNSActionIdentifiers { public static readonly ActionIdentifier AllSNSActions = new ActionIdentifier("sns:*"); public static readonly ActionIdentifier AddPermission = new ActionIdentifier("sns:AddPermission"); public static readonly ActionIdentifier ConfirmSubscription = new ActionIdentifier("sns:ConfirmSubscription"); public static readonly ActionIdentifier CreatePlatformApplication = new ActionIdentifier("sns:CreatePlatformApplication"); public static readonly ActionIdentifier CreatePlatformEndpoint = new ActionIdentifier("sns:CreatePlatformEndpoint"); public static readonly ActionIdentifier CreateTopic = new ActionIdentifier("sns:CreateTopic"); public static readonly ActionIdentifier DeleteEndpoint = new ActionIdentifier("sns:DeleteEndpoint"); public static readonly ActionIdentifier DeletePlatformApplication = new ActionIdentifier("sns:DeletePlatformApplication"); public static readonly ActionIdentifier DeleteTopic = new ActionIdentifier("sns:DeleteTopic"); public static readonly ActionIdentifier GetEndpointAttributes = new ActionIdentifier("sns:GetEndpointAttributes"); public static readonly ActionIdentifier GetPlatformApplicationAttributes = new ActionIdentifier("sns:GetPlatformApplicationAttributes"); public static readonly ActionIdentifier GetSubscriptionAttributes = new ActionIdentifier("sns:GetSubscriptionAttributes"); public static readonly ActionIdentifier GetTopicAttributes = new ActionIdentifier("sns:GetTopicAttributes"); public static readonly ActionIdentifier ListEndpointsByPlatformApplication = new ActionIdentifier("sns:ListEndpointsByPlatformApplication"); public static readonly ActionIdentifier ListPlatformApplications = new ActionIdentifier("sns:ListPlatformApplications"); public static readonly ActionIdentifier ListSubscriptions = new ActionIdentifier("sns:ListSubscriptions"); public static readonly ActionIdentifier ListSubscriptionsByTopic = new ActionIdentifier("sns:ListSubscriptionsByTopic"); public static readonly ActionIdentifier ListTopics = new ActionIdentifier("sns:ListTopics"); public static readonly ActionIdentifier Publish = new ActionIdentifier("sns:Publish"); public static readonly ActionIdentifier RemovePermission = new ActionIdentifier("sns:RemovePermission"); public static readonly ActionIdentifier SetEndpointAttributes = new ActionIdentifier("sns:SetEndpointAttributes"); public static readonly ActionIdentifier SetPlatformApplicationAttributes = new ActionIdentifier("sns:SetPlatformApplicationAttributes"); public static readonly ActionIdentifier SetSubscriptionAttributes = new ActionIdentifier("sns:SetSubscriptionAttributes"); public static readonly ActionIdentifier SetTopicAttributes = new ActionIdentifier("sns:SetTopicAttributes"); public static readonly ActionIdentifier Subscribe = new ActionIdentifier("sns:Subscribe"); public static readonly ActionIdentifier Unsubscribe = new ActionIdentifier("sns:Unsubscribe"); } }
60
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon SQS. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class SQSActionIdentifiers { public static readonly ActionIdentifier AllSQSActions = new ActionIdentifier("sqs:*"); public static readonly ActionIdentifier AddPermission = new ActionIdentifier("sqs:AddPermission"); public static readonly ActionIdentifier ChangeMessageVisibility = new ActionIdentifier("sqs:ChangeMessageVisibility"); public static readonly ActionIdentifier CreateQueue = new ActionIdentifier("sqs:CreateQueue"); public static readonly ActionIdentifier DeleteMessage = new ActionIdentifier("sqs:DeleteMessage"); public static readonly ActionIdentifier DeleteQueue = new ActionIdentifier("sqs:DeleteQueue"); public static readonly ActionIdentifier GetQueueAttributes = new ActionIdentifier("sqs:GetQueueAttributes"); public static readonly ActionIdentifier GetQueueUrl = new ActionIdentifier("sqs:GetQueueUrl"); public static readonly ActionIdentifier ListQueues = new ActionIdentifier("sqs:ListQueues"); public static readonly ActionIdentifier ReceiveMessage = new ActionIdentifier("sqs:ReceiveMessage"); public static readonly ActionIdentifier RemovePermission = new ActionIdentifier("sqs:RemovePermission"); public static readonly ActionIdentifier SendMessage = new ActionIdentifier("sqs:SendMessage"); public static readonly ActionIdentifier SetQueueAttributes = new ActionIdentifier("sqs:SetQueueAttributes"); } }
47
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon Storage Gateway. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class StorageGatewayActionIdentifiers { public static readonly ActionIdentifier AllStorageGatewayActions = new ActionIdentifier("storagegateway:*"); public static readonly ActionIdentifier ActivateGateway = new ActionIdentifier("storagegateway:ActivateGateway"); public static readonly ActionIdentifier AddCache = new ActionIdentifier("storagegateway:AddCache"); public static readonly ActionIdentifier AddUploadBuffer = new ActionIdentifier("storagegateway:AddUploadBuffer"); public static readonly ActionIdentifier AddWorkingStorage = new ActionIdentifier("storagegateway:AddWorkingStorage"); public static readonly ActionIdentifier CancelArchival = new ActionIdentifier("storagegateway:CancelArchival"); public static readonly ActionIdentifier CancelRetrieval = new ActionIdentifier("storagegateway:CancelRetrieval"); public static readonly ActionIdentifier CreateCachediSCSIVolume = new ActionIdentifier("storagegateway:CreateCachediSCSIVolume"); public static readonly ActionIdentifier CreateSnapshot = new ActionIdentifier("storagegateway:CreateSnapshot"); public static readonly ActionIdentifier CreateSnapshotFromVolumeRecoveryPoint = new ActionIdentifier("storagegateway:CreateSnapshotFromVolumeRecoveryPoint"); public static readonly ActionIdentifier CreateStorediSCSIVolume = new ActionIdentifier("storagegateway:CreateStorediSCSIVolume"); public static readonly ActionIdentifier CreateTapes = new ActionIdentifier("storagegateway:CreateTapes"); public static readonly ActionIdentifier DeleteBandwidthRateLimit = new ActionIdentifier("storagegateway:DeleteBandwidthRateLimit"); public static readonly ActionIdentifier DeleteChapCredentials = new ActionIdentifier("storagegateway:DeleteChapCredentials"); public static readonly ActionIdentifier DeleteGateway = new ActionIdentifier("storagegateway:DeleteGateway"); public static readonly ActionIdentifier DeleteSnapshotSchedule = new ActionIdentifier("storagegateway:DeleteSnapshotSchedule"); public static readonly ActionIdentifier DeleteTape = new ActionIdentifier("storagegateway:DeleteTape"); public static readonly ActionIdentifier DeleteTapeArchive = new ActionIdentifier("storagegateway:DeleteTapeArchive"); public static readonly ActionIdentifier DeleteVolume = new ActionIdentifier("storagegateway:DeleteVolume"); public static readonly ActionIdentifier DescribeBandwidthRateLimit = new ActionIdentifier("storagegateway:DescribeBandwidthRateLimit"); public static readonly ActionIdentifier DescribeCache = new ActionIdentifier("storagegateway:DescribeCache"); public static readonly ActionIdentifier DescribeCachediSCSIVolumes = new ActionIdentifier("storagegateway:DescribeCachediSCSIVolumes"); public static readonly ActionIdentifier DescribeChapCredentials = new ActionIdentifier("storagegateway:DescribeChapCredentials"); public static readonly ActionIdentifier DescribeGatewayInformation = new ActionIdentifier("storagegateway:DescribeGatewayInformation"); public static readonly ActionIdentifier DescribeMaintenanceStartTime = new ActionIdentifier("storagegateway:DescribeMaintenanceStartTime"); public static readonly ActionIdentifier DescribeSnapshotSchedule = new ActionIdentifier("storagegateway:DescribeSnapshotSchedule"); public static readonly ActionIdentifier DescribeStorediSCSIVolumes = new ActionIdentifier("storagegateway:DescribeStorediSCSIVolumes"); public static readonly ActionIdentifier DescribeTapeArchives = new ActionIdentifier("storagegateway:DescribeTapeArchives"); public static readonly ActionIdentifier DescribeTapeRecoveryPoints = new ActionIdentifier("storagegateway:DescribeTapeRecoveryPoints"); public static readonly ActionIdentifier DescribeTapes = new ActionIdentifier("storagegateway:DescribeTapes"); public static readonly ActionIdentifier DescribeUploadBuffer = new ActionIdentifier("storagegateway:DescribeUploadBuffer"); public static readonly ActionIdentifier DescribeVTLDevices = new ActionIdentifier("storagegateway:DescribeVTLDevices"); public static readonly ActionIdentifier DescribeWorkingStorage = new ActionIdentifier("storagegateway:DescribeWorkingStorage"); public static readonly ActionIdentifier DisableGateway = new ActionIdentifier("storagegateway:DisableGateway"); public static readonly ActionIdentifier ListGateways = new ActionIdentifier("storagegateway:ListGateways"); public static readonly ActionIdentifier ListLocalDisks = new ActionIdentifier("storagegateway:ListLocalDisks"); public static readonly ActionIdentifier ListVolumeRecoveryPoints = new ActionIdentifier("storagegateway:ListVolumeRecoveryPoints"); public static readonly ActionIdentifier ListVolumes = new ActionIdentifier("storagegateway:ListVolumes"); public static readonly ActionIdentifier RetrieveTapeArchive = new ActionIdentifier("storagegateway:RetrieveTapeArchive"); public static readonly ActionIdentifier RetrieveTapeRecoveryPoint = new ActionIdentifier("storagegateway:RetrieveTapeRecoveryPoint"); public static readonly ActionIdentifier ShutdownGateway = new ActionIdentifier("storagegateway:ShutdownGateway"); public static readonly ActionIdentifier StartGateway = new ActionIdentifier("storagegateway:StartGateway"); public static readonly ActionIdentifier UpdateBandwidthRateLimit = new ActionIdentifier("storagegateway:UpdateBandwidthRateLimit"); public static readonly ActionIdentifier UpdateChapCredentials = new ActionIdentifier("storagegateway:UpdateChapCredentials"); public static readonly ActionIdentifier UpdateGatewayInformation = new ActionIdentifier("storagegateway:UpdateGatewayInformation"); public static readonly ActionIdentifier UpdateGatewaySoftwareNow = new ActionIdentifier("storagegateway:UpdateGatewaySoftwareNow"); public static readonly ActionIdentifier UpdateMaintenanceStartTime = new ActionIdentifier("storagegateway:UpdateMaintenanceStartTime"); public static readonly ActionIdentifier UpdateSnapshotSchedule = new ActionIdentifier("storagegateway:UpdateSnapshotSchedule"); } }
82
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for AWS Whispersync. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class WhispersyncActionIdentifiers { public static readonly ActionIdentifier AllWhispersyncActions = new ActionIdentifier("whispersync:*"); public static readonly ActionIdentifier GetDatamapUpdates = new ActionIdentifier("whispersync:GetDatamapUpdates"); public static readonly ActionIdentifier PatchDatamapUpdates = new ActionIdentifier("whispersync:PatchDatamapUpdates"); } }
37
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.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon Zocalo. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> [Obsolete( "The Amazon.Auth.AccessContolPolicy classes are out of date and are no longer being maintained.\n" + "Please construct policy documents using the information found here: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json")] public static class ZocaloActionIdentifiers { public static readonly ActionIdentifier AllZocaloActions = new ActionIdentifier("zocalo:*"); public static readonly ActionIdentifier ActivateUser = new ActionIdentifier("zocalo:ActivateUser"); public static readonly ActionIdentifier AddUserToGroup = new ActionIdentifier("zocalo:AddUserToGroup"); public static readonly ActionIdentifier CheckAlias = new ActionIdentifier("zocalo:CheckAlias"); public static readonly ActionIdentifier CreateInstance = new ActionIdentifier("zocalo:CreateInstance"); public static readonly ActionIdentifier DeactivateUser = new ActionIdentifier("zocalo:DeactivateUser"); public static readonly ActionIdentifier DeleteInstance = new ActionIdentifier("zocalo:DeleteInstance"); public static readonly ActionIdentifier DeregisterDirectory = new ActionIdentifier("zocalo:DeregisterDirectory"); public static readonly ActionIdentifier DescribeAvailableDirectories = new ActionIdentifier("zocalo:DescribeAvailableDirectories"); public static readonly ActionIdentifier DescribeInstances = new ActionIdentifier("zocalo:DescribeInstances"); public static readonly ActionIdentifier RegisterDirectory = new ActionIdentifier("zocalo:RegisterDirectory"); public static readonly ActionIdentifier RemoveUserFromGroup = new ActionIdentifier("zocalo:RemoveUserFromGroup"); public static readonly ActionIdentifier UpdateInstanceAlias = new ActionIdentifier("zocalo:UpdateInstanceAlias"); } }
47
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.Auth.AccessControlPolicy.Internal { internal static class JsonDocumentFields { internal const string VERSION = "Version"; internal const string POLICY_ID = "Id"; internal const string STATEMENT = "Statement"; internal const string STATEMENT_EFFECT = "Effect"; internal const string EFFECT_VALUE_ALLOW = "Allow"; internal const string STATEMENT_ID = "Sid"; internal const string PRINCIPAL = "Principal"; internal const string ACTION = "Action"; internal const string RESOURCE = "Resource"; internal const string CONDITION = "Condition"; } }
37
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.IO; using System.Collections.Generic; using System.Text; using ThirdParty.Json.LitJson; namespace Amazon.Auth.AccessControlPolicy.Internal { /// <summary> /// Deserializes a JSON string into a AWS policy object. /// </summary> internal static class JsonPolicyReader { public static Policy ReadJsonStringToPolicy(string jsonString) { Policy policy = new Policy(); JsonData jPolicy = JsonMapper.ToObject(jsonString); if (jPolicy[JsonDocumentFields.POLICY_ID] != null && jPolicy[JsonDocumentFields.POLICY_ID].IsString) { policy.Id = (string)jPolicy[JsonDocumentFields.POLICY_ID]; } JsonData jStatements = jPolicy[JsonDocumentFields.STATEMENT] as JsonData; if (jStatements != null && jStatements.IsArray) { foreach (JsonData jStatement in jStatements) { Statement statement = convertStatement(jStatement); if (statement != null) { policy.Statements.Add(statement); } } } return policy; } private static Statement convertStatement(JsonData jStatement) { if (jStatement[JsonDocumentFields.STATEMENT_EFFECT] == null || !jStatement[JsonDocumentFields.STATEMENT_EFFECT].IsString) return null; string jEffect = (string)jStatement[JsonDocumentFields.STATEMENT_EFFECT]; Statement.StatementEffect effect; if (JsonDocumentFields.EFFECT_VALUE_ALLOW.Equals(jEffect)) effect = Statement.StatementEffect.Allow; else effect = Statement.StatementEffect.Deny; Statement statement = new Statement(effect); if (jStatement[JsonDocumentFields.STATEMENT_ID] != null && jStatement[JsonDocumentFields.STATEMENT_ID].IsString) statement.Id = (string)jStatement[JsonDocumentFields.STATEMENT_ID]; convertActions(statement, jStatement); convertResources(statement, jStatement); convertCondition(statement, jStatement); convertPrincipals(statement, jStatement); return statement; } private static void convertPrincipals(Statement statement, JsonData jStatement) { JsonData jPrincipals = jStatement[JsonDocumentFields.PRINCIPAL]; if (jPrincipals == null) { return; } if (jPrincipals.IsObject) { convertPrincipalRecord(statement, jPrincipals); } else if (jPrincipals.IsArray) { foreach (JsonData jPrincipal in jPrincipals) { convertPrincipalRecord(statement, jPrincipal); } } else if (jPrincipals.IsString && jPrincipals.Equals("*")) { statement.Principals.Add(Principal.Anonymous); } } private static void convertPrincipalRecord(Statement statement, JsonData jPrincipal) { foreach (KeyValuePair<string, JsonData> kvp in jPrincipal) { if (kvp.Value == null) { continue; } if (kvp.Value.IsArray) { foreach (JsonData tok in kvp.Value) { if (tok.IsString) { // Don't strip '-' and assume the policy being deserialized is already valid. Principal principal = new Principal(kvp.Key, (string)tok, false); statement.Principals.Add(principal); } } } else if(kvp.Value.IsString) { // Don't strip '-' and assume the policy being deserialized is already valid. Principal principal = new Principal(kvp.Key, (string)kvp.Value, false); statement.Principals.Add(principal); } } } private static void convertActions(Statement statement, JsonData jStatement) { JsonData jActions = jStatement[JsonDocumentFields.ACTION]; if (jActions == null) { return; } if (jActions.IsString) { statement.Actions.Add(new ActionIdentifier((string)jActions)); } else if (jActions.IsArray) { foreach (JsonData jActionValue in jActions) { if (jActionValue.IsString) { statement.Actions.Add(new ActionIdentifier((string)jActionValue)); } } } } private static void convertResources(Statement statement, JsonData jStatement) { JsonData jResources = jStatement[JsonDocumentFields.RESOURCE]; if (jResources == null) { return; } if (jResources.IsString) { statement.Resources.Add(new Resource((string)jResources)); } else if (jResources.IsArray) { foreach (JsonData jResourceValue in jResources) { if (jResourceValue.IsString) { statement.Resources.Add(new Resource((string)jResourceValue)); } } } } private static void convertCondition(Statement statement, JsonData jStatement) { JsonData jConditions = jStatement[JsonDocumentFields.CONDITION]; if (jConditions == null) { return; } if (jConditions.IsObject) { convertConditionRecord(statement, jConditions); } else if (jConditions.IsArray) { foreach (JsonData jCondition in jConditions) { convertConditionRecord(statement, jCondition); } } } private static void convertConditionRecord(Statement statement, JsonData jCondition) { foreach (KeyValuePair<string, JsonData> kvp1 in jCondition) { string type = kvp1.Key; JsonData comparisons = kvp1.Value; foreach (KeyValuePair<string, JsonData> kvp2 in comparisons) { string key = kvp2.Key; List<string> values = new List<string>(); if (kvp2.Value != null) { if (kvp2.Value.IsString) { values.Add((string)kvp2.Value); } else if (kvp2.Value.IsArray) { foreach (JsonData jValue in kvp2.Value) { if (jValue.IsString) { values.Add((string)jValue); } } } } Condition condition = new Condition(type, key, values.ToArray()); statement.Conditions.Add(condition); } } } } }
241
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.IO; using System.Collections.Generic; using System.Text; using ThirdParty.Json.LitJson; using System.Globalization; namespace Amazon.Auth.AccessControlPolicy.Internal { /// <summary> /// Serializes an AWS policy object to a JSON string, suitable for sending to an /// AWS service. /// </summary> internal static class JsonPolicyWriter { /** * Converts the specified AWS policy object to a JSON string, suitable for * passing to an AWS service. * * @param policy * The AWS policy object to convert to a JSON string. * * @return The JSON string representation of the specified policy object. * * @throws IllegalArgumentException * If the specified policy is null or invalid and cannot be * serialized to a JSON string. */ public static string WritePolicyToString(bool prettyPrint, Policy policy) { if (policy == null) { throw new ArgumentNullException("policy"); } StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); try { JsonWriter generator = new JsonWriter(writer); generator.IndentValue = 4; generator.PrettyPrint = prettyPrint; writePolicy(policy, generator); return writer.ToString().Trim(); } catch (Exception e) { string message = "Unable to serialize policy to JSON string: " + e.Message; throw new ArgumentException(message, e); } } private static void writePolicy(Policy policy, JsonWriter generator) { generator.WriteObjectStart(); writePropertyValue(generator, JsonDocumentFields.VERSION, policy.Version); if (policy.Id != null) { writePropertyValue(generator, JsonDocumentFields.POLICY_ID, policy.Id); } generator.WritePropertyName(JsonDocumentFields.STATEMENT); generator.WriteArrayStart(); foreach (Statement statement in policy.Statements) { generator.WriteObjectStart(); if (statement.Id != null) { writePropertyValue(generator, JsonDocumentFields.STATEMENT_ID, statement.Id); } writePropertyValue(generator, JsonDocumentFields.STATEMENT_EFFECT, statement.Effect.ToString()); writePrincipals(statement, generator); writeActions(statement, generator); writeResources(statement, generator); writeConditions(statement, generator); generator.WriteObjectEnd(); } generator.WriteArrayEnd(); generator.WriteObjectEnd(); } /// <summary> /// Uses the specified generator to write the JSON data for the principals in /// the specified policy statement. /// </summary> private static void writePrincipals(Statement statement, JsonWriter generator) { IList<Principal> principals = statement.Principals; if (principals == null || principals.Count == 0) return; generator.WritePropertyName(JsonDocumentFields.PRINCIPAL); if (principals.Count == 1 && principals[0] != null && principals[0].Provider.Equals(Principal.ANONYMOUS_PROVIDER, StringComparison.Ordinal)) { generator.Write("*"); return; } generator.WriteObjectStart(); Dictionary<string, List<string>> principalIdsByScheme = new Dictionary<string, List<string>>(); foreach (Principal p in principals) { List<string> principalIds; if (!principalIdsByScheme.TryGetValue(p.Provider, out principalIds)) { principalIds = new List<string>(); principalIdsByScheme[p.Provider] = principalIds; } principalIds.Add(p.Id); } foreach (string scheme in principalIdsByScheme.Keys) { generator.WritePropertyName(scheme); if (principalIdsByScheme[scheme].Count > 1) { generator.WriteArrayStart(); } foreach (string principalId in principalIdsByScheme[scheme]) { generator.Write(principalId); } if (principalIdsByScheme[scheme].Count > 1) { generator.WriteArrayEnd(); } } generator.WriteObjectEnd(); } private static void writeActions(Statement statement, JsonWriter generator) { IList<ActionIdentifier> actions = statement.Actions; if (actions == null || actions.Count == 0) { return; } generator.WritePropertyName(JsonDocumentFields.ACTION); if (actions.Count > 1) { generator.WriteArrayStart(); } foreach (ActionIdentifier action in actions) { generator.Write(action.ActionName); } if (actions.Count > 1) { generator.WriteArrayEnd(); } } private static void writeResources(Statement statement, JsonWriter generator) { IList<Resource> resources = statement.Resources; if (resources == null || resources.Count == 0) { return; } generator.WritePropertyName(JsonDocumentFields.RESOURCE); if (resources.Count > 1) { generator.WriteArrayStart(); } foreach (Resource resource in resources) { generator.Write(resource.Id); } if (resources.Count > 1) { generator.WriteArrayEnd(); } } private static void writeConditions(Statement statement, JsonWriter generator) { IList<Condition> conditions = statement.Conditions; if (conditions == null || conditions.Count == 0) { return; } /* * The condition values must be grouped by all the unique condition types and keys because * the values are written out as an array per type and key. */ Dictionary<string, Dictionary<string, List<string>>> conditionsByTypeAndKeys = sortConditionsByTypeAndKey(conditions); generator.WritePropertyName(JsonDocumentFields.CONDITION); generator.WriteObjectStart(); foreach (KeyValuePair<string, Dictionary<string, List<string>>> typeEntry in conditionsByTypeAndKeys) { generator.WritePropertyName(typeEntry.Key); generator.WriteObjectStart(); foreach (KeyValuePair<string, List<string>> keyEntry in typeEntry.Value) { IList<string> conditionValues = keyEntry.Value; if (conditionValues.Count == 0) continue; generator.WritePropertyName(keyEntry.Key); if (conditionValues.Count > 1) { generator.WriteArrayStart(); } if (conditionValues != null && conditionValues.Count != 0) { foreach (string conditionValue in conditionValues) { generator.Write(conditionValue); } } if (conditionValues.Count > 1) { generator.WriteArrayEnd(); } } generator.WriteObjectEnd(); } generator.WriteObjectEnd(); } /// <summary> /// This sorts the conditions by condition type and key with the list of values for that combination. /// </summary> /// <param name="conditions">The list of conditions to be sorted.</param> /// <returns></returns> private static Dictionary<string, Dictionary<string, List<string>>> sortConditionsByTypeAndKey(IList<Condition> conditions) { Dictionary<string, Dictionary<string, List<string>>> conditionsByTypeAndKeys = new Dictionary<string, Dictionary<string, List<string>>>(); foreach (Condition condition in conditions) { string conditionType = condition.Type; string conditionKey = condition.ConditionKey; Dictionary<string, List<string>> keys; if (!conditionsByTypeAndKeys.TryGetValue(conditionType, out keys)) { keys = new Dictionary<string, List<string>>(); conditionsByTypeAndKeys[conditionType] = keys; } List<string> values; if (!keys.TryGetValue(conditionKey, out values)) { values = new List<string>(); keys[conditionKey] = values; } if (condition.Values != null) { foreach (string value in condition.Values) { values.Add(value); } } } return conditionsByTypeAndKeys; } private static void writePropertyValue(JsonWriter generator, string propertyName, string value) { generator.WritePropertyName(propertyName); generator.Write(value); } } }
303
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> /// Base exception for AccountId error. /// </summary> #if !NETSTANDARD [Serializable] #endif public class AmazonAccountIdException : AmazonClientException { /// <summary> /// Construct an instance of AmazonAccountIdException /// </summary> public AmazonAccountIdException() : base("AccountId is invalid. The AccountId length should be 12 and only contain numeric characters with no spaces or periods.") { } /// <summary> /// Construct an instance of AmazonAccountIdException /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public AmazonAccountIdException(string message) : base(message) { } /// <summary> /// Construct an instance of AmazonAccountIdException /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public AmazonAccountIdException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AmazonAccountIdException 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 AmazonAccountIdException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
70
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 { /// <summary> /// Exception thrown by the SDK for errors that occur within the SDK. /// </summary> #if !NETSTANDARD [Serializable] #endif public class AmazonClientException : Exception { public AmazonClientException(string message) : base(message) { } public AmazonClientException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AmazonClientException 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 AmazonClientException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
48
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 { /// <summary> /// This exception is thrown when there is a parse error on the response back from AWS. /// </summary> #if !NETSTANDARD [Serializable] #endif public class AmazonDateTimeUnmarshallingException : AmazonUnmarshallingException { #region Public properties /// <summary> /// The string value which could not be converted into a valid DateTime instance. /// </summary> public string InvalidDateTimeToken { get; private set; } #endregion #region Constructors public AmazonDateTimeUnmarshallingException(string requestId, string lastKnownLocation, string invalidDateTimeToken,Exception innerException) : base(requestId, lastKnownLocation, innerException) { this.InvalidDateTimeToken = invalidDateTimeToken; } public AmazonDateTimeUnmarshallingException(string requestId, string lastKnownLocation, string responseBody, string invalidDateTimeToken,Exception innerException) : base(requestId, lastKnownLocation, responseBody, innerException) { this.InvalidDateTimeToken = invalidDateTimeToken; } public AmazonDateTimeUnmarshallingException(string requestId, string lastKnownLocation, string responseBody, string invalidDateTimeToken,string message, Exception innerException) : base(requestId, lastKnownLocation, responseBody, message, innerException) { this.InvalidDateTimeToken = invalidDateTimeToken; } #endregion #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AmazonDateTimeUnmarshallingException 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 AmazonDateTimeUnmarshallingException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { if (info != null) { this.InvalidDateTimeToken = info.GetString("InvalidDateTimeToken"); } } /// <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); if (info != null) { info.AddValue("InvalidDateTimeToken", this.InvalidDateTimeToken); } } #endif } }
104
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 Amazon.Util; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Linq; using System.Threading; using Amazon.Util.Internal; using ExecutionContext = Amazon.Runtime.Internal.ExecutionContext; namespace Amazon.Runtime { public abstract class AmazonServiceClient : IDisposable { private static volatile bool _isProtocolUpdated; private bool _disposed; private Logger _logger; protected EndpointDiscoveryResolverBase EndpointDiscoveryResolver { get; private set; } protected RuntimePipeline RuntimePipeline { get; set; } protected internal AWSCredentials Credentials { get; private set; } public IClientConfig Config => _config; private readonly ClientConfig _config; protected virtual IServiceMetadata ServiceMetadata { get; } = new ServiceMetadata(); protected virtual bool SupportResponseLogging { get { return true; } } #region Events private PreRequestEventHandler mBeforeMarshallingEvent; /// <summary> /// Occurs before a request is marshalled. /// </summary> internal event PreRequestEventHandler BeforeMarshallingEvent { add { lock (this) { mBeforeMarshallingEvent += value; } } remove { lock (this) { mBeforeMarshallingEvent -= value; } } } private RequestEventHandler mBeforeRequestEvent; /// <summary> /// Occurs before a request is issued against the service. /// </summary> public event RequestEventHandler BeforeRequestEvent { add { lock (this) { mBeforeRequestEvent += value; } } remove { lock (this) { mBeforeRequestEvent -= value; } } } private ResponseEventHandler mAfterResponseEvent; /// <summary> /// Occurs after a response is received from the service. /// </summary> public event ResponseEventHandler AfterResponseEvent { add { lock (this) { mAfterResponseEvent += value; } } remove { lock (this) { mAfterResponseEvent -= value; } } } private ExceptionEventHandler mExceptionEvent; /// <summary> /// Occurs after an exception is encountered. /// </summary> public event ExceptionEventHandler ExceptionEvent { add { lock (this) { mExceptionEvent += value; } } remove { lock (this) { mExceptionEvent -= value; } } } #endregion #region Constructors protected AmazonServiceClient(AWSCredentials credentials, ClientConfig config) { if (config.DisableLogging) _logger = Logger.EmptyLogger; else _logger = Logger.GetLogger(this.GetType()); config.Validate(); this.Credentials = credentials; _config = config; Signer = CreateSigner(); EndpointDiscoveryResolver = new EndpointDiscoveryResolver(config, _logger); Initialize(); UpdateSecurityProtocol(); BuildRuntimePipeline(); } protected AbstractAWSSigner Signer { get; private set; } protected AmazonServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, ClientConfig config) : this(new SessionAWSCredentials(awsAccessKeyId, awsSecretAccessKey, awsSessionToken), config) { } protected AmazonServiceClient(string awsAccessKeyId, string awsSecretAccessKey, ClientConfig config) : this(new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey), config) { } protected virtual void Initialize() { } #endregion #region Invoke methods [Obsolete("Invoke taking marshallers is obsolete. Use Invoke taking InvokeOptionsBase instead.")] protected TResponse Invoke<TRequest, TResponse>(TRequest request, IMarshaller<IRequest, AmazonWebServiceRequest> marshaller, ResponseUnmarshaller unmarshaller) where TRequest : AmazonWebServiceRequest where TResponse : AmazonWebServiceResponse { var options = new InvokeOptions(); options.RequestMarshaller = marshaller; options.ResponseUnmarshaller = unmarshaller; return Invoke<TResponse>(request, options); } protected TResponse Invoke<TResponse>(AmazonWebServiceRequest request, InvokeOptionsBase options) where TResponse : AmazonWebServiceResponse { ThrowIfDisposed(); var executionContext = new ExecutionContext( new RequestContext(this.Config.LogMetrics, Signer) { ClientConfig = this.Config, Marshaller = options.RequestMarshaller, OriginalRequest = request, Unmarshaller = options.ResponseUnmarshaller, IsAsync = false, ServiceMetaData = this.ServiceMetadata, Options = options }, new ResponseContext() ); SetupCSMHandler(executionContext.RequestContext); var response = (TResponse)this.RuntimePipeline.InvokeSync(executionContext).Response; return response; } #if AWS_ASYNC_API [Obsolete("InvokeAsync taking marshallers is obsolete. Use InvokeAsync taking InvokeOptionsBase instead.")] protected System.Threading.Tasks.Task<TResponse> InvokeAsync<TRequest, TResponse>( TRequest request, IMarshaller<IRequest, AmazonWebServiceRequest> marshaller, ResponseUnmarshaller unmarshaller, System.Threading.CancellationToken cancellationToken) where TRequest: AmazonWebServiceRequest where TResponse : AmazonWebServiceResponse, new() { var options = new InvokeOptions(); options.RequestMarshaller = marshaller; options.ResponseUnmarshaller = unmarshaller; return InvokeAsync<TResponse>(request, options, cancellationToken); } protected System.Threading.Tasks.Task<TResponse> InvokeAsync<TResponse>( AmazonWebServiceRequest request, InvokeOptionsBase options, System.Threading.CancellationToken cancellationToken) where TResponse : AmazonWebServiceResponse, new() { ThrowIfDisposed(); #if AWS_ASYNC_API if (cancellationToken == default(CancellationToken)) cancellationToken = _config.BuildDefaultCancellationToken(); #endif var executionContext = new ExecutionContext( new RequestContext(this.Config.LogMetrics, Signer) { ClientConfig = this.Config, Marshaller = options.RequestMarshaller, OriginalRequest = request, Unmarshaller = options.ResponseUnmarshaller, IsAsync = true, CancellationToken = cancellationToken, ServiceMetaData = this.ServiceMetadata, Options = options }, new ResponseContext() ); SetupCSMHandler(executionContext.RequestContext); return this.RuntimePipeline.InvokeAsync<TResponse>(executionContext); } #elif AWS_APM_API [Obsolete("BeginInvoke taking marshallers is obsolete. Use BeginInvoke taking InvokeOptionsBase instead.")] protected IAsyncResult BeginInvoke<TRequest>(TRequest request, IMarshaller<IRequest, AmazonWebServiceRequest> marshaller, ResponseUnmarshaller unmarshaller, AsyncCallback callback, object state) where TRequest : AmazonWebServiceRequest { var options = new InvokeOptions(); options.RequestMarshaller = marshaller; options.ResponseUnmarshaller = unmarshaller; return BeginInvoke(request, options, callback, state); } protected IAsyncResult BeginInvoke(AmazonWebServiceRequest request, InvokeOptionsBase options, AsyncCallback callback, object state) { ThrowIfDisposed(); var executionContext = new AsyncExecutionContext( new AsyncRequestContext(this.Config.LogMetrics, Signer) { ClientConfig = this.Config, Marshaller = options.RequestMarshaller, OriginalRequest = request, Unmarshaller = options.ResponseUnmarshaller, Callback = callback, State = state, IsAsync = true, ServiceMetaData = this.ServiceMetadata, Options = options }, new AsyncResponseContext() ); SetupCSMHandler(executionContext.RequestContext); var asyncResult = this.RuntimePipeline.InvokeAsync(executionContext); return asyncResult; } protected static TResponse EndInvoke<TResponse>(IAsyncResult result) where TResponse : AmazonWebServiceResponse { if (result == null) throw new ArgumentNullException("result", "Parameter result cannot be null."); var asyncResult = result as RuntimeAsyncResult; if (asyncResult == null) throw new ArgumentOutOfRangeException("result", "Parameter result is not of type RuntimeAsyncResult."); using (asyncResult) { if (!asyncResult.IsCompleted) { asyncResult.AsyncWaitHandle.WaitOne(); } if (asyncResult.Exception != null) { AWSSDKUtils.PreserveStackTrace(asyncResult.Exception); throw asyncResult.Exception; } return (TResponse)asyncResult.Response; } } #endif protected virtual IEnumerable<DiscoveryEndpointBase> EndpointOperation(EndpointOperationContextBase context) { return null; } #endregion #region Process Handlers protected void ProcessPreRequestHandlers(IExecutionContext executionContext) { //if (request == null) // return; if (mBeforeMarshallingEvent == null) return; PreRequestEventArgs args = PreRequestEventArgs.Create(executionContext.RequestContext.OriginalRequest); mBeforeMarshallingEvent(this, args); } protected void ProcessRequestHandlers(IExecutionContext executionContext) { var request = executionContext.RequestContext.Request; WebServiceRequestEventArgs args = WebServiceRequestEventArgs.Create(request); if (request.OriginalRequest != null) request.OriginalRequest.FireBeforeRequestEvent(this, args); if (mBeforeRequestEvent != null) mBeforeRequestEvent(this, args); } protected void ProcessResponseHandlers(IExecutionContext executionContext) { if (mAfterResponseEvent == null) return; WebServiceResponseEventArgs args = WebServiceResponseEventArgs.Create( executionContext.ResponseContext.Response, executionContext.RequestContext.Request, executionContext.ResponseContext.HttpResponse); mAfterResponseEvent(this, args); } protected virtual void ProcessExceptionHandlers(IExecutionContext executionContext, Exception exception) { if (mExceptionEvent == null) return; WebServiceExceptionEventArgs args = WebServiceExceptionEventArgs.Create(exception, executionContext.RequestContext.Request); mExceptionEvent(this, args); } #endregion #region Dispose methods public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { if (RuntimePipeline != null) RuntimePipeline.Dispose(); _disposed = true; } } private void ThrowIfDisposed() { if (this._disposed) throw new ObjectDisposedException(GetType().FullName); } #endregion protected abstract AbstractAWSSigner CreateSigner(); protected virtual void CustomizeRuntimePipeline(RuntimePipeline pipeline) { } private void BuildRuntimePipeline() { #if BCL var httpRequestFactory = new HttpWebRequestFactory(); var httpHandler = new HttpHandler<Stream>(httpRequestFactory, this); #else var httpRequestFactory = new HttpRequestMessageFactory(this.Config); var httpHandler = new HttpHandler<System.Net.Http.HttpContent>(httpRequestFactory, this); #endif var preMarshallHandler = new CallbackHandler(); preMarshallHandler.OnPreInvoke = this.ProcessPreRequestHandlers; var postMarshallHandler = new CallbackHandler(); postMarshallHandler.OnPreInvoke = this.ProcessRequestHandlers; var postUnmarshallHandler = new CallbackHandler(); postUnmarshallHandler.OnPostInvoke = this.ProcessResponseHandlers; var errorCallbackHandler = new ErrorCallbackHandler(); errorCallbackHandler.OnError = this.ProcessExceptionHandlers; //Determine which retry policy to use based on the retry mode RetryPolicy retryPolicy; switch (this.Config.RetryMode) { case RequestRetryMode.Adaptive: retryPolicy = new AdaptiveRetryPolicy(this.Config); break; case RequestRetryMode.Standard: retryPolicy = new StandardRetryPolicy(this.Config); break; case RequestRetryMode.Legacy: retryPolicy = new DefaultRetryPolicy(this.Config); break; default: throw new InvalidOperationException("Unknown retry mode"); } // Build default runtime pipeline. this.RuntimePipeline = new RuntimePipeline(new List<IPipelineHandler> { httpHandler, new Unmarshaller(this.SupportResponseLogging), new ErrorHandler(_logger), postUnmarshallHandler, new Signer(), //EndpointDiscoveryResolver must come after CredentialsRetriever, RetryHander, and EndpointResolver as it depends on //credentials, retrying of requests for 421 web exceptions, and the current set regional endpoint. new EndpointDiscoveryHandler(), new CredentialsRetriever(this.Credentials), new RetryHandler(retryPolicy), postMarshallHandler, new EndpointResolver(), new Marshaller(), preMarshallHandler, errorCallbackHandler, new MetricsHandler() }, _logger ); if (DeterminedCSMConfiguration.Instance.CSMConfiguration.Enabled && !string.IsNullOrEmpty(ServiceMetadata.ServiceId)) { this.RuntimePipeline.AddHandlerBefore<ErrorHandler>(new CSMCallAttemptHandler()); this.RuntimePipeline.AddHandlerBefore<MetricsHandler>(new CSMCallEventHandler()); } CustomizeRuntimePipeline(this.RuntimePipeline); // Apply global pipeline customizations RuntimePipelineCustomizerRegistry.Instance.ApplyCustomizations(this.GetType(), this.RuntimePipeline); } /// <summary> /// Some AWS services like Cloud 9 require at least TLS 1.1. Version of .NET Framework 4.5 and earlier /// do not eanble TLS 1.1 and TLS 1.2 by default. This code adds those protocols if using an earlier /// version of .NET that explicitly set the protocol and didn't have TLS 1.1 and TLS 1.2. /// </summary> private void UpdateSecurityProtocol() { if (_isProtocolUpdated) return; var amazonSecurityProtocolManager = new AmazonSecurityProtocolManager(); try { if (!amazonSecurityProtocolManager.IsSecurityProtocolSystemDefault()) { amazonSecurityProtocolManager.UpdateProtocolsToSupported(); } } catch (Exception ex) { if (ex is NotSupportedException) { _logger.InfoFormat(ex.Message); } else { _logger.InfoFormat("Unexpected error " + ex.GetType().Name + " encountered when trying to set Security Protocol.\n" + ex); } } _isProtocolUpdated = true; } /// <summary> /// Assembles the Uri for a given SDK request /// </summary> /// <param name="iRequest">Request to compute Uri for</param> /// <returns>Uri for the given SDK request</returns> public static Uri ComposeUrl(IRequest iRequest) { return ComposeUrl(iRequest, true); } /// <summary> /// Assembles the Uri for a given SDK request /// </summary> /// <param name="internalRequest">Request to compute Uri for</param> /// <param name="skipEncodingValidPathChars">If true the accepted path characters {/+:} are not encoded.</param> /// <returns>Uri for the given SDK request</returns> public static Uri ComposeUrl(IRequest internalRequest, bool skipEncodingValidPathChars) { Uri url = internalRequest.Endpoint; var resourcePath = internalRequest.ResourcePath; if (resourcePath == null) resourcePath = string.Empty; else { if (resourcePath.StartsWith("/", StringComparison.Ordinal)) resourcePath = resourcePath.Substring(1); // Microsoft added support for unicode bidi control characters to the Uri class in .NET 4.7.2 // https://github.com/microsoft/dotnet/blob/master/Documentation/compatibility/uri-unicode-bidirectional-characters.md // However, we only want to support it on .NET Core 3.1 and higher due to not having to deal with .NET Standard support matrix. #if BCL || NETSTANDARD20 if (AWSSDKUtils.HasBidiControlCharacters(resourcePath) || (internalRequest.PathResources?.Any(v => AWSSDKUtils.HasBidiControlCharacters(v.Value)) == true)) { resourcePath = string.Join("/", AWSSDKUtils.SplitResourcePathIntoSegments(resourcePath, internalRequest.PathResources).ToArray()); throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "Target resource path [{0}] has bidirectional characters, which are not supported" + "by System.Uri and thus cannot be handled by the .NET SDK.", resourcePath)); } #endif resourcePath = AWSSDKUtils.ResolveResourcePath(resourcePath, internalRequest.PathResources, skipEncodingValidPathChars); } // Construct any sub resource/query parameter additions to append to the // resource path. Services like S3 which allow '?' and/or '&' in resource paths // should use SubResources instead of appending them to the resource path with // query string delimiters during request marshalling. var delim = "?"; var sb = new StringBuilder(); if (internalRequest.SubResources?.Count > 0) { foreach (var subResource in internalRequest.SubResources) { sb.AppendFormat("{0}{1}", delim, subResource.Key); if (subResource.Value != null) sb.AppendFormat("={0}", subResource.Value); delim = "&"; } } if (internalRequest.UseQueryString && internalRequest.Parameters?.Count > 0) { var queryString = AWSSDKUtils.GetParametersAsString(internalRequest); sb.AppendFormat("{0}{1}", delim, queryString); } var parameterizedPath = string.Empty; if(internalRequest.MarshallerVersion >= 2) { parameterizedPath = string.Concat(resourcePath, sb); } else { if (AWSSDKUtils.HasBidiControlCharacters(resourcePath)) throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "Target resource path [{0}] has bidirectional characters, which are not supported" + "by System.Uri and thus cannot be handled by the .NET SDK.", resourcePath)); parameterizedPath = string.Concat(AWSSDKUtils.ProtectEncodedSlashUrlEncode(resourcePath, skipEncodingValidPathChars), sb); } var hasSlash = url.AbsoluteUri.EndsWith("/", StringComparison.Ordinal) || parameterizedPath.StartsWith("/", StringComparison.Ordinal); var uri = hasSlash ? new Uri(url.AbsoluteUri + parameterizedPath) : new Uri(url.AbsoluteUri + "/" + parameterizedPath); DontUnescapePathDotsAndSlashes(uri); return uri; } /// <summary> /// Patches the in-flight uri to stop it unescaping the path etc (what Uri did before /// Microsoft deprecated the constructor flag). This is particularly important for /// Amazon S3 customers who want to use backslash (\) in their key names. /// </summary> /// <remarks> /// Different behavior in the various runtimes has been observed and in addition some /// 'documented' ways of doing this between 2.x and 4.x runtimes has also been observed /// to not be reliable. /// /// This patch effectively emulates what adding a schemesettings element to the /// app.config file with value 'name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes"' /// does. As we're a dll, that avenue is not open to us. /// </remarks> /// <param name="uri"></param> private static void DontUnescapePathDotsAndSlashes(Uri uri) { #if BCL // System.UriSyntaxFlags is internal const int UnEscapeDotsAndSlashes = 0x2000000; if (uri == null) throw new ArgumentNullException("uri"); try { // currently prefer silent return than exceptions or log messages if reflection fails to // find the fields we need, otherwise we could generate a lot of noise if someone // runs on a platform without these fields FieldInfo fieldInfo = uri.GetType().GetField("m_Syntax", BindingFlags.Instance | BindingFlags.NonPublic); if (fieldInfo == null) return; var uriParser = fieldInfo.GetValue(uri); fieldInfo = typeof(UriParser).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic); if (fieldInfo == null) return; var uriSyntaxFlags = fieldInfo.GetValue(uriParser); uriSyntaxFlags = (int)uriSyntaxFlags & ~UnEscapeDotsAndSlashes; fieldInfo.SetValue(uriParser, uriSyntaxFlags); } catch (Exception) { // swallow the exception because this platform doesn't support the hack to fix the big in the Uri class. } #endif } /// <summary> /// Used to create a copy of the config for a different service than the current instance. /// </summary> /// <typeparam name="C">Target service ClientConfig</typeparam> /// <returns>The new ClientConfig for the desired service</returns> internal C CloneConfig<C>() where C : ClientConfig, new() { var config = new C(); CloneConfig(config); return config; } internal void CloneConfig(ClientConfig newConfig) { if (!string.IsNullOrEmpty(this.Config.ServiceURL)) { var regionName = Util.AWSSDKUtils.DetermineRegion(this.Config.ServiceURL); RegionEndpoint region = RegionEndpoint.GetBySystemName(regionName); newConfig.RegionEndpoint = region; } else { newConfig.RegionEndpoint = this.Config.RegionEndpoint; } newConfig.UseHttp = this.Config.UseHttp; newConfig.ProxyCredentials = this.Config.ProxyCredentials; newConfig.ProxyHost = this.Config.ProxyHost; newConfig.ProxyPort = this.Config.ProxyPort; } private static void SetupCSMHandler(IRequestContext requestContext) { if (requestContext.CSMEnabled) { requestContext.CSMCallEvent = new MonitoringAPICallEvent(requestContext); } } } }
720
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.Net; using System.Text; namespace Amazon.Runtime { /// <summary> /// A base exception for some Amazon Web Services. /// <para> /// Most exceptions thrown to client code will be service-specific exceptions, though some services /// may throw this exception if there is a problem which is caught in the core client code. /// </para> /// </summary> #if !NETSTANDARD [Serializable] #endif public class AmazonServiceException : Exception { private ErrorType errorType; private string errorCode; private string requestId; private HttpStatusCode statusCode; public AmazonServiceException() : base() { } public AmazonServiceException(string message) : base(message) { } public AmazonServiceException(string message, Exception innerException) : base(message, innerException) { } public AmazonServiceException(string message, Exception innerException, HttpStatusCode statusCode) : base(message, innerException) { this.statusCode = statusCode; } public AmazonServiceException(Exception innerException) : base(innerException.Message, innerException) { } public AmazonServiceException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message ?? BuildGenericErrorMessage(errorCode, statusCode)) { this.errorCode = errorCode; this.errorType = errorType; this.requestId = requestId; this.statusCode = statusCode; } public AmazonServiceException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message ?? BuildGenericErrorMessage(errorCode, statusCode), innerException) { this.errorCode = errorCode; this.errorType = errorType; this.requestId = requestId; this.statusCode = statusCode; } static string BuildGenericErrorMessage(string errorCode, HttpStatusCode statusCode) { return string.Format(CultureInfo.InvariantCulture, "Error making request with Error Code {0} and Http Status Code {1}. No further error information was returned by the service.", errorCode, statusCode); } /// <summary> /// Whether the error was attributable to <c>Sender</c> or <c>Reciever</c>. /// </summary> public ErrorType ErrorType { get { return this.errorType; } set { this.errorType = value; } } /// <summary> /// The error code returned by the service /// </summary> public string ErrorCode { get { return this.errorCode; } set { this.errorCode = value; } } /// <summary> /// The id of the request which generated the exception. /// </summary> public string RequestId { get { return this.requestId; } set { this.requestId = value; } } /// <summary> /// The HTTP status code from the service response /// </summary> public HttpStatusCode StatusCode { get { return this.statusCode; } set { this.statusCode = value; } } /// <summary> /// Flag indicating if the exception is retryable and the associated retry /// details. A null value indicates that the exception is not retryable. /// </summary> public virtual RetryableDetails Retryable { get { return null; } } #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AmazonServiceException 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 AmazonServiceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { if (info != null) { this.errorCode = info.GetString("errorCode"); this.errorType = (ErrorType)info.GetValue("errorType", typeof(ErrorType)); this.requestId = info.GetString("requestId"); this.statusCode = (HttpStatusCode)info.GetValue("statusCode", typeof(HttpStatusCode)); } } /// <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); if (info != null) { info.AddValue("errorCode", this.errorCode); info.AddValue("errorType", this.errorType); info.AddValue("requestId", this.requestId); info.AddValue("statusCode", this.statusCode); } } #endif } /// <summary> /// Class containing the retryable details for an AmazonServiceException /// </summary> public class RetryableDetails { public RetryableDetails(bool throttling) { Throttling = throttling; } /// <summary> /// This property indicates that this exception is a /// throttling exception and should be subject to congestion /// control throttling. /// </summary> public bool Throttling { get; private set; } } }
210
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 { /// <summary> /// This exception is thrown when there is a parse error on the response back from AWS. /// </summary> #if !NETSTANDARD [Serializable] #endif public class AmazonUnmarshallingException : AmazonServiceException { #region Constructors public AmazonUnmarshallingException(string requestId, string lastKnownLocation, Exception innerException) : base("Error unmarshalling response back from AWS.", innerException) { this.RequestId = requestId; this.LastKnownLocation = lastKnownLocation; } public AmazonUnmarshallingException(string requestId, string lastKnownLocation, string responseBody, Exception innerException) : base("Error unmarshalling response back from AWS.", innerException) { this.RequestId = requestId; this.LastKnownLocation = lastKnownLocation; this.ResponseBody = responseBody; } public AmazonUnmarshallingException(string requestId, string lastKnownLocation, string responseBody, string message, Exception innerException) : base("Error unmarshalling response back from AWS. " + message, innerException) { this.RequestId = requestId; this.LastKnownLocation = lastKnownLocation; this.ResponseBody = responseBody; } public AmazonUnmarshallingException(string requestId, string lastKnownLocation, Exception innerException, HttpStatusCode statusCode) : base("Error unmarshalling response back from AWS.", innerException, statusCode) { this.RequestId = requestId; this.LastKnownLocation = lastKnownLocation; } public AmazonUnmarshallingException(string requestId, string lastKnownLocation, string responseBody, Exception innerException, HttpStatusCode statusCode) : base("Error unmarshalling response back from AWS.", innerException, statusCode) { this.RequestId = requestId; this.LastKnownLocation = lastKnownLocation; this.ResponseBody = responseBody; } #endregion #region Public properties /// <summary> /// Last known location in the response that was parsed, if available. /// </summary> public string LastKnownLocation { get; private set; } /// <summary> /// The entire response body that caused this exception, if available. /// </summary> public string ResponseBody { get; private set; } #endregion #region Overrides public override string Message { get { StringBuilder sb = new StringBuilder(); AppendFormat(sb, "Request ID: {0}", this.RequestId); AppendFormat(sb, "Response Body: {0}", this.ResponseBody); AppendFormat(sb, "Last Parsed Path: {0}", this.LastKnownLocation); AppendFormat(sb, "HTTP Status Code: {0}", (int)(this.StatusCode) + " " + this.StatusCode.ToString()); var partialMessage = sb.ToString(); return base.Message + " " + partialMessage; } } #endregion #region Private methods private static void AppendFormat(StringBuilder sb, string format, string value) { if (string.IsNullOrEmpty(value)) return; if (sb.Length > 0) sb.Append(", "); sb.AppendFormat(format, value); } #endregion #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AmazonSimpleDBException 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 AmazonUnmarshallingException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { if (info != null) { this.LastKnownLocation = info.GetString("LastKnownLocation"); this.ResponseBody = info.GetString("ResponseBody"); } } /// <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); if (info != null) { info.AddValue("LastKnownLocation", this.LastKnownLocation); info.AddValue("ResponseBody", this.ResponseBody); } } #endif } }
169
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 { /// <summary> /// Base class for request used by some of the services. /// </summary> public abstract partial class AmazonWebServiceRequest : Amazon.Runtime.Internal.IAmazonWebServiceRequest { internal RequestEventHandler mBeforeRequestEvent; internal string UserAgentAddition { get; set; } = null; internal event RequestEventHandler BeforeRequestEvent { add { lock (this) { mBeforeRequestEvent += value; } } remove { lock (this) { mBeforeRequestEvent -= value; } } } EventHandler<StreamTransferProgressArgs> Amazon.Runtime.Internal.IAmazonWebServiceRequest.StreamUploadProgressCallback { get; set; } private Dictionary<string, object> requestState = null; Dictionary<string, object> Amazon.Runtime.Internal.IAmazonWebServiceRequest.RequestState { get { if (requestState == null) { requestState = new Dictionary<string, object>(); } return requestState; } } protected AmazonWebServiceRequest() { } void Amazon.Runtime.Internal.IAmazonWebServiceRequest.AddBeforeRequestHandler(RequestEventHandler handler) { BeforeRequestEvent += handler; } void Amazon.Runtime.Internal.IAmazonWebServiceRequest.RemoveBeforeRequestHandler(RequestEventHandler handler) { BeforeRequestEvent -= handler; } internal void FireBeforeRequestEvent(object sender, RequestEventArgs args) { if (mBeforeRequestEvent != null) mBeforeRequestEvent(sender, args); } } }
83
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 { /// <summary> /// Abstract class for Response objects, contains only metadata, /// and no result information. /// </summary> #if !NETSTANDARD [Serializable] #endif public class AmazonWebServiceResponse { private ResponseMetadata responseMetadataField; private long contentLength; private HttpStatusCode httpStatusCode; /// <summary> /// Contains additional information about the request, such as the /// Request Id. /// </summary> public ResponseMetadata ResponseMetadata { get { return responseMetadataField; } set { responseMetadataField = value; } } /// <summary> /// Returns the content length of the HTTP response. /// </summary> public long ContentLength { get { return this.contentLength; } set { this.contentLength = value; } } /// <summary> /// Returns the status code of the HTTP response. /// </summary> public HttpStatusCode HttpStatusCode { get { return this.httpStatusCode; } set { this.httpStatusCode = value; } } } }
64
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 for issues related to the AWS Common Runtime (CRT) /// </summary> #if !NETSTANDARD [Serializable] #endif public class AWSCommonRuntimeException : AmazonClientException { /// <summary> /// Initializes a new instance of an AWSCommonRuntimeException /// </summary> /// <param name="message">The message that desribes the error</param> public AWSCommonRuntimeException(string message) : base(message) { } /// <summary> /// Initializes a new instance of an AWSCommonRuntimeException /// </summary> /// <param name="message">The message that desribes the error</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param> public AWSCommonRuntimeException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AWSCommonRuntimeException 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 AWSCommonRuntimeException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
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. */ using System; using System.Globalization; using Amazon.Runtime.Internal.Util; using System.Collections.Generic; using Amazon.Util; using Amazon.Runtime.CredentialManagement; namespace Amazon.Runtime { /// <summary> /// Base class for determining region based on inspection. /// </summary> public abstract class AWSRegion { public RegionEndpoint Region { get; protected set; } /// <summary> /// Sets the Region property by looking up the corresponding RegionEndpoint /// from the supplied region system name (us-east-1, us-west-2 etc). /// </summary> /// <param name="regionSystemName">The system name of the region.</param> protected void SetRegionFromName(string regionSystemName) { Region = RegionEndpoint.GetBySystemName(regionSystemName); } } /// <summary> /// Determines region based on application configuration settings. If the configuration does not contain /// the region setting key an InvalidOperationException is thrown. /// </summary> public class AppConfigAWSRegion : AWSRegion { /// <summary> /// Attempts to construct an instance of ApplicationConfigAWSRegion. If no region is found in the /// application configuration file then an InvalidOperationException is thrown. /// </summary> public AppConfigAWSRegion() { var region = AWSConfigs.RegionEndpoint; if (region != null) { this.Region = region; var logger = Logger.GetLogger(typeof(AppConfigAWSRegion)); logger.InfoFormat("Region {0} found using {1} setting in application configuration file.", region.SystemName, AWSConfigs.AWSRegionKey); } else throw new InvalidOperationException("The app.config/web.config files for the application did not contain region information"); } } /// <summary> /// Determines region based on an environment variable. If the environment does not contain /// the region setting key an InvalidOperationException is thrown. /// </summary> public class EnvironmentVariableAWSRegion : AWSRegion { public const string ENVIRONMENT_VARIABLE_REGION = "AWS_REGION"; public const string ENVIRONMENT_VARIABLE_DEFAULT_REGION = "AWS_DEFAULT_REGION"; /// <summary> /// Attempts to construct an instance of EnvironmentVariableAWSRegion. If no region is found in the /// environment then an InvalidOperationException is thrown. /// </summary> public EnvironmentVariableAWSRegion() { string regionName = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_REGION); if (string.IsNullOrEmpty(regionName)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The environment variable {0} was not set with AWS region data.", ENVIRONMENT_VARIABLE_REGION)); } SetRegionFromName(regionName); var logger = Logger.GetLogger(typeof(EnvironmentVariableAWSRegion)); logger.InfoFormat("Region found using environment variable."); } } /// <summary> /// Determines region based on inspection of the instance metadata if running on an EC2 instance. /// If instance metadata cannot be read or does not contain region information an InvalidOperationException is thrown. /// </summary> public class InstanceProfileAWSRegion : AWSRegion { /// <summary> /// Attempts to construct an instance of InstanceProfileAWSRegion. If no region is found in the /// metadata or we are not running on an EC2 instance an InvalidOperationException is thrown. /// </summary> public InstanceProfileAWSRegion() { var region = EC2InstanceMetadata.Region; if (region == null) { throw new InvalidOperationException("EC2 instance metadata was not available or did not contain region information."); } this.Region = region; var logger = Logger.GetLogger(typeof(InstanceProfileAWSRegion)); logger.InfoFormat("Region found using EC2 instance metadata."); } } /// <summary> /// Determines region based on a <see cref="CredentialProfile"/> stored in an <see cref="ICredentialProfileSource"/>. /// If the profile doesn't exist or there is no region information an InvalidOperationException is thrown. /// </summary> public class ProfileAWSRegion : AWSRegion { /// <summary> /// Attempts to construct an instance of <see cref="ProfileAWSRegion"/>. /// If the AWS_PROFILE environment variable is set the instance will be constructed using that profile, /// otherwise it will use the default profile. /// /// If the profile doesn't exist or there is no region information an InvalidOperationException is thrown. /// </summary> /// <param name="source">The ICredentialProfileSource to read the profile from.</param> public ProfileAWSRegion(ICredentialProfileSource source) { var profileName = FallbackCredentialsFactory.GetProfileName(); Setup(source, profileName); } /// <summary> /// Attempts to construct an instance of <see cref="ProfileAWSRegion"/>. /// If the profile doesn't exist or there is no region information an InvalidOperationException is thrown. /// </summary> /// <param name="source">The ICredentialProfileSource to read the profile from.</param> /// <param name="profileName">The name of the profile.</param> public ProfileAWSRegion(ICredentialProfileSource source, string profileName) { Setup(source, profileName); } private void Setup(ICredentialProfileSource source, string profileName) { RegionEndpoint region = null; CredentialProfile profile; if (source.TryGetProfile(profileName, out profile)) { region = profile.Region; } else throw new InvalidOperationException("Unable to find a profile named '" + profileName + "' in store " + source.GetType()); if (region == null) throw new InvalidOperationException("There is no Region set in the profile named '" + profileName + "' in store " + source.GetType()); else { this.Region = region; var logger = Logger.GetLogger(typeof(ProfileAWSRegion)); logger.InfoFormat("Region found in profile '" + profileName + "' in store " + source.GetType()); } } } /// <summary> /// Probing mechanism to determine region from various sources. /// </summary> public static class FallbackRegionFactory { private static CredentialProfileStoreChain credentialProfileChain = new CredentialProfileStoreChain(); private static object _lock = new object(); static FallbackRegionFactory() { Reset(); } private delegate AWSRegion RegionGenerator(); private static List<RegionGenerator> AllGenerators { get; set; } private static List<RegionGenerator> NonMetadataGenerators { get; set; } public static void Reset() { cachedRegion = null; AllGenerators = new List<RegionGenerator> { () => new AppConfigAWSRegion(), () => new EnvironmentVariableAWSRegion(), () => new ProfileAWSRegion(credentialProfileChain), () => new InstanceProfileAWSRegion() }; NonMetadataGenerators = new List<RegionGenerator> { () => new AppConfigAWSRegion(), () => new EnvironmentVariableAWSRegion(), () => new ProfileAWSRegion(credentialProfileChain), }; } private static AWSRegion cachedRegion; public static RegionEndpoint GetRegionEndpoint() { return GetRegionEndpoint(true); } public static RegionEndpoint GetRegionEndpoint(bool includeInstanceMetadata) { lock(_lock) { if (cachedRegion != null) return cachedRegion.Region; List<Exception> errors = new List<Exception>(); IEnumerable<RegionGenerator> generators = includeInstanceMetadata ? AllGenerators : NonMetadataGenerators; foreach (var generator in generators) { try { cachedRegion = generator(); } catch (Exception e) { cachedRegion = null; errors.Add(e); } if (cachedRegion != null) break; } return cachedRegion != null ? cachedRegion.Region : null; } } } }
252
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; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Util; namespace Amazon.Runtime { public class BearerTokenSigner : AbstractAWSSigner { public override bool RequiresCredentials { get; } = false; #if BCL public override void Sign( IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { if (request.Endpoint.Scheme == "http") { throw new AmazonClientException( $"The configured endpoint [{request.Endpoint}] is invalid for the bearer authorization scheme. " + "Endpoint must not use 'http'."); } if (null == clientConfig.AWSTokenProvider) return; if (!clientConfig.AWSTokenProvider.TryResolveToken(out var token) || string.IsNullOrEmpty(token.Token)) { throw new AmazonClientException("No Token found. Operation requires a Bearer token."); } request.Headers["Authorization"] = $"Bearer {token}"; } #else public override void Sign( IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { throw new NotSupportedException($"Use {nameof(SignAsync)} instead."); } #endif #if AWS_ASYNC_API public override async Task SignAsync( IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials, CancellationToken token = default) { if (request.Endpoint.Scheme == "http") { throw new AmazonClientException( $"The configured endpoint [{request.Endpoint}] is invalid for the bearer authorization scheme. " + "Endpoint must not use 'http'."); } if (null == clientConfig.AWSTokenProvider) return; var result = await clientConfig.AWSTokenProvider.TryResolveTokenAsync(token).ConfigureAwait(false); if (true != result.Success || string.IsNullOrEmpty(result.Value.Token)) throw new AmazonClientException("No Token found. Operation requires a Bearer token."); request.Headers["Authorization"] = $"Bearer {result.Value.Token}"; } #endif public override ClientProtocol Protocol { get; } = ClientProtocol.Unknown; } }
98
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.Threading; namespace Amazon.Runtime.Internal { /// <summary> /// This class is responsible for keeping track of Retry capacity across different ServiceURLs. /// </summary> public class CapacityManager:IDisposable { /// <summary> /// CapacityType determines the type of capacity to obtain or use. /// </summary> public enum CapacityType { /// <summary> /// The increment capacity type adds capacity. /// </summary> Increment, /// <summary> /// The default retry capacity type uses the default capacity amount. /// </summary> Retry, /// <summary> /// The timeout capacity type uses the timeout capacity amount. /// </summary> Timeout } //Dispose Method public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { _disposed = true; } } public CapacityManager(int throttleRetryCount, int throttleRetryCost, int throttleCost) : this(throttleRetryCount, throttleRetryCost, throttleCost, throttleRetryCost) { } public CapacityManager(int throttleRetryCount, int throttleRetryCost, int throttleCost, int timeoutRetryCost) { retryCost = throttleRetryCost; initialRetryTokens = throttleRetryCount; noRetryIncrement = throttleCost; this.timeoutRetryCost = timeoutRetryCost; } /// <summary> /// This method acquires a said retry capacity if the container has the capacity. /// </summary> /// <param name="retryCapacity">Contains the RetryCapacity object for the said ServiceURL.</param> public bool TryAcquireCapacity(RetryCapacity retryCapacity) { return TryAcquireCapacity(retryCapacity, CapacityType.Retry); } /// <summary> /// This method acquires a said retry capacity if the container has the capacity. /// </summary> /// <param name="retryCapacity">Contains the RetryCapacity object for the said ServiceURL.</param> /// <param name="capacityType">Specifies what capacity type cost to use for obtaining capacity</param> public bool TryAcquireCapacity(RetryCapacity retryCapacity, CapacityType capacityType) { var capacityCost = capacityType == CapacityType.Timeout ? timeoutRetryCost : retryCost; if (capacityCost < 0) { return false; } lock (retryCapacity) { if (retryCapacity.AvailableCapacity - capacityCost >= 0) { retryCapacity.AvailableCapacity -= capacityCost; return true; } else { return false; } } } /// <summary> /// This method calls a method to release capacity back /// based on whether it was a successful response or a successful retry response. This is invoked by a retry request response. /// </summary> /// <param name="isRetryRequest">if this request is a retry, use a different capacity cost</param> /// <param name="retryCapacity">Contains the RetryCapacity object for the said ServiceURL.</param> [Obsolete("This method is no longer used in favor of allowing the caller to specify the type of capacity to release.")] public void TryReleaseCapacity(bool isRetryRequest, RetryCapacity retryCapacity) { ReleaseCapacity(isRetryRequest ? CapacityType.Retry : CapacityType.Increment, retryCapacity); } /// <summary> /// This method calls a method to release capacity back /// based on whether it was a successful response or a successful retry response. This is invoked by a retry request response. /// </summary> /// <param name="capacityType">Specifies what capacity type cost to use for adding capacity</param> /// <param name="retryCapacity">Contains the RetryCapacity object for the said ServiceURL.</param> public void ReleaseCapacity(CapacityType capacityType, RetryCapacity retryCapacity) { switch (capacityType) { case CapacityType.Retry: ReleaseCapacity(retryCost, retryCapacity); break; case CapacityType.Timeout: ReleaseCapacity(timeoutRetryCost, retryCapacity); break; case CapacityType.Increment: ReleaseCapacity(noRetryIncrement, retryCapacity); break; default: throw new NotSupportedException($"Unsupported CapacityType {capacityType}"); } } /// <summary> /// Ths method fetches the RetryCapacity for the given ServiceURL from CapacityManager.CapacityContainer /// </summary> public RetryCapacity GetRetryCapacity(string serviceURL) { RetryCapacity retryCapacity; if (!(TryGetRetryCapacity(serviceURL, out retryCapacity))) { retryCapacity = AddNewRetryCapacity(serviceURL); } return retryCapacity; } private bool _disposed; //Dictionary that keeps track of the available capacity by ServiceURLs private static Dictionary<string, RetryCapacity> _serviceUrlToCapacityMap = new Dictionary<string, RetryCapacity>(); //Read write slim lock for performing said operations on CapacityManager._serviceUrlToCapacityMap. private static ReaderWriterLockSlim _rwlock = new ReaderWriterLockSlim(); // This parameter sets the cost of making a retry call on a request.The default value is set at 5. private readonly int retryCost; // This parameter sets the cost of making a retry call when the request was a timeout. The default value is 5 for // legacy retry modes and 10 for all other retry modes. private readonly int timeoutRetryCost; // Maximum capacity in a bucket set to 100 for legacy retry mode and 500 for all other retry modes. private readonly int initialRetryTokens; // For every successful request, lesser value capacity would be released. This // is done to ensure that the bucket has a strategy for filling up if an explosion of bad retry requests // were to deplete the entire capacity.The default value is set at 1. private readonly int noRetryIncrement; private static bool TryGetRetryCapacity(string key, out RetryCapacity value) { _rwlock.EnterReadLock(); try { if (_serviceUrlToCapacityMap.TryGetValue(key, out value)) { return true; } return false; } finally { _rwlock.ExitReadLock(); } } private RetryCapacity AddNewRetryCapacity(string serviceURL) { RetryCapacity retryCapacity; _rwlock.EnterUpgradeableReadLock(); try { if (!(_serviceUrlToCapacityMap.TryGetValue(serviceURL, out retryCapacity))) { _rwlock.EnterWriteLock(); try { retryCapacity = new RetryCapacity(retryCost * initialRetryTokens); _serviceUrlToCapacityMap.Add(serviceURL, retryCapacity); return retryCapacity; } finally { _rwlock.ExitWriteLock(); } } else { return retryCapacity; } } finally { _rwlock.ExitUpgradeableReadLock(); } } /// <summary> /// This method releases capacity back. This is invoked by the TryReleaseCapacity method. /// </summary> /// <param name="retryCapacity">Contains the RetryCapacity object for the said ServiceURL.</param> /// <param name="capacity">The capacity that needs to be released based on whether it was a successful response or a successful retry response.</param> private static void ReleaseCapacity(int capacity, RetryCapacity retryCapacity) { if (retryCapacity.AvailableCapacity >= 0 && retryCapacity.AvailableCapacity < retryCapacity.MaxCapacity) { lock (retryCapacity) { retryCapacity.AvailableCapacity = Math.Min((retryCapacity.AvailableCapacity + capacity), retryCapacity.MaxCapacity); } } } } /// <summary> /// This class is the RetryCapacity class for a given ServiceURL. /// </summary> public class RetryCapacity { //maximum capacity in a bucket. private readonly int _maxCapacity; //available ncapacity in a bucket for a given ServiceURL. public int AvailableCapacity { get; set; } //maximum capacity in a bucket. public int MaxCapacity { get { return _maxCapacity; } } public RetryCapacity(int maxCapacity) { _maxCapacity = maxCapacity; this.AvailableCapacity = maxCapacity; } } }
275
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.Specialized; using System.Net; using System.Text; using System.Threading; using Amazon.Runtime.Internal.Auth; using Amazon.Util; using System.Globalization; using Amazon.Internal; using Amazon.Runtime.Endpoints; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Util; #if NETSTANDARD using System.Runtime.InteropServices; #endif namespace Amazon.Runtime { /// <summary> /// This class is the base class of all the configurations settings to connect /// to a service. /// </summary> public abstract partial class ClientConfig : IClientConfig { // Represents infinite timeout. http://msdn.microsoft.com/en-us/library/system.threading.timeout.infinite.aspx internal static readonly TimeSpan InfiniteTimeout = TimeSpan.FromMilliseconds(-1); // Represents max timeout. public static readonly TimeSpan MaxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private IDefaultConfigurationProvider _defaultConfigurationProvider; private DefaultConfigurationMode? defaultConfigurationMode; private RegionEndpoint regionEndpoint = null; private bool probeForRegionEndpoint = true; private bool throttleRetries = true; private bool useHttp = false; private bool useAlternateUserAgentHeader = AWSConfigs.UseAlternateUserAgentHeader; private string serviceURL = null; private string authRegion = null; private string authServiceName = null; private string signatureVersion = "4"; private SigningAlgorithm signatureMethod = SigningAlgorithm.HmacSHA256; private bool readEntireResponse = false; private bool logResponse = false; private int bufferSize = AWSSDKUtils.DefaultBufferSize; private long progressUpdateInterval = AWSSDKUtils.DefaultProgressUpdateInterval; private bool resignRetries = false; private ICredentials proxyCredentials; private bool logMetrics = AWSConfigs.LoggingConfig.LogMetrics; private bool disableLogging = false; private TimeSpan? timeout = null; private bool allowAutoRedirect = true; private bool? useDualstackEndpoint; private bool? useFIPSEndpoint; private TimeSpan? readWriteTimeout = null; private bool disableHostPrefixInjection = false; private bool? endpointDiscoveryEnabled = null; private int endpointDiscoveryCacheLimit = 1000; private RequestRetryMode? retryMode = null; private int? maxRetries = null; private const int MaxRetriesDefault = 2; private const int MaxRetriesLegacyDefault = 4; private IAWSTokenProvider _awsTokenProvider = new DefaultAWSTokenProviderChain(); #if BCL private readonly TcpKeepAlive tcpKeepAlive = new TcpKeepAlive(); #endif /// <inheritdoc /> public IAWSTokenProvider AWSTokenProvider { get { return this._awsTokenProvider; } set { this._awsTokenProvider = value; } } /// <summary> /// Gets Service Version /// </summary> public abstract string ServiceVersion { get; } /// <summary> /// Gets and sets of the signatureMethod property. /// </summary> public SigningAlgorithm SignatureMethod { get { return this.signatureMethod; } set { this.signatureMethod = value; } } /// <summary> /// Gets and sets of the SignatureVersion property. /// /// Note: This property exists for backward compatibility but is no longer /// used by any service other than S3. /// </summary> public string SignatureVersion { get { return this.signatureVersion; } set { this.signatureVersion = value; } } /// <summary> /// Gets and sets of the UserAgent property. /// </summary> public abstract string UserAgent { get; } /// <summary> /// When set to true, the service client will use the x-amz-user-agent /// header instead of the User-Agent header to report version and /// environment information to the AWS service. /// /// Note: This is especially useful when using a platform like WebAssembly /// which doesn't allow to specify the User-Agent header. /// </summary> public bool UseAlternateUserAgentHeader { get { return this.useAlternateUserAgentHeader; } set { this.useAlternateUserAgentHeader = value; } } /// <summary> /// <para> /// Gets and sets the RegionEndpoint property. The region constant that /// determines the endpoint to use. /// /// Setting this property to null will force the SDK to recalculate the /// RegionEndpoint value based on App/WebConfig, environment variables, /// profile, etc. /// </para> /// <para> /// RegionEndpoint and ServiceURL are mutually exclusive properties. /// Whichever property is set last will cause the other to automatically /// be reset to null. /// </para> /// </summary> public RegionEndpoint RegionEndpoint { get { if (probeForRegionEndpoint) { RegionEndpoint = GetDefaultRegionEndpoint(); this.probeForRegionEndpoint = false; } return this.regionEndpoint; } set { this.defaultConfigurationBackingField = null; this.serviceURL = null; this.regionEndpoint = value; this.probeForRegionEndpoint = this.regionEndpoint == null; // legacy support for initial pseudo regions - convert to base Region // and set FIPSEndpoint to true if (!string.IsNullOrEmpty(value?.SystemName) && (value.SystemName.Contains("fips-") || value.SystemName.Contains("-fips"))) { Logger.GetLogger(GetType()).InfoFormat($"FIPS Pseudo Region support is deprecated. Will attempt to convert {value.SystemName}."); this.UseFIPSEndpoint = true; this.regionEndpoint = RegionEndpoint.GetBySystemName( value.SystemName.Replace("fips-", "").Replace("-fips", "")); this.RegionEndpoint.OriginalSystemName = value.SystemName; } } } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public abstract string RegionEndpointServiceName { get; } /// <summary> /// <para> /// Gets and sets of the ServiceURL property. /// This is an optional property; change it /// only if you want to try a different service /// endpoint. /// </para> /// <para> /// RegionEndpoint and ServiceURL are mutually exclusive properties. /// Whichever property is set last will cause the other to automatically /// be reset to null. /// </para> /// </summary> public string ServiceURL { get { return this.serviceURL; } set { this.regionEndpoint = null; this.probeForRegionEndpoint = false; if(!string.IsNullOrEmpty(value)) { // If the URL passed in only has a host name make sure there is an ending "/" to avoid signature mismatch issues. // If there is a resource path do not add a "/" because the marshallers are relying on the URL to be in format without the "/". // API Gateway Management API is an example of a service that vends its own URL that users have to set which has a resource path. // The marshallers add new segments to the resource path with the "/". try { var path = new Uri(value).PathAndQuery; if (string.IsNullOrEmpty(path) || path == "/") { if (!string.IsNullOrEmpty(value) && !value.EndsWith("/")) { value += "/"; } } } catch(UriFormatException) { throw new AmazonClientException("Value for ServiceURL is not a valid URL: " + value); } } this.serviceURL = value; } } /// <summary> /// Gets and sets the UseHttp. /// If this property is set to true, the client attempts /// to use HTTP protocol, if the target endpoint supports it. /// By default, this property is set to false. /// </summary> /// <remarks>This does not apply if an explicit <see cref="ServiceURL"/> is specified.</remarks> public bool UseHttp { get { return this.useHttp; } set { this.useHttp = value; } } /// <summary> /// Given this client configuration, return a string form ofthe service endpoint url. /// </summary> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public virtual string DetermineServiceURL() { string url; if (this.ServiceURL != null) { url = this.ServiceURL; } else { url = GetUrl(this, RegionEndpoint); } return url; } /// <summary> /// Given this client configuration, return a DNS suffix for service endpoint url. /// </summary> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public virtual string DetermineDnsSuffix() { var endpoint = regionEndpoint.GetEndpointForService(this); return endpoint.DnsSuffix; } internal static string GetUrl(IClientConfig config, RegionEndpoint regionEndpoint) { var endpoint = regionEndpoint.GetEndpointForService( config.RegionEndpointServiceName, config.ToGetEndpointForServiceOptions()); string url = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", config.UseHttp ? "http://" : "https://", endpoint.Hostname)).AbsoluteUri; return url; } /// <summary> /// Gets and sets the AuthenticationRegion property. /// Used in AWS4 request signing, this is an optional property; /// change it only if the region cannot be determined from the /// service endpoint. /// </summary> public string AuthenticationRegion { get { return this.authRegion; } set { this.authRegion = value; } } /// <summary> /// Gets and sets the AuthenticationServiceName property. /// Used in AWS4 request signing, this is the short-form /// name of the service being called. /// </summary> public string AuthenticationServiceName { get { return this.authServiceName; } set { this.authServiceName = value; } } /// <summary> /// Returns the flag indicating how many retry HTTP requests an SDK should /// make for a single SDK operation invocation before giving up. This flag will /// return 4 when the RetryMode is set to "Legacy" which is the default. For /// RetryMode values of "Standard" or "Adaptive" this flag will return 2. In /// addition to the values returned that are dependent on the RetryMode, the /// value can be set to a specific value by using the AWS_MAX_ATTEMPTS environment /// variable, max_attempts in the shared configuration file, or by setting a /// value directly on this property. When using AWS_MAX_ATTEMPTS or max_attempts /// the value returned from this property will be one less than the value entered /// because this flag is the number of retry requests, not total requests. To /// learn more about the RetryMode property that affects the values returned by /// this flag, see <see cref="RetryMode"/>. /// </summary> public int MaxErrorRetry { get { if (!this.maxRetries.HasValue) { //For legacy mode there was no MaxAttempts shared config or //environment variables so use the legacy default value. if (RetryMode == RequestRetryMode.Legacy) { return MaxRetriesLegacyDefault; } //For standard and adaptive modes first check the environment variables //and shared config for a value. Otherwise default to the new default value. //In the shared config or environment variable MaxAttempts is the total number //of attempts. This will include the initial call and must be deducted from //from the number of actual retries. return FallbackInternalConfigurationFactory.MaxAttempts - 1 ?? MaxRetriesDefault; } return this.maxRetries.Value; } set { this.maxRetries = value; } } /// <summary> /// Determines if MaxErrorRetry has been manually set. /// </summary> public bool IsMaxErrorRetrySet { get { return this.maxRetries.HasValue; } } /// <summary> /// Gets and sets the LogResponse property. /// If this property is set to true, the service response is logged. /// The size of response being logged is controlled by the AWSConfigs.LoggingConfig.LogResponsesSizeLimit property. /// </summary> public bool LogResponse { get { return this.logResponse; } set { this.logResponse = value; } } /// <summary> /// Gets and sets the ReadEntireResponse property. /// NOTE: This property does not effect response processing and is deprecated. /// To enable response logging, the ClientConfig.LogResponse and AWSConfigs.LoggingConfig /// properties can be used. /// </summary> [Obsolete("This property does not effect response processing and is deprecated." + "To enable response logging, the ClientConfig.LogResponse and AWSConfigs.LoggingConfig.LogResponses properties can be used.")] public bool ReadEntireResponse { get { return this.readEntireResponse; } set { this.readEntireResponse = value; } } /// <summary> /// Gets and Sets the BufferSize property. /// The BufferSize controls the buffer used to read in from input streams and write /// out to the request. /// </summary> public int BufferSize { get { return this.bufferSize; } set { this.bufferSize = value; } } /// <summary> /// <para> /// Gets or sets the interval at which progress update events are raised /// for upload operations. By default, the progress update events are /// raised at every 100KB of data transferred. /// </para> /// <para> /// If the value of this property is set less than ClientConfig.BufferSize, /// progress updates events will be raised at the interval specified by ClientConfig.BufferSize. /// </para> /// </summary> public long ProgressUpdateInterval { get { return progressUpdateInterval; } set { progressUpdateInterval = value; } } /// <summary> /// Flag on whether to resign requests on retry or not. /// For Amazon S3 and Amazon Glacier this value will always be set to true. /// </summary> public bool ResignRetries { get { return this.resignRetries; } set { this.resignRetries = value; } } /// <summary> /// This flag controls if .NET HTTP infrastructure should follow redirection /// responses (e.g. HTTP 307 - temporary redirect). /// </summary> public bool AllowAutoRedirect { get { return this.allowAutoRedirect; } set { this.allowAutoRedirect = value; } } /// <summary> /// Flag on whether to log metrics for service calls. /// /// This can be set in the application's configs, as below: /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSLogMetrics" value"true"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// </summary> public bool LogMetrics { get { return this.logMetrics; } set { this.logMetrics = value; } } /// <summary> /// Gets and sets the DisableLogging. If true logging for this client will be disabled. /// </summary> public bool DisableLogging { get { return this.disableLogging; } set { this.disableLogging = value; } } /// <summary> /// Specify a <see cref="Amazon.Runtime.DefaultConfigurationMode"/> to use. /// <para /> /// Returns the <see cref="Amazon.Runtime.DefaultConfigurationMode"/> that will be used. If none is specified, /// than the correct one is computed by <see cref="IDefaultConfigurationProvider"/>. /// </summary> public DefaultConfigurationMode DefaultConfigurationMode { get { if (this.defaultConfigurationMode.HasValue) return this.defaultConfigurationMode.Value; return DefaultConfiguration.Name; } set { this.defaultConfigurationMode = value; defaultConfigurationBackingField = null; } } private IDefaultConfiguration defaultConfigurationBackingField; protected IDefaultConfiguration DefaultConfiguration { get { if (defaultConfigurationBackingField != null) return defaultConfigurationBackingField; defaultConfigurationBackingField = _defaultConfigurationProvider.GetDefaultConfiguration(RegionEndpoint, defaultConfigurationMode); return defaultConfigurationBackingField; } } /// <summary> /// Credentials to use with a proxy. /// </summary> public ICredentials ProxyCredentials { get { if(this.proxyCredentials == null && (!string.IsNullOrEmpty(AWSConfigs.ProxyConfig.Username) || !string.IsNullOrEmpty(AWSConfigs.ProxyConfig.Password))) { return new NetworkCredential(AWSConfigs.ProxyConfig.Username, AWSConfigs.ProxyConfig.Password ?? string.Empty); } return this.proxyCredentials; } set { this.proxyCredentials = value; } } #if BCL /// <summary> /// Specifies the TCP keep-alive values to use for service requests. /// </summary> public TcpKeepAlive TcpKeepAlive { get { return this.tcpKeepAlive; } } #endif #region Constructor protected ClientConfig(IDefaultConfigurationProvider defaultConfigurationProvider) { _defaultConfigurationProvider = defaultConfigurationProvider; Initialize(); } public ClientConfig() : this(new LegacyOnlyDefaultConfigurationProvider()) { this.defaultConfigurationBackingField = _defaultConfigurationProvider.GetDefaultConfiguration(null, null); this.defaultConfigurationMode = this.defaultConfigurationBackingField.Name; } /// <summary> /// Specialized <see cref="IDefaultConfigurationProvider"/> that is only meant to provide backwards /// compatibility for the obsolete <see cref="ClientConfig"/> constructor. /// </summary> private class LegacyOnlyDefaultConfigurationProvider : IDefaultConfigurationProvider { public IDefaultConfiguration GetDefaultConfiguration(RegionEndpoint clientRegion, DefaultConfigurationMode? requestedConfigurationMode = null) { if (requestedConfigurationMode.HasValue && requestedConfigurationMode.Value != Runtime.DefaultConfigurationMode.Legacy) throw new AmazonClientException($"This ClientConfig only supports {Runtime.DefaultConfigurationMode.Legacy}"); return new DefaultConfiguration { Name = Runtime.DefaultConfigurationMode.Legacy, RetryMode = RequestRetryMode.Legacy, S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Legacy, StsRegionalEndpoints = StsRegionalEndpointsValue.Legacy }; } } #endregion protected virtual void Initialize() { } #if BCL35 /// <summary> /// Overrides the default request timeout value. /// This field does not impact Begin*/End* calls. A manual timeout must be implemented. /// </summary> #elif BCL45 /// <summary> /// Overrides the default request timeout value. /// This field does not impact *Async calls. A manual timeout (for instance, using CancellationToken) must be implemented. /// </summary> #endif /// <remarks> /// <para> /// If the value is set, the value is assigned to the Timeout property of the HttpWebRequest/HttpClient object used /// to send requests. /// </para> /// <para> /// Please specify a timeout value only if the operation will not complete within the default intervals /// specified for an HttpWebRequest/HttpClient. /// </para> /// </remarks> /// <exception cref="System.ArgumentNullException">The timeout specified is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">The timeout specified is less than or equal to zero and is not Infinite.</exception> /// <seealso cref="P:System.Net.HttpWebRequest.Timeout"/> /// <seealso cref="P:System.Net.Http.HttpClient.Timeout"/> public TimeSpan? Timeout { get { if (this.timeout.HasValue) return this.timeout; // TimeToFirstByteTimeout is not a perfect match with HttpWebRequest/HttpClient.Timeout. However, given // that both are configured to only use Timeout until the Response Headers are downloaded, this value // provides a reasonable default value. return DefaultConfiguration.TimeToFirstByteTimeout; } set { ValidateTimeout(value); this.timeout = value; } } #if AWS_ASYNC_API /// <summary> /// Generates a <see cref="CancellationToken"/> based on the value /// for <see cref="DefaultConfiguration.TimeToFirstByteTimeout"/>. /// <para /> /// NOTE: <see cref="Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync"/> uses /// </summary> internal CancellationToken BuildDefaultCancellationToken() { // legacy mode never had a working cancellation token, so keep it to default() if (DefaultConfiguration.Name == Runtime.DefaultConfigurationMode.Legacy) return default(CancellationToken); // TimeToFirstByteTimeout is not a perfect match with HttpWebRequest/HttpClient.Timeout. However, given // that both are configured to only use Timeout until the Response Headers are downloaded, this value // provides a reasonable default value. var cancelTimeout = DefaultConfiguration.TimeToFirstByteTimeout; return cancelTimeout.HasValue ? new CancellationTokenSource(cancelTimeout.Value).Token : default(CancellationToken); } #endif /// <summary> /// Configures the endpoint calculation for a service to go to a dual stack (ipv6 enabled) endpoint /// for the configured region. /// </summary> /// <remarks> /// Note: AWS services are enabling dualstack endpoints over time. It is your responsibility to check /// that the service actually supports a dualstack endpoint in the configured region before enabling /// this option for a service. /// </remarks> public bool UseDualstackEndpoint { get { if (!this.useDualstackEndpoint.HasValue) { return FallbackInternalConfigurationFactory.UseDualStackEndpoint ?? false; } return this.useDualstackEndpoint.Value; } set { useDualstackEndpoint = value; } } /// <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 { if (!this.useFIPSEndpoint.HasValue) { return FallbackInternalConfigurationFactory.UseFIPSEndpoint ?? false; } return this.useFIPSEndpoint.Value; } set { useFIPSEndpoint = value; } } /// <summary> /// Enable or disable the Retry Throttling feature by setting the ThrottleRetries flag to True/False respectively. /// Retry Throttling is a feature that intelligently throttles retry attempts when a large percentage of requests /// are failing and retries are unsuccessful as well. In such situations the allotted retry capacity for the service URL /// will be drained until requests start to succeed again. Once the requisite capacity is available, retries would /// be permitted again. When retries are throttled, the service enters a fail-fast behaviour as the traditional retry attempt /// for the request would be circumvented. Hence, errors will resurface quickly. This will result in a greater number of exceptions /// but prevents requests being tied up in unsuccessful retry attempts. /// Note: Retry Throttling is enabled by default. Set the ThrottleRetries flag to false to switch off this feature. /// </summary> public bool ThrottleRetries { get { return throttleRetries; } set { throttleRetries = value; } } /// <summary> /// Enable or disable the Nagle algorithm on the underlying http /// client. /// /// This method is not intended to be called by consumers of the AWS SDK for .NET /// </summary> /// <param name="useNagle"></param> public void SetUseNagleIfAvailable(bool useNagle) { #if BCL this.UseNagleAlgorithm = useNagle; #endif } /// <summary> /// Performs validation on this config object. /// Throws exception if any of the required values are missing/invalid. /// </summary> public virtual void Validate() { if (RegionEndpoint == null && string.IsNullOrEmpty(this.ServiceURL)) throw new AmazonClientException("No RegionEndpoint or ServiceURL configured"); #if BCL if (TcpKeepAlive.Enabled) { ValidateTcpKeepAliveTimeSpan(TcpKeepAlive.Timeout, "TcpKeepAlive.Timeout"); ValidateTcpKeepAliveTimeSpan(TcpKeepAlive.Interval, "TcpKeepAlive.Interval"); } #endif } /// <summary> /// Returns the current UTC now after clock correction for this endpoint. /// </summary> [Obsolete("Please use CorrectClockSkew.GetCorrectedUtcNowForEndpoint(string endpoint) instead.", false)] public DateTime CorrectedUtcNow { get { return CorrectClockSkew.GetCorrectedUtcNowForEndpoint(DetermineServiceURL()); } } /// <summary> /// The calculated clock skew correction for a specific endpoint, if there is one. /// This field will be set if a service call resulted in an exception /// and the SDK has determined that there is a difference between local /// and server times. /// /// If <seealso cref="CorrectForClockSkew"/> is set to true, this /// value will still be set to the correction, but it will not be used by the /// SDK and clock skew errors will not be retried. /// </summary> public TimeSpan ClockOffset { get { if (AWSConfigs.ManualClockCorrection.HasValue) { return AWSConfigs.ManualClockCorrection.Value; } else { string endpoint = DetermineServiceURL(); return CorrectClockSkew.GetClockCorrectionForEndpoint(endpoint); } } } /// <summary> /// Gets and sets the DisableHostPrefixInjection flag. If true, host prefix injection will be disabled for this client, the default value of this flag is false. /// Host prefix injection prefixes the service endpoint with request members from APIs which use this feature. /// Example: for a hostPrefix of "foo-name." and a endpoint of "service.region.amazonaws.com" the default behavior is to /// prefix the endpoint with the hostPrefix resulting in a final endpoint of "foo-name.service.region.amazonaws.com". Setting /// DisableHostPrefixInjection to true will disable hostPrefix injection resulting in a final endpoint of /// "service.region.amazonaws.com" regardless of the value of hostPrefix. E.g. You may want to disable host prefix injection for testing against a local mock endpoint. /// </summary> public bool DisableHostPrefixInjection { get { return this.disableHostPrefixInjection; } set { this.disableHostPrefixInjection = value; } } /// <summary> /// Returns the flag indicating if endpoint discovery should be enabled or disabled for operations that are not required to use endpoint discovery. /// </summary> public bool EndpointDiscoveryEnabled { get { if (!this.endpointDiscoveryEnabled.HasValue) { return FallbackInternalConfigurationFactory.EndpointDiscoveryEnabled ?? false; } return this.endpointDiscoveryEnabled.Value; } set { this.endpointDiscoveryEnabled = value; } } /// <summary> /// Returns the maximum number of discovered endpoints that can be stored within the cache for the client. The default limit is 1000 cache entries. /// </summary> public int EndpointDiscoveryCacheLimit { get { return this.endpointDiscoveryCacheLimit; } set { this.endpointDiscoveryCacheLimit = value; } } /// <summary> /// Returns the flag indicating the current mode in use for request /// retries and influences the value returned from <see cref="MaxErrorRetry"/>. /// The default value is RequestRetryMode.Legacy. This flag can be configured /// by using the AWS_RETRY_MODE environment variable, retry_mode in the /// shared configuration file, or by setting this value directly. /// </summary> public RequestRetryMode RetryMode { get { if (!this.retryMode.HasValue) { return FallbackInternalConfigurationFactory.RetryMode ?? DefaultConfiguration.RetryMode; } return this.retryMode.Value; } set { this.retryMode = value; } } /// <summary> /// Under Adaptive retry mode, this flag determines if the client should wait for /// a send token to become available or don't block and fail the request immediately /// if a send token is not available. /// </summary> public bool FastFailRequests { get; set; } = false; /// <summary> /// Throw an exception if the boxed TimeSpan parameter doesn't have a value or is out of range. /// </summary> public static void ValidateTimeout(TimeSpan? timeout) { if (!timeout.HasValue) { throw new ArgumentNullException("timeout"); } if (timeout != InfiniteTimeout && (timeout <= TimeSpan.Zero || timeout > MaxTimeout)) { throw new ArgumentOutOfRangeException("timeout"); } } #if BCL private static void ValidateTcpKeepAliveTimeSpan(TimeSpan? value, string paramName) { if (!value.HasValue) { throw new ArgumentNullException(paramName); } if (value > MaxTimeout || (int)value.Value.TotalMilliseconds <= 0) { throw new ArgumentOutOfRangeException(paramName); } } #endif /// <summary> /// Returns the request timeout value if its value is set, /// else returns client timeout value. /// </summary> public static TimeSpan? GetTimeoutValue(TimeSpan? clientTimeout, TimeSpan? requestTimeout) { return requestTimeout.HasValue ? requestTimeout : (clientTimeout.HasValue ? clientTimeout : null); } #if NETSTANDARD /// <summary> /// <para> /// This is a switch used for performance testing and is not intended for production applications /// to change. This switch may be removed in a future version of the SDK as the .NET Core platform matures. /// </para> /// <para> /// If true, the HttpClient is cached and reused for every request made by the service client /// and shared with other service clients. /// </para> /// <para> /// For the .NET Core platform this is default to true because the HttpClient manages the connection /// pool. /// </para> /// </summary> public bool CacheHttpClient {get; set;} = true; private int? _httpClientCacheSize; /// <summary> /// If CacheHttpClient is set to true then HttpClientCacheSize controls the number of HttpClients cached. /// <para> /// The default value is 1 which is suitable for Windows and for all other platforms that have HttpClient /// implementations using <see cref="System.Net.Http.SocketsHttpHandler"/> (.NET Core 2.1 and higher). /// </para> /// </summary> public int HttpClientCacheSize { get { if(_httpClientCacheSize.HasValue) { return _httpClientCacheSize.Value; } // Use both NETCOREAPP3_1 and NETCOREAPP3_1_OR_GREATER because currently the build server only has .NET Core 3.1 SDK installed // which predates the OR_GREATER preprocessor statements. The NETCOREAPP3_1_OR_GREATER is used for future proofing. #if NETCOREAPP3_1 || NETCOREAPP3_1_OR_GREATER return 1; #else return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 1 : Environment.ProcessorCount; #endif } set => _httpClientCacheSize = value; } #endif /// <summary> /// Overrides the default read-write timeout value. /// </summary> /// <remarks> /// <para> /// If the value is set, the value is assigned to the ReadWriteTimeout property of the HttpWebRequest object used /// to send requests. /// </para> /// <exception cref="System.ArgumentNullException">The timeout specified is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">The timeout specified is less than or equal to zero and is not Infinite.</exception> /// </remarks> /// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/> #if NETSTANDARD [Obsolete("ReadWriteTimeout is not consumed in asynchronous HTTP requests. Please use a cancellation token to handle stream read/write timeouts.")] #endif public TimeSpan? ReadWriteTimeout { get { return this.readWriteTimeout; } set { ValidateTimeout(value); this.readWriteTimeout = value; } } /// <summary> /// Gets and sets of the EndpointProvider property. /// This property is used for endpoints resolution. /// During service client creation it is set to service's default generated EndpointProvider, /// but can be changed to use custom user supplied EndpointProvider. /// </summary> public IEndpointProvider EndpointProvider { get; set; } } }
971
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 ThirdParty.Json.LitJson; using Amazon.Util; using Amazon.Util.Internal; using Amazon.Util.Internal.PlatformServices; using Amazon.Runtime; namespace Amazon.Runtime.Internal { /// <summary> /// This class composes Client Context header for Amazon Web Service client. /// It contains information like app title, version code, version name, client id, OS platform etc. /// </summary> public partial class ClientContext { //client related keys private const string CLIENT_KEY = "client"; private const string CLIENT_ID_KEY = "client_id"; private const string CLIENT_APP_TITLE_KEY = "app_title"; private const string CLIENT_APP_VERSION_NAME_KEY = "app_version_name"; private const string CLIENT_APP_VERSION_CODE_KEY = "app_version_code"; private const string CLIENT_APP_PACKAGE_NAME_KEY = "app_package_name"; //custom keys private const string CUSTOM_KEY = "custom"; //env related keys private const string ENV_KEY = "env"; private const string ENV_PLATFORM_KEY = "platform"; private const string ENV_MODEL_KEY = "model"; private const string ENV_MAKE_KEY = "make"; private const string ENV_PLATFORM_VERSION_KEY = "platform_version"; private const string ENV_LOCALE_KEY = "locale"; //servies related keys private const string SERVICES_KEY = "services"; // TODO: add support to other services private const string SERVICE_MOBILE_ANALYTICS_KEY = "mobile_analytics"; private const string SERVICE_MOBILE_ANALYTICS_APP_ID_KEY = "app_id"; private IDictionary<string,string> _client; private IDictionary<string,string> _custom; private IDictionary<string,string> _env; private IDictionary<string,IDictionary> _services; private IDictionary _clientContext; private static object _lock = new object(); #if BCL private static string _clientID = null; #endif private const string APP_ID_KEY = "APP_ID_KEY"; private const string CLIENT_ID_CACHE_FILENAME = "client-ID-cache"; public string AppID { get; set; } /// <summary> /// Adds the custom attributes to the Client Context. /// </summary> /// <param name="key">Key.</param> /// <param name="value">Value.</param> public void AddCustomAttributes(string key, string value) { lock(_lock) { if (_custom == null) _custom = new Dictionary<string, string>(); _custom.Add(key,value); } } /// <summary> /// Gets a Json Representation of the Client Context. /// </summary> /// <returns>Json Representation of Client Context</returns> public String ToJsonString() { lock(_lock) { _client = new Dictionary<string, string>(); _env = new Dictionary<string, string>(); _services = new Dictionary<string, IDictionary>(); #if BCL // client _client.Add(CLIENT_ID_KEY, _clientID); if (!string.IsNullOrEmpty(_config.AppTitle)) _client.Add(CLIENT_APP_TITLE_KEY, _config.AppTitle); if (!string.IsNullOrEmpty(_config.AppVersionName)) _client.Add(CLIENT_APP_VERSION_NAME_KEY, _config.AppVersionName); if (!string.IsNullOrEmpty(_config.AppVersionCode)) _client.Add(CLIENT_APP_VERSION_CODE_KEY, _config.AppVersionCode); if (!string.IsNullOrEmpty(_config.AppPackageName)) _client.Add(CLIENT_APP_PACKAGE_NAME_KEY, _config.AppPackageName); // env if (!string.IsNullOrEmpty(_config.Platform)) _env.Add(ENV_PLATFORM_KEY, _config.Platform); else _env.Add(ENV_PLATFORM_KEY, Environment.OSVersion.Platform.ToString()); if (!string.IsNullOrEmpty(_config.PlatformVersion)) _env.Add(ENV_PLATFORM_VERSION_KEY, _config.PlatformVersion); else _env.Add(ENV_PLATFORM_VERSION_KEY, Environment.OSVersion.Version.ToString()); if (!string.IsNullOrEmpty(_config.Locale)) _env.Add(ENV_LOCALE_KEY, _config.Locale); else _env.Add(ENV_LOCALE_KEY, System.Globalization.CultureInfo.CurrentCulture.Name); if (!string.IsNullOrEmpty(_config.Make)) _env.Add(ENV_MAKE_KEY, _config.Make); if (!string.IsNullOrEmpty(_config.Model)) _env.Add(ENV_MODEL_KEY, _config.Model); #endif // services if (!string.IsNullOrEmpty(this.AppID)) { IDictionary mobileAnalyticsService = new Dictionary<string, string>(); mobileAnalyticsService.Add(SERVICE_MOBILE_ANALYTICS_APP_ID_KEY, AppID); _services.Add(SERVICE_MOBILE_ANALYTICS_KEY, mobileAnalyticsService); } _clientContext = new Dictionary<string, IDictionary>(); _clientContext.Add(CLIENT_KEY, _client); _clientContext.Add(ENV_KEY, _env); _clientContext.Add(CUSTOM_KEY, _custom); _clientContext.Add(SERVICES_KEY, _services); return JsonMapper.ToJson(_clientContext); } } } }
162
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 * API Version: 2006-03-01 * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Amazon.Util.Internal; namespace Amazon.Runtime { /// <summary> /// Base class for constant class that holds the value that will be sent to AWS for the static constants. /// </summary> public class ConstantClass { static readonly object staticFieldsLock = new object(); static Dictionary<Type, Dictionary<string, ConstantClass>> staticFields = new Dictionary<Type, Dictionary<string, ConstantClass>>(); protected ConstantClass(string value) { this.Value = value; } /// <summary> /// Gets the value that needs to be used when send the value to AWS /// </summary> public string Value { get; private set; } public override string ToString() { return this.Intern().Value; } public string ToString(IFormatProvider provider) { return this.Intern().Value; } public static implicit operator string(ConstantClass value) { if (value == null) return null; return value.Intern().Value; } /// <summary> /// Attempt to find correct-cased constant value using whatever cased value the user /// has provided. This is primarily useful for mapping any-cased values from a CLI /// tool to the specific casing required by the service, avoiding the need for the /// user to (a) remember the specific case and (b) actually type it correctly. /// </summary> /// <returns>The properly cased service constant matching the value</returns> internal ConstantClass Intern() { if (!staticFields.ContainsKey(this.GetType())) LoadFields(this.GetType()); var map = staticFields[this.GetType()]; ConstantClass foundValue; return map.TryGetValue(this.Value, out foundValue) ? foundValue : this; } protected static T FindValue<T>(string value) where T : ConstantClass { if (value == null) return null; if (!staticFields.ContainsKey(typeof(T))) LoadFields(typeof (T)); var fields = staticFields[typeof(T)]; ConstantClass foundValue; if (!fields.TryGetValue(value, out foundValue)) { var typeInfo = TypeFactory.GetTypeInfo(typeof(T)); var constructor = typeInfo.GetConstructor(new ITypeInfo[] { TypeFactory.GetTypeInfo(typeof(string)) }); return constructor.Invoke(new object[] { value }) as T; } return foundValue as T; } private static void LoadFields(Type t) { if (staticFields.ContainsKey(t)) return; lock (staticFieldsLock) { if (staticFields.ContainsKey(t)) return; var map = new Dictionary<string, ConstantClass>(StringComparer.OrdinalIgnoreCase); var typeInfo = TypeFactory.GetTypeInfo(t); foreach (var fieldInfo in typeInfo.GetFields()) { if (fieldInfo.IsStatic && fieldInfo.FieldType == t) { var cc = fieldInfo.GetValue(null) as ConstantClass; map[cc.Value] = cc; } } // create copy of dictionary with new value var newDictionary = new Dictionary<Type, Dictionary<string, ConstantClass>>(staticFields); newDictionary[t] = map; // swap in the new dictionary staticFields = newDictionary; } } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { // If obj is null, return false. return false; } // If both are the same instance, return true. if (System.Object.ReferenceEquals(this, obj)) { return true; } var objConstantClass = obj as ConstantClass; if (this.Equals(objConstantClass)) { return true; } var objString = obj as string; if (objString != null) { return Equals(objString); } // obj is of an incompatible type, return false. return false; } public virtual bool Equals(ConstantClass obj) { if ((object)obj == null) { // If obj is null, return false. return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } protected virtual bool Equals(string value) { return StringComparer.OrdinalIgnoreCase.Equals(this.Value, value); } public static bool operator ==(ConstantClass a, ConstantClass b) { if (System.Object.ReferenceEquals(a, b)) { // If both are null, or both are the same instance, return true. return true; } if ((object)a == null) { // If either is null, return false. return false; } else { return a.Equals(b); } } public static bool operator !=(ConstantClass a, ConstantClass b) { return !(a == b); } public static bool operator ==(ConstantClass a, string b) { if ((object)a == null && b == null) { return true; } if ((object)a == null) { // If either is null, return false. return false; } else { return a.Equals(b); } } public static bool operator ==(string a, ConstantClass b) { return (b == a); } public static bool operator !=(ConstantClass a, string b) { return !(a == b); } public static bool operator !=(string a, ConstantClass b) { return !(a == b); } } }
248
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 * API Version: 2006-03-01 * */ using System; using System.Collections.Generic; using Amazon.Util.Internal; using System.Threading; namespace Amazon.Runtime { /// <summary> /// Utility class that stores clock skew information. /// </summary> public static class CorrectClockSkew { private static TimeSpan? manualClockCorrection; private static ReaderWriterLockSlim manualClockCorrectionLock = new ReaderWriterLockSlim(); /// <summary> /// GlobalClockCorrection should be only set by AWSConfigs.ManualClockCorrection property /// and is only available to maintain backward compatibilty. This should override any /// endpoint specific clockskew correction. /// </summary> internal static TimeSpan? GlobalClockCorrection { get { TimeSpan? value; manualClockCorrectionLock.EnterReadLock(); { value = manualClockCorrection; } manualClockCorrectionLock.ExitReadLock(); return value; } set { manualClockCorrectionLock.EnterWriteLock(); { manualClockCorrection = value; } manualClockCorrectionLock.ExitWriteLock(); } } private static IDictionary<string, TimeSpan> clockCorrectionDictionary = new Dictionary<string, TimeSpan>(); private static ReaderWriterLockSlim clockCorrectionDictionaryLock = new ReaderWriterLockSlim(); /// <summary> /// Return clock skew correction value for an endpoint if there is one. /// /// AWSConfigs.ManualClockCorrection overrides globally any calculated service endpoint specific /// clock correction value. /// </summary> /// <param name="endpoint">Endpoint should in a form such as "https://s3"</param> /// <returns>Clock correction value for an endpoint in TimeSpan. TimeSpan.Zero if no such clock correction is set.</returns> public static TimeSpan GetClockCorrectionForEndpoint(string endpoint) { TimeSpan span; bool hasValue = false; clockCorrectionDictionaryLock.EnterReadLock(); try { hasValue = clockCorrectionDictionary.TryGetValue(endpoint, out span); } finally { clockCorrectionDictionaryLock.ExitReadLock(); } return hasValue ? span : TimeSpan.Zero; } /// <summary> /// Get clock skew corrected UTC now value. If ManualClockCorrection is set, /// use ManualClockCorrection instead of endpoint specific clock correction value. /// </summary> /// <param name="endpoint"></param> /// <returns></returns> public static DateTime GetCorrectedUtcNowForEndpoint(string endpoint) { TimeSpan adjustment = TimeSpan.Zero; manualClockCorrectionLock.EnterReadLock(); try { if (manualClockCorrection != null) adjustment = manualClockCorrection.Value; } finally { manualClockCorrectionLock.ExitReadLock(); } if (AWSConfigs.CorrectForClockSkew && (adjustment == TimeSpan.Zero)) { adjustment = GetClockCorrectionForEndpoint(endpoint); } return AWSConfigs.utcNowSource() + adjustment; } internal static void SetClockCorrectionForEndpoint(string endpoint, TimeSpan correction) { clockCorrectionDictionaryLock.EnterWriteLock(); try { clockCorrectionDictionary[endpoint] = correction; #pragma warning disable CS0618 // Type or member is obsolete AWSConfigs.ClockOffset = correction; #pragma warning restore CS0618 // Type or member is obsolete } finally { clockCorrectionDictionaryLock.ExitWriteLock(); } } } }
141
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; namespace Amazon.Runtime { /// <summary> /// A defaults mode determines how certain default configuration options are resolved in the SDK. Based on the provided /// mode, the SDK will vend sensible default values tailored to the specific <see cref="DefaultConfigurationMode"/>. /// <para /> /// All options above can be configured by users, and the overridden value will take precedence. /// <para /> /// <b>Note:</b> for any mode other than <see cref="DefaultConfigurationMode.Legacy"/>, the vended default values /// might change as best practices may evolve. As a result, it is encouraged to perform testing when upgrading the SDK /// if you are using a mode other than <see cref="DefaultConfigurationMode.Legacy"/>. /// <para /> /// While the <see cref="DefaultConfigurationMode.Legacy"/> defaults mode is specific to .NET, /// other modes are standardized across all of the AWS SDKs. /// <para /> /// The defaults mode can be configured: /// <list type="number"> /// <item>When constructing an <see cref="AmazonServiceClient"/> implementation by setting <see cref="ClientConfig.DefaultConfigurationMode"/>.</item> /// <item>Globally via the "AWS_DEFAULTS_MODE" environment variable.</item> /// <item>On a configuration profile via the "defaults_mode" profile file property.</item> /// </list> /// </summary> public interface IDefaultConfiguration { /// <summary> /// Identifies a specific configuration mode. Example legacy, mobile, cross-region, etc /// </summary> DefaultConfigurationMode Name { get; } /// <summary> /// A retry mode specifies how the SDK attempts retries. /// See https://docs.aws.amazon.com/sdkref/latest/guide/setting-global-retry_mode.html /// </summary> RequestRetryMode RetryMode { get; } /// <summary> /// Specifies how the SDK determines the AWS service endpoint that it uses to talk to the AWS Security Token Service (AWS STS). /// See https://docs.aws.amazon.com/sdkref/latest/guide/setting-global-sts_regional_endpoints.html /// </summary> StsRegionalEndpointsValue StsRegionalEndpoints { get; } /// <summary> /// Specifies how the SDK determines the AWS service endpoint that it uses to talk to the Amazon S3 for the us-east-1 region /// </summary> S3UsEast1RegionalEndpointValue S3UsEast1RegionalEndpoint { get; } /// <summary> /// The amount of time after making an initial connect attempt on a socket, where if the client does not /// receive a completion of the connect handshake, the client gives up and fails the operation. /// </summary> TimeSpan? ConnectTimeout { get; } /// <summary> /// The maximum amount of time that a TLS handshake is allowed to take from the time the CLIENT HELLO message is sent to /// the client and server have fully negotiated ciphers and exchanged keys /// </summary> TimeSpan? TlsNegotiationTimeout { get; } /// <summary> /// How long an application will attempt to read the first byte over an established, /// open connection after write request before timing out. /// </summary> TimeSpan? TimeToFirstByteTimeout { get; } /// <summary> /// This timeout measures the time between when the first byte is sent over an established, /// open connection and when the last byte is received from the service. /// If the response is not received by the timeout, then the request is considered timed out. /// </summary> TimeSpan? HttpRequestTimeout { get; } } /// <inheritdoc cref="IDefaultConfiguration"/> [DebuggerDisplay("{" + nameof(Name) + "}")] public class DefaultConfiguration : IDefaultConfiguration { /// <inheritdoc /> public DefaultConfigurationMode Name { get; set; } /// <inheritdoc /> public RequestRetryMode RetryMode { get; set; } /// <inheritdoc /> public StsRegionalEndpointsValue StsRegionalEndpoints { get; set; } /// <inheritdoc /> public S3UsEast1RegionalEndpointValue S3UsEast1RegionalEndpoint { get; set; } /// <inheritdoc /> public TimeSpan? ConnectTimeout { get; set; } /// <inheritdoc /> public TimeSpan? TlsNegotiationTimeout { get; set; } /// <inheritdoc /> public TimeSpan? TimeToFirstByteTimeout { get; set; } /// <inheritdoc /> public TimeSpan? HttpRequestTimeout { get; set; } } }
105
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 * */ /* * Do not modify this file. This file is generated from the sdk-default-configuration.json file. */ namespace Amazon.Runtime { /// <summary> /// Enumeration of the supported Default Configurations available to to <see cref="AmazonServiceClient" /> objects. /// </summary> public enum DefaultConfigurationMode { /// <summary> /// <p>The STANDARD mode provides the latest recommended default values that should be safe to run in most scenarios</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> Standard, /// <summary> /// <p>The IN_REGION mode builds on the standard mode and includes optimization tailored for applications which call AWS services from within the same AWS region</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> InRegion, /// <summary> /// <p>The CROSS_REGION mode builds on the standard mode and includes optimization tailored for applications which call AWS services in a different region</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> CrossRegion, /// <summary> /// <p>The MOBILE mode builds on the standard mode and includes optimization tailored for mobile applications</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> Mobile, /// <summary> /// <p>The AUTO mode is an experimental mode that builds on the standard mode. The SDK will attempt to discover the execution environment to determine the appropriate settings automatically.</p><p>Note that the auto detection is heuristics-based and does not guarantee 100% accuracy. STANDARD mode will be used if the execution environment cannot be determined. The auto detection might query <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">EC2 Instance Metadata service</a>, which might introduce latency. Therefore we recommend choosing an explicit defaults_mode instead if startup latency is critical to your application</p> /// </summary> Auto, /// <summary> /// <p>The LEGACY mode provides default settings that vary per SDK and were used prior to establishment of defaults_mode</p> /// </summary> Legacy } }
58
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; using Amazon.Runtime.CredentialManagement; namespace Amazon.Runtime { /// <summary> /// Determines the endpoint discovery enabled value based on an environment variable. If no value is found in the /// environment then an InvalidOperationException is thrown. /// </summary> [Obsolete("This class has been deprecated in favor of EnvironmentVariableAWSConfiguration.")] public class EnvironmentVariableAWSEndpointDiscoveryEnabled { public const string ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY = "AWS_ENABLE_ENDPOINT_DISCOVERY"; public bool Enabled { get; private set; } /// <summary> /// Attempts to construct an instance of EnvironmentVariable AWS_ENABLED_ENDPOINT_DISCOVERY. If no value is found in the /// environment then an InvalidOperationException is thrown. /// </summary> public EnvironmentVariableAWSEndpointDiscoveryEnabled() { string enabledValue = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY); if (string.IsNullOrEmpty(enabledValue)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The environment variable {0} was not set with a boolean value.", ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY)); } bool enabled; if(!bool.TryParse(enabledValue, out enabled)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The environment variable {0} was set with value {1}, but it could not be parsed as a valid boolean value.", ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY, enabledValue)); } this.Enabled = enabled; var logger = Logger.GetLogger(typeof(EnvironmentVariableAWSEndpointDiscoveryEnabled)); logger.InfoFormat("Endpoint discovery enabled found using environment variable."); } } /// <summary> /// Determines endpoint discovery enabled based on a <see cref="CredentialProfile"/> stored in an <see cref="ICredentialProfileSource"/>. /// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown. /// </summary> [Obsolete("This class has been deprecated in favor of ProfileAWSConfiguration.")] public class ProfileAWSEndpointDiscoveryEnabled { public bool Enabled { get; private set; } /// <summary> /// Attempts to construct an instance of <see cref="ProfileAWSEndpointDiscoveryEnabled"/>. /// If the AWS_PROFILE environment variable is set the instance will be constructed using that profile, /// otherwise it will use the default profile. /// /// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown. /// </summary> /// <param name="source">The ICredentialProfileSource to read the profile from.</param> public ProfileAWSEndpointDiscoveryEnabled(ICredentialProfileSource source) { var profileName = FallbackCredentialsFactory.GetProfileName(); Setup(source, profileName); } /// <summary> /// Attempts to construct an instance of <see cref="ProfileAWSEndpointDiscoveryEnabled"/>. /// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown. /// </summary> /// <param name="source">The ICredentialProfileSource to read the profile from.</param> /// <param name="profileName">The name of the profile.</param> public ProfileAWSEndpointDiscoveryEnabled(ICredentialProfileSource source, string profileName) { Setup(source, profileName); } private void Setup(ICredentialProfileSource source, string profileName) { bool? enabled = null; CredentialProfile profile; if (source.TryGetProfile(profileName, out profile)) { enabled = profile.EndpointDiscoveryEnabled; } else throw new InvalidOperationException("Unable to find a profile named '" + profileName + "' in store " + source.GetType()); if (enabled == null) throw new InvalidOperationException("There is no endpoint_discovery_enabled set in the profile named '" + profileName + "' in store " + source.GetType()); else { this.Enabled = enabled.Value; var logger = Logger.GetLogger(typeof(ProfileAWSEndpointDiscoveryEnabled)); logger.InfoFormat("endpoint_discovery_enabled found in profile '" + profileName + "' in store " + source.GetType()); } } } /// <summary> /// Probing mechanism to determine the endpoint discovery enabled value from various sources. /// </summary> [Obsolete("This class has been deprecated in favor of FallbackConfigurationFactory.")] public static class FallbackEndpointDiscoveryEnabledFactory { private static CredentialProfileStoreChain credentialProfileChain = new CredentialProfileStoreChain(); private static object _lock = new object(); static FallbackEndpointDiscoveryEnabledFactory() { Reset(); } private delegate bool ConfigGenerator(); private static List<ConfigGenerator> EnabledGenerators { get; set; } public static void Reset() { endpointDiscoveryEnabled = null; EnabledGenerators = new List<ConfigGenerator> { () => (new EnvironmentVariableAWSEndpointDiscoveryEnabled()).Enabled, () => (new ProfileAWSEndpointDiscoveryEnabled(credentialProfileChain)).Enabled, }; } private static bool? endpointDiscoveryEnabled; public static bool? GetEnabled() { lock (_lock) { if (endpointDiscoveryEnabled != null) return endpointDiscoveryEnabled; List<Exception> errors = new List<Exception>(); //Determine the Enabled flag foreach (var generator in EnabledGenerators) { try { endpointDiscoveryEnabled = generator(); } catch (Exception e) { errors.Add(e); continue; } if (endpointDiscoveryEnabled.HasValue) break; } return endpointDiscoveryEnabled; } } } }
180
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 { /// <summary> /// The valid hashing algorithm supported by the sdk for request signing. /// </summary> public enum SigningAlgorithm { HmacSHA1, HmacSHA256 }; /// <summary> /// Which end of a request was responsible for a service error response. /// </summary> public enum ErrorType { /// <summary> /// The sender was responsible for the error, i.e. the client /// request failed validation or was improperly formatted. /// </summary> Sender, /// <summary> /// The error occured within the service. /// </summary> Receiver, /// <summary> /// An unrecognized error type was returned. /// </summary> Unknown } /// <summary> /// Sts Regional Endpoints Value determines whether or not /// to send the sts request to the regional endpoint or to /// the global sts endpoint /// </summary> public enum StsRegionalEndpointsValue { /// <summary> /// Send the request to the global sts endpoint /// if the region is a legacy global region /// </summary> Legacy, /// <summary> /// Send the request to the regional endpoint /// </summary> Regional } /// <summary> /// S3 US East 1 endpoint value determines wheter or not /// to send the us-east-1 s3 requests to the regional endpoint or to /// the legacy global endpoint /// </summary> public enum S3UsEast1RegionalEndpointValue { /// <summary> /// Sends the requests to the legacy global s3 endpoint for us-east-1 /// </summary> Legacy, /// <summary> /// Sends the request to the regional s3 endpoint for us-east-1 /// </summary> Regional } /// <summary> /// RetryMode determines which request retry mode is used for requests that do /// not complete successfully. /// </summary> public enum RequestRetryMode { /// <summary> /// Legacy request retry strategy. /// </summary> Legacy, /// <summary> /// Standardized request retry strategy that is consistent across all SDKs. /// </summary> Standard, /// <summary> /// An experimental request retry strategy that builds on the Standard strategy /// and introduces congestion control through client side rate limiting. /// </summary> Adaptive } /// <summary> /// EC2MetadataServiceEndpointMode determines the internet protocol version /// to be used for communicating with the EC2 Instance Metadata Service /// </summary> public enum EC2MetadataServiceEndpointMode { /// <summary> /// Internet Protocol version 4 /// </summary> IPv4, /// <summary> /// Internet Protocol version 6 /// </summary> IPv6 } /// <summary> /// SignatureVersion determines which signature version is used for the request /// </summary> public enum SignatureVersion { /// <summary> /// Signature Version 2 /// </summary> SigV2, /// <summary> /// Signature Version 4 /// </summary> SigV4, /// <summary> /// Asymmetric Signature Version 4 /// </summary> SigV4a } /// <summary> /// Algorithms for validating request and response integrity for supported operations. /// These are the algorithms support by the .NET SDK, a given service may /// only use a subset of these. /// </summary> public enum CoreChecksumAlgorithm { NONE, CRC32C, CRC32, SHA256, SHA1 } /// <summary> /// Behavior to be used for verifying the checksum of response content /// that may be returned by supported service operations. /// </summary> public enum CoreChecksumResponseBehavior { /// <summary> /// The SDK will not attempt to verify the response checksum /// </summary> DISABLED, /// <summary> /// The SDK will attempt to verify the response checksum /// </summary> ENABLED } }
171
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; using Amazon.Runtime.Internal; namespace Amazon.Runtime { public delegate void ExceptionEventHandler(object sender, ExceptionEventArgs e); public class ExceptionEventArgs : EventArgs { #region Constructor protected ExceptionEventArgs() { } #endregion } public class WebServiceExceptionEventArgs : ExceptionEventArgs { #region Constructor protected WebServiceExceptionEventArgs() { } #endregion #region Properties public IDictionary<string, string> Headers { get; protected set; } public IDictionary<string, string> Parameters { get; protected set; } public string ServiceName { get; protected set; } public Uri Endpoint { get; protected set; } public AmazonWebServiceRequest Request { get; protected set; } public Exception Exception { get; protected set; } #endregion #region Creator method internal static WebServiceExceptionEventArgs Create(Exception exception, IRequest request) { WebServiceExceptionEventArgs args; if (request == null) args = new WebServiceExceptionEventArgs { Exception = exception }; else args = new WebServiceExceptionEventArgs { Headers = request.Headers, Parameters = request.Parameters, ServiceName = request.ServiceName, Request = request.OriginalRequest, Endpoint = request.Endpoint, Exception = exception }; return args; } #endregion } }
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. */ namespace Amazon.Runtime { /// <summary> /// All Amazon service interfaces like IAmazonS3 extend from this interface. This allows all the /// Amazon service interfaces be identified by this base interface and helps with generic constraints. /// </summary> public interface IAmazonService { /// <summary> /// A readonly view of the configuration for the service client. /// </summary> IClientConfig Config { get; } } }
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; using System.Net; using Amazon.Runtime.Internal; using Amazon.Runtime.Endpoints; using Amazon.Runtime.Internal.Auth; using Amazon.Util; #if NETSTANDARD using System.Net.Http; #endif namespace Amazon.Runtime { /// <summary> /// This interface is the read only access to the ClientConfig object used when setting up service clients. Once service clients /// are initiated the config object should not be changed to avoid issues with using a service client in a multi threaded environment. /// </summary> public partial interface IClientConfig { /// <summary> /// For Services using Bearer authentication, this controls how <see cref="BearerTokenSigner"/> /// resolves a <see cref="AWSToken"/>. /// <para /> /// See <see cref="DefaultAWSTokenProviderChain"/> for additional information. /// </summary> IAWSTokenProvider AWSTokenProvider { get; } /// <summary> /// Returns the <see cref="Amazon.Runtime.DefaultConfigurationMode"/> that will be used. If none is specified, /// than the correct one is computed by <see cref="IDefaultConfigurationProvider"/>. /// </summary> DefaultConfigurationMode DefaultConfigurationMode { get; } /// <summary> /// Gets the RegionEndpoint property. The region constant to use that /// determines the endpoint to use. If this is not set /// then the client will fallback to the value of ServiceURL. /// </summary> RegionEndpoint RegionEndpoint { get; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> string RegionEndpointServiceName { get; } /// <summary> /// Gets and sets of the ServiceURL property. /// This is an optional property if you need to set a specific service URL /// instead setting the region with the RegionEndpoint property. /// </summary> string ServiceURL { get; } /// <summary> /// Gets and sets of the EndpointProvider property. /// This property is used for endpoints resolution. /// During service client creation it is set to service's default generated EndpointProvider, /// but can be changed to use custom user supplied EndpointProvider. /// </summary> IEndpointProvider EndpointProvider { get; } /// <summary> /// Gets the UseHttp property. /// If this property is set to true, the client attempts /// to use HTTP protocol. /// By default, this property is set to false. /// </summary> bool UseHttp { get; } /// <summary> /// Gets Service Version /// </summary> string ServiceVersion { get; } /// <summary> /// Gets the signatureMethod property. /// </summary> SigningAlgorithm SignatureMethod { get; } /// <summary> /// Gets the SignatureVersion property. /// /// Note: This property exists for backward compatibility but is no longer /// used by any service other than S3. /// </summary> string SignatureVersion { get; } /// <summary> /// Gets the AuthenticationRegion property. /// Used in AWS4 request signing, this is an optional property; /// change it only if the region cannot be determined from the /// service endpoint. /// </summary> string AuthenticationRegion { get; } /// <summary> /// Gets the AuthenticationServiceName property. /// Used in AWS4 request signing, this is the short-form /// name of the service being called. /// </summary> string AuthenticationServiceName { get; } /// <summary> /// Gets the UserAgent property. /// </summary> string UserAgent { get; } /// <summary> /// Gets the DisableLogging. If true logging for this client will be disabled. /// </summary> bool DisableLogging { get; } /// <summary> /// Flag on whether to log metrics for service calls. /// /// This can be set in the application's configs, as below: /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSLogMetrics" value"true"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// </summary> bool LogMetrics { get; } /// <summary> /// Gets the LogResponse property. /// If this property is set to true, the service response /// is read in its entirety and logged. /// </summary> bool LogResponse { get; } /// <summary> /// Gets the ReadEntireResponse. /// If this property is set to true, the service response /// is read in its entirety before being processed. /// </summary> bool ReadEntireResponse { get; } /// <summary> /// This flag controls if .NET HTTP infrastructure should follow redirection /// responses (e.g. HTTP 307 - temporary redirect). /// </summary> bool AllowAutoRedirect { get; } /// <summary> /// Gets the BufferSize property. /// The BufferSize controls the buffer used to read in from input streams and write /// out to the request. /// </summary> int BufferSize { get; } /// <summary> /// Returns the flag indicating how many retry HTTP requests an SDK should /// make for a single SDK operation invocation before giving up. This flag will /// return 4 when the RetryMode is set to "Legacy" which is the default. For /// RetryMode values of "Standard" or "Adaptive" this flag will return 2. In /// addition to the values returned that are dependant on the RetryMode, the /// value can be set to a specific value by using the AWS_MAX_ATTEMPTS environment /// variable, max_attempts in the shared configuration file, or by setting a /// value directly on this property. When using AWS_MAX_ATTEMPTS or max_attempts /// the value returned from this property will be one less than the value entered /// because this flag is the number of retry requests, not total requests. To /// learn more about the RetryMode property that affects the values returned by /// this flag, see <see cref="RetryMode"/>. /// </summary> int MaxErrorRetry { get; } /// <summary> /// Determines if MaxErrorRetry has been manually set. /// </summary> bool IsMaxErrorRetrySet { get; } /// <summary> /// Gets the interval at which progress update events are raised /// for upload operations. By default, the progress update events are /// raised at every 100KB of data transferred. /// </summary> long ProgressUpdateInterval { get; } /// <summary> /// Flag on whether to resign requests on retry or not. /// </summary> bool ResignRetries { get; } /// <summary> /// Credentials to use with a proxy. /// </summary> ICredentials ProxyCredentials { get; } /// <summary> /// Gets the default request timeout value. /// </summary> /// <remarks> /// <para> /// If the value is set, the value is assigned to the Timeout property of the HTTPWebRequest/HttpClient object used /// to send requests. /// </para> /// <para> /// Please specify a timeout value only if the operation will not complete within the default intervals /// specified for an HttpWebRequest/HttpClient. /// </para> /// </remarks> TimeSpan? Timeout { get; } /// <summary> /// Configures the endpoint calculation for a service to go to a dual stack (ipv6 enabled) endpoint /// for the configured region. /// </summary> /// <remarks> /// Note: AWS services are enabling dualstack endpoints over time. It is your responsibility to check /// that the service actually supports a dualstack endpoint in the configured region before enabling /// this option for a service. /// </remarks> bool UseDualstackEndpoint { get; } /// <summary> /// Configures the endpoint calculation to go to a FIPS (https://aws.amazon.com/compliance/fips/) endpoint /// for the configured region. /// </summary> bool UseFIPSEndpoint { get; } /// <summary> /// Configures a flag enabling to either opt in or opt out of the retry throttling service. /// Note: set value to true to enable retry throttling feature. The Default value for this flag is false. /// </summary> bool ThrottleRetries { get; } /// <summary> /// Using either the RegionEndpoint or the ServiceURL determine what the URL to the service is. /// </summary> /// <returns>The URL to the service.</returns> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] string DetermineServiceURL(); /// <summary> /// Given this client configuration, return a DNS suffix for service endpoint url. /// </summary> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] string DetermineDnsSuffix(); /// <summary> /// Performs validation on this config object. /// Throws exception if any of the required values are missing/invalid. /// </summary> /// <exception cref="Amazon.Runtime.AmazonClientException">The timeout specified is null.</exception> void Validate(); /// <summary> /// Returns the clock skew adjusted utc now. This value is affected by AWSConfigs.ManualClockCorrection /// </summary> DateTime CorrectedUtcNow { get; } /// <summary> /// Returns the calculated clock skew value for this config's service endpoint. If AWSConfigs.CorrectForClockSkew is false, /// this value won't be used to construct service requests. /// </summary> TimeSpan ClockOffset { get; } /// <summary> /// Gets the DisableHostPrefixInjection flag. If true, host prefix injection will be disabled for this client, the default value of this flag is false. /// Host prefix injection prefixes the service endpoint with request members from APIs which use this feature. /// Example: for a hostPrefix of "foo-name." and a endpoint of "service.region.amazonaws.com" the default behavior is to /// prefix the endpoint with the hostPrefix resulting in a final endpoint of "foo-name.service.region.amazonaws.com". Setting /// DisableHostPrefixInjection to true will disable hostPrefix injection resulting in a final endpoint of /// "service.region.amazonaws.com" regardless of the value of hostPrefix. E.g. You may want to disable host prefix injection for testing against a local mock endpoint. /// </summary> bool DisableHostPrefixInjection { get; } /// <summary> /// Returns the flag indicating if endpoint discovery should be enabled or disabled for operations that are not required to use endpoint discovery. /// </summary> bool EndpointDiscoveryEnabled { get; } /// <summary> /// Returns the maximum number of discovered endpoints that can be stored within the cache for the client. The default limit is 1000 cache entries. /// </summary> int EndpointDiscoveryCacheLimit { get; } /// <summary> /// Returns the flag indicating the current mode in use for request /// retries and influences the value returned from <see cref="MaxErrorRetry"/>. /// The default value is RequestRetryMode.Legacy. This flag can be configured /// by using the AWS_RETRY_MODE environment variable, retry_mode in the /// shared configuration file, or by setting this value directly. /// </summary> RequestRetryMode RetryMode { get; } /// <summary> /// Under Adaptive retry mode, this flag determines if the client should wait for /// a send token to become available or don't block and fail the request immediately /// if a send token is not available. /// </summary> bool FastFailRequests { get; } /// <summary> /// When set to true, the service client will use the x-amz-user-agent /// header instead of the User-Agent header to report version and /// environment information to the AWS service. /// /// Note: This is especially useful when using a platform like WebAssembly /// which doesn't allow to specify the User-Agent header. /// </summary> bool UseAlternateUserAgentHeader { get; } #if BCL /// <summary> /// Gets the TCP keep-alive values to use for service requests. Enabling TCP keep-alive sends periodic TCP keep-alive probe packets, to prevent disconnection due to /// network inactivity. This is useful when you make API calls that take a long time to respond. In this case, the connection could be dropped by an intermediate /// node (e.g. proxy) as the connection is inactive for a long time. Timeout controls the duration of inactivity before a keep-alive probe packet is sent. /// Interval controls the amount of time to wait before retrying a keep-alive probe packet in the event the server doesn't respond to a keep-alive probe. /// </summary> TcpKeepAlive TcpKeepAlive { get; } #endif #if NETSTANDARD /// <summary> /// Get the value to use for <see cref="HttpClientHandler.MaxConnectionsPerServer"/> on requests. /// If this property is null, <see cref="HttpClientHandler.MaxConnectionsPerServer"/> /// will be left at its default value of <see cref="int.MaxValue"/>. /// </summary> int? MaxConnectionsPerServer { get; } /// <summary> /// <para> /// This is a switch used for performance testing and is not intended for production applications /// to change. This switch may be removed in a future version of the SDK as the .NET Core platform matures. /// </para> /// <para> /// If true, the HttpClient is cached and reused for every request made by the service client /// and shared with other service clients. /// </para> /// <para> /// For the .NET Core platform this is default to true because the HttpClient manages the connection /// pool. /// </para> /// </summary> bool CacheHttpClient { get; } /// <summary> /// If CacheHttpClient is set to true then HttpClientCacheSize controls the number of HttpClients cached. /// </summary> int HttpClientCacheSize { get; } #endif } }
366
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> /// Interface for a single logged message. /// </summary> public interface ILogMessage { /// <summary> /// Log message format. /// </summary> string Format { get; } /// <summary> /// Log message arguments. /// </summary> object[] Args { get; } /// <summary> /// Culture-specific formatting provider. /// </summary> IFormatProvider Provider { get; } } }
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. */ using System; using System.Collections.Generic; using System.Globalization; 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; namespace Amazon.Runtime.Internal { /// <summary> /// Collection of parameters that an SDK client will send to a service. /// </summary> public class ParameterCollection : SortedDictionary<string, ParameterValue> { /// <summary> /// Constructs empty ParameterCollection. /// </summary> public ParameterCollection() : base(comparer: StringComparer.Ordinal) { } /// <summary> /// Adds a parameter with a string value. /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void Add(string key, string value) { Add(key, new StringParameterValue(value)); } /// <summary> /// Adds a parameter with a list-of-strings value. /// </summary> /// <param name="key"></param> /// <param name="values"></param> public void Add(string key, List<string> values) { Add(key, new StringListParameterValue(values)); } /// <summary> /// Adds a parameter with a list-of-doubles value. /// </summary> /// <param name="key"></param> /// <param name="values"></param> public void Add(string key, List<double> values) { Add(key, new DoubleListParameterValue(values)); } /// <summary> /// Converts the current parameters into a list of key-value pairs. /// </summary> /// <returns></returns> public List<KeyValuePair<string,string>> GetSortedParametersList() { return GetParametersEnumerable().ToList(); } private IEnumerable<KeyValuePair<string, string>> GetParametersEnumerable() { foreach (var kvp in this) { var name = kvp.Key; var value = kvp.Value; switch (value) { case StringParameterValue stringParameterValue: yield return new KeyValuePair<string, string>(name, stringParameterValue.Value); break; case StringListParameterValue stringListParameterValue: var sortedStringListParameterValue = stringListParameterValue.Value; sortedStringListParameterValue.Sort(StringComparer.Ordinal); foreach (var listValue in sortedStringListParameterValue) yield return new KeyValuePair<string, string>(name, listValue); break; case DoubleListParameterValue doubleListParameterValue: var sortedDoubleListParameterValue = doubleListParameterValue.Value; sortedDoubleListParameterValue.Sort(); foreach (var listValue in sortedDoubleListParameterValue) yield return new KeyValuePair<string, string>(name, listValue.ToString(CultureInfo.InvariantCulture)); break; default: throw new AmazonClientException("Unsupported parameter value type '" + value.GetType().FullName + "'"); } } } } }
111
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 { /// <summary> /// Abstract parameter value. /// </summary> public abstract class ParameterValue { } /// <summary> /// String parameter value. /// </summary> public class StringParameterValue : ParameterValue { /// <summary> /// String value of the parameter. /// </summary> public string Value { get; set; } /// <summary> /// Constructs ParameterValue for a single string. /// </summary> /// <param name="value"></param> public StringParameterValue(string value) { Value = value; } internal StringParameterValue() { } } /// <summary> /// String list parameter value. /// </summary> public class StringListParameterValue : ParameterValue { /// <summary> /// List of strings value of the parameter. /// </summary> public List<string> Value { get; set; } /// <summary> /// Constructs ParameterValue for a list of strings. /// </summary> /// <param name="values"></param> public StringListParameterValue(List<string> values) { Value = values; } internal StringListParameterValue() { } } /// <summary> /// Double list parameter value. /// </summary> public class DoubleListParameterValue : ParameterValue { /// <summary> /// List of doubles value of the parameter. /// </summary> public List<double> Value { get; set; } /// <summary> /// Constructs ParameterValue for a list of doubles. /// </summary> /// <param name="values"></param> public DoubleListParameterValue(List<double> values) { Value = values; } internal DoubleListParameterValue() { } } }
106
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 Amazon.Runtime.Internal; using System.Net; using System.Collections.Specialized; namespace Amazon.Runtime { public class PreRequestEventArgs : EventArgs { #region Constructor protected PreRequestEventArgs() { } #endregion #region Properties public AmazonWebServiceRequest Request { get; protected set; } #endregion #region Creator method internal static PreRequestEventArgs Create(AmazonWebServiceRequest request) { PreRequestEventArgs args = new PreRequestEventArgs { Request = request }; return args; } #endregion } public delegate void PreRequestEventHandler(object sender, PreRequestEventArgs e); }
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 System; using System.Collections.Generic; using System.Text; using Amazon.Runtime.Internal; using System.Net; using System.Collections.Specialized; namespace Amazon.Runtime { public class RequestEventArgs : EventArgs { #region Constructor protected RequestEventArgs() { } #endregion } public class WebServiceRequestEventArgs : RequestEventArgs { #region Constructor protected WebServiceRequestEventArgs() { } #endregion #region Properties public IDictionary<string, string> Headers { get; protected set; } [Obsolete("Parameters property has been deprecated in favor of the ParameterCollection property")] public IDictionary<string, string> Parameters { get; protected set; } public ParameterCollection ParameterCollection { get; protected set; } public string ServiceName { get; protected set; } public Uri Endpoint { get; protected set; } public AmazonWebServiceRequest Request { get; protected set; } [Obsolete("OriginalRequest property has been deprecated in favor of the Request property")] public AmazonWebServiceRequest OriginalRequest { get { return Request; } } #endregion #region Creator method internal static WebServiceRequestEventArgs Create(IRequest request) { WebServiceRequestEventArgs args = new WebServiceRequestEventArgs { Headers = request.Headers, #pragma warning disable CS0618 // Type or member is obsolete Parameters = request.Parameters, #pragma warning restore CS0618 // Type or member is obsolete ParameterCollection = request.ParameterCollection, ServiceName = request.ServiceName, Request = request.OriginalRequest, Endpoint = request.Endpoint }; return args; } #endregion } public class HeadersRequestEventArgs : RequestEventArgs { protected HeadersRequestEventArgs() { } public IDictionary<string, string> Headers { get; protected set; } internal static HeadersRequestEventArgs Create(IDictionary<string, string> headers) { HeadersRequestEventArgs args = new HeadersRequestEventArgs { Headers = headers }; return args; } } public delegate void RequestEventHandler(object sender, RequestEventArgs e); }
93
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Runtime { /// <summary> /// Metrics collected by the SDK on a per-request basis. /// </summary> /// <remarks> /// Each request made to an AWS service by the SDK can have metrics /// collected and logged. This interface represents the collected /// metrics for a request. The metrics include properties (i.e. request id /// and other metadata), timings for each stage of the request, and counters. /// </remarks> public interface IRequestMetrics { /// <summary> /// Collection of properties being tracked /// </summary> Dictionary<Metric, List<object>> Properties { get; } /// <summary> /// Timings for metrics being tracked /// </summary> Dictionary<Metric, List<IMetricsTiming>> Timings { get; } /// <summary> /// Counters being tracked /// </summary> Dictionary<Metric, long> Counters { get; } /// <summary> /// Whether metrics are enabled for the request /// </summary> bool IsEnabled { get; } /// <summary> /// JSON representation of the current metrics /// </summary> /// <returns>JSON string</returns> string ToJSON(); } /// <summary> /// Represents how long a phase of an SDK request took. /// </summary> public interface IMetricsTiming { /// <summary> /// Whether the timing has been stopped /// </summary> bool IsFinished { get; } /// <summary> /// Elapsed ticks from start to stop. /// If timing hasn't been stopped yet, returns 0. /// </summary> long ElapsedTicks { get; } /// <summary> /// Elapsed time from start to stop. /// If timing hasn't been stopped yet, returns TimeSpan.Zero /// </summary> TimeSpan ElapsedTime { get; } } /// <summary> /// User supplied type to perform metrics formatting. /// </summary> public interface IMetricsFormatter { /// <summary> /// Produce custom formatting for SDK metrics. /// </summary> /// <remarks> /// If defined, this method will be called for every request made by the SDK. /// </remarks> /// <param name="metrics">An instance of IRequestMetrics produced by the SDK</param> /// <returns>formatted string representation of the metrics</returns> string FormatMetrics(IRequestMetrics metrics); } /// <summary> /// Predefined request metrics that are collected by the SDK. /// </summary> public enum Metric { // response enums AWSErrorCode, AWSRequestID, AmzId2, BytesProcessed, Exception, RedirectLocation, ResponseProcessingTime, ResponseUnmarshallTime, ResponseReadTime, StatusCode, // request enums AttemptCount, CredentialsRequestTime, HttpRequestTime, ProxyHost, ProxyPort, RequestSigningTime, RetryPauseTime, StringToSign, CanonicalRequest, // CSM metric added to measure the latency of each http // request CSMAttemptLatency, // overall enums AsyncCall, ClientExecuteTime, MethodName, ServiceEndpoint, ServiceName, RequestSize, AmzCfId, } }
127
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; namespace Amazon.Runtime { public delegate void ResponseEventHandler(object sender, ResponseEventArgs e); public class ResponseEventArgs : EventArgs { #region Constructor protected ResponseEventArgs() { } #endregion } public class WebServiceResponseEventArgs : ResponseEventArgs { #region Constructor protected WebServiceResponseEventArgs() { } #endregion #region Properties public IDictionary<string, string> RequestHeaders { get; private set; } public IDictionary<string, string> ResponseHeaders { get; private set; } public IDictionary<string, string> Parameters { get; private set; } public string ServiceName { get; private set; } public Uri Endpoint { get; private set; } public AmazonWebServiceRequest Request { get; private set; } public AmazonWebServiceResponse Response { get; private set; } #endregion #region Creator method internal static WebServiceResponseEventArgs Create(AmazonWebServiceResponse response, IRequest request, IWebResponseData webResponseData) { WebServiceResponseEventArgs args = new WebServiceResponseEventArgs { RequestHeaders = request.Headers, Parameters = request.Parameters, ServiceName = request.ServiceName, Request = request.OriginalRequest, Endpoint = request.Endpoint, Response = response }; args.ResponseHeaders = new Dictionary<string, string>(); if (webResponseData != null) { var headerNames = webResponseData.GetHeaderNames(); foreach (var responseHeaderName in headerNames) { string responseHeaderValue = webResponseData.GetHeaderValue(responseHeaderName); args.ResponseHeaders[responseHeaderName] = responseHeaderValue; } } return args; } #endregion } }
69
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 { /// <summary> /// Information about the request. /// </summary> #if !NETSTANDARD [Serializable] #endif public class ResponseMetadata { private string requestIdField; private IDictionary<string, string> _metadata; /// <summary> /// Gets and sets the RequestId property. /// ID that uniquely identifies a request. Amazon keeps track of request IDs. If you have a question about a request, include the request ID in your correspondence. /// </summary> public string RequestId { get { return this.requestIdField; } set { this.requestIdField = value; } } public IDictionary<string, string> Metadata { get { if (this._metadata == null) this._metadata = new Dictionary<string, string>(); return this._metadata; } } /// <summary> /// Checksum algorithm that was selected to validate the response's integrity /// </summary> public CoreChecksumAlgorithm ChecksumAlgorithm { get; set; } /// <summary> ///Status of checksum validation for this response /// </summary> public ChecksumValidationStatus ChecksumValidationStatus { get; set; } } /// <summary> /// States for response checksum validation /// </summary> public enum ChecksumValidationStatus { /// <summary> /// Set when the SDK did not perform checksum validation. /// </summary> NOT_VALIDATED, /// <summary> /// Set when a checksum was selected to be validated, but validation /// will not completed until the response stream is fully read. At that point an exception /// will be thrown if the checksum is invalid. /// </summary> PENDING_RESPONSE_READ, /// <summary> /// The checksum has been validated successfully during response unmarshalling. /// </summary> SUCCESSFUL, /// <summary> /// The checksum of the response stream did not match the header sent by the service. /// </summary> INVALID } }
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; using System.Collections.Generic; using System.Text; namespace Amazon.Runtime { /// <summary> /// This exception is thrown if there are problems signing the request. /// </summary> #if !NETSTANDARD [Serializable] #endif public class SignatureException : Amazon.Runtime.Internal.Auth.SignatureException { 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 System; using System.Collections.Generic; using System.Text; namespace Amazon.Runtime { public class StreamTransferProgressArgs : EventArgs { long _incrementTransferred; long _total; long _transferred; /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> public StreamTransferProgressArgs(long incrementTransferred, long transferred, long total) { this._incrementTransferred = incrementTransferred; this._transferred = transferred; this._total = total; } /// <summary> /// Gets the percentage of transfer completed /// </summary> public int PercentDone { get { return (int)((_transferred * 100) / _total); } } /// <summary> /// Gets the number of bytes transferred since last event /// </summary> public long IncrementTransferred { get { return this._incrementTransferred; } } /// <summary> /// Gets the number of bytes transferred /// </summary> public long TransferredBytes { get { return _transferred; } } /// <summary> /// Gets the total number of bytes to be transferred /// </summary> public long TotalBytes { get { return _total; } } /// <summary> /// Returns a string representation of this object /// </summary> /// <returns></returns> public override string ToString() { return String.Concat( "Transfer Statistics. Percentage completed: ", PercentDone, ", Bytes transferred: ", _transferred, ", Total bytes to transfer: ", _total ); } } }
92
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.Linq; using System.Text; using System.Threading; namespace Amazon.Runtime.Internal { /// <summary> /// This class is responsible for managing adaptive retry mode client rate limiting. /// </summary> public class TokenBucket { private const int MaxAttempts = 15; private readonly object _bucketLock = new object(); private readonly double _minFillRate; private readonly double _minCapacity; private readonly double _beta; private readonly double _scaleConstant; private readonly double _smooth; private static readonly DateTime _epoch = new DateTime(1970, 1, 1); /// <summary> /// The rate at which token are replenished. /// </summary> protected double? FillRate { get; set; } /// <summary> /// The maximum capacity allowed in the token /// </summary> protected double? MaxCapacity { get; set; } /// <summary> /// The current capacity of the token /// </summary> protected double CurrentCapacity { get; set; } /// <summary> /// The last time the token bucket was refilled. /// </summary> protected double? LastTimestamp { get; set; } /// <summary> /// The smoothed rate which tokens are being retrieved. /// </summary> protected double MeasuredTxRate { get; set; } /// <summary> /// The last half second time bucket used. /// </summary> protected double LastTxRateBucket { get; set; } /// <summary> /// The number of requests seen within the current time /// </summary> protected long RequestCount { get; set; } /// <summary> /// The maximum rate when the client was last throttled. /// </summary> protected double LastMaxRate { get; set; } /// <summary> /// The last time when the client was throttled. /// </summary> protected double LastThrottleTime { get; set; } /// <summary> /// The cached time window calculation /// </summary> protected double TimeWindow { get; set; } /// <summary> /// Boolean indicating if the token bucket is enabled. /// </summary> protected bool Enabled { get; set; } public TokenBucket() : this(minFillRate: 0.5, minCapacity: 1.0, beta: 0.7, scaleConstant: 0.4, smooth: 0.8) { } public TokenBucket(double minFillRate, double minCapacity, double beta, double scaleConstant, double smooth) { _minFillRate = minFillRate; _minCapacity = minCapacity; _beta = beta; _scaleConstant = scaleConstant; _smooth = smooth; LastTxRateBucket = Math.Floor(GetTimestamp()); LastThrottleTime = GetTimestamp(); } /// <summary> /// This method attempts to acquire capacity from the client's token /// </summary> /// <param name="amount">The amount of capacity to obtain from the token bucket</param> /// <param name="failFast">Indicates that the client should or shouldn't sleep and /// try again if capacity cannot be obtained. /// </param> public bool TryAcquireToken(double amount, bool failFast) { var result = SetupAcquireToken(amount); if (result != null) { return result.Value; } //We should never get to 15 attempts as the operation is only //waiting for any good capacity. If we still cannot obtain //capacity return false indicating that capacity couldn't be //obtained. for (int attempt = 0; attempt < MaxAttempts; attempt++) { var delay = ObtainCapacity(amount); if (delay == 0) { break; } //If the client has asked us to fail quickly if we cannot get a send token //return indicating a token couldn't be obtained. if (failFast || attempt + 1 == MaxAttempts) { return false; } WaitForToken(delay); } return true; } #if AWS_ASYNC_API /// <summary> /// This method attempts to acquire capacity from the client's token /// </summary> /// <param name="amount">The amount of capacity to obtain from the token bucket</param> /// <param name="failFast">Indicates that the client should or shouldn't sleep and /// try again if capacity cannot be obtained. /// </param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> public async System.Threading.Tasks.Task<bool> TryAcquireTokenAsync(double amount, bool failFast, CancellationToken cancellationToken) { var result = SetupAcquireToken(amount); if(result != null) { return result.Value; } //We should never get to 15 attempts as the operation is only //waiting for any good capacity. If we still cannot obtain //capacity return false indicating that capacity couldn't be //obtained. for (int attempt = 0; attempt < MaxAttempts; attempt++) { var delay = ObtainCapacity(amount); if(delay == 0) { break; } //If the client has asked us to fail quickly if we cannot get a send token //return indicating a token couldn't be obtained. if (failFast || attempt + 1 == MaxAttempts) { return false; } await WaitForTokenAsync(delay, cancellationToken).ConfigureAwait(false); } return true; } #endif private bool? SetupAcquireToken(double amount) { if (amount <= 0) { return false; } lock (_bucketLock) { if (!Enabled) { return true; } TokenBucketRefill(); } return null; } private int ObtainCapacity(double amount) { //Next see if we have capacity for the requested amount. double currentCapacity; double fillRate; lock (_bucketLock) { if (amount <= CurrentCapacity) { CurrentCapacity -= amount; return 0; } currentCapacity = CurrentCapacity; fillRate = FillRate.Value; } return CalculateWait(amount, currentCapacity, fillRate); } /// <summary> /// Updates the sending rate within the client's token bucket /// </summary> /// <param name="isThrottlingError">Indicates if the request resulted in a throttling error.</param> public void UpdateClientSendingRate(bool isThrottlingError) { lock (_bucketLock) { UpdateMeasuredRate(); double calculatedRate; if (isThrottlingError) { double rateToUse; if (!Enabled) { rateToUse = MeasuredTxRate; } else { rateToUse = Math.Min(MeasuredTxRate, FillRate.Value); } //The fill_rate is from the token LastMaxRate = rateToUse; CalculateTimeWindow(); LastThrottleTime = GetTimestamp(); calculatedRate = CUBICThrottle(rateToUse); Enabled = true; } else { CalculateTimeWindow(); calculatedRate = CUBICSuccess(GetTimestamp()); } var newRate = Math.Min(calculatedRate, 2.0 * MeasuredTxRate); TokenBucketUpdateRate(newRate); } } protected virtual void TokenBucketRefill() { double timestamp = GetTimestamp(); if (LastTimestamp == null) { LastTimestamp = timestamp; return; } double fillAmount = (timestamp - LastTimestamp.Value) * FillRate.Value; CurrentCapacity = Math.Min(MaxCapacity.Value, CurrentCapacity + fillAmount); LastTimestamp = timestamp; } protected virtual void TokenBucketUpdateRate(double newRps) { //Refill based on our current rate before we update to the new fill rate. TokenBucketRefill(); FillRate = Math.Max(newRps, _minFillRate); MaxCapacity = Math.Max(newRps, _minCapacity); //When we scale down we can't have a current capacity that exceeds our max_capacity. CurrentCapacity = Math.Min(CurrentCapacity, MaxCapacity.Value); } protected virtual void UpdateMeasuredRate() { var timestamp = GetTimestamp(); var time_bucket = Math.Floor(timestamp * 2) / 2; RequestCount++; if (time_bucket > LastTxRateBucket) { var current_rate = RequestCount / (time_bucket - LastTxRateBucket); MeasuredTxRate = (current_rate * _smooth) + (MeasuredTxRate * (1 - _smooth)); RequestCount = 0; LastTxRateBucket = time_bucket; } } protected virtual void CalculateTimeWindow() { //This is broken out into a separate calculation because it only //gets updated when LastMaxRate changes so it can be cached. TimeWindow = Math.Pow(((LastMaxRate * (1.0 - _beta)) / _scaleConstant), (1.0 / 3.0)); } /// <summary> /// Calculates the rate /// </summary> /// <param name="timestamp"></param> /// <returns>Returns the calculated rate for a successful call</returns> protected virtual double CUBICSuccess(double timestamp) { timestamp -= LastThrottleTime; return (_scaleConstant * Math.Pow(timestamp - TimeWindow, 3)) + LastMaxRate; } /// <summary> /// Calculates the rate. /// </summary> /// <param name="rateToUse">The rate to use in the calculation</param> /// <returns>Returns the calculated rate for a throttled call</returns> protected virtual double CUBICThrottle(double rateToUse) { return rateToUse * _beta; } protected virtual int CalculateWait(double amount, double currentCapacity, double fillRate) { return (int)((amount - currentCapacity) / fillRate * 1000.0); } protected virtual void WaitForToken(int delayMs) { AWSSDKUtils.Sleep(delayMs); } #if AWS_ASYNC_API protected virtual async System.Threading.Tasks.Task WaitForTokenAsync(int delayMs, CancellationToken cancellationToken) { await System.Threading.Tasks.Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); } #endif protected virtual double GetTimestamp() { return GetTimeInSeconds(); } private static double GetTimeInSeconds() { return (DateTime.UtcNow - _epoch).TotalSeconds; } } }
372
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 { #if AWS_ASYNC_API /// <summary> /// Helper class to support a TryGetFoo(out var foo) pattern for async operations. /// This is necessary because async methods do not support output parameters. /// </summary> public class TryResponse<T> { public bool Success { get; set; } public T Value { get; set; } #pragma warning disable CA1000 // Do not declare static members on generic types public static TryResponse<T> Failure => new TryResponse<T>{ Success = false }; #pragma warning restore CA1000 // Do not declare static members on generic types } #endif }
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 Amazon.Runtime.Internal; using Amazon.Runtime.CredentialManagement.Internal; using Amazon.Util; using System; using System.Collections.Generic; using System.Globalization; using System.IO; #if !BCL35 using Amazon.Runtime.Credentials.Internal; #endif using Amazon.Runtime.Internal.Settings; using Amazon.Util.Internal; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// Factory to construct different types of AWSCredentials based on a profile. /// </summary> public static class AWSCredentialsFactory { private static HashSet<CredentialProfileType> CallbackProfileTypes = new HashSet<CredentialProfileType>() { CredentialProfileType.SAMLRoleUserIdentity, CredentialProfileType.AssumeRoleExternalMFA, CredentialProfileType.AssumeRoleMFA, #if !BCL35 CredentialProfileType.SSO, #endif }; private const string RoleSessionNamePrefix = "aws-dotnet-sdk-session-"; /// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="profile">The profile to get AWSCredentials for.</param> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <returns>AWSCredentials for this profile.</returns> public static AWSCredentials GetAWSCredentials(CredentialProfile profile, ICredentialProfileSource profileSource) { return GetAWSCredentials(profile.Name, profileSource, profile.Options, profile.Region, false); } /// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="options">The options to get AWSCredentials for.</param> /// <param name="profileSource">The profile source, for options that reference other profiles.</param> /// <returns>AWSCredentials for the options given.</returns> public static AWSCredentials GetAWSCredentials(CredentialProfileOptions options, ICredentialProfileSource profileSource) { return GetAWSCredentials(null, profileSource, options, null, false); } /// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="profile">The profile to get AWSCredentials for.</param> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <param name="nonCallbackOnly">If true, throw a descriptive exception for any credentials that would not operate as-is. /// In other words, any credentials that require programmatic callbacks at runtime.</param> /// <returns>AWSCredentials for this profile.</returns> public static AWSCredentials GetAWSCredentials(CredentialProfile profile, ICredentialProfileSource profileSource, bool nonCallbackOnly) { return GetAWSCredentials(profile.Name, profileSource, profile.Options, profile.Region, nonCallbackOnly); } /// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="options">The options to get AWSCredentials for.</param> /// <param name="profileSource">The profile source, for options that reference other profiles.</param> /// <param name="nonCallbackOnly">If true, throw a descriptive exception for any credentials that would not operate as-is. /// In other words, any credentials that require programmatic callbacks at runtime.</param> /// <returns>AWSCredentials for the options given.</returns> public static AWSCredentials GetAWSCredentials(CredentialProfileOptions options, ICredentialProfileSource profileSource, bool nonCallbackOnly) { return GetAWSCredentials(null, profileSource, options, null, nonCallbackOnly); } /// <summary> /// Return the credentials for the profile if valid credentials can created. /// </summary> /// <param name="profile">The profile to create credentials with.</param> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <param name="credentials">The credentials for the profile.</param> /// <returns>True if credentials can be created from the profile, false otherwise.</returns> public static bool TryGetAWSCredentials(CredentialProfile profile, ICredentialProfileSource profileSource, out AWSCredentials credentials) { credentials = GetAWSCredentialsInternal(profile.Name, profile.ProfileType, profile.Options, profile.Region, profileSource, false); return credentials != null; } /// <summary> /// Return the credentials for the profile if valid credentials can created. /// </summary> /// <param name="options">The options to get AWSCredentials for.</param> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <param name="credentials">The credentials for the profile.</param> /// <returns>True if credentials can be created from the profile, false otherwise.</returns> public static bool TryGetAWSCredentials(CredentialProfileOptions options, ICredentialProfileSource profileSource, out AWSCredentials credentials) { var profileType = CredentialProfileTypeDetector.DetectProfileType(options); credentials = GetAWSCredentialsInternal(null, profileType, options, null, profileSource, false); return credentials != null; } /// <summary> /// Determine if the profileType will generate AWSCredentials that require a callback to be set on them. /// </summary> /// <param name="profileType"></param> /// <returns></returns> internal static bool IsCallbackRequired(CredentialProfileType? profileType) { return profileType.HasValue && CallbackProfileTypes.Contains(profileType.Value); } private static AWSCredentials GetAWSCredentials( string profileName, ICredentialProfileSource profileSource, CredentialProfileOptions options, RegionEndpoint stsRegion, bool nonCallbackOnly) { #if !BCL35 var ssoTokenFileCache = new SSOTokenFileCache( CryptoUtilFactory.CryptoInstance, new FileRetriever(), new DirectoryRetriever()); #endif var profileType = CredentialProfileTypeDetector.DetectProfileType(options); if (nonCallbackOnly && profileType.HasValue && IsCallbackRequired(profileType.Value)) { if (profileType == CredentialProfileType.AssumeRoleExternalMFA || profileType == CredentialProfileType.AssumeRoleMFA) { var mfaMessage = profileName == null ? "The credential options represent AssumeRoleAWSCredentials that require an MFA. This is not allowed here. " + "Please use credential options for AssumeRoleAWSCredentials that don't require an MFA, or a different type of credentials." : String.Format(CultureInfo.InvariantCulture, "The profile [{0}] is an assume role profile that requires an MFA. This type of profile is not allowed here. " + "Please use an assume role profile that doesn't require an MFA, or a different type of profile.", profileName); throw new InvalidOperationException(mfaMessage); } #if !BCL35 else if (profileType == CredentialProfileType.SSO && !ssoTokenFileCache.Exists(options)) { var ssoMessage = profileName == null ? $"The credential options represent {nameof(SSOAWSCredentials)}. This is not allowed here. " + "Please use a different type of credentials." : String.Format(CultureInfo.InvariantCulture, "The profile [{0}] is an SSO profile. This type of profile is not allowed here. " + "Please use a different type of profile.", profileName); throw new InvalidOperationException(ssoMessage); } #endif else if (profileType == CredentialProfileType.SAMLRoleUserIdentity) { var samlMessage = profileName == null ? "The credential options represent FederatedAWSCredentials that specify a user identity. This is not allowed here. " + "Please use credential options for FederatedAWSCredentials without an explicit user identity, or a different type of credentials." : String.Format(CultureInfo.InvariantCulture, "The profile [{0}] is a SAML role profile that specifies a user identity. This type of profile is not allowed here. " + "Please use a SAML role profile without an explicit user identity, or a different type of profile.", profileName); throw new InvalidOperationException(samlMessage); } } return GetAWSCredentialsInternal(profileName, profileType, options, stsRegion, profileSource, true); } private static AWSCredentials GetAWSCredentialsInternal( string profileName, CredentialProfileType? profileType, CredentialProfileOptions options, RegionEndpoint stsRegion, ICredentialProfileSource profileSource, bool throwIfInvalid, HashSet<string> profileLoopAvoidance = null) { if (profileType.HasValue) { switch (profileType) { case CredentialProfileType.Basic: return new BasicAWSCredentials(options.AccessKey, options.SecretKey); case CredentialProfileType.Session: return new SessionAWSCredentials(options.AccessKey, options.SecretKey, options.Token); case CredentialProfileType.AssumeRole: case CredentialProfileType.AssumeRoleExternal: case CredentialProfileType.AssumeRoleMFA: case CredentialProfileType.AssumeRoleExternalMFA: case CredentialProfileType.AssumeRoleSessionName: case CredentialProfileType.AssumeRoleExternalSessionName: case CredentialProfileType.AssumeRoleMFASessionName: case CredentialProfileType.AssumeRoleExternalMFASessionName: if (profileName != null) { if (profileLoopAvoidance == null) { profileLoopAvoidance = new HashSet<string>(); } else if (profileLoopAvoidance.Contains(profileName)) { var sourceMessage = string.Format(CultureInfo.InvariantCulture, "Error reading profile [{0}]: the source profile definition is cyclical.", profileName); return ThrowOrReturnNull(sourceMessage, null, throwIfInvalid); } profileLoopAvoidance.Add(profileName); } AWSCredentials sourceCredentials; try { sourceCredentials = GetSourceAWSCredentials(options.SourceProfile, profileSource, throwIfInvalid, profileLoopAvoidance); } catch (InvalidDataException e) { var sourceMessage = profileName == null ? string.Format(CultureInfo.InvariantCulture, "Error reading source profile [{0}] for the credential options provided.", options.SourceProfile) : string.Format(CultureInfo.InvariantCulture, "Error reading source profile [{0}] for profile [{1}].", options.SourceProfile, profileName); return ThrowOrReturnNull(sourceMessage, e, throwIfInvalid); } #pragma warning disable CS0612 // Type or member is obsolete var roleSessionName = options.RoleSessionName ?? RoleSessionNamePrefix + AWSSDKUtils.CorrectedUtcNow.Ticks; #pragma warning restore CS0612 // Type or member is obsolete var assumeRoleOptions = new AssumeRoleAWSCredentialsOptions() { ExternalId = options.ExternalID, MfaSerialNumber = options.MfaSerial }; return new AssumeRoleAWSCredentials(sourceCredentials, options.RoleArn, roleSessionName, assumeRoleOptions); case CredentialProfileType.AssumeRoleCredentialSource: case CredentialProfileType.AssumeRoleCredentialSourceSessionName: // get credentials specified by credentialSource try { sourceCredentials = GetCredentialSourceAWSCredentials(options.CredentialSource, throwIfInvalid); } catch (InvalidDataException e) { var sourceMessage = profileName == null ? string.Format(CultureInfo.InvariantCulture, "Error reading credential source [{0}] for the credential options provided.", options.CredentialSource) : string.Format(CultureInfo.InvariantCulture, "Error reading credential source [{0}] for profile [{1}].", options.CredentialSource, profileName); return ThrowOrReturnNull(sourceMessage, e, throwIfInvalid); } #pragma warning disable CS0612 // Type or member is obsolete roleSessionName = options.RoleSessionName ?? RoleSessionNamePrefix + AWSSDKUtils.CorrectedUtcNow.Ticks; #pragma warning restore CS0612 // Type or member is obsolete assumeRoleOptions = new AssumeRoleAWSCredentialsOptions(); return new AssumeRoleAWSCredentials(sourceCredentials, options.RoleArn, roleSessionName, assumeRoleOptions); case CredentialProfileType.AssumeRoleWithWebIdentity: case CredentialProfileType.AssumeRoleWithWebIdentitySessionName: return new AssumeRoleWithWebIdentityCredentials(options.WebIdentityTokenFile, options.RoleArn, options.RoleSessionName); #if !BCL35 case CredentialProfileType.SSO: { var ssoCredentialsOptions = new SSOAWSCredentialsOptions { SessionName = options.SsoSession }; return new SSOAWSCredentials( options.SsoAccountId, options.SsoRegion, options.SsoRoleName, options.SsoStartUrl, ssoCredentialsOptions ); } #endif case CredentialProfileType.SAMLRole: case CredentialProfileType.SAMLRoleUserIdentity: if (UserCrypto.IsUserCryptAvailable) { var federatedOptions = new FederatedAWSCredentialsOptions() { STSRegion = stsRegion, UserIdentity = options.UserIdentity, ProfileName = profileName }; return new FederatedAWSCredentials(new SAMLEndpointManager().GetEndpoint(options.EndpointName), options.RoleArn, federatedOptions); } else { return ThrowOrReturnNull("Federated credentials are not available on this platform.", null, throwIfInvalid); } case CredentialProfileType.CredentialProcess: return new ProcessAWSCredentials(options.CredentialProcess); default: var defaultMessage = profileName == null ? string.Format(CultureInfo.InvariantCulture, "Invalid ProfileType {0} for the credential options provided.", profileType) : string.Format(CultureInfo.InvariantCulture, "Invalid ProfileType {0} for credential profile [{1}].", profileType, profileName); return ThrowOrReturnNull(defaultMessage, null, throwIfInvalid); } } else { return ThrowInvalidOrReturnNull(profileName, throwIfInvalid); } } private static AWSCredentials GetCredentialSourceAWSCredentials(string credentialSourceType, bool throwIfInvalid) { AWSCredentials credentials; CredentialSourceType type; try { type = (CredentialSourceType)Enum.Parse(typeof(CredentialSourceType), credentialSourceType, true); } catch { return ThrowOrReturnNull(string.Format(CultureInfo.InvariantCulture, "Credential source [{0}] is invalid.", credentialSourceType), null, throwIfInvalid); } switch (type) { case CredentialSourceType.Ec2InstanceMetadata: credentials = DefaultInstanceProfileAWSCredentials.Instance; break; case CredentialSourceType.Environment: credentials = new EnvironmentVariablesAWSCredentials(); break; case CredentialSourceType.EcsContainer: var relativeUri = Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable); var fullUri = Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsFullURIEnvVariable); if (string.IsNullOrEmpty(relativeUri) && string.IsNullOrEmpty(fullUri)) { return ThrowOrReturnNull($"Cannot fetch credentials from container - neither {ECSTaskCredentials.ContainerCredentialsURIEnvVariable} or {ECSTaskCredentials.ContainerCredentialsFullURIEnvVariable}" + " environment variables are set.", null, throwIfInvalid); } credentials = new ECSTaskCredentials(null); break; default: return ThrowOrReturnNull(string.Format(CultureInfo.InvariantCulture, "Credential source [{0}] is not implemented.", credentialSourceType), null, throwIfInvalid); } return credentials; } private static AWSCredentials GetSourceAWSCredentials(string sourceProfileName, ICredentialProfileSource profileSource, bool throwIfInvalid, HashSet<string> profileLoopAvoidance = null) { CredentialProfile sourceProfile = null; if (profileSource.TryGetProfile(sourceProfileName, out sourceProfile)) { if (sourceProfile.CanCreateAWSCredentials) { var sourceCredentials = GetAWSCredentialsInternal(sourceProfile.Name, sourceProfile.ProfileType, sourceProfile.Options, sourceProfile.Region, profileSource, throwIfInvalid, profileLoopAvoidance); if (sourceCredentials == null) { return ThrowOrReturnNull(string.Format(CultureInfo.InvariantCulture, "Could not get credentials from source profile [{0}].", sourceProfileName), null, throwIfInvalid); } return sourceCredentials; } else { return ThrowInvalidOrReturnNull(sourceProfileName, throwIfInvalid); } } else { return ThrowOrReturnNull(string.Format(CultureInfo.InvariantCulture, "Source profile [{0}] was not found.", sourceProfileName), null, throwIfInvalid); } } private static BasicAWSCredentials ThrowInvalidOrReturnNull(string profileName, bool doThrow) { var message = profileName == null ? "The credential options provided are not valid. Please ensure the options contain a valid combination of properties." : string.Format(CultureInfo.InvariantCulture, "Credential profile [{0}] is not valid. Please ensure the profile contains a valid combination of properties.", profileName); return ThrowOrReturnNull(message, null, doThrow); } private static BasicAWSCredentials ThrowOrReturnNull(string message, Exception innerException, bool doThrow) { if (doThrow) { throw new InvalidDataException(message, innerException); } else { return null; } } } }
432
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.CredentialManagement.Internal; using Amazon.Runtime.Internal.Util; using Amazon.Util; using System; using System.Collections.Generic; using System.Linq; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// A named group of options that are persisted and used to obtain AWSCredentials. /// </summary> public class CredentialProfile { private Dictionary<string, string> _properties; /// <summary> /// The name of the CredentialProfile /// </summary> public string Name { get; private set; } /// <summary> /// The options to be used to create AWSCredentials. /// </summary> public CredentialProfileOptions Options { get; private set; } /// <summary> /// The region to be used with this CredentialProfile /// </summary> public RegionEndpoint Region { get; set; } /// <summary> /// The unique key for this CredentialProfile. /// This key is used by the Visual Studio Toolkit to associate external artifacts with this profile. /// </summary> internal Guid? UniqueKey { get; set; } /// <summary> /// The desired <see cref="DefaultConfiguration.Name"/> that /// <see cref="IDefaultConfigurationProvider"/> should use. /// <para /> /// If this is null/empty, then the <see cref="DefaultConfigurationMode.Legacy"/> Mode will be used. /// </summary> public string DefaultConfigurationModeName { get; set; } /// <summary> /// The endpoint discovery enabled value for this CredentialProfile /// </summary> public bool? EndpointDiscoveryEnabled { get; set; } /// <summary> /// If true the region identified in the S3 access point arn will be used when making requests. /// </summary> public bool? S3UseArnRegion { get; set; } /// <summary> /// If true, the use of multi-region access points is disabled. /// </summary> public bool? S3DisableMultiRegionAccessPoints { get; set; } /// <summary> /// The Sts Regional Endpoints Value as either legacy or regional /// </summary> public StsRegionalEndpointsValue? StsRegionalEndpoints { get; set; } /// <summary> /// The S3 Regional Endpoint Value as either legacy or regional /// </summary> public S3UsEast1RegionalEndpointValue? S3RegionalEndpoint { get; set; } /// <summary> /// The request retry mode as legacy, standard, or adaptive /// </summary> public RequestRetryMode? RetryMode { get; set; } /// <summary> /// Specified how many HTTP requests an SDK should make for a single /// SDK operation invocation before giving up. /// </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; } /// <summary> /// Configures the endpoint calculation 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; } /// <summary> /// An optional dictionary of name-value pairs stored with the CredentialProfile /// </summary> internal Dictionary<string, string> Properties { get => _properties ?? (_properties = new Dictionary<string, string>()); set => _properties = value; } /// <summary> /// True if the properties of the Options object can be converted into AWSCredentials, false otherwise. /// See <see cref="CredentialProfileOptions"/> for more details about which options are available. /// </summary> public bool CanCreateAWSCredentials => ProfileType.HasValue; /// <summary> /// The <see cref="ICredentialProfileStore"/> that this <see cref="CredentialProfile"/> is associated with. /// Null if this <see cref="CredentialProfile"/> is not associated with a <see cref="ICredentialProfileStore"/>. /// </summary> public ICredentialProfileStore CredentialProfileStore { get; internal set; } /// <summary> /// If CanCreateAWSCredentials is true, returns a short description of the type of /// credentials that would be created. /// If CanCreateAWSCredentials is false, return null. /// </summary> public string CredentialDescription => CredentialProfileTypeDetector.GetUserFriendlyCredentialType(ProfileType); /// <summary> /// The CredentialProfileType of this CredentialProfile, if one applies. /// </summary> internal CredentialProfileType? ProfileType => CredentialProfileTypeDetector.DetectProfileType(Options); /// <summary> /// Determine this CredentialProfile will generate AWSCredentials that require a callback to be set on them. /// </summary> internal bool IsCallbackRequired => AWSCredentialsFactory.IsCallbackRequired(ProfileType); /// <summary> /// Construct a new CredentialProfile. /// </summary> /// <param name="name"></param> /// <param name="profileOptions"></param> public CredentialProfile(string name, CredentialProfileOptions profileOptions) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Name must not be null or empty."); } Options = profileOptions ?? throw new ArgumentNullException("profileOptions"); Name = name; } /// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <returns>AWSCredentials for this profile.</returns> public AWSCredentials GetAWSCredentials(ICredentialProfileSource profileSource) { return GetAWSCredentials(profileSource, false); } /// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <param name="nonCallbackOnly">If true, throw a descriptive exception for any credentials that would not operate as-is. /// In other words, any credentials that require programmatic callbacks at runtime.</param> /// <returns>AWSCredentials for this profile.</returns> internal AWSCredentials GetAWSCredentials(ICredentialProfileSource profileSource, bool nonCallbackOnly) { return AWSCredentialsFactory.GetAWSCredentials(this, profileSource, nonCallbackOnly); } private string GetPropertiesString() { return "{" + string.Join(",", Properties.OrderBy(p=>p.Key).Select(p => p.Key + "=" + p.Value).ToArray()) + "}"; } public override string ToString() { return "[Name=" + Name + "," + "Options = " + Options + "," + "Region = " + (Region == null ? "" : Region.SystemName) + "," + "Properties = " + GetPropertiesString() + "," + "ProfileType = " + ProfileType + "," + "UniqueKey = " + UniqueKey + "," + "CanCreateAWSCredentials = " + CanCreateAWSCredentials + "," + "RetryMode= " + RetryMode + "," + "MaxAttempts= " + MaxAttempts + "]"; } public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; var p = obj as CredentialProfile; if (p == null) return false; return AWSSDKUtils.AreEqual( new object[] { Name, Options, Region, ProfileType, CanCreateAWSCredentials, UniqueKey }, new object[] { p.Name, p.Options, p.Region, p.ProfileType, p.CanCreateAWSCredentials, p.UniqueKey }) && AWSSDKUtils.DictionariesAreEqual(Properties, p.Properties); } public override int GetHashCode() { return Hashing.Hash(Name, Options, Region, ProfileType, CanCreateAWSCredentials, GetPropertiesString(), UniqueKey); } } }
245
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; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// The options that are available for creating AWSCredentials with the AWSCredentialsFactory. /// The type of AWSCredentials that are created depends on which Options are set. /// /// Below are the different types of credentials returned, along with the options that are used to obtain them. /// ([] denotes options that are not required) /// /// BasicAWSCredentials AccessKey SecretKey /// SessionAWSCredentials AccessKey SecretKey Token /// AssmeRoleAWSCredentials SourceProfile RoleArn [ExternalID] [MfaSerial] /// FederatedAWSCredentials EndpointName RoleArn [UserIdentity] #if !BCL35 /// SSO SsoAccountId SsoRegion SsoRoleName SsoStartUrl SsoSession #endif /// </summary> public class CredentialProfileOptions { /// <summary> /// The access key to be used in the AWSCredentials. /// </summary> public string AccessKey { get; set; } /// <summary> /// The source of credentials to be used to obtain AWSCredentials. /// </summary> public string CredentialSource { get; set; } /// <summary> /// The endpoint name to be used for federated AWSCredentials. /// </summary> public string EndpointName { get; set; } /// <summary> /// The external id to use in assume role AWSCredentials. /// </summary> public string ExternalID { get; set; } /// <summary> /// The serial number of the MFA to use in assume role AWSCredentials. /// </summary> public string MfaSerial { get; set; } /// <summary>The role ARN to use when creating assume role or federated AWSCredentials.</summary> public string RoleArn { get; set; } /// <summary> /// An identifier for the assumed role session. /// </summary> public string RoleSessionName { get; set; } /// <summary> /// The secret key to use when creating AWSCredentials. /// </summary> public string SecretKey { get; set; } /// <summary> /// When this CredentialProfileOptions object references another CredentialProfile, /// the name of the referenced CredentialProfile. /// </summary> public string SourceProfile { get; set; } /// <summary> /// The session token to be used to create AWSCredentials. /// </summary> public string Token { get; set; } /// <summary> /// The user identity to use when creating federated AWSCredentials. /// If not set, the user identity that the code is running under will be used. /// </summary> public string UserIdentity { get; set; } /// <summary> /// Contains the executable information to be used by the process credential retriever /// to either fetch Basic or Session credentials /// </summary> public string CredentialProcess { get; set; } /// <summary> /// Absolute path to the file on disk containing an OIDC token. /// </summary> public string WebIdentityTokenFile { get; set; } #if !BCL35 /// <summary> /// The AWS account ID that temporary AWS credentials will be resolved for using AWS SSO. /// </summary> public string SsoAccountId { get; set; } /// <summary> /// The AWS region where the SSO directory for <see cref="SsoStartUrl"/> is hosted. /// </summary> public string SsoRegion { get; set; } /// <summary> /// The corresponding IAM role in the AWS account that temporary AWS credentials will be resolved for using AWS SSO. /// </summary> public string SsoRoleName { get; set; } /// <summary> /// Name of the Sso Session section used to retrieve <see cref="SsoRegion"/> and /// <see cref="SsoStartUrl"/>. /// </summary> public string SsoSession { get; 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 SsoStartUrl { get; set; } #endif /// <summary> /// Return true the properties are all null or empty, false otherwise. /// </summary> internal bool IsEmpty { get { return string.IsNullOrEmpty(EndpointName) && string.IsNullOrEmpty(UserIdentity) && string.IsNullOrEmpty(AccessKey) && string.IsNullOrEmpty(ExternalID) && string.IsNullOrEmpty(MfaSerial) && string.IsNullOrEmpty(RoleArn) && string.IsNullOrEmpty(RoleSessionName) && string.IsNullOrEmpty(SecretKey) && string.IsNullOrEmpty(SourceProfile) && string.IsNullOrEmpty(Token) && string.IsNullOrEmpty(CredentialProcess) && #if !BCL35 string.IsNullOrEmpty(SsoAccountId) && string.IsNullOrEmpty(SsoRegion) && string.IsNullOrEmpty(SsoRoleName) && string.IsNullOrEmpty(SsoStartUrl) && string.IsNullOrEmpty(SsoSession) && #endif string.IsNullOrEmpty(WebIdentityTokenFile); } } public override string ToString() { return "[AccessKey=" + AccessKey + ", " + "EndpointName=" + EndpointName + ", " + "ExternalID=" + ExternalID + ", " + "MfaSerial=" + MfaSerial + ", " + "RoleArn=" + RoleArn + ", " + "RoleSessionName=" + RoleSessionName + ", " + "SecretKey=XXXXX, " + "SourceProfile=" + SourceProfile + ", " + "Token=" + Token + ", " + "UserIdentity=" + UserIdentity + ", " + "CredentialProcess=" + CredentialProcess + ", " + "WebIdentityTokenFile=" + WebIdentityTokenFile + #if !BCL35 ", " + "SsoAccountId=" + SsoAccountId + ", " + "SsoRegion=" + SsoRegion + ", " + "SsoRoleName=" + SsoRoleName + ", " + "SsoStartUrl=" + SsoStartUrl + ", " + "SsoSession=" + SsoSession + #endif "]"; } public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; var po = obj as CredentialProfileOptions; if (po == null) return false; #if !BCL35 return AWSSDKUtils.AreEqual( new object[] { AccessKey, EndpointName, ExternalID, MfaSerial, RoleArn, RoleSessionName, SecretKey, SourceProfile, Token, UserIdentity, CredentialProcess, WebIdentityTokenFile, SsoAccountId, SsoRegion, SsoRoleName, SsoStartUrl, SsoSession }, new object[] { po.AccessKey, po.EndpointName, po.ExternalID, po.MfaSerial, po.RoleArn, po.RoleSessionName, po.SecretKey, po.SourceProfile, po.Token, po.UserIdentity, po.CredentialProcess, po.WebIdentityTokenFile, po.SsoAccountId, po.SsoRegion, po.SsoRoleName, po.SsoStartUrl, po.SsoSession }); #else return AWSSDKUtils.AreEqual( new object[] { AccessKey, EndpointName, ExternalID, MfaSerial, RoleArn, RoleSessionName, SecretKey, SourceProfile, Token, UserIdentity, CredentialProcess, WebIdentityTokenFile }, new object[] { po.AccessKey, po.EndpointName, po.ExternalID, po.MfaSerial, po.RoleArn, po.RoleSessionName, po.SecretKey, po.SourceProfile, po.Token, po.UserIdentity, po.CredentialProcess, po.WebIdentityTokenFile }); #endif } public override int GetHashCode() { #if !BCL35 return Hashing.Hash(AccessKey, EndpointName, ExternalID, MfaSerial, RoleArn, RoleSessionName, SecretKey, SourceProfile, Token, UserIdentity, CredentialProcess, WebIdentityTokenFile, SsoAccountId, SsoRegion, SsoRoleName, SsoStartUrl, SsoSession); #else return Hashing.Hash(AccessKey, EndpointName, ExternalID, MfaSerial, RoleArn, RoleSessionName, SecretKey, SourceProfile, Token, UserIdentity, CredentialProcess, WebIdentityTokenFile); #endif } } }
207
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.Util.Internal; using Amazon.Runtime.Internal.Settings; using System.Linq; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// Class to abstract the combined use of NetSDKCredentialsFile and SharedCredentialsFile where possible. /// </summary> /// <returns></returns> public class CredentialProfileStoreChain : ICredentialProfileSource { /// <summary> /// The location of the shared credentials file, or null to use the default location. /// </summary> public string ProfilesLocation { get; private set; } /// <summary> /// Construct a CredentialProfileChain. /// </summary> public CredentialProfileStoreChain() : this(null) { } /// <summary> /// Construct a CredentialProfileChain. /// </summary> /// <param name="profilesLocation">The path to the aws credentials file to look at.</param> public CredentialProfileStoreChain(string profilesLocation) { ProfilesLocation = profilesLocation; } /// <summary> /// <para> /// Try to get <see cref="AWSCredentials"/> from a profile. /// </para> /// <para> /// If ProfilesLocation is non-null and non-empty search the shared credentials /// file at the disk path in the ProfilesLocation property. /// </para> /// <para> /// If ProfilesLocation is null or empty and the platform supports the .NET SDK credentials file /// search the SDK credentials file. If the profile is not found search the shared credentials file in the default location. /// </para> ///<para> /// If ProfilesLocation is null or empty and the platform doesn't support the .NET SDK credentials file /// search the shared credentials file in the default location. /// </para> /// </summary> /// <param name="profileName">The name of the profile to get credentials from.</param> /// <param name="credentials">The credentials, if the profile is found and credentials can be created.</param> /// <returns>True if the profile was found and credentials could be created, false otherwise.</returns> public bool TryGetAWSCredentials(string profileName, out AWSCredentials credentials) { CredentialProfile profile; if (TryGetProfile(profileName, out profile)) return AWSCredentialsFactory.TryGetAWSCredentials(profile, profile.CredentialProfileStore, out credentials); credentials = null; return false; } /// <summary> /// <para> /// Try to get a <see cref="CredentialProfile"/> /// </para> /// <para> /// If ProfilesLocation is non-null and non-empty search the shared credentials /// file at the disk path in the ProfilesLocation property. /// </para> /// <para> /// If ProfilesLocation is null or empty and the platform supports the .NET SDK credentials file /// search the SDK credentials file. If the profile is not found search the shared credentials file in the default location. /// </para> ///<para> /// If ProfilesLocation is null or empty and the platform doesn't support the .NET SDK credentials file /// search the shared credentials file in the default location. /// </para> /// </summary> /// <param name="profileName">The name of the profile to get.</param> /// <param name="profile">The profile, if found</param> /// <returns>True if the profile was found, false otherwise.</returns> public bool TryGetProfile(string profileName, out CredentialProfile profile) { if (string.IsNullOrEmpty(ProfilesLocation) && UserCrypto.IsUserCryptAvailable) { var netCredentialsFile = new NetSDKCredentialsFile(); if (netCredentialsFile.TryGetProfile(profileName, out profile)) { return true; } } var sharedCredentialsFile = new SharedCredentialsFile(ProfilesLocation); if (sharedCredentialsFile.TryGetProfile(profileName, out profile)) { return true; } profile = null; return false; } /// <summary> /// <para> /// Get a list of available <see cref="CredentialProfile"/> objects. /// </para> /// <para> /// If ProfilesLocation is non-null and non-empty include profiles in the shared credentials /// file at the disk path in the ProfilesLocation property. /// </para> /// <para> /// If ProfilesLocation is null or empty and the platform supports the .NET SDK credentials file /// include profiles from the SDK credentials file and from the shared credentials file in the default location. /// </para> ///<para> /// If ProfilesLocation is null or empty and the platform doesn't support the .NET SDK credentials file /// include profiles from the shared credentials file in the default location. /// </para> /// </summary> /// <returns>A list of <see cref="CredentialProfile"/> objects.</returns> public List<CredentialProfile> ListProfiles() { var profiles = new List<CredentialProfile>(); if (string.IsNullOrEmpty(ProfilesLocation) && UserCrypto.IsUserCryptAvailable) { var netSdkFile = new NetSDKCredentialsFile(); profiles.AddRange(netSdkFile.ListProfiles()); } var sharedFile = new SharedCredentialsFile(ProfilesLocation); profiles.AddRange(sharedFile.ListProfiles()); return profiles; } /// <summary> /// <para> /// Register a <see cref="CredentialProfile"/> /// </para> /// <para> /// If ProfilesLocation is non-null and non-empty register the profile in the shared credentials /// file at the disk path in the ProfilesLocation property. /// </para> /// <para> /// If ProfilesLocation is null or empty and the platform supports the .NET SDK credentials file /// register the profile in the SDK credentials file. /// </para> ///<para> /// If ProfilesLocation is null or empty and the platform doesn't support the .NET SDK credentials file /// register the profile in the shared credentials file in the default location. /// </para> /// </summary> /// <param name="profile">The profile to register.</param> public void RegisterProfile(CredentialProfile profile) { if (string.IsNullOrEmpty(ProfilesLocation) && UserCrypto.IsUserCryptAvailable) { new NetSDKCredentialsFile().RegisterProfile(profile); } else { new SharedCredentialsFile(ProfilesLocation).RegisterProfile(profile); } } /// <summary> /// <para> /// Unregister a <see cref="CredentialProfile"/> /// </para> /// <para> /// If ProfilesLocation is non-null and non-empty unregister the profile from the shared credentials /// file at the disk path in the ProfilesLocation property. /// </para> /// <para> /// If ProfilesLocation is null or empty and the platform supports the .NET SDK credentials file /// search the SDK credentials file. If the profile is found there unregister it. /// If the profile was not found search the shared credentials file in the default location. /// If the profile is found in the shared credentials file in the default location unregister it. /// </para> ///<para> /// If ProfilesLocation is null or empty and the platform doesn't support the .NET SDK credentials file /// search the shared credentials file in the default location. If the profile is found in the /// shared credentials file in the default location unregister it. /// </para> /// </summary> /// <param name="profileName">The name of the profile to unregister.</param> public void UnregisterProfile(string profileName) { CredentialProfile profile; if (TryGetProfile(profileName, out profile)) { profile.CredentialProfileStore.UnregisterProfile(profileName); } } } }
217
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.CredentialManagement { /// <summary> /// Interface to define the necessary operations for a CredentialProfile lookup mechanism. /// </summary> public interface ICredentialProfileSource { /// <summary> /// Get the profile with the given name, if one exists. /// </summary> /// <param name="profileName">The name of the profile to get.</param> /// <param name="profile">The profile, if it was found, null otherwise.</param> /// <returns>True if the profile was found, false otherwise.</returns> bool TryGetProfile(string profileName, out CredentialProfile profile); } }
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. */ using Amazon.Runtime.CredentialManagement; using System.Collections.Generic; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// Interface to define the necessary operations for a CredentialProfile storage mechanism. /// </summary> public interface ICredentialProfileStore : ICredentialProfileSource { /// <summary> /// Rename the profile with oldProfileName to newProfileName. /// </summary> /// <param name="oldProfileName">The profile to rename.</param> /// <param name="newProfileName">The new name for the profile.</param> void RenameProfile(string oldProfileName, string newProfileName); /// <summary> /// Rename the profile with oldProfileName to newProfileName. /// </summary> /// <param name="oldProfileName">The profile to rename.</param> /// <param name="newProfileName">The new name for the profile.</param> /// <param name="force">If true and the destination profile exists it will be overwritten.</param> void RenameProfile(string oldProfileName, string newProfileName, bool force); /// <summary> /// Make a copy of the profile with fromProfileName called toProfileName. /// </summary> /// <param name="fromProfileName">The name of the profile to copy from.</param> /// <param name="toProfileName">The name of the new profile.</param> void CopyProfile(string fromProfileName, string toProfileName); /// <summary> /// Make a copy of the profile with fromProfileName called toProfileName. /// </summary> /// <param name="fromProfileName">The name of the profile to copy from.</param> /// <param name="toProfileName">The name of the new profile.</param> /// <param name="force">If true and the destination profile exists it will be overwritten.</param> void CopyProfile(string fromProfileName, string toProfileName, bool force); /// <summary> /// Add the given profile to the store, or update it if one with the same name already exists. /// </summary> /// <param name="profile"></param> void RegisterProfile(CredentialProfile profile); /// <summary> /// Delete the profile with profileName if it exists. /// </summary> /// <param name="profileName">The name of the profile to delete.</param> void UnregisterProfile(string profileName); /// <summary> /// Get a list of valid profile names from this store. /// Invalid profiles are ignored. /// See <see cref="CredentialProfileOptions"/> for more information /// about valid profiles. /// </summary> /// <returns></returns> List<string> ListProfileNames(); /// <summary> /// Get a list of valid profiles from this store. /// Invalid profiles are ignored. /// See <see cref="CredentialProfileOptions"/> for more information /// about valid profiles. /// </summary> /// <returns></returns> List<CredentialProfile> ListProfiles(); } }
86
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.CredentialManagement.Internal; using Amazon.Runtime.Internal.Settings; using Amazon.Runtime.Internal.Util; using Amazon.Util; using Amazon.Util.Internal; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Diagnostics.CodeAnalysis; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// This class allows profiles supporting AWSCredentials to be registered with /// the SDK so that they can later be reference by a profile name. The credential profiles will be available /// for use in the AWS Toolkit for Visual Studio and the AWS Tools for Windows PowerShell. /// <para> /// The credentials are stored under the current users AppData folder encrypted using Windows Data Protection API. /// </para> /// <para> /// This class is not threadsafe. /// </para> /// </summary> public class NetSDKCredentialsFile : ICredentialProfileStore { public const string DefaultProfileName = "Default"; // Values kept from ProfileManager to support backward compatibility. private const string AWSCredentialsProfileType = "AWS"; private const string SAMLRoleProfileType = "SAML"; private const string DefaultConfigurationModeNameField = "DefaultsMode"; private const string RegionField = "Region"; private const string EndpointDiscoveryEnabledField = "EndpointDiscoveryEnabled"; private const string S3UseArnRegionField = "S3UseArnRegion"; private const string StsRegionalEndpointsField = "StsRegionalEndpoints"; private const string S3RegionalEndpointField = "S3RegionalEndpoint"; private const string S3DisableMultiRegionAccessPointsField = "S3DisableMultiRegionAccessPoints"; private const string RetryModeField = "RetryMode"; private const string MaxAttemptsField = "MaxAttempts"; private const string SsoAccountId = "sso_account_id"; private const string SsoRegion = "sso_region"; private const string SsoRoleName = "sso_role_name"; private const string SsoStartUrl = "sso_start_url"; private const string SsoSession = "sso_session"; private static readonly HashSet<string> ReservedPropertyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { SettingsConstants.DisplayNameField, SettingsConstants.ProfileTypeField, DefaultConfigurationModeNameField, RegionField, EndpointDiscoveryEnabledField, S3UseArnRegionField, StsRegionalEndpointsField, S3RegionalEndpointField, S3DisableMultiRegionAccessPointsField, RetryModeField, MaxAttemptsField, SsoAccountId, SsoRegion, SsoRoleName, SsoStartUrl, }; private static readonly CredentialProfilePropertyMapping PropertyMapping = new CredentialProfilePropertyMapping( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "AccessKey", SettingsConstants.AccessKeyField }, { "CredentialSource", SettingsConstants.CredentialSourceField }, { "EndpointName", SettingsConstants.EndpointNameField }, { "ExternalID", SettingsConstants.ExternalIDField}, { "MfaSerial", SettingsConstants.MfaSerialField}, { "RoleArn", SettingsConstants.RoleArnField }, { "RoleSessionName", SettingsConstants.RoleSessionName}, { "SecretKey", SettingsConstants.SecretKeyField }, { "SourceProfile", SettingsConstants.SourceProfileField }, { "Token", SettingsConstants.SessionTokenField }, { "UserIdentity", SettingsConstants.UserIdentityField }, // Not implemented for NetSDKCredentials. Applicable only // for SharedCredentials { "CredentialProcess" , SettingsConstants.CredentialProcess }, { "WebIdentityTokenFile", SettingsConstants.WebIdentityTokenFile }, #if !BCL35 { nameof(CredentialProfileOptions.SsoAccountId), SsoAccountId }, { nameof(CredentialProfileOptions.SsoRegion), SsoRegion }, { nameof(CredentialProfileOptions.SsoRoleName), SsoRoleName }, { nameof(CredentialProfileOptions.SsoStartUrl), SsoStartUrl }, { nameof(CredentialProfileOptions.SsoSession), SsoSession} #endif } ); private readonly NamedSettingsManager _settingsManager; public NetSDKCredentialsFile() { _settingsManager = new NamedSettingsManager(SettingsConstants.RegisteredProfiles); } public List<string> ListProfileNames() { return ListProfiles().Select(p => p.Name).ToList(); } public List<CredentialProfile> ListProfiles() { var profiles = new List<CredentialProfile>(); foreach (var profileName in _settingsManager.ListObjectNames()) { CredentialProfile profile = null; if (TryGetProfile(profileName, out profile) && profile.CanCreateAWSCredentials) { profiles.Add(profile); } } return profiles; } /// <summary> /// Get the profile with the name given, if it exists in this store. /// </summary> /// <param name="profileName">The name of the profile to find.</param> /// <param name="profile">The profile, if it was found, null otherwise</param> /// <returns>True if the profile was found, false otherwise.</returns> public bool TryGetProfile(string profileName, out CredentialProfile profile) { Dictionary<string, string> properties; string uniqueKeyStr; if (_settingsManager.TryGetObject(profileName, out uniqueKeyStr, out properties)) { try { CredentialProfileOptions profileOptions; Dictionary<string, string> userProperties; Dictionary<string, string> reservedProperties; PropertyMapping.ExtractProfileParts( properties, ReservedPropertyNames, out profileOptions, out reservedProperties, out userProperties); string defaultConfigurationModeName; reservedProperties.TryGetValue(DefaultConfigurationModeNameField, out defaultConfigurationModeName); string regionString; RegionEndpoint region = null; if (reservedProperties.TryGetValue(RegionField, out regionString)) { region = RegionEndpoint.GetBySystemName(regionString); } Guid? uniqueKey = null; if (!GuidUtils.TryParseNullableGuid(uniqueKeyStr, out uniqueKey)) { profile = null; return false; } string endpointDiscoveryEnabledString; bool? endpointDiscoveryEnabled = null; if (reservedProperties.TryGetValue(EndpointDiscoveryEnabledField, out endpointDiscoveryEnabledString)) { bool endpointDiscoveryEnabledOut; if (!bool.TryParse(endpointDiscoveryEnabledString, out endpointDiscoveryEnabledOut)) { profile = null; return false; } endpointDiscoveryEnabled = endpointDiscoveryEnabledOut; } StsRegionalEndpointsValue? stsRegionalEndpoints = null; if (reservedProperties.TryGetValue(StsRegionalEndpointsField, out var stsRegionalEndpointsString)) { #if BCL35 try { stsRegionalEndpoints = (StsRegionalEndpointsValue)Enum.Parse(typeof(StsRegionalEndpointsValue), stsRegionalEndpointsString, true); } catch (Exception) { profile = null; return false; } #else if (!Enum.TryParse<StsRegionalEndpointsValue>(stsRegionalEndpointsString, true, out var tempStsRegionalEndpoints)) { profile = null; return false; } stsRegionalEndpoints = tempStsRegionalEndpoints; #endif } string s3UseArnRegionString; bool? s3UseArnRegion = null; if(reservedProperties.TryGetValue(S3UseArnRegionField, out s3UseArnRegionString)) { bool s3UseArnRegionOut; if (!bool.TryParse(s3UseArnRegionString, out s3UseArnRegionOut)) { profile = null; return false; } s3UseArnRegion = s3UseArnRegionOut; } string s3DisableMultiRegionAccessPointsString; bool? s3DisableMultiRegionAccessPoints = null; if (reservedProperties.TryGetValue(S3DisableMultiRegionAccessPointsField, out s3DisableMultiRegionAccessPointsString)) { bool s3DisableMultiRegionAccessPointsOut; if (!bool.TryParse(s3DisableMultiRegionAccessPointsString, out s3DisableMultiRegionAccessPointsOut)) { profile = null; return false; } s3DisableMultiRegionAccessPoints = s3DisableMultiRegionAccessPointsOut; } S3UsEast1RegionalEndpointValue? s3RegionalEndpoint = null; if (reservedProperties.TryGetValue(S3RegionalEndpointField, out var s3RegionalEndpointString)) { #if BCL35 try { s3RegionalEndpoint = (S3UsEast1RegionalEndpointValue)Enum.Parse(typeof(S3UsEast1RegionalEndpointValue), s3RegionalEndpointString, true); } catch (Exception) { profile = null; return false; } #else if (!Enum.TryParse<S3UsEast1RegionalEndpointValue>(s3RegionalEndpointString, true, out var tempS3RegionalEndpoint)) { profile = null; return false; } s3RegionalEndpoint = tempS3RegionalEndpoint; #endif } RequestRetryMode? requestRetryMode = null; if (reservedProperties.TryGetValue(RetryModeField, out var retryModeString)) { #if BCL35 try { requestRetryMode = (RequestRetryMode)Enum.Parse(typeof(RequestRetryMode), retryModeString, true); } catch (Exception) { profile = null; return false; } #else if (!Enum.TryParse<RequestRetryMode>(retryModeString, true, out var tempRetryMode)) { profile = null; return false; } requestRetryMode = tempRetryMode; #endif } int? maxAttempts = null; if (reservedProperties.TryGetValue(MaxAttemptsField, out var maxAttemptsString)) { if (!int.TryParse(maxAttemptsString, out var maxAttemptsTemp) || maxAttemptsTemp <= 0) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A positive integer is expected.", maxAttemptsString, MaxAttemptsField, profileName); profile = null; return false; } maxAttempts = maxAttemptsTemp; } profile = new CredentialProfile(profileName, profileOptions) { UniqueKey = uniqueKey, Properties = userProperties, Region = region, CredentialProfileStore = this, DefaultConfigurationModeName = defaultConfigurationModeName, EndpointDiscoveryEnabled = endpointDiscoveryEnabled, StsRegionalEndpoints = stsRegionalEndpoints, S3UseArnRegion = s3UseArnRegion, S3RegionalEndpoint = s3RegionalEndpoint, S3DisableMultiRegionAccessPoints = s3DisableMultiRegionAccessPoints, RetryMode = requestRetryMode, MaxAttempts = maxAttempts }; return true; } catch (ArgumentException) { profile = null; return false; } } else { profile = null; return false; } } /// <summary> /// Add the profile to this store, if it's valid. /// </summary> /// <param name="profile">The profile to add.</param> [SuppressMessage("Microsoft.Globalization", "CA1308", Justification = "Value is not surfaced to user. Booleans have been lowercased by SDK precedent.")] public void RegisterProfile(CredentialProfile profile) { if (profile.CanCreateAWSCredentials || profile.Options.IsEmpty) { var reservedProperties = new Dictionary<string, string>(); if (profile.CanCreateAWSCredentials) { // set profile type field for backward compatibility SetProfileTypeField(reservedProperties, profile.ProfileType.Value); } if (profile.Region != null) reservedProperties[RegionField] = profile.Region.SystemName; if (profile.EndpointDiscoveryEnabled != null) reservedProperties[EndpointDiscoveryEnabledField] = profile.EndpointDiscoveryEnabled.Value.ToString().ToLowerInvariant(); if (profile.StsRegionalEndpoints != null) reservedProperties[StsRegionalEndpointsField] = profile.StsRegionalEndpoints.ToString().ToLowerInvariant(); if (profile.S3UseArnRegion != null) reservedProperties[S3UseArnRegionField] = profile.S3UseArnRegion.Value.ToString().ToLowerInvariant(); if (profile.S3RegionalEndpoint != null) reservedProperties[S3RegionalEndpointField] = profile.S3RegionalEndpoint.ToString().ToLowerInvariant(); if (profile.S3DisableMultiRegionAccessPoints != null) reservedProperties[S3DisableMultiRegionAccessPointsField] = profile.S3DisableMultiRegionAccessPoints.ToString().ToLowerInvariant(); if (profile.RetryMode != null) reservedProperties[RetryModeField] = profile.RetryMode.ToString().ToLowerInvariant(); if (profile.MaxAttempts != null) reservedProperties[MaxAttemptsField] = profile.MaxAttempts.ToString().ToLowerInvariant(); var profileDictionary = PropertyMapping.CombineProfileParts( profile.Options, ReservedPropertyNames, reservedProperties, profile.Properties); // Set the UniqueKey. It might change if the unique key is set by the objectManger, // or if this is an update to an existing profile. string newUniqueKeyStr = _settingsManager.RegisterObject(profile.Name, profileDictionary); Guid? newUniqueKey; if (GuidUtils.TryParseNullableGuid(newUniqueKeyStr, out newUniqueKey)) profile.UniqueKey = newUniqueKey; profile.CredentialProfileStore = this; } else { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Unable to register profile {0}. The CredentialProfileOptions provided is not valid.", profile.Name)); } } /// <summary> /// If there is a profile in the store with the given name, delete it. /// </summary> /// <param name="profileName">The name of the profile to delete.</param> public void UnregisterProfile(string profileName) { _settingsManager.UnregisterObject(profileName); } /// <summary> /// Rename the profile with oldProfileName to newProfileName. /// </summary> /// <param name="oldProfileName">The profile to rename.</param> /// <param name="newProfileName">The new name for the profile.</param> public void RenameProfile(string oldProfileName, string newProfileName) { RenameProfile(oldProfileName, newProfileName, false); } /// <summary> /// Rename the profile with oldProfileName to newProfileName. /// </summary> /// <param name="oldProfileName">The profile to rename.</param> /// <param name="newProfileName">The new name for the profile.</param> /// <param name="force">If true and the destination profile exists it will be overwritten.</param> public void RenameProfile(string oldProfileName, string newProfileName, bool force) { _settingsManager.RenameObject(oldProfileName, newProfileName, force); } /// <summary> /// Make a copy of the profile with fromProfileName called toProfileName. /// </summary> /// <param name="fromProfileName">The name of the profile to copy from.</param> /// <param name="toProfileName">The name of the new profile.</param> public void CopyProfile(string fromProfileName, string toProfileName) { CopyProfile(fromProfileName, toProfileName, false); } /// <summary> /// Make a copy of the profile with fromProfileName called toProfileName. /// </summary> /// <param name="fromProfileName">The name of the profile to copy from.</param> /// <param name="toProfileName">The name of the new profile.</param> /// <param name="force">If true and the destination profile exists it will be overwritten.</param> public void CopyProfile(string fromProfileName, string toProfileName, bool force) { _settingsManager.CopyObject(fromProfileName, toProfileName, force); } /// <summary> /// Set the ProfileType field to maintain backward compatibility with ProfileManager. /// The value is ignored when it's read back in. /// </summary> /// <param name="properties"></param> /// <param name="profileType"></param> private static void SetProfileTypeField(IDictionary<string, string> properties, CredentialProfileType profileType) { switch (profileType) { case CredentialProfileType.Basic: properties[SettingsConstants.ProfileTypeField] = AWSCredentialsProfileType; break; case CredentialProfileType.SAMLRole: case CredentialProfileType.SAMLRoleUserIdentity: properties[SettingsConstants.ProfileTypeField] = SAMLRoleProfileType; break; default: properties[SettingsConstants.ProfileTypeField] = profileType.ToString(); break; } } } }
471
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.CredentialManagement { /// <summary> /// Represents the different types of authentication available for SAML endpoints. /// </summary> public enum SAMLAuthenticationType { NTLM, Digest, Kerberos, Negotiate } /// <summary> /// Representation of a SAML Endpoint. /// </summary> public class SAMLEndpoint { private SAMLAuthenticationType DefaultAuthenticationType = SAMLAuthenticationType.Kerberos; /// <summary> /// The name given to this SAMLEndpoint. /// </summary> public string Name { get; private set; } /// <summary> /// The URI of the SAML endnpoint. /// </summary> public Uri EndpointUri { get; private set; } /// <summary> /// The authentication type associated with the SAML endpoint. /// </summary> public SAMLAuthenticationType AuthenticationType { get; private set; } /// <summary> /// Internal constructor. Used by SAMLEndpointManager when reading endpoints from the encrypted store. /// </summary> /// <param name="name"></param> /// <param name="endpointUri"></param> /// <param name="authenticationType"></param> internal SAMLEndpoint(string name, string endpointUri, string authenticationType) { var parsedEndpointUri = new Uri(endpointUri, UriKind.RelativeOrAbsolute); var parsedAuthenticationType = DefaultAuthenticationType; if (!string.IsNullOrEmpty(authenticationType)) { parsedAuthenticationType = (SAMLAuthenticationType)Enum.Parse(typeof(SAMLAuthenticationType), authenticationType); } SetProperties(name, parsedEndpointUri, parsedAuthenticationType); } /// <summary> /// Construct a SAMLEndpoint using the default SAMLAuthenticationType - Kerberos. /// </summary> /// <param name="name">The name of the endpoint.</param> /// <param name="endpointUri">The URI of the endpoint.</param> public SAMLEndpoint(string name, Uri endpointUri) { SetProperties(name, endpointUri, DefaultAuthenticationType); } /// <summary> /// Construct a SAMLEndpoint. /// </summary> /// <param name="name">The name of the endpoint.</param> /// <param name="endpointUri">The URI of the endpoint.</param> /// <param name="authenticationType">The authentication type of the endpoint.</param> public SAMLEndpoint(string name, Uri endpointUri, SAMLAuthenticationType authenticationType) { SetProperties(name, endpointUri, authenticationType); } private void SetProperties(string name, Uri endpointUri, SAMLAuthenticationType authenticationType) { if (!string.Equals(endpointUri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("EndpointUri is not Https protocol."); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Name is null or empty."); } Name = name; EndpointUri = endpointUri; AuthenticationType = authenticationType; } } }
111
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; using Amazon.Runtime.Internal.Settings; using Amazon.Runtime.Internal.Util; using Amazon.Util.Internal; using System; using System.Collections.Generic; using System.Globalization; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// Manages endpoints to be used in conjunction with SAML role profiles. The role profiles /// reference the endpoint to obtain the actual endpoint and any customization settings /// needed to perform authentication. /// </summary> public class SAMLEndpointManager { private NamedSettingsManager settingsManager; /// <summary> /// Construct a SAMLEndpointManager. /// </summary> public SAMLEndpointManager() { settingsManager = new NamedSettingsManager(SettingsConstants.RegisteredSAMLEndpoints); } /// <summary> /// True if the SAMLEndpointManager is available on the current platform, false otherwise. /// </summary> public static bool IsAvailable { get { return NamedSettingsManager.IsAvailable; } } /// <summary> /// Register an endpoint, or update an existing one. /// </summary> /// <param name="samlEndpoint">The endpoint to register.</param> public void RegisterEndpoint(SAMLEndpoint samlEndpoint) { var properties = new Dictionary<string, string>() { { SettingsConstants.EndpointField, samlEndpoint.EndpointUri.ToString() }, { SettingsConstants.AuthenticationTypeField, samlEndpoint.AuthenticationType.ToString() } }; settingsManager.RegisterObject(samlEndpoint.Name, properties); } /// <summary> /// Get an endpoint, if it exists and is valid. /// </summary> /// <param name="endpointName">The name of the endpoint to get.</param> /// <param name="samlEndpoint">The endpoint, or null if it's invalid or doesn't exist.</param> /// <returns>True if the endpoint exists and is valid, false otherwise.</returns> public bool TryGetEndpoint(string endpointName, out SAMLEndpoint samlEndpoint) { samlEndpoint = null; try { samlEndpoint = GetEndpoint(endpointName); } catch (AmazonClientException e) { Logger.GetLogger(typeof(SAMLEndpointManager)).Error(e, "Unable to load SAML Endpoint '{0}'.", endpointName); } return samlEndpoint != null; } /// <summary> /// Get an endpoint from the store. /// Throws an exception if there's an error reading the endpoint, or if it doesn't exist. /// </summary> /// <param name="endpointName">The name of the endpoint to get.</param> /// <returns>The endpoint with the given name.</returns> public SAMLEndpoint GetEndpoint(string endpointName) { Dictionary<string, string> properties; if (settingsManager.TryGetObject(endpointName, out properties)) { try { string authenticationType; if (properties.TryGetValue(SettingsConstants.AuthenticationTypeField, out authenticationType)) { return new SAMLEndpoint(endpointName, properties[SettingsConstants.EndpointField], authenticationType); } else { return new SAMLEndpoint(endpointName, properties[SettingsConstants.EndpointField], null); } } catch (Exception e) { throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "Error reading A SAML endpoint with name {0}.", endpointName), e); } } else { throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "There is no SAML endpoint registered with name {0}.", endpointName)); } } /// <summary> /// Delete an endpoint from the store, if it exists. /// </summary> /// <param name="endpointName">The name of the endpoint to delete.</param> public void UnregisterEndpoint(string endpointName) { settingsManager.UnregisterObject(endpointName); } /// <summary> /// List the names of valid endpoints in the store. /// </summary> /// <returns></returns> public List<string> ListEndpointNames() { return settingsManager.ListObjectNames(); } /// <summary> /// List valid endopints that can be read from the store. /// </summary> /// <returns></returns> public List<SAMLEndpoint> ListEndpoints() { var endpoints = new List<SAMLEndpoint>(); foreach (var endpointName in settingsManager.ListObjectNames()) { SAMLEndpoint endpoint; if (TryGetEndpoint(endpointName, out endpoint)) { endpoints.Add(endpoint); } } return endpoints; } } }
160
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.Internal; using Amazon.Runtime.Internal.Util; using Amazon.Runtime; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Diagnostics.CodeAnalysis; namespace Amazon.Runtime.CredentialManagement { /// <summary> /// Provides access to read and write to the shared credentials INI file. /// The file is read, parsed, and validated at construction time. /// Changes can be made using the RegisterProfile() and /// UnregisterProfile() methods. /// /// This class is not threadsafe. /// </summary> public class SharedCredentialsFile : ICredentialProfileStore { public const string DefaultProfileName = "default"; public const string SharedCredentialsFileEnvVar = "AWS_SHARED_CREDENTIALS_FILE"; public const string SharedConfigFileEnvVar = "AWS_CONFIG_FILE"; private const string ToolkitArtifactGuidField = "toolkit_artifact_guid"; private const string RegionField = "region"; private const string EndpointDiscoveryEnabledField = "endpoint_discovery_enabled"; private const string ConfigFileName = "config"; private const string DefaultDirectoryName = ".aws"; private const string DefaultFileName = "credentials"; private const string DefaultConfigurationModeField = "defaults_mode"; private const string CredentialProcess = "credential_process"; private const string StsRegionalEndpointsField = "sts_regional_endpoints"; private const string S3UseArnRegionField = "s3_use_arn_region"; private const string S3RegionalEndpointField = "s3_us_east_1_regional_endpoint"; private const string S3DisableMultiRegionAccessPointsField = "s3_disable_multiregion_access_points"; private const string RetryModeField = "retry_mode"; private const string MaxAttemptsField = "max_attempts"; private const string SsoAccountId = "sso_account_id"; private const string SsoRegion = "sso_region"; private const string SsoRoleName = "sso_role_name"; private const string SsoStartUrl = "sso_start_url"; private const string SsoSession = "sso_session"; private const string EC2MetadataServiceEndpointField = "ec2_metadata_service_endpoint"; private const string EC2MetadataServiceEndpointModeField = "ec2_metadata_service_endpoint_mode"; private const string UseDualstackEndpointField = "use_dualstack_endpoint"; private const string UseFIPSEndpointField = "use_fips_endpoint"; private readonly Logger _logger = Logger.GetLogger(typeof(SharedCredentialsFile)); private static readonly HashSet<string> ReservedPropertyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ToolkitArtifactGuidField, RegionField, EndpointDiscoveryEnabledField, CredentialProcess, StsRegionalEndpointsField, S3UseArnRegionField, S3RegionalEndpointField, S3DisableMultiRegionAccessPointsField, RetryModeField, MaxAttemptsField, SsoAccountId, SsoRegion, SsoRoleName, SsoStartUrl, SsoSession, EC2MetadataServiceEndpointField, EC2MetadataServiceEndpointModeField, UseDualstackEndpointField, UseFIPSEndpointField, DefaultConfigurationModeField }; /// <summary> /// To maintain compatibility with the CLI, /// SharedCredentialsFile doesn't support the SAML profileTypes. /// </summary> private static readonly HashSet<CredentialProfileType> ProfileTypeWhitelist = new HashSet<CredentialProfileType>() { CredentialProfileType.AssumeRole, CredentialProfileType.AssumeRoleCredentialSource, CredentialProfileType.AssumeRoleExternal, CredentialProfileType.AssumeRoleExternalMFA, CredentialProfileType.AssumeRoleMFA, CredentialProfileType.AssumeRoleWithWebIdentity, CredentialProfileType.AssumeRoleWithWebIdentitySessionName, CredentialProfileType.Basic, CredentialProfileType.Session, CredentialProfileType.CredentialProcess, CredentialProfileType.AssumeRoleSessionName, CredentialProfileType.AssumeRoleCredentialSourceSessionName, CredentialProfileType.AssumeRoleExternalSessionName, CredentialProfileType.AssumeRoleExternalMFASessionName, CredentialProfileType.AssumeRoleMFASessionName, #if !BCL35 CredentialProfileType.SSO, #endif }; private static readonly CredentialProfilePropertyMapping PropertyMapping = new CredentialProfilePropertyMapping( new Dictionary<string, string>() { { "AccessKey", "aws_access_key_id" }, { "CredentialSource", "credential_source" }, { "EndpointName", null }, { "ExternalID", "external_id" }, { "MfaSerial", "mfa_serial" }, { "RoleArn", "role_arn" }, { "RoleSessionName", "role_session_name" }, { "SecretKey", "aws_secret_access_key" }, { "SourceProfile", "source_profile" }, { "Token", "aws_session_token" }, { "UserIdentity", null }, { "CredentialProcess" , "credential_process" }, { "WebIdentityTokenFile", "web_identity_token_file" }, #if !BCL35 { nameof(CredentialProfileOptions.SsoAccountId), SsoAccountId }, { nameof(CredentialProfileOptions.SsoRegion), SsoRegion }, { nameof(CredentialProfileOptions.SsoRoleName), SsoRoleName }, { nameof(CredentialProfileOptions.SsoSession), SsoSession }, { nameof(CredentialProfileOptions.SsoStartUrl), SsoStartUrl }, #endif } ); /// <summary> /// The default directory for the credentials file. By default it searches in ~/.aws. This behavior can be overridden. /// </summary> public static readonly string DefaultDirectory; /// <summary> /// The default file path for the credentials file. By default it searches for ~/.aws/credentials. This behavior can be overriden. /// </summary> public static string DefaultFilePath { get; private set; } /// <summary> /// The default directory for the config file. By default it searches in ~/.aws This behavior can be overriden. /// </summary> public static readonly string DefaultConfigDirectory; /// <summary> /// The default file path for the config file. By default it searches in ~/.aws/config /// </summary> public static string DefaultConfigFilePath { get; private set; } static SharedCredentialsFile() { var awsCredentialsEnvironmentPath = Environment.GetEnvironmentVariable(SharedCredentialsFileEnvVar); var awsConfigEnvironmentPath = Environment.GetEnvironmentVariable(SharedConfigFileEnvVar); if (!string.IsNullOrEmpty(awsConfigEnvironmentPath)) { if (File.Exists(awsConfigEnvironmentPath)) { DefaultConfigDirectory = Directory.GetParent(awsConfigEnvironmentPath).FullName; DefaultConfigFilePath = awsConfigEnvironmentPath; } } if (!string.IsNullOrEmpty(awsCredentialsEnvironmentPath)) { if (File.Exists(awsCredentialsEnvironmentPath)) { DefaultDirectory = Directory.GetParent(awsCredentialsEnvironmentPath).FullName; DefaultFilePath = awsCredentialsEnvironmentPath; } } if (DefaultFilePath == null || DefaultConfigFilePath == null) { var baseDirectory = Environment.GetEnvironmentVariable("HOME"); if (string.IsNullOrEmpty(baseDirectory)) baseDirectory = Environment.GetEnvironmentVariable("USERPROFILE"); if (string.IsNullOrEmpty(baseDirectory)) #if NETSTANDARD baseDirectory = Directory.GetCurrentDirectory(); #else baseDirectory = Environment.CurrentDirectory; #endif if (DefaultFilePath == null) { DefaultDirectory = Path.Combine(baseDirectory, DefaultDirectoryName); DefaultFilePath = Path.Combine(DefaultDirectory, DefaultFileName); } if (DefaultConfigFilePath == null) { DefaultConfigDirectory = Path.Combine(baseDirectory, DefaultDirectoryName); DefaultConfigFilePath = Path.Combine(DefaultConfigDirectory, ConfigFileName); } } } private ProfileIniFile _credentialsFile; private ProfileIniFile _configFile; /// <summary> /// The path to the credentials file /// </summary> public string FilePath { get; private set; } /// <summary> /// The path to the config file /// </summary> public string ConfigFilePath { get; private set; } /// <summary> /// Construct a new SharedCredentialsFile in the default location. /// </summary> public SharedCredentialsFile() { SetUpFilePath(null); Refresh(); } /// <summary> /// Construct a new SharedCredentialsFile. /// </summary> /// <param name="filePath">The path of the shared credentials file.</param> public SharedCredentialsFile(string filePath) { SetUpFilePath(filePath); Refresh(); } /// <summary> /// SetUpFilePath sets FilePath and ConfigFilePath using the DefaultFilePath and DefaultConfigFilePath set in /// the static constructor. If AWSConfigs.AWSProfilesLocation is provided, FilePath supercedes DefaultFilePath /// </summary> /// <param name="filePath"></param> private void SetUpFilePath(string filePath) { if (string.IsNullOrEmpty(filePath)) { if (string.IsNullOrEmpty(AWSConfigs.AWSProfilesLocation)) { FilePath = DefaultFilePath; ConfigFilePath = DefaultConfigFilePath; } else { FilePath = AWSConfigs.AWSProfilesLocation; ConfigFilePath = DefaultConfigFilePath; } } else { FilePath = filePath; ConfigFilePath = DefaultConfigFilePath; } } public List<string> ListProfileNames() { Refresh(); return ListProfiles().Select(p => p.Name).ToList(); } public List<CredentialProfile> ListProfiles() { Refresh(); var profiles = new List<CredentialProfile>(); foreach (var profileName in ListAllProfileNames()) { CredentialProfile profile = null; if (TryGetProfile(profileName, doRefresh: false, isSsoSession: false, out profile) && profile.CanCreateAWSCredentials) { profiles.Add(profile); } } return profiles; } public bool TryGetProfile(string profileName, out CredentialProfile profile) { return TryGetProfile(profileName, doRefresh: true, isSsoSession: false, out profile); } /// <summary> /// Add the profile given. If the profile already exists, update it. /// </summary> /// <param name="profile">The profile to be written.</param> public void RegisterProfile(CredentialProfile profile) { Refresh(); if (profile.CanCreateAWSCredentials || profile.Options.IsEmpty) { if (!IsSupportedProfileType(profile.ProfileType)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to update profile {0}. The CredentialProfile object provided represents a " + "{1} profile but {2} does not support the {1} profile type.", profile.Name, profile.ProfileType, GetType().Name)); } RegisterProfileInternal(profile); } else { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Unable to update profile {0}. The CredentialProfile provided is not a valid profile.", profile.Name)); } } /// <summary> /// Update the profile on disk regardless of the profile type. /// </summary> /// <param name="profile"></param> [SuppressMessage("Microsoft.Globalization", "CA1308", Justification = "Value is not surfaced to user. Booleans have been lowercased by SDK precedent.")] private void RegisterProfileInternal(CredentialProfile profile) { var reservedProperties = new Dictionary<string, string>(); if (profile.UniqueKey != null) reservedProperties[ToolkitArtifactGuidField] = profile.UniqueKey.Value.ToString("D"); if (profile.Region != null) reservedProperties[RegionField] = profile.Region.SystemName; if (profile.EndpointDiscoveryEnabled != null) reservedProperties[EndpointDiscoveryEnabledField] = profile.EndpointDiscoveryEnabled.Value.ToString().ToLowerInvariant(); if (profile.StsRegionalEndpoints != null) reservedProperties[StsRegionalEndpointsField] = profile.StsRegionalEndpoints.ToString().ToLowerInvariant(); if (profile.S3UseArnRegion != null) reservedProperties[S3UseArnRegionField] = profile.S3UseArnRegion.Value.ToString().ToLowerInvariant(); if (profile.S3RegionalEndpoint != null) reservedProperties[S3RegionalEndpointField] = profile.S3RegionalEndpoint.ToString().ToLowerInvariant(); if (profile.S3DisableMultiRegionAccessPoints != null) reservedProperties[S3DisableMultiRegionAccessPointsField] = profile.S3DisableMultiRegionAccessPoints.ToString().ToLowerInvariant(); if (profile.RetryMode != null) reservedProperties[RetryModeField] = profile.RetryMode.ToString().ToLowerInvariant(); if (profile.MaxAttempts != null) reservedProperties[MaxAttemptsField] = profile.MaxAttempts.ToString().ToLowerInvariant(); if (profile.EC2MetadataServiceEndpoint != null) reservedProperties[EC2MetadataServiceEndpointField] = profile.EC2MetadataServiceEndpoint.ToString().ToLowerInvariant(); if (profile.EC2MetadataServiceEndpointMode != null) reservedProperties[EC2MetadataServiceEndpointModeField] = profile.EC2MetadataServiceEndpointMode.ToString().ToLowerInvariant(); if (profile.UseDualstackEndpoint != null) reservedProperties[UseDualstackEndpointField] = profile.UseDualstackEndpoint.ToString().ToLowerInvariant(); if (profile.UseFIPSEndpoint != null) reservedProperties[UseFIPSEndpointField] = profile.UseFIPSEndpoint.ToString().ToLowerInvariant(); var profileDictionary = PropertyMapping.CombineProfileParts( profile.Options, ReservedPropertyNames, reservedProperties, profile.Properties); // The config file might contain parts of the profile // These parts are updated at the config file and removed from profileDictionary to avoid duplication UpdateConfigSectionsFromProfile(profile, profileDictionary); _credentialsFile.EditSection(profile.Name, new SortedDictionary<string, string>(profileDictionary)); _credentialsFile.Persist(); profile.CredentialProfileStore = this; } private void UpdateConfigSectionsFromProfile(CredentialProfile profile, Dictionary<string, string> profileDictionary) { if (_configFile == null || !_configFile.TryGetSection(profile.Name, out var configProperties)) return; var configPropertiesNames = configProperties.Keys.ToArray(); foreach (var propertyName in configPropertiesNames) { if (profileDictionary.ContainsKey(propertyName)) { configProperties[propertyName] = profileDictionary[propertyName]; profileDictionary.Remove(propertyName); // Remove the property from profileDictionary as we updated it in the config } else { configProperties[propertyName] = null; } } _configFile.EditSection(profile.Name, new SortedDictionary<string, string>(configProperties)); _configFile.Persist(); if (configProperties.TryGetValue(SsoSession, out var session) && _configFile.TryGetSection(session, true, out var ssoSessionProperties)) { // Skip SsoSession properties as it might be used by other profiles var ssoSessionPropertiesNames = ssoSessionProperties.Keys.ToArray(); foreach (var propertyName in ssoSessionPropertiesNames) { profileDictionary.Remove(propertyName); } } } /// <summary> /// Deletes the section with the given ProfileName from the SharedCredentialsFile, if one exists. /// </summary> /// <param name="profileName">The ProfileName of the section to delete.</param> public void UnregisterProfile(string profileName) { Refresh(); _credentialsFile.DeleteSection(profileName); _credentialsFile.Persist(); } /// <summary> /// Rename the profile with oldProfileName to newProfileName. /// </summary> /// <param name="oldProfileName">The profile to rename.</param> /// <param name="newProfileName">The new name for the profile.</param> public void RenameProfile(string oldProfileName, string newProfileName) { RenameProfile(oldProfileName, newProfileName, false); } /// <summary> /// Rename the profile with oldProfileName to newProfileName. /// </summary> /// <param name="oldProfileName">The profile to rename.</param> /// <param name="newProfileName">The new name for the profile.</param> /// <param name="force">If true and the destination profile exists it will be overwritten.</param> public void RenameProfile(string oldProfileName, string newProfileName, bool force) { Refresh(); _credentialsFile.RenameSection(oldProfileName, newProfileName, force); _credentialsFile.Persist(); } /// <summary> /// Make a copy of the profile with fromProfileName called toProfileName. /// </summary> /// <param name="fromProfileName">The name of the profile to copy from.</param> /// <param name="toProfileName">The name of the new profile.</param> public void CopyProfile(string fromProfileName, string toProfileName) { CopyProfile(fromProfileName, toProfileName, false); } /// <summary> /// Make a copy of the profile with fromProfileName called toProfileName. /// </summary> /// <param name="fromProfileName">The name of the profile to copy from.</param> /// <param name="toProfileName">The name of the new profile.</param> /// <param name="force">If true and the destination profile exists it will be overwritten.</param> public void CopyProfile(string fromProfileName, string toProfileName, bool force) { Refresh(); // Do the copy but make sure to replace the toolkitArtifactGuid with a new one, if it's there. _credentialsFile.CopySection(fromProfileName, toProfileName, new Dictionary<string, string> { { ToolkitArtifactGuidField, Guid.NewGuid().ToString() } }, force); _credentialsFile.Persist(); } private void Refresh() { _credentialsFile = new ProfileIniFile(FilePath, false); //Re-check if they set an explicit config file path, use that if it's set var awsConfigEnvironmentPath = Environment.GetEnvironmentVariable(SharedConfigFileEnvVar); if (!string.IsNullOrEmpty(awsConfigEnvironmentPath)) { _configFile = new ProfileIniFile(ConfigFilePath, true); } // If a config file exists in the same location as the credentials file and no env vars are set // load it for use as a read-only source of profile properties. else { var configPath = Path.Combine(Path.GetDirectoryName(FilePath), ConfigFileName); if (File.Exists(configPath)) { _configFile = new ProfileIniFile(configPath, true); } } } private HashSet<string> ListAllProfileNames() { var profileNames = _credentialsFile.ListSectionNames(); if (_configFile != null) { profileNames.UnionWith(_configFile.ListSectionNames()); } return profileNames; } private bool TryGetProfile(string profileName, bool doRefresh, bool isSsoSession, out CredentialProfile profile) { if (doRefresh) { Refresh(); } Dictionary<string, string> profileDictionary = null; if (TryGetSection(profileName, isSsoSession, out profileDictionary)) { CredentialProfileOptions profileOptions; Dictionary<string, string> reservedProperties; Dictionary<string, string> userProperties; PropertyMapping.ExtractProfileParts( profileDictionary, ReservedPropertyNames, out profileOptions, out reservedProperties, out userProperties); string toolkitArtifactGuidStr; Guid? toolkitArtifactGuid = null; if (reservedProperties.TryGetValue(ToolkitArtifactGuidField, out toolkitArtifactGuidStr)) { if (!GuidUtils.TryParseNullableGuid(toolkitArtifactGuidStr, out toolkitArtifactGuid)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. GUID expected.", toolkitArtifactGuidStr, ToolkitArtifactGuidField, profileName); profile = null; return false; } } string regionString; RegionEndpoint region = null; if (reservedProperties.TryGetValue(RegionField, out regionString)) { region = RegionEndpoint.GetBySystemName(regionString); } string endpointDiscoveryEnabledString; bool? endpointDiscoveryEnabled = null; if (reservedProperties.TryGetValue(EndpointDiscoveryEnabledField, out endpointDiscoveryEnabledString)) { bool endpointDiscoveryEnabledOut; if (!bool.TryParse(endpointDiscoveryEnabledString, out endpointDiscoveryEnabledOut)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A boolean true/false is expected.", endpointDiscoveryEnabledString, EndpointDiscoveryEnabledField, profileName); profile = null; return false; } endpointDiscoveryEnabled = endpointDiscoveryEnabledOut; } StsRegionalEndpointsValue? stsRegionalEndpoints = null; if (reservedProperties.TryGetValue(StsRegionalEndpointsField, out var stsRegionalEndpointsString)) { #if BCL35 try { stsRegionalEndpoints = (StsRegionalEndpointsValue) Enum.Parse(typeof(StsRegionalEndpointsValue), stsRegionalEndpointsString, true); } catch (Exception) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", stsRegionalEndpointsString, StsRegionalEndpointsField, profileName); profile = null; return false; } #else if (!Enum.TryParse<StsRegionalEndpointsValue>(stsRegionalEndpointsString, true, out var stsRegionalEndpointsTemp)) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", stsRegionalEndpointsString, StsRegionalEndpointsField, profileName); profile = null; return false; } stsRegionalEndpoints = stsRegionalEndpointsTemp; #endif } string s3UseArnRegionString; bool? s3UseArnRegion = null; if (reservedProperties.TryGetValue(S3UseArnRegionField, out s3UseArnRegionString)) { bool s3UseArnRegionOut; if (!bool.TryParse(s3UseArnRegionString, out s3UseArnRegionOut)) { profile = null; return false; } s3UseArnRegion = s3UseArnRegionOut; } S3UsEast1RegionalEndpointValue? s3RegionalEndpoint = null; if (reservedProperties.TryGetValue(S3RegionalEndpointField, out var s3RegionalEndpointString)) { #if BCL35 try { s3RegionalEndpoint = (S3UsEast1RegionalEndpointValue) Enum.Parse(typeof(S3UsEast1RegionalEndpointValue), s3RegionalEndpointString, true); } catch (Exception) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", s3RegionalEndpointString, S3RegionalEndpointField, profileName); profile = null; return false; } #else if (!Enum.TryParse<S3UsEast1RegionalEndpointValue>(s3RegionalEndpointString, true, out var s3RegionalEndpointTemp)) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", s3RegionalEndpointString, S3RegionalEndpointField, profileName); profile = null; return false; } s3RegionalEndpoint = s3RegionalEndpointTemp; #endif } string s3DisableMultiRegionAccessPointsString; bool? s3DisableMultiRegionAccessPoints = null; if (reservedProperties.TryGetValue(S3DisableMultiRegionAccessPointsField, out s3DisableMultiRegionAccessPointsString)) { bool s3DisableMultiRegionAccessPointsOut; if (!bool.TryParse(s3DisableMultiRegionAccessPointsString, out s3DisableMultiRegionAccessPointsOut)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A boolean true/false is expected.", s3DisableMultiRegionAccessPointsString, S3DisableMultiRegionAccessPointsField, profileName); profile = null; return false; } s3DisableMultiRegionAccessPoints = s3DisableMultiRegionAccessPointsOut; } RequestRetryMode? requestRetryMode = null; if (reservedProperties.TryGetValue(RetryModeField, out var retryModeString)) { #if BCL35 try { requestRetryMode = (RequestRetryMode) Enum.Parse(typeof(RequestRetryMode), retryModeString, true); } catch (Exception) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string legacy/standard/adaptive is expected.", retryModeString, RetryModeField, profileName); profile = null; return false; } #else if (!Enum.TryParse<RequestRetryMode>(retryModeString, true, out var retryModeTemp)) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string legacy/standard/adaptive is expected.", retryModeString, RetryModeField, profileName); profile = null; return false; } requestRetryMode = retryModeTemp; #endif } int? maxAttempts = null; if (reservedProperties.TryGetValue(MaxAttemptsField, out var maxAttemptsString)) { if (!int.TryParse(maxAttemptsString, out var maxAttemptsTemp) || maxAttemptsTemp <= 0) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A positive integer is expected.", maxAttemptsString, MaxAttemptsField, profileName); profile = null; return false; } maxAttempts = maxAttemptsTemp; } string defaultConfigurationModeName; reservedProperties.TryGetValue(DefaultConfigurationModeField, out defaultConfigurationModeName); string ec2MetadataServiceEndpoint; if (reservedProperties.TryGetValue(EC2MetadataServiceEndpointField, out ec2MetadataServiceEndpoint)) { if (!Uri.IsWellFormedUriString(ec2MetadataServiceEndpoint, UriKind.Absolute)) { throw new AmazonClientException($"Invalid value {ec2MetadataServiceEndpoint} for {EC2MetadataServiceEndpointField} in profile {profileName}. A well-formed Uri is expected."); } } EC2MetadataServiceEndpointMode? ec2MetadataServiceEndpointMode = null; if (reservedProperties.TryGetValue(EC2MetadataServiceEndpointModeField, out var ec2MetadataServiceEndpointModeString)) { #if BCL35 try { ec2MetadataServiceEndpointMode = (EC2MetadataServiceEndpointMode)Enum.Parse(typeof(EC2MetadataServiceEndpointMode), ec2MetadataServiceEndpointModeString, true); } catch (Exception) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string IPv4 or IPV6 is expected.", ec2MetadataServiceEndpointModeString, EC2MetadataServiceEndpointModeField, profileName); profile = null; return false; } #else if (!Enum.TryParse<EC2MetadataServiceEndpointMode>(ec2MetadataServiceEndpointModeString, true, out var ec2MetadataServiceEndpointModeTemp)) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string IPv4 or IPV6 is expected.", ec2MetadataServiceEndpointModeString, EC2MetadataServiceEndpointModeField, profileName); profile = null; return false; } ec2MetadataServiceEndpointMode = ec2MetadataServiceEndpointModeTemp; #endif } #if !BCL35 if (profileDictionary.TryGetValue(SsoSession, out var session)) { profileOptions.SsoSession = session; if (TryGetProfile(session, doRefresh: false, isSsoSession: true, out var sessionProfile)) { profileOptions.SsoRegion = sessionProfile.Options.SsoRegion; profileOptions.SsoStartUrl = sessionProfile.Options.SsoStartUrl; } else { _logger.InfoFormat($"Failed to find {SsoSession} [{session}]"); throw new AmazonClientException($"Invalid Configuration. Failed to find {SsoSession} [{session}]"); } } #endif string useDualstackEndpointString; bool? useDualstackEndpoint = null; if (reservedProperties.TryGetValue(UseDualstackEndpointField, out useDualstackEndpointString)) { bool useDualstackEndpointOut; if (!bool.TryParse(useDualstackEndpointString, out useDualstackEndpointOut)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A boolean true/false is expected.", useDualstackEndpointString, UseDualstackEndpointField, profileName); profile = null; return false; } useDualstackEndpoint = useDualstackEndpointOut; } string useFIPSEndpointString; bool? useFIPSEndpoint = null; if (reservedProperties.TryGetValue(UseFIPSEndpointField, out useFIPSEndpointString)) { bool useFIPSEndpointOut; if (!bool.TryParse(useFIPSEndpointString, out useFIPSEndpointOut)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A boolean true/false is expected.", useFIPSEndpointString, UseFIPSEndpointField, profileName); profile = null; return false; } useFIPSEndpoint = useFIPSEndpointOut; } profile = new CredentialProfile(profileName, profileOptions) { UniqueKey = toolkitArtifactGuid, Properties = userProperties, Region = region, CredentialProfileStore = this, DefaultConfigurationModeName = defaultConfigurationModeName, EndpointDiscoveryEnabled = endpointDiscoveryEnabled, StsRegionalEndpoints = stsRegionalEndpoints, S3UseArnRegion = s3UseArnRegion, S3RegionalEndpoint = s3RegionalEndpoint, S3DisableMultiRegionAccessPoints = s3DisableMultiRegionAccessPoints, RetryMode = requestRetryMode, MaxAttempts = maxAttempts, EC2MetadataServiceEndpoint = ec2MetadataServiceEndpoint, EC2MetadataServiceEndpointMode = ec2MetadataServiceEndpointMode, UseDualstackEndpoint = useDualstackEndpoint, UseFIPSEndpoint = useFIPSEndpoint }; if (!IsSupportedProfileType(profile.ProfileType)) { _logger.InfoFormat("The profile type {0} is not supported by SharedCredentialsFile.", profile.ProfileType); profile = null; return false; } return true; } profile = null; return false; } /// <summary> /// Try to get a profile that may be partially in the credentials file and partially in the config file. /// If there are identically named properties in both files, the properties in the credentials file take precedence. /// </summary> private bool TryGetSection(string sectionName, bool isSsoSession, out Dictionary<string, string> iniProperties) { Dictionary<string, string> credentialsProperties = null; Dictionary<string, string> configProperties = null; var hasCredentialsProperties = _credentialsFile.TryGetSection(sectionName, isSsoSession, out credentialsProperties); var hasConfigProperties = false; if (_configFile != null) { _configFile.ProfileMarkerRequired = sectionName != DefaultProfileName; hasConfigProperties = _configFile.TryGetSection(sectionName, isSsoSession, out configProperties); } if (hasConfigProperties) { iniProperties = configProperties; if (hasCredentialsProperties) { // Add all the properties from the credentials file. // If a property exits in both, the one from the credentials // file takes precedence and overwrites the one from // the config file. foreach (var pair in credentialsProperties) { iniProperties[pair.Key] = pair.Value; } } return true; } iniProperties = credentialsProperties; return hasCredentialsProperties; } private static bool IsSupportedProfileType(CredentialProfileType? profileType) { return !profileType.HasValue || ProfileTypeWhitelist.Contains(profileType.Value); } } }
830
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 System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; namespace Amazon.Runtime.CredentialManagement.Internal { /// <summary> /// Class to easily convert from Dictionary&lt;string, string&gt; to ProfileOptions and back. /// </summary> public class CredentialProfilePropertyMapping { private static readonly HashSet<string> TypePropertySet = new HashSet<string>(typeof(CredentialProfileOptions).GetProperties().Select((p) => p.Name), StringComparer.OrdinalIgnoreCase); private static readonly PropertyInfo[] CredentialProfileReflectionProperties = typeof(CredentialProfileOptions).GetProperties(); private readonly Dictionary<string, string> _nameMapping; private readonly HashSet<string> _mappedNames; public CredentialProfilePropertyMapping(Dictionary<string, string> nameMapping) { if (!TypePropertySet.SetEquals(new HashSet<string>(nameMapping.Keys, StringComparer.OrdinalIgnoreCase))) { throw new ArgumentException("The nameMapping Dictionary must contain a name mapping for each ProfileOptions property, and no additional keys."); } this._nameMapping = nameMapping; _mappedNames = new HashSet<string>(nameMapping.Values.Where(v => !string.IsNullOrEmpty(v)), StringComparer.OrdinalIgnoreCase); } /// <summary> /// Separate the profileDictionary into its parts. /// profileDictionary = profileOptions + reservedProperties + userProperties /// </summary> /// <param name="profileDictionary">Dictionary with everything in it</param> /// <param name="reservedKeys">Keys to ignore</param> /// <param name="profileOptions">The resulting CredentialProfileOptions</param> /// <param name="userProperties">The properties that are left</param> public void ExtractProfileParts(Dictionary<string, string> profileDictionary, HashSet<string> reservedKeys, out CredentialProfileOptions profileOptions, out Dictionary<string, string> userProperties) { Dictionary<string, string> reservedProperties; ExtractProfileParts(profileDictionary, reservedKeys, out profileOptions, out reservedProperties, out userProperties); } /// <summary> /// Separate the profileDictionary into its parts. /// profileDictionary = profileOptions + reservedProperties + userProperties /// </summary> /// <param name="profileDictionary">Dictionary with everything in it</param> /// <param name="reservedKeys">Keys for the reservedKeys dictionary</param> /// <param name="profileOptions">The resulting CredentialProfileOptions</param> /// <param name="reservedProperties">The resulting reserved properties</param> /// <param name="userProperties">The properties that are left</param> public void ExtractProfileParts( Dictionary<string, string> profileDictionary, HashSet<string> reservedKeys, out CredentialProfileOptions profileOptions, out Dictionary<string, string> reservedProperties, out Dictionary<string, string> userProperties) { // profileDictionary = profileOptions + reservedProperties + userProperties // algorithm: userProperties = profileDictionary - profileOptions - reservedProperties // userProperties = profileDictionary userProperties = new Dictionary<string, string>(profileDictionary); // userProperties -= profileOptions profileOptions = new CredentialProfileOptions(); foreach (var reflectionProperty in CredentialProfileReflectionProperties) { string value = null; var mappedName = _nameMapping[reflectionProperty.Name]; if (mappedName != null) { if (userProperties.TryGetValue(mappedName, out value)) { reflectionProperty.SetValue(profileOptions, value, null); userProperties.Remove(mappedName); } } } // userProperties -= reservedProperties if (reservedKeys == null) { reservedProperties = null; } else { reservedProperties = new Dictionary<string, string>(); foreach (var key in reservedKeys) { string value = null; if (userProperties.TryGetValue(key, out value)) { reservedProperties.Add(key, value); userProperties.Remove(key); } } } } /// <summary> /// Validate the userProperties and then combine profileOptions, reservedProperties, and userProperties into one Dictionary. /// </summary> /// <param name="profileOptions"></param> /// <param name="reservedPropertyNames"></param> /// <param name="reservedProperties"></param> /// <param name="userProperties"></param> /// <returns></returns> public Dictionary<string, string> CombineProfileParts(CredentialProfileOptions profileOptions, HashSet<string> reservedPropertyNames, Dictionary<string, string> reservedProperties, Dictionary<string, string> userProperties) { ValidateNoProfileOptionsProperties(userProperties); ValidateNoReservedProperties(reservedPropertyNames, userProperties); var profileDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (var pair in Convert(profileOptions).Concat(reservedProperties).Concat(userProperties)) { profileDictionary.Add(pair.Key, pair.Value); } return profileDictionary; } /// <summary> /// Make sure the userProperties dictionary doesn't contain any keys that are reserved. /// Check is case-insensitive for added safety. /// </summary> /// <param name="reservedPropertyNames"></param> /// <param name="userProperties"></param> private static void ValidateNoReservedProperties(HashSet<string> reservedPropertyNames, Dictionary<string, string> userProperties) { if (userProperties != null) { List<string> reservedKeys = new List<string>(); foreach (var key in reservedPropertyNames) { if (userProperties.Keys.Contains(key, StringComparer.OrdinalIgnoreCase)) { reservedKeys.Add(key); } } if (reservedKeys.Count > 0) throw new ArgumentException("The profile properties cannot contain reserved names as keys: " + string.Join(" or ", reservedKeys.ToArray())); } } /// <summary> /// Make sure the userProperties dictionary doesn't contain any keys that /// overlap with the names of mapped names for CredentialProfileOptions property names. /// Check is case-insensitive for added safety. /// </summary> /// <param name="userProperties"></param> private void ValidateNoProfileOptionsProperties(Dictionary<string, string> userProperties) { if (userProperties != null) { foreach (var key in userProperties.Keys) { if (_mappedNames.Contains(key, StringComparer.OrdinalIgnoreCase)) { throw new ArgumentException("The profile properties dictionary cannot contain a key named " + key + " because it is in the name mapping dictionary."); } } } } private Dictionary<string, string> Convert(CredentialProfileOptions profileOptions) { var dictionary = new Dictionary<string, string>(); // if profileOptions.IsEmpty then leave all the credentials keys untouched if (!profileOptions.IsEmpty) { var properties = typeof(CredentialProfileOptions).GetProperties(); // ensure repeatable order Array.Sort(properties.Select((p) => p.Name).ToArray(), properties); foreach (var property in properties) { var value = (string)property.GetValue(profileOptions, null); if (string.IsNullOrEmpty(value)) value = null; if (_nameMapping[property.Name] != null) { dictionary.Add(_nameMapping[property.Name], value); } } } return dictionary; } } }
221
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.CredentialManagement; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Amazon.Runtime.CredentialManagement.Internal { public enum CredentialProfileType { AssumeRole, AssumeRoleCredentialSource, AssumeRoleExternal, AssumeRoleExternalMFA, AssumeRoleMFA, Basic, SAMLRole, SAMLRoleUserIdentity, Session, CredentialProcess, AssumeRoleWithWebIdentity, AssumeRoleWithWebIdentitySessionName, AssumeRoleSessionName, AssumeRoleCredentialSourceSessionName, AssumeRoleExternalSessionName, AssumeRoleExternalMFASessionName, AssumeRoleMFASessionName, #if !BCL35 SSO, #endif } public enum CredentialSourceType { Ec2InstanceMetadata, Environment, EcsContainer } public static class CredentialProfileTypeDetector { private const string BasicCredentials = "Basic"; private const string SessionCredentials = "Session"; private const string AssumeRoleCredentials = "Assume Role"; private const string AssumeRoleWithWebIdentityCredentials = "Assume Role with OIDC Web Identity"; private const string SAMLCredentials = "SAML"; private const string AccessKey = "AccessKey"; private const string CredentialSource = "CredentialSource"; private const string EndpointName = "EndpointName"; private const string ExternalID = "ExternalID"; private const string MfaSerial = "MfaSerial"; private const string RoleArn = "RoleArn"; private const string RoleSessionName = "RoleSessionName"; private const string SecretKey = "SecretKey"; private const string SourceProfile = "SourceProfile"; private const string Token = "Token"; private const string WebIdentityTokenFile = "WebIdentityTokenFile"; private const string UserIdentity = "UserIdentity"; private const string CredentialProcess = "CredentialProcess"; #if !BCL35 private const string SsoAccountId = nameof(CredentialProfileOptions.SsoAccountId); private const string SsoRegion = nameof(CredentialProfileOptions.SsoRegion); private const string SsoRoleName = nameof(CredentialProfileOptions.SsoRoleName); private const string SsoStartUrl = nameof(CredentialProfileOptions.SsoStartUrl); private const string SsoSession = nameof(CredentialProfileOptions.SsoSession); private static HashSet<string> SsoProperties = new HashSet<string>( new string[] {SsoAccountId, SsoRegion, SsoRoleName, SsoStartUrl, SsoSession}, StringComparer.OrdinalIgnoreCase); #endif private static Dictionary<CredentialProfileType, HashSet<string>> TypePropertyDictionary = new Dictionary<CredentialProfileType, HashSet<string>>() { { CredentialProfileType.CredentialProcess, new HashSet<string>() { CredentialProcess } }, { CredentialProfileType.AssumeRole, new HashSet<string>() { RoleArn, SourceProfile, } }, { CredentialProfileType.AssumeRoleCredentialSource, new HashSet<string>() { RoleArn, CredentialSource, } }, { CredentialProfileType.AssumeRoleExternal, new HashSet<string>() { ExternalID, RoleArn, SourceProfile, } }, { CredentialProfileType.AssumeRoleExternalMFA, new HashSet<string>() { ExternalID, MfaSerial, RoleArn, SourceProfile, } }, { CredentialProfileType.AssumeRoleWithWebIdentity, new HashSet<string>() { RoleArn, WebIdentityTokenFile, } }, { CredentialProfileType.AssumeRoleWithWebIdentitySessionName, new HashSet<string>() { RoleArn, WebIdentityTokenFile, RoleSessionName } }, { CredentialProfileType.AssumeRoleMFA, new HashSet<string>() { MfaSerial, RoleArn, SourceProfile, } }, { CredentialProfileType.Basic, new HashSet<string>() { AccessKey, SecretKey, } }, { CredentialProfileType.SAMLRole, new HashSet<string>() { EndpointName, RoleArn, } }, { CredentialProfileType.SAMLRoleUserIdentity, new HashSet<string>() { EndpointName, RoleArn, UserIdentity, } }, { CredentialProfileType.Session, new HashSet<string>() { AccessKey, SecretKey, Token, } }, { CredentialProfileType.AssumeRoleSessionName, new HashSet<string>() { RoleArn, SourceProfile, RoleSessionName } }, { CredentialProfileType.AssumeRoleCredentialSourceSessionName, new HashSet<string>() { RoleArn, CredentialSource, RoleSessionName } }, { CredentialProfileType.AssumeRoleExternalSessionName, new HashSet<string>() { ExternalID, RoleArn, SourceProfile, RoleSessionName } }, { CredentialProfileType.AssumeRoleExternalMFASessionName, new HashSet<string>() { ExternalID, MfaSerial, RoleArn, SourceProfile, RoleSessionName } }, { CredentialProfileType.AssumeRoleMFASessionName, new HashSet<string>() { MfaSerial, RoleArn, SourceProfile, RoleSessionName } }, #if !BCL35 { CredentialProfileType.SSO, new HashSet<string>() { SsoAccountId, SsoRegion, SsoRoleName, SsoStartUrl, SsoSession } }, #endif }; private static Dictionary<CredentialProfileType, string> CredentialTypeDictionary = new Dictionary<CredentialProfileType, string>() { { CredentialProfileType.AssumeRole, AssumeRoleCredentials }, { CredentialProfileType.AssumeRoleExternal, AssumeRoleCredentials }, { CredentialProfileType.AssumeRoleExternalMFA, AssumeRoleCredentials }, { CredentialProfileType.AssumeRoleMFA, AssumeRoleCredentials }, { CredentialProfileType.AssumeRoleWithWebIdentity, AssumeRoleWithWebIdentityCredentials }, { CredentialProfileType.AssumeRoleWithWebIdentitySessionName, AssumeRoleWithWebIdentityCredentials }, { CredentialProfileType.AssumeRoleSessionName, AssumeRoleCredentials }, { CredentialProfileType.AssumeRoleExternalSessionName, AssumeRoleCredentials }, { CredentialProfileType.AssumeRoleExternalMFASessionName, AssumeRoleCredentials }, { CredentialProfileType.AssumeRoleMFASessionName, AssumeRoleCredentials }, { CredentialProfileType.Basic, BasicCredentials }, { CredentialProfileType.SAMLRole, SAMLCredentials }, { CredentialProfileType.SAMLRoleUserIdentity, SAMLCredentials }, { CredentialProfileType.Session, SessionCredentials }, { CredentialProfileType.CredentialProcess, CredentialProcess } }; public static string GetUserFriendlyCredentialType(CredentialProfileType? profileType) { if (profileType.HasValue) { return CredentialTypeDictionary[profileType.Value]; } else { return null; } } public static CredentialProfileType? DetectProfileType(CredentialProfileOptions profileOptions) { CredentialProfileType? profileType = null; HashSet<string> propertyNames = GetPropertyNames(profileOptions); #if !BCL35 // Spec: If one or more of the SSO properties is present, the profile MUST be resolved by the SSO credential provider. if (propertyNames.Any(propertyName => SsoProperties.Contains(propertyName))) { return CredentialProfileType.SSO; } #endif // brute force algorithm - but it's a very small set foreach (var pair in TypePropertyDictionary) { if (pair.Value.SetEquals(propertyNames)) { // exact match profileType = pair.Key; } } return profileType; } public static HashSet<string> GetPropertiesForProfileType(CredentialProfileType profileType) { return new HashSet<string>(TypePropertyDictionary[profileType]); } private static HashSet<string> GetPropertyNames(CredentialProfileOptions profileOptions) { HashSet<string> propertyNames = new HashSet<string>(); foreach (var property in typeof(CredentialProfileOptions).GetProperties()) { var value = (string)property.GetValue(profileOptions, null); if (!string.IsNullOrEmpty(value)) { propertyNames.Add(property.Name); } } return propertyNames; } } }
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. */ using Amazon.Runtime.CredentialManagement; using Amazon.Runtime.Internal.Settings; using Amazon.Util; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Amazon.Runtime.CredentialManagement.Internal { /// <summary> /// This class is used internally and should not be accessed by SDK users. /// /// Provide access to internal properties of CredentialProfile to /// PowerShell tools and the Visual Studio Toolkit. /// </summary> public static class CredentialProfileUtils { public static Dictionary<string, string> GetProperties(CredentialProfile profile) { return profile.Properties; } public static void SetProperty(CredentialProfile profile, string key, string value) { profile.Properties[key] = value; } public static string GetProperty(CredentialProfile profile, string key) { string value; profile.Properties.TryGetValue(key, out value); return value; } public static Guid EnsureUniqueKeyAssigned(CredentialProfile profile, ICredentialProfileStore profileStore) { if (!profile.UniqueKey.HasValue) { profile.UniqueKey = Guid.NewGuid(); profileStore.RegisterProfile(profile); } return profile.UniqueKey.Value; } public static String GetUniqueKey(CredentialProfile profile) { return profile.UniqueKey.HasValue ? profile.UniqueKey.Value.ToString("D") : null; } public static void SetUniqueKey(CredentialProfile profile, Guid? uniqueKey) { profile.UniqueKey = uniqueKey; } public static CredentialProfileType? GetProfileType(CredentialProfile profile) { return profile.ProfileType; } public static bool IsCallbackRequired(CredentialProfile profile) { return profile.IsCallbackRequired; } } }
80
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.Settings; using Amazon.Runtime.Internal.Util; using Amazon.Util; using Amazon.Util.Internal; using System; using System.Collections.Generic; namespace Amazon.Runtime.CredentialManagement.Internal { public class SAMLRoleSessionManager { private SettingsManager settingsManager; public static bool IsAvailable { get { return SettingsManager.IsAvailable; } } public SAMLRoleSessionManager() { settingsManager = new SettingsManager(SettingsConstants.RegisteredRoleSessions); } public void Clear() { foreach (string roleSessionName in settingsManager.ListUniqueKeys()) { settingsManager.UnregisterObject(roleSessionName); } } /// <summary> /// Attempt to read a role session with the given name. /// If the session is invalid or expired it will not be returned. /// </summary> /// <param name="roleSessionName">The name of the role session to get.</param> /// <param name="credentials">The credentials for the session, if found.</param> /// <returns>True if the session was found, false otherwise.</returns> public bool TryGetRoleSession(string roleSessionName, out SAMLImmutableCredentials credentials) { Dictionary<string, string> properties; credentials = null; if (settingsManager.TryGetObject(roleSessionName, out properties)) { try { credentials = SAMLImmutableCredentials.FromJson(properties[SettingsConstants.RoleSession]); } catch (Exception e) { Logger.GetLogger(typeof(SAMLRoleSessionManager)).Error(e, "Unable to load SAML role session '{0}'.", roleSessionName); } } return credentials != null; } public void RegisterRoleSession(string roleSessionName, SAMLImmutableCredentials credentials) { var properties = new Dictionary<string, string>() { { SettingsConstants.RoleSession, credentials.ToJson() } }; settingsManager.RegisterObject(roleSessionName, properties); } public void UnregisterRoleSession(string roleSessionName) { settingsManager.UnregisterObject(roleSessionName); } } }
88
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> /// Anonymous credentials. /// Using these credentials, the client does not sign the request. /// </summary> public class AnonymousAWSCredentials : AWSCredentials { #region Abstract class overrides /// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { throw new NotSupportedException("AnonymousAWSCredentials do not support this operation"); } #endregion } }
39
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 { /// <summary> /// AWS Credentials that automatically refresh by calling AssumeRole on /// the Amazon Security Token Service. /// </summary> public class AssumeRoleAWSCredentials : RefreshingAWSCredentials { private RegionEndpoint DefaultSTSClientRegion = RegionEndpoint.USEast1; private Logger _logger = Logger.GetLogger(typeof(AssumeRoleAWSCredentials)); /// <summary> /// The credentials of the user that will be used to call AssumeRole. /// </summary> public AWSCredentials SourceCredentials { get; private set; } /// <summary> /// The Amazon Resource Name (ARN) of the role to assume. /// </summary> public string RoleArn { get; private set; } /// <summary> /// An identifier for the assumed role session. /// </summary> public string RoleSessionName { get; private set; } /// <summary> /// Options to be used in the call to AssumeRole. /// </summary> public AssumeRoleAWSCredentialsOptions Options { get; private set; } /// <summary> /// Constructs an AssumeRoleAWSCredentials object. /// </summary> /// <param name="sourceCredentials">The credentials of the user that will be used to call AssumeRole.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param> /// <param name="roleSessionName">An identifier for the assumed role session.</param> public AssumeRoleAWSCredentials(AWSCredentials sourceCredentials, string roleArn, string roleSessionName) : this(sourceCredentials, roleArn, roleSessionName, new AssumeRoleAWSCredentialsOptions()) { } /// <summary> /// Constructs an AssumeRoleAWSCredentials object. /// </summary> /// <param name="sourceCredentials">The credentials of the user that will be used to call AssumeRole.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param> /// <param name="roleSessionName">An identifier for the assumed role session.</param> /// <param name="options">Options to be used in the call to AssumeRole.</param> public AssumeRoleAWSCredentials(AWSCredentials sourceCredentials, string roleArn, string roleSessionName, AssumeRoleAWSCredentialsOptions options) { if (options == null) { throw new ArgumentNullException("options"); } SourceCredentials = sourceCredentials; RoleArn = roleArn; RoleSessionName = roleSessionName; Options = options; // Make sure to fetch new credentials well before the current credentials expire to avoid // any request being made with expired credentials. PreemptExpiryTime = TimeSpan.FromMinutes(5); } protected override CredentialsRefreshState GenerateNewCredentials() { var region = FallbackRegionFactory.GetRegionEndpoint() ?? DefaultSTSClientRegion; ICoreAmazonSTS coreSTSClient; try { var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME); stsConfig.RegionEndpoint = region; if (Options != null && Options.ProxySettings != null) { stsConfig.SetWebProxy(Options.ProxySettings); } coreSTSClient = ServiceClientHelpers.CreateServiceFromAssembly<ICoreAmazonSTS>( ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, SourceCredentials, stsConfig); } catch (Exception e) { var msg = string.Format(CultureInfo.CurrentCulture, "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use Amazon.Runtime.AssumeRoleAWSCredentials.", ServiceClientHelpers.STS_ASSEMBLY_NAME); var exception = new InvalidOperationException(msg, e); Logger.GetLogger(typeof(AssumeRoleAWSCredentials)).Error(exception, exception.Message); throw exception; } var credentials = coreSTSClient.CredentialsFromAssumeRoleAuthentication(RoleArn, RoleSessionName, Options); _logger.InfoFormat("New credentials created for assume role that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture)); return new CredentialsRefreshState(credentials, credentials.Expiration); } } }
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 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 AssumeRoleAWSCredentialsOptions { /// <summary> /// A unique identifier that is used by third parties when assuming roles in their customers' accounts. /// </summary> public string ExternalId { get; set; } /// <summary> /// An IAM policy in JSON format. /// </summary> public string Policy { get; set; } /// <summary> /// The length of time in seconds before the credentials will expire. /// </summary> public int? DurationSeconds { get; set; } /// <summary> /// The proxy settings to use when calling AssumeRole. /// </summary> #if BCL public WebProxy ProxySettings { get; set; } #elif NETSTANDARD public IWebProxy ProxySettings { get; set; } #endif /// <summary> /// The identification number of the MFA device that is associated with the user who is making the assume-role call. /// </summary> public string MfaSerialNumber { get; set; } /// <summary> /// The value provided by the MFA device, if the trust policy of the role being assumed requires MFA. /// </summary> public string MfaTokenCode { get { if (String.IsNullOrEmpty(MfaSerialNumber)) { return null; } else if (MfaTokenCodeCallback == null) { throw new InvalidOperationException("The MfaSerialNumber has been set but the MfaTokenCodeCallback hasn't. " + "MfaTokenCodeCallback is required in order to determine the MfaTokenCode when MfaSerialNumber is set."); } else { return MfaTokenCodeCallback(); } } } /// <summary> /// A callback that's used to obtain the MFA token code when the AssumeRoleAWSCredentials are refreshed. /// </summary> public Func<string> MfaTokenCodeCallback { get; set; } /// <summary> /// The source identity specified by the principal that is calling the <code>AssumeRole</code> /// operation. /// </summary> public string SourceIdentity { get; set; } } }
90
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 with the AssumeRole method of the Security Token Service. /// </summary> public class AssumeRoleImmutableCredentials : ImmutableCredentials { /// <summary> /// The expiry time of the credentials, obtained from the AssumeRoleResponse. /// </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 AssumeRoleImmutableCredentials(string awsAccessKeyId, string awsSecretAccessKey, string token, DateTime expiration) : base(awsAccessKeyId, awsSecretAccessKey, token) { if (string.IsNullOrEmpty(token)) throw new ArgumentNullException("token"); Expiration = expiration; } /// <summary> /// Get a copy of this AssumeRoleImmutableCredentials object. /// </summary> /// <returns>A copy of this object.</returns> new public AssumeRoleImmutableCredentials Copy() { return new AssumeRoleImmutableCredentials(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; AssumeRoleImmutableCredentials aric = obj as AssumeRoleImmutableCredentials; if (aric == null) return false; return AWSSDKUtils.AreEqual( new object[] { AccessKey, SecretKey, Token, Expiration }, new object[] { aric.AccessKey, aric.SecretKey, aric.Token, Expiration }); } } }
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.IO; using System.Net; using System.Text.RegularExpressions; #if AWS_ASYNC_API using System.Threading.Tasks; #endif namespace Amazon.Runtime { /// <summary> /// AWS Credentials that automatically refresh by calling AssumeRole on /// the Amazon Security Token Service. /// </summary> public class AssumeRoleWithWebIdentityCredentials : RefreshingAWSCredentials { private const int PREEMPT_EXPIRY_MINUTES = 5; private static readonly RegionEndpoint _defaultSTSClientRegion = RegionEndpoint.USEast1; private static readonly string _roleSessionNameDefault = Guid.NewGuid().ToString(); /// <summary> /// As established by STS, the regex used to validate the role session names is a string of 2-64 characters consisting of /// upper- and lower-case alphanumeric characters with no spaces. You can also include /// underscores or any of the following characters: =,.@- /// </summary> public const string WebIdentityTokenFileEnvVariable = "AWS_WEB_IDENTITY_TOKEN_FILE"; public const string RoleArnEnvVariable = "AWS_ROLE_ARN"; public const string RoleSessionNameEnvVariable = "AWS_ROLE_SESSION_NAME"; private static readonly Regex _roleSessionNameRegex = new Regex(@"^[\w+=,.@-]{2,64}$", RegexOptions.Compiled); private readonly Logger _logger = Logger.GetLogger(typeof(AssumeRoleWithWebIdentityCredentials)); /// <summary> /// Options to be used in the call to AssumeRole. /// </summary> private AssumeRoleWithWebIdentityCredentialsOptions _options; #region Properties /// <summary> /// The absolute path to the file on disk containing an OIDC token /// </summary> public string WebIdentityTokenFile { get; } /// <summary> /// The Amazon Resource Name (ARN) of the role to assume. /// </summary> public string RoleArn { get; } /// <summary> /// An identifier for the assumed role session. /// </summary> public string RoleSessionName { get; } #endregion Properties /// <summary> /// Constructs an AssumeRoleWithWebIdentityCredentials object. /// </summary> /// <param name="webIdentityTokenFile">The absolute path to the file on disk containing an OIDC token.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param> /// <param name="roleSessionName">An identifier for the assumed role session.</param> public AssumeRoleWithWebIdentityCredentials(string webIdentityTokenFile, string roleArn, string roleSessionName) : this(webIdentityTokenFile, roleArn, roleSessionName, new AssumeRoleWithWebIdentityCredentialsOptions()) { } /// <summary> /// Constructs an AssumeRoleWithWebIdentityCredentials object. /// </summary> /// <param name="webIdentityTokenFile">The absolute path to the file on disk containing an OIDC token.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param> /// <param name="roleSessionName">An identifier for the assumed role session.</param> /// <param name="options">Options to be used in the call to AssumeRole.</param> public AssumeRoleWithWebIdentityCredentials(string webIdentityTokenFile, string roleArn, string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options) { if (string.IsNullOrEmpty(webIdentityTokenFile)) { throw new ArgumentNullException(nameof(webIdentityTokenFile), $"The {nameof(webIdentityTokenFile)} must be an absolute path."); } else if (!AWSSDKUtils.IsAbsolutePath(webIdentityTokenFile)) { throw new ArgumentException($"The {nameof(webIdentityTokenFile)} must be an absolute path.", nameof(webIdentityTokenFile)); } if (string.IsNullOrEmpty(roleArn)) { throw new ArgumentNullException(nameof(roleArn), "The role ARN must be specified."); } if (!string.IsNullOrEmpty(roleSessionName) && !_roleSessionNameRegex.IsMatch(roleSessionName)) { throw new ArgumentOutOfRangeException(nameof(roleSessionName), roleSessionName, $"The value must match the regex pattern @\"{_roleSessionNameRegex}\"."); } WebIdentityTokenFile = webIdentityTokenFile; RoleArn = roleArn; RoleSessionName = string.IsNullOrEmpty(roleSessionName) ? _roleSessionNameDefault : roleSessionName; _options = options; // Make sure to fetch new credentials well before the current credentials expire to avoid // any request being made with expired credentials. PreemptExpiryTime = TimeSpan.FromMinutes(PREEMPT_EXPIRY_MINUTES); } /// <summary> /// Creates an instance of <see cref="AssumeRoleWithWebIdentityCredentials"/> from environment variables. /// </summary> /// <exception>Throws an <see cref="InvalidOperationException"/> if the needed environment variables are not set.</exception> /// <returns>The new credentials.</returns> public static AssumeRoleWithWebIdentityCredentials FromEnvironmentVariables() { var webIdentityTokenFile = Environment.GetEnvironmentVariable(WebIdentityTokenFileEnvVariable); var roleArn = Environment.GetEnvironmentVariable(RoleArnEnvVariable); var roleSessionName = Environment.GetEnvironmentVariable(RoleSessionNameEnvVariable); return new AssumeRoleWithWebIdentityCredentials(webIdentityTokenFile, roleArn, roleSessionName); } protected override CredentialsRefreshState GenerateNewCredentials() { string token = null; for (var retry = 0; retry <= AWSSDKUtils.DefaultMaxRetry; retry++) { try { using (var fileStream = new FileStream(WebIdentityTokenFile, FileMode.Open, FileAccess.Read)) // Using FileStream to support NetStandard 1.3 { using (var streamReader = new StreamReader(fileStream)) { token = streamReader.ReadToEnd(); } } break; } catch (Exception e) { if (retry == AWSSDKUtils.DefaultMaxRetry) { _logger.Debug(e, $"A token could not be loaded from the WebIdentityTokenFile at {WebIdentityTokenFile}."); throw new InvalidOperationException("A token could not be loaded from the WebIdentityTokenFile.", e); } DefaultRetryPolicy.WaitBeforeRetry(retry, 1000); } } AssumeRoleImmutableCredentials credentials; using (var coreStsClient = CreateClient()) { credentials = coreStsClient.CredentialsFromAssumeRoleWithWebIdentityAuthentication(token, RoleArn, RoleSessionName, _options); // Will retry InvalidIdentityToken and IDPCommunicationError } _logger.InfoFormat("New credentials created using assume role with web identity that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture)); return new CredentialsRefreshState(credentials, credentials.Expiration); } #if AWS_ASYNC_API protected override async Task<CredentialsRefreshState> GenerateNewCredentialsAsync() { string token = null; for (var retry = 0; retry <= AWSSDKUtils.DefaultMaxRetry; retry++) { try { using (var fileStream = new FileStream(WebIdentityTokenFile, FileMode.Open, FileAccess.Read)) // Using FileStream to support NetStandard 1.3 { using (var streamReader = new StreamReader(fileStream)) { token = await streamReader.ReadToEndAsync().ConfigureAwait(false); } } break; } catch (Exception e) { if (retry == AWSSDKUtils.DefaultMaxRetry) { _logger.Debug(e, $"A token could not be loaded from the WebIdentityTokenFile at {WebIdentityTokenFile}."); throw new InvalidOperationException("A token could not be loaded from the WebIdentityTokenFile.", e); } DefaultRetryPolicy.WaitBeforeRetry(retry, 1000); } } AssumeRoleImmutableCredentials credentials; using (var coreStsClient = CreateClient()) { credentials = await coreStsClient.CredentialsFromAssumeRoleWithWebIdentityAuthenticationAsync(token, RoleArn, RoleSessionName, _options).ConfigureAwait(false); // Will retry InvalidIdentityToken and IDPCommunicationError } _logger.InfoFormat("New credentials created using assume role with web identity that expire at {0}", credentials.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture)); return new CredentialsRefreshState(credentials, credentials.Expiration); } #endif /// <summary> /// Gets a client to be used for AssumeRoleWithWebIdentity requests. /// </summary> /// <returns>The STS client.</returns> protected virtual ICoreAmazonSTS_WebIdentity CreateClient() { var region = FallbackRegionFactory.GetRegionEndpoint() ?? _defaultSTSClientRegion; try { var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME); stsConfig.RegionEndpoint = region; if (_options?.ProxySettings != null) { stsConfig.SetWebProxy(_options.ProxySettings); } return ServiceClientHelpers.CreateServiceFromAssembly<ICoreAmazonSTS_WebIdentity>( ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, new AnonymousAWSCredentials(), region); } 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 Amazon.Runtime.AssumeRoleAWSCredentials.", ServiceClientHelpers.STS_ASSEMBLY_NAME); throw new InvalidOperationException(msg, e); } } } }
242
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.Net; namespace Amazon.Runtime { /// <summary> /// Options for using a credentials object to make AssumeRoleWithWebIdentity calls. /// </summary> public class AssumeRoleWithWebIdentityCredentialsOptions { /// <summary> /// Gets and sets the property DurationSeconds. /// <para> /// The duration, in seconds, of the role session. The value can range from 900 seconds /// (15 minutes) up to the maximum session duration setting for the role. This setting /// can have a value from 1 hour to 12 hours. If you specify a value higher than this /// setting, the operation fails. For example, if you specify a session duration of 12 /// hours, but your administrator set the maximum session duration to 6 hours, your operation /// fails. To learn how to view the maximum value for your role, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session">View /// the Maximum Session Duration Setting for a Role</a> in the <i>IAM User Guide</i>. /// </para> /// /// <para> /// By default, the value is set to <code>3600</code> seconds. /// </para> /// <note> /// <para> /// The <code>DurationSeconds</code> parameter is separate from the duration of a console /// session that you might request using the returned credentials. The request to the /// federation endpoint for a console sign-in token takes a <code>SessionDuration</code> /// parameter that specifies the maximum length of the console session. For more information, /// see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html">Creating /// a URL that Enables Federated Users to Access the AWS Management Console</a> in the /// <i>IAM User Guide</i>. /// </para> /// </note> /// </summary> public int? DurationSeconds { get; set; } /// <summary> /// Gets and sets the property ProviderId. /// <para> /// The fully qualified host component of the domain name of the identity provider. /// </para> /// /// <para> /// Specify this value only for OAuth 2.0 access tokens. Currently <code>www.amazon.com</code> /// and <code>graph.facebook.com</code> are the only supported identity providers for /// OAuth 2.0 access tokens. Do not include URL schemes and port numbers. /// </para> /// /// <para> /// Do not specify this value for OpenID Connect ID tokens. /// </para> /// </summary> public string ProviderId { get; set; } /// <summary> /// Gets and sets the property Policy. /// <para> /// An IAM policy in JSON format that you want to use as an inline session policy. /// </para> /// /// <para> /// This parameter is optional. Passing policies to this operation returns new temporary /// credentials. The resulting session's permissions are the intersection of the role's /// identity-based policy and the session policies. You can use the role's temporary credentials /// in subsequent AWS API calls to access resources in the account that owns the role. /// You cannot use session policies to grant more permissions than those allowed by the /// identity-based policy of the role that is being assumed. For more information, see /// <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session">Session /// Policies</a> in the <i>IAM User Guide</i>. /// </para> /// /// <para> /// The plain text that you use for both inline and managed session policies shouldn't /// exceed 2048 characters. The JSON policy characters can be any ASCII character from /// the space character to the end of the valid character list (\u0020 through \u00FF). /// It can also include the tab (\u0009), linefeed (\u000A), and carriage return (\u000D) /// characters. /// </para> /// <note> /// <para> /// The characters in this parameter count towards the 2048 character session policy guideline. /// However, an AWS conversion compresses the session policies into a packed binary format /// that has a separate limit. This is the enforced limit. The <code>PackedPolicySize</code> /// response element indicates by percentage how close the policy is to the upper size /// limit. /// </para> /// </note> /// </summary> public string Policy { get; set; } /// <summary> /// Gets and sets the property PolicyArns. /// <para> /// The Amazon Resource Names (ARNs) of the IAM managed policies that you want to use /// as managed session policies. The policies must exist in the same account as the role. /// </para> /// /// <para> /// This parameter is optional. You can provide up to 10 managed policy ARNs. However, /// the plain text that you use for both inline and managed session policies shouldn't /// exceed 2048 characters. For more information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon /// Resource Names (ARNs) and AWS Service Namespaces</a> in the AWS General Reference. /// </para> /// <note> /// <para> /// The characters in this parameter count towards the 2048 character session policy guideline. /// However, an AWS conversion compresses the session policies into a packed binary format /// that has a separate limit. This is the enforced limit. The <code>PackedPolicySize</code> /// response element indicates by percentage how close the policy is to the upper size /// limit. /// </para> /// </note> /// <para> /// Passing policies to this operation returns new temporary credentials. The resulting /// session's permissions are the intersection of the role's identity-based policy and /// the session policies. You can use the role's temporary credentials in subsequent AWS /// API calls to access resources in the account that owns the role. You cannot use session /// policies to grant more permissions than those allowed by the identity-based policy /// of the role that is being assumed. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session">Session /// Policies</a> in the <i>IAM User Guide</i>. /// </para> /// </summary> public List<string> PolicyArns { get; set; } /// <summary> /// The proxy settings to use when calling AssumeRoleWithWebIdentity. /// <para> /// This parameter is optional. /// </para> /// </summary> #if BCL public WebProxy ProxySettings { get; set; } #elif NETSTANDARD public IWebProxy ProxySettings { get; set; } #endif } }
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. */ namespace Amazon.Runtime { /// <summary> /// Abstract class that represents a credentials object for AWS services. /// </summary> public abstract class AWSCredentials { /// <summary> /// Returns a copy of ImmutableCredentials /// </summary> /// <returns></returns> public abstract ImmutableCredentials GetCredentials(); /// <summary> /// Called by AmazonServiceClient to validate the credential state /// on client construction. /// </summary> protected virtual void Validate() { } #if AWS_ASYNC_API public virtual System.Threading.Tasks.Task<ImmutableCredentials> GetCredentialsAsync() { return System.Threading.Tasks.Task.FromResult<ImmutableCredentials>(this.GetCredentials()); } #endif } }
43
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; namespace Amazon.Runtime { /// <summary> /// Basic set of credentials consisting of an AccessKey and SecretKey /// </summary> public class BasicAWSCredentials : AWSCredentials { #region Private members private ImmutableCredentials _credentials; #endregion #region Constructors /// <summary> /// Constructs a BasicAWSCredentials object for the specified accessKey and secretKey. /// </summary> /// <param name="accessKey"></param> /// <param name="secretKey"></param> public BasicAWSCredentials(string accessKey, string secretKey) { if (!string.IsNullOrEmpty(accessKey)) { _credentials = new ImmutableCredentials(accessKey, secretKey, null); } } #endregion #region Abstract class overrides /// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { if (this._credentials == null) return null; return _credentials.Copy(); } #endregion public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; var bac = obj as BasicAWSCredentials; if (bac == null) return false; return AWSSDKUtils.AreEqual( new object[] { _credentials }, new object[] { bac._credentials }); } public override int GetHashCode() { return Hashing.Hash(_credentials); } } }
88
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 { /// <summary> /// State class passed on callback to demand user credentials when authentication /// needs to be performed using a non-default identity. /// </summary> public class CredentialRequestCallbackArgs { /// <summary> /// If the current authentication callback is associated with /// a credential profile, this can be used to give the user /// some context on the request for his/her authentication. /// </summary> public string ProfileName { get; internal set; } /// <summary> /// Contains the user identity that the user should supply a password /// for. The user can ignore if they choose and return credentials for /// an alternate account. /// </summary> public string UserIdentity { get; internal set; } /// <summary> /// Any custom state that was registered with the callback. /// </summary> public object CustomState { get; internal set; } /// <summary> /// Set if the callback was due to a failed authentication attempt. /// If false we are beginning to obtain or refresh credentials. /// </summary> public bool PreviousAuthenticationFailed { get; internal set; } } }
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. */ using Amazon.Runtime.Internal.Util; using Amazon.Util; using System; using System.Globalization; using System.Threading; #if AWS_ASYNC_API using System.Threading.Tasks; #endif namespace Amazon.Runtime { /// <summary> /// InstanceProfileAWSCredentials allows configuring Roles and every instance hits IMDS individually. /// This class has a singleton timer task that caches instance profile credentials every 2 minutes. /// </summary> internal class DefaultInstanceProfileAWSCredentials : AWSCredentials, IDisposable { private static readonly object _instanceLock = new object(); private readonly ReaderWriterLockSlim _credentialsLock = new ReaderWriterLockSlim(); // Lock to control getting credentials across multiple threads. private readonly Timer _credentialsRetrieverTimer; private RefreshingAWSCredentials.CredentialsRefreshState _lastRetrievedCredentials; private Logger _logger; private static readonly TimeSpan _neverTimespan = TimeSpan.FromMilliseconds(-1); private static readonly TimeSpan _refreshRate = TimeSpan.FromMinutes(2); // EC2 refreshes credentials 5 min before expiration private const string FailedToGetCredentialsMessage = "Failed to retrieve credentials from EC2 Instance Metadata Service."; private static readonly TimeSpan _credentialsLockTimeout = TimeSpan.FromSeconds(5); /// <summary> /// Control flag: in the event IMDS returns an expired credential, a refresh must be immediately /// retried, if it continues to fail, then retry every 5-10 minutes. /// </summary> private static volatile bool _imdsRefreshFailed = false; private const string _usingExpiredCredentialsFromIMDS = "Attempting credential expiration extension due to a credential service availability issue. " + "A refresh of these credentials will be attempted again in 5-10 minutes."; private static DefaultInstanceProfileAWSCredentials _instance; public static DefaultInstanceProfileAWSCredentials Instance { get { CheckIsIMDSEnabled(); if (_instance == null) { lock (_instanceLock) { if (_instance == null) { _instance = new DefaultInstanceProfileAWSCredentials(); } } } return _instance; } } private DefaultInstanceProfileAWSCredentials() { // if IMDS is turned off, no need to spin up the timer task if (!EC2InstanceMetadata.IsIMDSEnabled) return; _logger = Logger.GetLogger(typeof(DefaultInstanceProfileAWSCredentials)); _credentialsRetrieverTimer = new Timer(RenewCredentials, null, TimeSpan.Zero, _neverTimespan); } #region Overrides /// <summary> /// Returns a copy of the most recent instance profile credentials. /// </summary> public override ImmutableCredentials GetCredentials() { CheckIsIMDSEnabled(); ImmutableCredentials credentials = null; // Try to acquire read lock. The thread would be blocked if another thread has write lock. if (_credentialsLock.TryEnterReadLock(_credentialsLockTimeout)) { try { if (null != _lastRetrievedCredentials) { if (_lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero) && !_imdsRefreshFailed) { // this is the first failure - immediately try to renew _imdsRefreshFailed = true; _lastRetrievedCredentials = FetchCredentials(); } // if credentials are expired, we'll still return them, but log a message about // them being expired. if (_lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero)) { _logger.InfoFormat(_usingExpiredCredentialsFromIMDS); } else { _imdsRefreshFailed = false; } return _lastRetrievedCredentials?.Credentials.Copy(); } } finally { _credentialsLock.ExitReadLock(); } } // If there's no credentials cached, hit IMDS directly. Try to acquire write lock. if (_credentialsLock.TryEnterWriteLock(_credentialsLockTimeout)) { try { // Check for last retrieved credentials again in case other thread might have already fetched it. if (null == _lastRetrievedCredentials) { _lastRetrievedCredentials = FetchCredentials(); } if (_lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero) && !_imdsRefreshFailed) { // this is the first failure - immediately try to renew _imdsRefreshFailed = true; _lastRetrievedCredentials = FetchCredentials(); } // if credentials are expired, we'll still return them, but log a message about // them being expired. if (_lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero)) { _logger.InfoFormat(_usingExpiredCredentialsFromIMDS); } else { _imdsRefreshFailed = false; } credentials = _lastRetrievedCredentials.Credentials?.Copy(); } finally { _credentialsLock.ExitWriteLock(); } } if (credentials == null) { throw new AmazonServiceException(FailedToGetCredentialsMessage); } return credentials; } #if AWS_ASYNC_API /// <summary> /// Returns a copy of the most recent instance profile credentials. /// </summary> public override Task<ImmutableCredentials> GetCredentialsAsync() { return Task.FromResult<ImmutableCredentials>(GetCredentials()); } #endif #endregion #region Private members private void RenewCredentials(object unused) { // By default, the refreshRate will continue to be // _refreshRate, but if FetchCredentials() returns an expired credential, // the refresh rate will be adjusted var refreshRate = _refreshRate; try { // if FetchCredentials() call were to fail, _lastRetrievedCredentials // would remain unchanged and would continue to be returned in GetCredentials() _lastRetrievedCredentials = FetchCredentials(); // check for a first time failure if (!_imdsRefreshFailed && _lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero)) { // this is the first failure - immediately try to renew _imdsRefreshFailed = true; _lastRetrievedCredentials = FetchCredentials(); } // first failure refresh failed OR subsequent refresh failed. if (_lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero)) { // relax the refresh rate to at least 5 minutes refreshRate = TimeSpan.FromMinutes(new Random().Next(5, 11)); } else { _imdsRefreshFailed = false; } } catch (OperationCanceledException e) { _logger.Error(e, "RenewCredentials task canceled"); } catch (Exception e) { // we want to suppress any exceptions from this timer task. _logger.Error(e, FailedToGetCredentialsMessage); } finally { // re-invoke this task once after time specified by refreshRate set at beginning of this method _credentialsRetrieverTimer.Change(refreshRate, _neverTimespan); } } private static RefreshingAWSCredentials.CredentialsRefreshState FetchCredentials() { var securityCredentials = EC2InstanceMetadata.IAMSecurityCredentials; if (securityCredentials == null) throw new AmazonServiceException("Unable to get IAM security credentials from EC2 Instance Metadata Service."); string firstRole = null; foreach (var role in securityCredentials.Keys) { firstRole = role; break; } if (string.IsNullOrEmpty(firstRole)) throw new AmazonServiceException("Unable to get EC2 instance role from EC2 Instance Metadata Service."); var metadata = securityCredentials[firstRole]; if (metadata == null) throw new AmazonServiceException("Unable to get credentials for role \"" + firstRole + "\" from EC2 Instance Metadata Service."); return new RefreshingAWSCredentials.CredentialsRefreshState( new ImmutableCredentials(metadata.AccessKeyId, metadata.SecretAccessKey, metadata.Token), metadata.Expiration); } private static void CheckIsIMDSEnabled() { // keep this behavior consistent with GetObjectFromResponse case. if (!EC2InstanceMetadata.IsIMDSEnabled) throw new AmazonServiceException("Unable to retrieve credentials."); } #endregion #region IDisposable Support private bool _isDisposed = false; protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { lock (_instanceLock) { _credentialsRetrieverTimer.Dispose(); _logger = null; _instance = null; } } _isDisposed = true; } } /// <summary> /// Dispose this object and all related resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
302
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.Globalization; using System.Net; namespace Amazon.Runtime { /// <summary> /// When running in an ECS container and AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set, /// use the given end point to retrieve the credentials. /// </summary> public class ECSTaskCredentials : URIBasedRefreshingCredentialHelper { /// <summary> /// These constants should not be consumed by client code. They are only relevant /// in the context of ECS container and, especially, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, AWS_CONTAINER_CREDENTIALS_FULL_URI & AWS_CONTAINER_AUTHORIZATION_TOKEN /// environment variable should not be overriden by the client code. /// </summary> public const string ContainerCredentialsURIEnvVariable = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; public const string ContainerCredentialsFullURIEnvVariable = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; public const string ContainerCredentialsAuthorizationTokenEnvVariable = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; public const string EndpointAddress = "http://169.254.170.2"; private Uri Uri { get { var relativeUri = Environment.GetEnvironmentVariable(ContainerCredentialsURIEnvVariable); var fullUri = Environment.GetEnvironmentVariable(ContainerCredentialsFullURIEnvVariable); // AWS_CONTAINER_CREDENTIALS_FULL_URI variable is not compatible with AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, and will not be used if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set. if (!string.IsNullOrEmpty(relativeUri)) { var uriBuilder = new UriBuilder(Server); uriBuilder.Path = relativeUri; return uriBuilder.Uri; } else if (!string.IsNullOrEmpty(fullUri)) { return new Uri(fullUri); } else { throw new ArgumentException($"Cannot fetch credentials from container - neither {ContainerCredentialsURIEnvVariable} or {ContainerCredentialsFullURIEnvVariable}" + $" environment variables are set."); } } } private string Server = null; private static int MaxRetries = 5; private IWebProxy Proxy; public ECSTaskCredentials() : this(null) { PreemptExpiryTime = TimeSpan.FromMinutes(5); } public ECSTaskCredentials(IWebProxy proxy) { Server = EndpointAddress; Proxy = proxy; PreemptExpiryTime = TimeSpan.FromMinutes(5); } protected override CredentialsRefreshState GenerateNewCredentials() { SecurityCredentials credentials = null; Uri ecsEndpointUri = Uri; JitteredDelay retry = new JitteredDelay(new TimeSpan(0, 0, 0, 0, 200), new TimeSpan(0, 0, 0, 0, 50)); // Attempt to get the credentials 4 times ignoring null return/exceptions and on the 5th try, escalate the exception if there is one. for (int i = 1; ; i++) { try { // AWS_CONTAINER_AUTHORIZATION_TOKEN is optional environment variable // If this variable is set the SDK will set the Authorization header on the HTTP request with the environment variable's value. var headers = CreateAuthorizationHeader(); credentials = GetObjectFromResponse<SecurityCredentials>(ecsEndpointUri, Proxy, headers); if (credentials != null) { break; } } catch (Exception e) { if (i == MaxRetries) { throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Unable to retrieve credentials. Message = \"{0}\".", e.Message)); } }; Util.AWSSDKUtils.Sleep(retry.Next()); } return new CredentialsRefreshState(new ImmutableCredentials(credentials.AccessKeyId, credentials.SecretAccessKey, credentials.Token), credentials.Expiration); } private static Dictionary<string, string> CreateAuthorizationHeader() { Dictionary<string, string> headers = null; var authorizationToken = Environment.GetEnvironmentVariable(ContainerCredentialsAuthorizationTokenEnvVariable); if (!string.IsNullOrEmpty(authorizationToken)) { headers = new Dictionary<string, string> { {HeaderKeys.AuthorizationHeader, authorizationToken} }; } return headers; } } }
129
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.Globalization; namespace Amazon.Runtime { /// <summary> /// Uses aws credentials stored in environment variables to construct the credentials object. /// AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are used for the access key id and secret key. /// If the variable AWS_SESSION_TOKEN exists then it will be used to create temporary session /// credentials. /// </summary> /// <remarks> /// For backwards compatibility the class will also attempt to discover the secret key from /// the AWS_SECRET_KEY variable, if a value cannot be obtained using the standard /// AWS_SECRET_ACCESS_KEY variable. /// </remarks> public class EnvironmentVariablesAWSCredentials : AWSCredentials { // these variable names are standard across all AWS SDKs that support reading keys from // environment variables public const string ENVIRONMENT_VARIABLE_ACCESSKEY = "AWS_ACCESS_KEY_ID"; public const string ENVIRONMENT_VARIABLE_SECRETKEY = "AWS_SECRET_ACCESS_KEY"; public const string ENVIRONMENT_VARIABLE_SESSION_TOKEN = "AWS_SESSION_TOKEN"; // this legacy key was used by previous versions of the AWS SDK for .NET and is // used if no value exists for the standard key for backwards compatibility. public const string LEGACY_ENVIRONMENT_VARIABLE_SECRETKEY = "AWS_SECRET_KEY"; private Logger logger; #region Public constructors /// <summary> /// Constructs an instance of EnvironmentVariablesAWSCredentials. If no credentials are found in /// the environment variables then an InvalidOperationException is thrown. /// </summary> public EnvironmentVariablesAWSCredentials() { logger = Logger.GetLogger(typeof(EnvironmentVariablesAWSCredentials)); // We need to do an initial fetch to validate that we can use environment variables to get the credentials. FetchCredentials(); } #endregion /// <summary> /// Creates immutable credentials from environment variables. /// </summary> /// <returns></returns> public ImmutableCredentials FetchCredentials() { string accessKeyId = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_ACCESSKEY); string secretKey = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_SECRETKEY); if (string.IsNullOrEmpty(secretKey)) { secretKey = Environment.GetEnvironmentVariable(LEGACY_ENVIRONMENT_VARIABLE_SECRETKEY); if (!string.IsNullOrEmpty(secretKey)) logger.InfoFormat("AWS secret key found using legacy and non-standard environment variable '{0}', consider updating to the cross-SDK standard variable '{1}'.", LEGACY_ENVIRONMENT_VARIABLE_SECRETKEY, ENVIRONMENT_VARIABLE_SECRETKEY); } if (string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(secretKey)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The environment variables {0}/{1}/{2} were not set with AWS credentials.", ENVIRONMENT_VARIABLE_ACCESSKEY, ENVIRONMENT_VARIABLE_SECRETKEY, ENVIRONMENT_VARIABLE_SESSION_TOKEN)); } string sessionToken = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_SESSION_TOKEN); logger.InfoFormat("Credentials found using environment variables."); return new ImmutableCredentials(accessKeyId, secretKey, sessionToken); } /// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { return FetchCredentials(); } } }
102
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.Internal.Util; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Security; namespace Amazon.Runtime { // Credentials fallback mechanism public static class FallbackCredentialsFactory { internal const string AWS_PROFILE_ENVIRONMENT_VARIABLE = "AWS_PROFILE"; internal const string DefaultProfileName = "default"; private static readonly CredentialProfileStoreChain credentialProfileChain = new CredentialProfileStoreChain(); static FallbackCredentialsFactory() { Reset(); } public delegate AWSCredentials CredentialsGenerator(); public static List<CredentialsGenerator> CredentialsGenerators { get; set; } public static void Reset() { Reset(null); } public static void Reset(IWebProxy proxy) { cachedCredentials = null; CredentialsGenerators = new List<CredentialsGenerator> { #if BCL () => new AppConfigAWSCredentials(), // Test explicit keys/profile name first. #endif () => AssumeRoleWithWebIdentityCredentials.FromEnvironmentVariables(), // Attempt to load the default profile. It could be Basic, Session, AssumeRole, or SAML. () => GetAWSCredentials(credentialProfileChain), () => new EnvironmentVariablesAWSCredentials(), // Look for credentials set in environment vars. () => ECSEC2CredentialsWrapper(proxy), // either get ECS credentials or instance profile credentials }; } internal static string GetProfileName() { var profileName = AWSConfigs.AWSProfileName; if (string.IsNullOrEmpty(profileName?.Trim())) profileName = Environment.GetEnvironmentVariable(AWS_PROFILE_ENVIRONMENT_VARIABLE); if (string.IsNullOrEmpty(profileName?.Trim())) profileName = DefaultProfileName; return profileName; } private static AWSCredentials GetAWSCredentials(ICredentialProfileSource source) { var profileName = GetProfileName(); CredentialProfile profile; if (source.TryGetProfile(profileName, out profile)) return profile.GetAWSCredentials(source, true); throw new AmazonClientException("Unable to find the '" + profileName + "' profile in CredentialProfileStoreChain."); } /// If either AWS_CONTAINER_CREDENTIALS_RELATIVE_URI or AWS_CONTAINER_CREDENTIALS_FULL_URI environment variables are set, we want to attempt to retrieve credentials /// using ECS endpoint instead of referring to instance profile credentials. private static AWSCredentials ECSEC2CredentialsWrapper() { return ECSEC2CredentialsWrapper(null); } /// If either AWS_CONTAINER_CREDENTIALS_RELATIVE_URI or AWS_CONTAINER_CREDENTIALS_FULL_URI environment variables are set, we want to attempt to retrieve credentials /// using ECS endpoint instead of referring to instance profile credentials. private static AWSCredentials ECSEC2CredentialsWrapper(IWebProxy proxy) { try { var relativeUri = Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable); if (!string.IsNullOrEmpty(relativeUri)) { return new ECSTaskCredentials(proxy); } var fullUri = Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsFullURIEnvVariable); if (!string.IsNullOrEmpty(fullUri)) { return new ECSTaskCredentials(proxy); } } catch (SecurityException e) { Logger.GetLogger(typeof(ECSTaskCredentials)).Error(e, $"Failed to access environment variables {ECSTaskCredentials.ContainerCredentialsURIEnvVariable} and {ECSTaskCredentials.ContainerCredentialsFullURIEnvVariable}." + $" Either {ECSTaskCredentials.ContainerCredentialsURIEnvVariable} or {ECSTaskCredentials.ContainerCredentialsFullURIEnvVariable} environment variables must be set."); } return DefaultInstanceProfileAWSCredentials.Instance; } private static AWSCredentials cachedCredentials; public static AWSCredentials GetCredentials() { return GetCredentials(false); } public static AWSCredentials GetCredentials(bool fallbackToAnonymous) { if (cachedCredentials != null) return cachedCredentials; List<Exception> errors = new List<Exception>(); foreach (CredentialsGenerator generator in CredentialsGenerators) { try { cachedCredentials = generator(); } // Breaking the FallbackCredentialFactory chain in case a ProcessAWSCredentialException exception // is encountered. ProcessAWSCredentialException is thrown by the ProcessAWSCredential provider // when an exception is encountered when running a user provided process to obtain Basic/Session // credentials. The motivation behind this is that, if the user has provided a process to be run // he expects to use the credentials obtained by running the process. Therefore the exception is // surfaced to the user. catch (ProcessAWSCredentialException) { throw; } catch (Exception e) { cachedCredentials = null; errors.Add(e); } if (cachedCredentials != null) break; } if (cachedCredentials == null) { if (fallbackToAnonymous) { return new AnonymousAWSCredentials(); } using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { writer.WriteLine("Unable to find credentials"); writer.WriteLine(); for (int i = 0; i < errors.Count; i++) { Exception e = errors[i]; writer.WriteLine("Exception {0} of {1}:", i + 1, errors.Count); writer.WriteLine(e.ToString()); writer.WriteLine(); } throw new AmazonServiceException(writer.ToString()); } } return cachedCredentials; } } }
185
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> /// Custom exception type thrown when a role profile with user identity is used /// in conjunction with a credential request callback. This exception is thrown /// if the callback returns null, indicating the user declined to supply credentials. /// </summary> #if !NETSTANDARD [Serializable] #endif public class FederatedAuthenticationCancelledException : Exception { /// <summary> /// Initializes a new exception instance. /// </summary> /// <param name="msg"></param> public FederatedAuthenticationCancelledException(string msg) : base(msg) { } /// <summary> /// Initializes a new exception instance. /// </summary> /// <param name="msg"></param> /// <param name="inner"></param> public FederatedAuthenticationCancelledException(string msg, Exception inner) : base(msg, inner) { } #if !NETSTANDARD /// <summary> /// Constructs a new instance of the FederatedAuthenticationCancelledException 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 FederatedAuthenticationCancelledException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
63
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> /// Custom exception type thrown when authentication for a user fails due to /// invalid credentials. /// </summary> #if !NETSTANDARD [Serializable] #endif public class FederatedAuthenticationFailureException : Exception { /// <summary> /// Initializes a new exception instance. /// </summary> /// <param name="msg"></param> public FederatedAuthenticationFailureException(string msg) : base(msg) { } /// <summary> /// Initializes a new exception instance. /// </summary> /// <param name="msg"></param> /// <param name="inner"></param> public FederatedAuthenticationFailureException(string msg, Exception inner) : base(msg, inner) { } #if !NETSTANDARD /// <summary> /// Constructs a new instance of the FederatedAuthenticationFailureException 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 FederatedAuthenticationFailureException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
62
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.Internal; using Amazon.Runtime.CredentialManagement.Internal; using Amazon.Runtime.Internal.Util; using Amazon.Runtime.SharedInterfaces; using Amazon.Util; using System; using System.Collections.Generic; 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> /// In order to use the FederatedAWSCredentials class the AWSSDK.SecurityToken assembly /// must be available to your application at runtime. /// </remarks> public class FederatedAWSCredentials : RefreshingAWSCredentials { private const int MaxAuthenticationRetries = 3; private static readonly RegionEndpoint DefaultSTSClientRegion = RegionEndpoint.USEast1; private static readonly TimeSpan MaximumCredentialTimespan = TimeSpan.FromHours(1); private static readonly TimeSpan DefaultPreemptExpiryTime = TimeSpan.FromMinutes(5); private readonly SAMLRoleSessionManager sessionManager = new SAMLRoleSessionManager(); /// <summary> /// Constructs an instance of FederatedAWSCredentials. After construction call GetCredentials /// to authenticate the user/process and obtain temporary AWS credentials. /// </summary> /// <param name="samlEndpoint">The SAML endpoint used for authentication.</param> /// <param name="roleArn">The role ARN used for authentication.</param> public FederatedAWSCredentials(SAMLEndpoint samlEndpoint, string roleArn) : this(samlEndpoint, roleArn, new FederatedAWSCredentialsOptions()) { } /// <summary> /// Constructs an instance of FederatedAWSCredentials. After construction call GetCredentials /// to authenticate the user/process and obtain temporary AWS credentials. /// </summary> /// <param name="samlEndpoint">The SAML endpoint used for authentication.</param> /// <param name="roleArn">The role ARN used for authentication.</param> /// <param name="options">The options used for authentication. /// See <see cref="FederatedAWSCredentialsOptions"/> for details about available options.</param> public FederatedAWSCredentials(SAMLEndpoint samlEndpoint, string roleArn, FederatedAWSCredentialsOptions options) { if (string.IsNullOrEmpty(roleArn)) { throw new ArgumentException("RoleArn must not be null or empty."); } Options = options ?? throw new ArgumentNullException("options"); SAMLEndpoint = samlEndpoint ?? throw new ArgumentNullException("samlEndpoint"); RoleArn = roleArn; PreemptExpiryTime = DefaultPreemptExpiryTime; } /// <summary> /// The SAML Endpoint used for authentication. /// </summary> public SAMLEndpoint SAMLEndpoint { get; private set; } /// <summary> /// The role ARN used for authentication. /// </summary> public string RoleArn { get; private set; } /// <summary> /// The options used for authentication. /// See <see cref="FederatedAWSCredentialsOptions"/> for details about available options. /// </summary> public FederatedAWSCredentialsOptions Options { get; private set; } /// <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(); // If the profile indicates the user has already authenticated and received // credentials which are still valid, adopt them instead of requiring a fresh // authentication. SAMLImmutableCredentials currentSession; if (TryGetRoleSession(out currentSession)) { // Since cached role session credentials can be obtained, stored credentials exist // and they were not expired. However, since the stored credentials are actual // expiration time and not preempt expiration time we must preempt the expiration // to check that they will not expire before this call completes. var cachedState = new CredentialsRefreshState(currentSession, currentSession.Expires); // Use the cached credentials as long as they are not within the preempt expiry window // or have since actually expired since the prior call to TryGetRoleSession. //Verify the actual expiration is not within the preempt expiration time. if (!cachedState.IsExpiredWithin(PreemptExpiryTime)) { // The credentials have plenty of time left before they expire so they can be used. After // return the expiration time will be preempted for future checks using ShouldUpdate. return cachedState; } } CredentialsRefreshState newState = null; var attempts = 0; do { try { NetworkCredential userCredential = null; if (Options.UserIdentity != null) { if (Options.CredentialRequestCallback != null) { var callbackArgs = new CredentialRequestCallbackArgs { ProfileName = Options.ProfileName, UserIdentity = Options.UserIdentity, CustomState = Options.CustomCallbackState, PreviousAuthenticationFailed = attempts > 0 }; userCredential = Options.CredentialRequestCallback(callbackArgs); if (userCredential == null) // user declined to authenticate { throw new FederatedAuthenticationCancelledException( "User cancelled credential request."); } } else { var logger = Logger.GetLogger(typeof(FederatedAWSCredentials)); logger.InfoFormat( "FederatedAWSCredentials configured for a specific user but no credential request callback registered; falling back to default identity."); } } newState = Authenticate(userCredential); } catch (FederatedAuthenticationFailureException) { if (attempts < MaxAuthenticationRetries) attempts++; else throw; } } while (newState == null && attempts < MaxAuthenticationRetries); return newState; } private CredentialsRefreshState Authenticate(ICredentials userCredential) { CredentialsRefreshState state; var region = Options.STSRegion; if (region == null) { region = FallbackRegionFactory.GetRegionEndpoint(); } if (region == null) { region = DefaultSTSClientRegion; } ICoreAmazonSTS coreSTSClient = null; try { var stsConfig = ServiceClientHelpers.CreateServiceConfig( ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME); stsConfig.RegionEndpoint = region; if (Options.ProxySettings != null) { stsConfig.SetWebProxy(Options.ProxySettings); } coreSTSClient = ServiceClientHelpers.CreateServiceFromAssembly<ICoreAmazonSTS>( ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, 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); } var samlCoreSTSClient #if NETSTANDARD = coreSTSClient as ICoreAmazonSTS_SAML; if (coreSTSClient == null) { throw new NotImplementedException("The currently loaded version of AWSSDK.SecurityToken doesn't support SAML authentication."); } #else = coreSTSClient; #endif try { var credentials = samlCoreSTSClient.CredentialsFromSAMLAuthentication( SAMLEndpoint.EndpointUri.ToString(), SAMLEndpoint.AuthenticationType.ToString(), RoleArn, MaximumCredentialTimespan, userCredential); RegisterRoleSession(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(FederatedAWSCredentials)); logger.Error(wrappedException, wrappedException.Message); throw wrappedException; } return state; } private string GetRoleSessionName() { if (string.IsNullOrEmpty(Options.ProfileName)) { return SAMLEndpoint.Name + "," + RoleArn + "," + Options.UserIdentity; } else { return Options.ProfileName; } } private bool TryGetRoleSession(out SAMLImmutableCredentials sessionCredentials) { if (SAMLRoleSessionManager.IsAvailable) { return sessionManager.TryGetRoleSession(GetRoleSessionName(), out sessionCredentials); } else { sessionCredentials = null; return false; } } private void RegisterRoleSession(SAMLImmutableCredentials sessionCredentials) { if (SAMLRoleSessionManager.IsAvailable) { sessionManager.RegisterRoleSession(GetRoleSessionName(), sessionCredentials); } } /// <summary> /// Clears currently-stored credentials, forcing the next GetCredentials call to generate new credentials. /// </summary> public override void ClearCredentials() { // For Federated AWS credentials, this method does not force the generation of new credentials. Even though // it clears the credential state to null, any cached credentials will immediately be picked up and used. // Changing this behavior is a possible breaking change. Once we decide to make this change, the proper course // of action would likely be to ensure the cache is cleared before setting the credential state to null. base.ClearCredentials(); } } }
296
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; namespace Amazon.Runtime { /// <summary> /// Options that control the behavior of <see cref="FederatedAWSCredentials"/>. /// </summary> public class FederatedAWSCredentialsOptions { private readonly object syncLock = new object(); private Func<CredentialRequestCallbackArgs, NetworkCredential> credentialRequestCallback; private object customCallbackState; private string userIdentity; private string profileName; private RegionEndpoint stsRegion; private WebProxy proxySettings; /// <summary> /// The identity to use when authenticating. /// This is in the form domain\username, or just username. /// If this option is not set, the current user's identity will be used. /// </summary> public string UserIdentity { get { lock(syncLock) { return userIdentity; } } set { lock(syncLock) { userIdentity = value; } } } /// <summary> /// <see cref="FederatedAWSCredentials"/> uses this callback to get credentials if the UserIdentity is set. /// </summary> public Func<CredentialRequestCallbackArgs, NetworkCredential> CredentialRequestCallback { get { lock (syncLock) { return credentialRequestCallback; } } set { lock (syncLock) { credentialRequestCallback = value; } } } /// <summary> /// When <see cref="FederatedAWSCredentials"/> makes a callback for credentials, /// this state will be included for use by the callback handler. /// </summary> public object CustomCallbackState { get { lock(syncLock) { return customCallbackState; } } set { lock(syncLock) { customCallbackState = value; } } } /// <summary> /// The proxy settings to use when calling the /// Secure Token Service and the ADFS endpoint. /// </summary> public WebProxy ProxySettings { get { lock (syncLock) { return proxySettings; } } set { lock (syncLock) { proxySettings = value; } } } /// <summary> /// Set this property when a region-specific STS endpoint must be used (eg cn-north-1). /// If left empty/null, the global sts.amazonaws.com endpoint will be used when credentials are obtained. /// </summary> public RegionEndpoint STSRegion { get { lock (syncLock) { return stsRegion; } } set { lock (syncLock) { stsRegion = value; } } } /// <summary> /// The profile name, if this FederatedAWSCredentialsOptions /// is associated with a CredentialProfile. /// </summary> public string ProfileName { get { lock (syncLock) { return profileName; } } set { lock (syncLock) { profileName = value; } } } } }
167
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. /// </summary> public class ImmutableCredentials { #region Properties /// <summary> /// Gets the AccessKey property for the current credentials. /// </summary> public string AccessKey { get; private set; } /// <summary> /// Gets the SecretKey property for the current credentials. /// </summary> public string SecretKey { get; private set; } /// <summary> /// Gets the Token property for the current credentials. /// </summary> public string Token { get; private set; } /// <summary> /// Gets the UseToken property for the current credentials. /// Specifies if Token property is non-empty. /// </summary> public bool UseToken { get { return !string.IsNullOrEmpty(Token); } } #endregion #region Constructors /// <summary> /// Constructs an ImmutableCredentials object with supplied accessKey, secretKey. /// </summary> /// <param name="awsAccessKeyId"></param> /// <param name="awsSecretAccessKey"></param> /// <param name="token">Optional. Can be set to null or empty for non-session credentials.</param> public ImmutableCredentials(string awsAccessKeyId, string awsSecretAccessKey, string token) { if (string.IsNullOrEmpty(awsAccessKeyId)) throw new ArgumentNullException("awsAccessKeyId"); if (string.IsNullOrEmpty(awsSecretAccessKey)) throw new ArgumentNullException("awsSecretAccessKey"); AccessKey = awsAccessKeyId; SecretKey = awsSecretAccessKey; Token = token ?? string.Empty; } private ImmutableCredentials() { } #endregion #region Public methods /// <summary> /// Returns a copy of the current credentials. /// </summary> /// <returns></returns> public virtual ImmutableCredentials Copy() { ImmutableCredentials credentials = new ImmutableCredentials { AccessKey = this.AccessKey, SecretKey = this.SecretKey, Token = this.Token, }; return credentials; } #endregion #region Overrides public override int GetHashCode() { return Hashing.Hash(AccessKey, SecretKey, Token); } public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; ImmutableCredentials ic = obj as ImmutableCredentials; if (ic == null) return false; return AWSSDKUtils.AreEqual( new object[] { AccessKey, SecretKey, Token }, new object[] { ic.AccessKey, ic.SecretKey, ic.Token }); } #endregion } }
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 Amazon.Runtime.Internal.Util; using Amazon.Util; using AWSSDK.Runtime.Internal.Util; using System; using System.Collections.Generic; using System.Globalization; using System.Net; namespace Amazon.Runtime { /// <summary> /// Credentials that are retrieved from the Instance Profile service on an EC2 instance /// </summary> /// <remarks> /// This is meant to be used when building a <see cref="AmazonServiceClient"/>, as opposed /// to <see cref="DefaultInstanceProfileAWSCredentials"/>, which is part of the /// <see cref="FallbackCredentialsFactory"/> chain. /// </remarks> public class InstanceProfileAWSCredentials : URIBasedRefreshingCredentialHelper { #region Private members // Set preempt expiry to 15 minutes. New access keys are available at least 15 minutes before expiry time. // http://docs.aws.amazon.com/IAM/latest/UserGuide/role-usecase-ec2app.html private static readonly TimeSpan _preemptExpiryTime = TimeSpan.FromMinutes(15); private static readonly TimeSpan _refreshAttemptPeriod = TimeSpan.FromHours(1); private CredentialsRefreshState _currentRefreshState = null; private readonly IWebProxy _proxy = null; private const string _receivedExpiredCredentialsFromIMDS = "Attempting credential expiration extension due to a credential service availability issue. " + "A refresh of these credentials will be attempted again in 5-10 minutes."; private Logger _logger; #endregion #region Properties /// <summary> /// Role for which the credentials are retrieved /// </summary> public string Role { get; set; } #endregion #region Overrides protected override CredentialsRefreshState GenerateNewCredentials() { CredentialsRefreshState newState = null; var token = EC2InstanceMetadata.FetchApiToken(); try { // Attempt to get early credentials. OK to fail at this point. newState = GetRefreshState(token); } catch (Exception e) { HttpStatusCode? httpStatusCode = ExceptionUtils.DetermineHttpStatusCode(e); if (httpStatusCode == HttpStatusCode.Unauthorized) { EC2InstanceMetadata.ClearTokenFlag(); Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "EC2 Metadata service returned unauthorized for token based secure data flow."); throw; } var logger = Logger.GetLogger(typeof(InstanceProfileAWSCredentials)); logger.InfoFormat("Error getting credentials from Instance Profile service: {0}", e); // if we already have cached credentials, we'll continue to use those credentials, // but try again to refresh them in 2 minutes. if (null != _currentRefreshState) { #pragma warning disable CS0612 // Type or member is obsolete var newExpiryTime = AWSSDKUtils.CorrectedUtcNow.ToLocalTime() + TimeSpan.FromMinutes(2); #pragma warning restore CS0612 // Type or member is obsolete _currentRefreshState = new CredentialsRefreshState(_currentRefreshState.Credentials.Copy(), newExpiryTime); return _currentRefreshState; } } if (newState?.IsExpiredWithin(TimeSpan.Zero) == true) { // special case - credentials returned are expired _logger.InfoFormat(_receivedExpiredCredentialsFromIMDS); // use a custom refresh time #pragma warning disable CS0612 // Type or member is obsolete var newExpiryTime = AWSSDKUtils.CorrectedUtcNow.ToLocalTime() + TimeSpan.FromMinutes(new Random().Next(5, 11)); #pragma warning restore CS0612 // Type or member is obsolete _currentRefreshState = new CredentialsRefreshState(newState.Credentials.Copy(), newExpiryTime); return _currentRefreshState; } // If successful, save new credentials if (newState != null) { _currentRefreshState = newState; } // If still not successful (no credentials available at start), attempt once more to // get credentials, but now without swallowing exception if (_currentRefreshState == null) { try { _currentRefreshState = GetRefreshState(token); } catch (Exception e) { HttpStatusCode? httpStatusCode = ExceptionUtils.DetermineHttpStatusCode(e); if (httpStatusCode == HttpStatusCode.Unauthorized) { EC2InstanceMetadata.ClearTokenFlag(); Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "EC2 Metadata service returned unauthorized for token based secure data flow."); } throw; } } // Return credentials that will expire in at most one hour CredentialsRefreshState state = GetEarlyRefreshState(_currentRefreshState); return state; } #endregion #region Constructors /// <summary> /// Constructs a InstanceProfileAWSCredentials object for specific role /// </summary> /// <param name="role">Role to use</param> public InstanceProfileAWSCredentials(string role) : this(role, null) { } /// <summary> /// Constructs a InstanceProfileAWSCredentials object for specific role /// </summary> /// <param name="role">Role to use</param> public InstanceProfileAWSCredentials(string role, IWebProxy proxy) { _logger = Logger.GetLogger(GetType()); this._proxy = proxy; if (role == null) throw new ArgumentNullException(nameof(role)); else if (IsNullOrWhiteSpace(role)) throw new ArgumentException("The argument '" + nameof(role) + "' must contain a valid role name."); Role = role; this.PreemptExpiryTime = _preemptExpiryTime; } /// <summary> /// Constructs a InstanceProfileAWSCredentials object for the first found role /// </summary> public InstanceProfileAWSCredentials() : this(proxy: null) { } /// <summary> /// Constructs a InstanceProfileAWSCredentials object for the first found role /// </summary> public InstanceProfileAWSCredentials(IWebProxy proxy) : this(GetFirstRole(proxy), proxy) { } #endregion #region Public static methods /// <summary> /// Retrieves a list of all roles available through current InstanceProfile service /// </summary> /// <returns></returns> public static IEnumerable<string> GetAvailableRoles() { return GetAvailableRoles(null); } /// <summary> /// Retrieves a list of all roles available through current InstanceProfile service /// </summary> /// <returns></returns> public static IEnumerable<string> GetAvailableRoles(IWebProxy proxy) { var token = EC2InstanceMetadata.FetchApiToken(); var allAliases = string.Empty; try { allAliases = GetContents(RolesUri, proxy, CreateMetadataTokenHeaders(token)); } catch (Exception e) { HttpStatusCode? httpStatusCode = ExceptionUtils.DetermineHttpStatusCode(e); if (httpStatusCode == HttpStatusCode.Unauthorized) { EC2InstanceMetadata.ClearTokenFlag(); Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "EC2 Metadata service returned unauthorized for token based secure data flow."); } throw; } if (string.IsNullOrEmpty(allAliases)) yield break; string[] parts = allAliases.Split(AliasSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) { var trim = part.Trim(); if (!string.IsNullOrEmpty(trim)) yield return trim; } } #endregion #region Private members private static string[] AliasSeparators = new string[] { "<br/>" }; private static string Server = EC2InstanceMetadata.ServiceEndpoint; private static string RolesPath = "/latest/meta-data/iam/security-credentials/"; private static string InfoPath = "/latest/meta-data/iam/info"; private static Uri RolesUri { get { return new Uri(Server + RolesPath); } } private Uri CurrentRoleUri { get { return new Uri(Server + RolesPath + Role); } } private static Uri InfoUri { get { return new Uri(Server + InfoPath); } } private CredentialsRefreshState GetEarlyRefreshState(CredentialsRefreshState state) { // New expiry time = Now + _refreshAttemptPeriod + PreemptExpiryTime #pragma warning disable CS0612 // Type or member is obsolete var newExpiryTime = AWSSDKUtils.CorrectedUtcNow.ToLocalTime() + _refreshAttemptPeriod + PreemptExpiryTime; #pragma warning restore CS0612 // Type or member is obsolete // Use this only if the time is earlier than the default expiration time if (newExpiryTime.ToUniversalTime() > state.Expiration.ToUniversalTime()) newExpiryTime = state.Expiration; return new CredentialsRefreshState(state.Credentials.Copy(), newExpiryTime); } private CredentialsRefreshState GetRefreshState(string token) { SecurityInfo info = GetServiceInfo(_proxy, token); if (!string.IsNullOrEmpty(info.Message)) { throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Unable to retrieve credentials. Message = \"{0}\".", info.Message)); } var credentials = GetRoleCredentials(token); var refreshState = new CredentialsRefreshState( new ImmutableCredentials( credentials.AccessKeyId, credentials.SecretAccessKey, credentials.Token), credentials.Expiration); return refreshState; } private static SecurityInfo GetServiceInfo(IWebProxy proxy, string token) { CheckIsIMDSEnabled(); return GetObjectFromResponse<SecurityInfo>(InfoUri, proxy, CreateMetadataTokenHeaders(token)); } private SecurityCredentials GetRoleCredentials(string token) { CheckIsIMDSEnabled(); return GetObjectFromResponse<SecurityCredentials>(CurrentRoleUri, _proxy, CreateMetadataTokenHeaders(token)); } private static void CheckIsIMDSEnabled() { // keep this behavior consistent with GetObjectFromResponse case. if (!EC2InstanceMetadata.IsIMDSEnabled) throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Unable to retrieve credentials.")); } private static string GetFirstRole() { return GetFirstRole(null); } private static string GetFirstRole(IWebProxy proxy) { IEnumerable<string> roles = GetAvailableRoles(proxy); foreach (string role in roles) { return role; } // no roles found throw new InvalidOperationException("No roles found"); } /// <summary> /// Return true if string is null or whitespace, false otherwise. /// We can't use String.IsNullOrWhitespace because it doesn't exist /// in all frameworks we support. /// </summary> /// <param name="s"></param> /// <returns></returns> private static bool IsNullOrWhiteSpace(string s) { if (s == null) return true; else if (s.Trim().Length == 0) return true; else return false; } private static Dictionary<string, string> CreateMetadataTokenHeaders(string token) { Dictionary<string, string> headers = null; if (!string.IsNullOrEmpty(token)) { headers = new Dictionary<string, string>(); headers.Add(HeaderKeys.XAwsEc2MetadataToken, token); } return headers; } #endregion } }
381
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; using System.Collections.Generic; using ThirdParty.Json.LitJson; using System.Diagnostics; #if AWS_ASYNC_API using System.Threading.Tasks; #endif using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Util; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; #if NETSTANDARD using System.Runtime.InteropServices; #endif namespace Amazon.Runtime { /// <summary> /// Process Credentials can retrieve credentials by running a process and reading its stdout. /// A new config option, "credential_process" is added to the shared config file that allows customers /// to specify which process to run. The credentials retrieved by running this process could be either /// Basic or Session credentials. /// </summary> public class ProcessAWSCredentials : RefreshingAWSCredentials { #region Private members private const string _versionString = "Version"; private Logger _logger = Logger.GetLogger(typeof(ProcessAWSCredentials)); private readonly ProcessStartInfo _processStartInfo; #endregion #region Public constructors [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public ProcessAWSCredentials(string processCredentialInfo) { processCredentialInfo = processCredentialInfo.Trim(); //Default to cmd on Windows since that is the only thing BCL runs on. var fileName = "cmd.exe"; var arguments = $@"/c {processCredentialInfo}"; #if NETSTANDARD //If it is netstandard and not running on Windows use sh. if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { fileName = "sh"; var escapedArgs = processCredentialInfo.Replace("\\", "\\\\").Replace("\"", "\\\""); arguments = $"-c \"{escapedArgs}\""; } #endif _processStartInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true }; // Make sure to fetch new credentials well before the current credentials expire to avoid // any request being made with expired credentials. PreemptExpiryTime = TimeSpan.FromMinutes(5); } #endregion #region Protected overridden methods protected override CredentialsRefreshState GenerateNewCredentials() { return DetermineProcessCredential(); } #if AWS_ASYNC_API protected override Task<CredentialsRefreshState> GenerateNewCredentialsAsync() { return DetermineProcessCredentialAsync(); } #endif #endregion #region Public methods /// <summary> /// Generates new credentials by running the "credential_process" process. /// </summary> public CredentialsRefreshState DetermineProcessCredential() { try { var processInfo = AWSSDKUtils.RunProcess(_processStartInfo); return SetCredentialsRefreshState(processInfo); } catch (ProcessAWSCredentialException) { throw; } catch (Exception e) { _logger.DebugFormat("Process recorded exception - {0}", e); throw new ProcessAWSCredentialException(string.Format(CultureInfo.CurrentCulture,"AWS credential process terminated with {0}", e.GetType()), e); } } #if AWS_ASYNC_API public async Task<CredentialsRefreshState> DetermineProcessCredentialAsync() { try { var processInfo = await AWSSDKUtils.RunProcessAsync(_processStartInfo).ConfigureAwait(false); return SetCredentialsRefreshState(processInfo); } catch (ProcessAWSCredentialException) { throw; } catch (Exception e) { _logger.DebugFormat("Process recorded exception - {0}", e); throw new ProcessAWSCredentialException(string.Format(CultureInfo.CurrentCulture,"AWS credential process terminated with {0}", e.GetType()), e); } } #endif #endregion #region Private methods [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] private CredentialsRefreshState SetCredentialsRefreshState(ProcessExecutionResult processInfo) { _logger.InfoFormat("Process ends with exitcode - {0}", processInfo.ExitCode); // Setting useShellExecute to false enables the user to just specify the executable name. // The system will attempt to find the executable within folders specified by the PATH environment variable. if (processInfo.ExitCode == 0) { JsonData data = null; try { data = JsonMapper.ToObject(processInfo.StandardOutput); } catch(JsonException je) { throw new ProcessAWSCredentialException("The response back from the process credential provider returned back a malformed JSON document.", je); } if (!data.PropertyNames.Contains(_versionString)|| string.IsNullOrEmpty(data[_versionString].ToString())) { throw new ProcessAWSCredentialException("Missing required parameter - Version in JSON Payload"); } var version = (int)data[_versionString]; switch (version) { case 1: ProcessCredentialVersion1 processCredentialDataV1 = null; try { processCredentialDataV1 = JsonMapper.ToObject<ProcessCredentialVersion1>(processInfo.StandardOutput); } catch (Exception e) { throw new ProcessAWSCredentialException("The response back from the process credential provider returned back a malformed JSON document.", e); } return new CredentialsRefreshState( new ImmutableCredentials(processCredentialDataV1.AccessKeyId, processCredentialDataV1.SecretAccessKey, processCredentialDataV1.SessionToken),processCredentialDataV1.Expiration); default: throw new ProcessAWSCredentialException(string.Format(CultureInfo.CurrentCulture,"Unsupported credential version: {0}" + version)); } } var processException = new ProcessAWSCredentialException(string.Format(CultureInfo.CurrentCulture, "Command returned non-zero exit value {0} with the error - {1}", processInfo.ExitCode, processInfo.StandardError)); _logger.DebugFormat("Process {0} recorded exception - {1}", _processStartInfo.FileName, processException); throw processException; } #endregion } /// <summary> /// Exception class to capture all exceptions encountered when starting or /// executing the "credential_process" process. If the user has specified an executable /// and the SDK is unable to execute it, the exception should be surfaces to the user /// instead of moving on to the next credential provider. /// </summary> #if !NETSTANDARD [Serializable] #endif public class ProcessAWSCredentialException : Exception { public ProcessAWSCredentialException(string message) : base(message) { } public ProcessAWSCredentialException(string message, Exception inner) : base(message, inner) { } #if !NETSTANDARD protected ProcessAWSCredentialException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
225
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.Internal { /// <summary> /// Class to which the Json stdout from credential process is /// de-serialized into. /// </summary> public class ProcessCredentialVersion1 { /// <summary> /// Version of the Json payload /// </summary> [JsonProperty(Required = true)] public int Version { get; set; } /// <summary> /// AWS Access key /// </summary> [JsonProperty(Required = true)] public string AccessKeyId { get; set; } /// <summary> /// AWS Secret key /// </summary> [JsonProperty(Required = true)] public string SecretAccessKey { get; set; } /// <summary> /// AWS Session token for session credentials /// </summary> public string SessionToken { get; set; } /// <summary> /// ISO8601 formatted timestamp till when the credential is valid. /// </summary> public DateTime Expiration { get; set; } = DateTime.MaxValue; } }
52
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; using System.Globalization; using System.Threading; namespace Amazon.Runtime { /// <summary> /// Abstract class for automatically refreshing AWS credentials /// </summary> public abstract class RefreshingAWSCredentials : AWSCredentials, IDisposable { private Logger _logger = Logger.GetLogger(typeof(RefreshingAWSCredentials)); #region Refresh data /// <summary> /// Refresh state container consisting of credentials /// and the date of the their expiration /// </summary> public class CredentialsRefreshState { public ImmutableCredentials Credentials { get; set; } public DateTime Expiration { get; set; } public CredentialsRefreshState() { } public CredentialsRefreshState(ImmutableCredentials credentials, DateTime expiration) { Credentials = credentials; Expiration = expiration; } internal bool IsExpiredWithin(TimeSpan preemptExpiryTime) { #pragma warning disable CS0612 // Type or member is obsolete var now = AWSSDKUtils.CorrectedUtcNow; #pragma warning restore CS0612 // Type or member is obsolete var exp = Expiration.ToUniversalTime(); return (now > exp - preemptExpiryTime); } } /// <summary> /// Represents the current state of the Credentials. /// </summary> /// <remarks>This can be cleared without synchronization.</remarks> protected CredentialsRefreshState currentState; #region Private members private TimeSpan _preemptExpiryTime = TimeSpan.FromMinutes(0); private bool _disposed; #if BCL35 /// <summary> /// Semaphore to control thread access to GetCredentialsAsync method. /// The semaphore will allow only one thread to generate new credentials and /// update the current state. /// </summary> private readonly Semaphore _updateGeneratedCredentialsSemaphore = new Semaphore(1, 1); #else /// <summary> /// Semaphore to control thread access to GetCredentialsAsync method. /// The semaphore will allow only one thread to generate new credentials and /// update the current state. /// </summary> private readonly SemaphoreSlim _updateGeneratedCredentialsSemaphore = new SemaphoreSlim(1, 1); #endif #endregion #endregion #region Properties /// <summary> /// The time before actual expiration to expire the credentials. /// Property cannot be set to a negative TimeSpan. /// </summary> public TimeSpan PreemptExpiryTime { get { return _preemptExpiryTime; } set { if (value < TimeSpan.Zero) throw new ArgumentOutOfRangeException("value", "PreemptExpiryTime cannot be negative"); _preemptExpiryTime = value; } } #endregion #region Override methods /// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { _updateGeneratedCredentialsSemaphore.Wait(); try { // We save the currentState as it might be modified or cleared. var tempState = currentState; // If credentials are expired or we don't have any state yet, update if (ShouldUpdateState(tempState, PreemptExpiryTime)) { tempState = GenerateNewCredentials(); UpdateToGeneratedCredentials(tempState, PreemptExpiryTime); currentState = tempState; } return tempState.Credentials.Copy(); } finally { _updateGeneratedCredentialsSemaphore.Release(); } } #if AWS_ASYNC_API public override async System.Threading.Tasks.Task<ImmutableCredentials> GetCredentialsAsync() { await _updateGeneratedCredentialsSemaphore.WaitAsync().ConfigureAwait(false); try { // We save the currentState as it might be modified or cleared. var tempState = currentState; // If credentials are expired, update if (ShouldUpdateState(tempState, PreemptExpiryTime)) { tempState = await GenerateNewCredentialsAsync().ConfigureAwait(false); UpdateToGeneratedCredentials(tempState, PreemptExpiryTime); currentState = tempState; } return tempState.Credentials.Copy(); } finally { _updateGeneratedCredentialsSemaphore.Release(); } } #endif #endregion #region Private/protected credential update methods private static void UpdateToGeneratedCredentials(CredentialsRefreshState state, TimeSpan preemptExpiryTime) { // Check if the new credentials are already expired if (ShouldUpdateState(state, preemptExpiryTime)) { string errorMessage; if (state == null) { errorMessage = "Unable to generate temporary credentials"; } else { errorMessage = string.Format(CultureInfo.InvariantCulture, "The retrieved credentials have already expired: Now = {0}, Credentials expiration = {1}", #pragma warning disable CS0612 // Type or member is obsolete AWSSDKUtils.CorrectedUtcNow.ToLocalTime(), state.Expiration); #pragma warning restore CS0612 // Type or member is obsolete } throw new AmazonClientException(errorMessage); } // Offset the Expiration by PreemptExpiryTime. This produces the expiration window // where the credentials should be updated before they actually expire. state.Expiration -= preemptExpiryTime; if (ShouldUpdateState(state, preemptExpiryTime)) { // This could happen if the default value of PreemptExpiryTime is // overridden and set too high such that ShouldUpdate returns true. var logger = Logger.GetLogger(typeof(RefreshingAWSCredentials)); logger.InfoFormat( "The preempt expiry time is set too high: Current time = {0}, Credentials expiry time = {1}, Preempt expiry time = {2}.", #pragma warning disable CS0612 // Type or member is obsolete AWSSDKUtils.CorrectedUtcNow.ToLocalTime(), #pragma warning restore CS0612 // Type or member is obsolete state.Expiration, preemptExpiryTime); } } /// <summary> /// Test credentials existence and expiration time /// should update if: /// credentials have not been loaded yet /// it's past the expiration time. At this point currentState.Expiration may /// have the PreemptExpiryTime baked into to the expiration from a call to /// UpdateToGeneratedCredentials but it may not if this is new application load. /// </summary> protected bool ShouldUpdate { get { return ShouldUpdateState(currentState, PreemptExpiryTime); } } // Test credentials existence and expiration time // should update if: // credentials have not been loaded yet // it's past the expiration time. At this point currentState.Expiration may // have the PreemptExpiryTime baked into to the expiration from a call to // UpdateToGeneratedCredentials but it may not if this is new application // load. private static bool ShouldUpdateState(CredentialsRefreshState state, TimeSpan preemptExpiryTime) { // it's past the expiration time. At this point currentState.Expiration may // have the PreemptExpiryTime baked into to the expiration from a call to // UpdateToGeneratedCredentials but it may not if this is new application // load. var isExpired = state?.IsExpiredWithin(TimeSpan.Zero); if (isExpired == true) { #pragma warning disable CS0612 // Type or member is obsolete var logger = Logger.GetLogger(typeof(RefreshingAWSCredentials)); logger.InfoFormat("Determined refreshing credentials should update. Expiration time: {0}, Current time: {1}", state.Expiration.Add(preemptExpiryTime).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture), AWSSDKUtils.CorrectedUtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture)); #pragma warning restore CS0612 // Type or member is obsolete } return isExpired ?? true; } /// <summary> /// When overridden in a derived class, generates new credentials and new expiration date. /// /// Called on first credentials request and when expiration date is in the past. /// </summary> /// <returns></returns> protected virtual CredentialsRefreshState GenerateNewCredentials() { throw new NotImplementedException(); } #if AWS_ASYNC_API /// <summary> /// When overridden in a derived class, generates new credentials and new expiration date. /// /// Called on first credentials request and when expiration date is in the past. /// </summary> /// <returns></returns> protected virtual System.Threading.Tasks.Task<CredentialsRefreshState> GenerateNewCredentialsAsync() { return System.Threading.Tasks.Task.Run(() => this.GenerateNewCredentials()); } #endif protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { _updateGeneratedCredentialsSemaphore.Dispose(); } _disposed = true; } #endregion #region Public Methods /// <summary> /// Clears currently-stored credentials, forcing the next GetCredentials call to generate new credentials. /// </summary> public virtual void ClearCredentials() { currentState = null; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
308
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; using System.Collections.Generic; using System.Globalization; using ThirdParty.Json.LitJson; namespace Amazon.Runtime { /// <summary> /// Immutable representation of AWS credentials obtained as a result of /// authenticating against a SAML-supporting federated identity provider. /// </summary> public class SAMLImmutableCredentials : ImmutableCredentials { #region Properties /// <summary> /// The expiry time of the credentials, obtained from the AssumeRoleWithSAML response. /// </summary> public DateTime Expires { get; private set; } /// <summary> /// The value of the NameID element in the Subject element of the SAML assertion, as returned in the /// AssumeRoleWithSAML response from the Security Token Service. /// </summary> public string Subject { get; private set; } #endregion #region Constructors /// <summary> /// Constructs an instance with supplied keys and SAML assertion data. /// </summary> /// <param name="awsAccessKeyId"></param> /// <param name="awsSecretAccessKey"></param> /// <param name="token"></param> /// <param name="expires"></param> /// <param name="subject"></param> public SAMLImmutableCredentials(string awsAccessKeyId, string awsSecretAccessKey, string token, DateTime expires, string subject) : base(awsAccessKeyId, awsSecretAccessKey, token) { Expires = expires; Subject = subject; } /// <summary> /// Constructs an instance with supplied keys and SAML assertion data. /// </summary> /// <param name="credentials"></param> /// <param name="subject"></param> /// <param name="expires"></param> public SAMLImmutableCredentials(ImmutableCredentials credentials, DateTime expires, string subject) : base(credentials.AccessKey, credentials.SecretKey, credentials.Token) { Expires = expires; Subject = subject; } #endregion #region Overrides public override int GetHashCode() { return Hashing.Hash(AccessKey, SecretKey, Token, Subject, Expires); } public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; var ic = obj as SAMLImmutableCredentials; if (ic == null) return false; if (base.Equals(obj)) return string.Equals(Subject, ic.Subject, StringComparison.Ordinal) && DateTime.Equals(Expires, ic.Expires); return false; } /// <summary> /// Returns a copy of the current credentials. /// </summary> /// <returns></returns> public override ImmutableCredentials Copy() { return new SAMLImmutableCredentials(AccessKey, SecretKey, Token, Expires, Subject); } #endregion #region Serialization const string AccessKeyProperty = "AccessKey"; const string SecretKeyProperty = "SecretKey"; const string TokenProperty = "Token"; const string ExpiresProperty = "Expires"; const string SubjectProperty = "Subject"; /// <summary> /// Serializes the instance to a json-format string for external storage /// </summary> /// <returns>The serialized object in json</returns> internal string ToJson() { // don't need all data, and we want to be explicit on the datetime format var props = new Dictionary<string, string>(); props.Add(AccessKeyProperty, AccessKey); props.Add(SecretKeyProperty, SecretKey); props.Add(TokenProperty, Token); props.Add(ExpiresProperty, Expires.ToString("u", CultureInfo.InvariantCulture)); props.Add(SubjectProperty, Subject); return JsonMapper.ToJson(props); } /// <summary> /// Instantiates an instance from persisted json data /// </summary> /// <param name="json">The serialized data</param> /// <returns>Deserialized instance corresponding to the json data</returns> internal static SAMLImmutableCredentials FromJson(string json) { try { var o = JsonMapper.ToObject(json); // get the expiry first - if the credentials have expired we can then // ignore the data var expires = DateTime.Parse((string)o[ExpiresProperty], CultureInfo.InvariantCulture).ToUniversalTime(); #pragma warning disable CS0612 // Type or member is obsolete if (expires <= AWSSDKUtils.CorrectedUtcNow) #pragma warning restore CS0612 // Type or member is obsolete { Logger.GetLogger(typeof(SAMLImmutableCredentials)).InfoFormat("Skipping serialized credentials due to expiry."); return null; } var accessKey = (string)o[AccessKeyProperty]; var secretKey = (string)o[SecretKeyProperty]; var token = (string)o[TokenProperty]; var subject = (string)o[SubjectProperty]; return new SAMLImmutableCredentials(accessKey, secretKey, token, expires, subject); } catch (Exception e) { Logger.GetLogger(typeof(SAMLImmutableCredentials)).Error(e, "Error during deserialization"); } return null; } #endregion } }
183
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> /// Session credentials consisting of AccessKey, SecretKey and Token /// </summary> public class SessionAWSCredentials : AWSCredentials { #region Public constructors /// <summary> /// Constructs a SessionAWSCredentials object for the specified accessKey, secretKey. /// </summary> /// <param name="awsAccessKeyId"></param> /// <param name="awsSecretAccessKey"></param> /// <param name="token"></param> public SessionAWSCredentials(string awsAccessKeyId, string awsSecretAccessKey, string token) { if (string.IsNullOrEmpty(awsAccessKeyId)) throw new ArgumentNullException("awsAccessKeyId"); if (string.IsNullOrEmpty(awsSecretAccessKey)) throw new ArgumentNullException("awsSecretAccessKey"); if (string.IsNullOrEmpty(token)) throw new ArgumentNullException("token"); _lastCredentials = new ImmutableCredentials(awsAccessKeyId, awsSecretAccessKey, token); } #endregion #region Credentials data private ImmutableCredentials _lastCredentials; #endregion #region Abstract class overrides /// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { return _lastCredentials.Copy(); } #endregion public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; var sac = obj as SessionAWSCredentials; if (sac == null) return false; return AWSSDKUtils.AreEqual( new object[] { _lastCredentials }, new object[] { sac._lastCredentials }); } public override int GetHashCode() { return Hashing.Hash(_lastCredentials); } } }
86
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.Internal; using Amazon.Runtime.Internal.Util; using Amazon.Util; using System; using System.IO; namespace Amazon.Runtime { /// <summary> /// <para> /// Credentials that are retrieved using a stored profile. /// </para> /// <para> /// Unless otherwise specified priority is given to loading credentials from the SDK credential store /// file which is shared between the SDK, PowerShell CLI and Toolkit. Credentials in profiles in this /// file are encrypted and can only be used by the user account on the current machine that stored the /// profile. Credentials can also be loaded from the plain-text ini-format credential file which is /// shared with other AWS SDKs. This file is expected to exist in a '.aws' folder in the user's home /// directory but alternate locations can be specified using either the AWSProfilesLocation setting in /// the application configuration file, or by using the AWS_SHARED_CREDENTIALS_FILE environment variable. /// </para> /// <para> /// The profile name can be specified in the App.config using the AWSProfileName setting. /// </para> /// </summary> [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.NetSDKCredentialsFile or SharedCredentialsFile.. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] public class StoredProfileAWSCredentials : AWSCredentials { private AWSCredentials _wrappedCredentials; public AWSCredentials WrappedCredentials { get { return _wrappedCredentials; } } #region Public constructors /// <summary> /// Constructs an instance for credentials stored in a profile. This constructor searches for credentials /// using the account name specified using the AWSProfileName setting, if set, in the application configuration /// file. If the configuration file setting is not set the SDK will attempt to locate a profile with the name /// 'default'. /// </summary> public StoredProfileAWSCredentials() : this(AWSConfigs.AWSProfileName) { } /// <summary> /// Constructs an instance for credentials stored in a profile with the specified name. The SDK will /// check the SDK credential store file first before looking for the shared ini-format credentials /// file unless the application configuration file contains a setting for the 'AWSProfilesLocation' /// indicating the search should be constrained to the shared credentials file at the specified /// location. /// </summary> /// <param name="profileName">The name of the profile in which the credentials were stored.</param> public StoredProfileAWSCredentials(string profileName) : this(profileName, AWSConfigs.AWSProfilesLocation) { } /// <summary> /// Constructs an instance for credentials stored in a profile with the specified name. /// </summary> /// <param name="profileName">The profile name to search for credentials for</param> /// <param name="profilesLocation"> /// Optional; instructs the SDK to check for the profile in the shared credentials file at the /// specified location. If not set, the SDK will inspect its own credential store file first before /// attempting to locate a shared credential file using either the default location beneath the user's /// home profile folder or the location specified in the AWS_SHARED_CREDENTIALS_FILE environment /// variable. /// </param> /// <remarks> /// If credential materials cannot be read or are invalid due to missing data an InvalidDataException /// is thrown. If no credentials can be located with the specified profile name, an ArgumentException /// is thrown. /// </remarks> public StoredProfileAWSCredentials(string profileName, string profilesLocation) { var lookupName = string.IsNullOrEmpty(profileName) ? StoredProfileCredentials.DEFAULT_PROFILE_NAME : profileName; ProfileName = lookupName; ProfilesLocation = null; // If not overriding the credentials lookup location check the SDK Store for credentials. If an override is being used then // assume the intent is to use the credentials file. if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(lookupName) && ProfileManager.IsAvailable) { if (ProfileManager.IsProfileKnown(lookupName) && AWSCredentialsProfile.CanCreateFrom(lookupName)) { _wrappedCredentials = ProfileManager.GetAWSCredentials(lookupName); var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); logger.InfoFormat("Credentials found using account name {0} and looking in SDK account store.", lookupName); } } // If credentials weren't found in the SDK store then search the shared credentials file. if (this._wrappedCredentials == null) { var credentialsFilePath = StoredProfileCredentials.ResolveSharedCredentialFileLocation(profilesLocation); if (!string.IsNullOrEmpty(credentialsFilePath)) { var sharedCredentialsFile = new SharedCredentialsFile(credentialsFilePath); CredentialProfile profile; if (sharedCredentialsFile.TryGetProfile(lookupName, out profile) && AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out _wrappedCredentials)) { var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); logger.InfoFormat("Credentials found using account name {0} and looking in {1}.", lookupName, credentialsFilePath); } ProfilesLocation = credentialsFilePath; } } // No credentials found so error out. if (this._wrappedCredentials == null) { throw new ArgumentException("App.config does not contain credentials information. Either add the AWSAccessKey and AWSSecretKey properties or the AWSProfileName property."); } } #endregion #region Public properties /// <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; } #endregion /// <summary> /// Tests if a profile has been registered in either the SDK store or the specified credential /// file. /// </summary> /// <param name="profileName">The name of the profile to test</param> /// <param name="profilesLocation"> /// Optional; instructs the SDK to check for the profile in the shared credentials file at the /// specified location. If not set, the SDK will inspect its own credential store file first before /// attempting to locate a shared credential file using either the default location beneath the user's /// home profile folder or the location specified in the AWS_SHARED_CREDENTIALS_FILE environment /// variable. /// </param> /// <returns>True if a profile with the specified name has been registered.</returns> public static bool IsProfileKnown(string profileName, string profilesLocation) { if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(profileName)) { return true; } else { return ValidCredentialsExistInSharedFile(profilesLocation, profileName); } } /// <summary> /// Tests if an instance can be created from the persisted profile data. /// If profilesLocation is null/empty, the SDK store is searched for the /// profile data before probing for the profile in the shared the ini-format /// credential file. /// </summary> /// <param name="profileName">The name of the profile to test</param> /// <param name="profilesLocation"> /// If null/empty, the SDK store is searched for the named profile otherwise /// the ini-format credential file at the specified location is inspected. /// </param> /// <returns>True if the persisted data would yield a valid credentials instance.</returns> public static bool CanCreateFrom(string profileName, string profilesLocation) { if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(profileName)) { return AWSCredentialsProfile.CanCreateFrom(profileName); } else { return ValidCredentialsExistInSharedFile(profilesLocation, profileName); } } private static bool ValidCredentialsExistInSharedFile(string profilesLocation, string profileName) { var credentialsFilePath = StoredProfileCredentials.ResolveSharedCredentialFileLocation(profilesLocation); if (!string.IsNullOrEmpty(credentialsFilePath)) { var doLog = false; try { var file = new SharedCredentialsFile(credentialsFilePath); CredentialProfile profile = null; if (file.TryGetProfile(profileName, out profile) && profile.CanCreateAWSCredentials) { return true; } else { doLog = true; } } catch (InvalidDataException) { doLog = true; } if (doLog) { var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); logger.InfoFormat("Credentials file {0} does not contain a valid profile named {1}.", credentialsFilePath, profileName); } } else { var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials)); logger.InfoFormat("Credentials file not found {0}.", credentialsFilePath); } return false; } #region Abstract class overrides /// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { return _wrappedCredentials.GetCredentials(); } #endregion } }
262
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.Globalization; using System.IO; using System.Text; namespace Amazon.Runtime { /// <summary> /// Helper routiners for AWS and Federated credential profiles. Probes the /// profile type for the supplied profile name and returns the appropriate profile /// instance. /// </summary> [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.NetSDKCredentialsFile or SharedCredentialsFile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] public abstract class StoredProfileCredentials { public const string DEFAULT_PROFILE_NAME = "default"; public const string SHARED_CREDENTIALS_FILE_ENVVAR = "AWS_SHARED_CREDENTIALS_FILE"; private static string[] PotentialEnvironmentPathsToCredentialsFile = new string[]{ "HOME", "USERPROFILE", }; public const string DefaultSharedCredentialFilename = "credentials"; public const string DefaultSharedCredentialLocation = ".aws/" + DefaultSharedCredentialFilename; /// <summary> /// Determines the type of the requested profile and returns the /// appropriate profile instance. /// </summary> /// <param name="profileName">The name of the profile (AWS or federated) to be loaded.</param> /// <returns>Instantiated profile type.</returns> public static AWSCredentials GetProfile(string profileName) { return GetProfile(profileName, AWSConfigs.AWSProfilesLocation); } /// <summary> /// Determines the type of the requested profile and returns the /// appropriate profile instance. /// </summary> /// <param name="profileName">The name of the profile (AWS or federated) to be loaded.</param> /// <param name="profileLocation"> /// The location of the shared credentials (.ini) file, for profiles that are not stored in the /// SDK credential store. /// </param> /// <returns>Instantiated profile type.</returns> public static AWSCredentials GetProfile(string profileName, string profileLocation) { if (StoredProfileAWSCredentials.CanCreateFrom(profileName, profileLocation)) return new StoredProfileAWSCredentials(profileName, profileLocation); #if !NETSTANDARD if (StoredProfileFederatedCredentials.CanCreateFrom(profileName, profileLocation)) return new StoredProfileFederatedCredentials(profileName, profileLocation); #endif var sb = new StringBuilder(); sb.AppendFormat(CultureInfo.InvariantCulture, "Profile {0} was not found in the SDK credential store", profileName); if (!string.IsNullOrEmpty(profileLocation)) sb.AppendFormat(CultureInfo.InvariantCulture, " or at location '{0}'.", profileLocation); throw new ArgumentException(sb.ToString()); } /// <summary> /// Probes for and returns the fully qualified name of the shared ini-format credentials /// file. /// </summary> /// <param name="profileLocation"> /// Contains the file or folder name of the credential file. If not specified, the /// routine will first check the application configuration file for a setting indicating /// the file location or filename. If the configuration file does not yield a credential /// file location then an environment variable is examined. Finally the routine will /// inspect the fallback default location beneath the user's home folder location. /// </param> /// <returns> /// The fully qualified name to the credential file that was located, or null /// if no credential file could be found. /// </returns> public static string ResolveSharedCredentialFileLocation(string profileLocation) { var logger = Logger.GetLogger(typeof(StoredProfileCredentials)); string credentialFile = TestSharedCredentialFileExists(profileLocation); if (!string.IsNullOrEmpty(credentialFile)) { logger.InfoFormat("Credentials file found at supplied location: {0}", credentialFile); return credentialFile; } credentialFile = TestSharedCredentialFileExists(AWSConfigs.AWSProfilesLocation); if (!string.IsNullOrEmpty(credentialFile)) { logger.InfoFormat("Credentials file found using application configuration setting: {0}", credentialFile); return credentialFile; } credentialFile = TestSharedCredentialFileExists(Environment.GetEnvironmentVariable(SHARED_CREDENTIALS_FILE_ENVVAR)); if (!string.IsNullOrEmpty(credentialFile)) { logger.InfoFormat("Credentials file found using environment variable '{0}': {1}", SHARED_CREDENTIALS_FILE_ENVVAR, credentialFile); return credentialFile; } foreach (string environmentVariable in PotentialEnvironmentPathsToCredentialsFile) { string envPath = Environment.GetEnvironmentVariable(environmentVariable); if (!string.IsNullOrEmpty(envPath)) { credentialFile = TestSharedCredentialFileExists(Path.Combine(envPath, DefaultSharedCredentialLocation)); if (!string.IsNullOrEmpty(credentialFile)) { logger.InfoFormat("Credentials file found using environment variable '{0}': {1}", environmentVariable, credentialFile); return credentialFile; } } } #if !BCL35 var profileFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); if (!string.IsNullOrEmpty(profileFolder)) { credentialFile = TestSharedCredentialFileExists(Path.Combine(profileFolder, DefaultSharedCredentialLocation)); if (!string.IsNullOrEmpty(credentialFile)) { logger.InfoFormat("Credentials file found in user profile location: {0}", credentialFile); return credentialFile; } } #else var profileFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal); if (!string.IsNullOrEmpty(profileFolder)) { var parent = Directory.GetParent(profileFolder); if (parent != null) { credentialFile = TestSharedCredentialFileExists(Path.Combine(parent.FullName, DefaultSharedCredentialLocation)); if (!string.IsNullOrEmpty(credentialFile)) { logger.InfoFormat("Credentials file found in user profile location: {0}", credentialFile); return credentialFile; } } } #endif logger.InfoFormat("No credentials file found using location probing."); return null; } private static string TestSharedCredentialFileExists(string pathOrFilename) { if (!string.IsNullOrEmpty(pathOrFilename)) { string testLocation = Directory.Exists(pathOrFilename) ? Path.Combine(pathOrFilename, DefaultSharedCredentialFilename) : pathOrFilename; if (File.Exists(testLocation)) return testLocation; } return null; } } }
181
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.Globalization; using System.IO; using System.Net; using ThirdParty.Json.LitJson; namespace Amazon.Runtime { public class URIBasedRefreshingCredentialHelper : RefreshingAWSCredentials { private static string SuccessCode = "Success"; protected static string GetContents(Uri uri) { return GetContents(uri, null); } protected static string GetContents(Uri uri, IWebProxy proxy) { return GetContents(uri, proxy, null); } protected static string GetContents(Uri uri, IWebProxy proxy, Dictionary<string, string> headers) { try { return AWSSDKUtils.ExecuteHttpRequest(uri, "GET", null, TimeSpan.Zero, proxy, headers); } catch (Exception e) { throw new AmazonServiceException("Unable to reach credentials server", e); } } protected static T GetObjectFromResponse<T>(Uri uri) { return GetObjectFromResponse<T>(uri, null, null); } protected static T GetObjectFromResponse<T>(Uri uri, IWebProxy proxy) { return GetObjectFromResponse<T>(uri, proxy, null); } protected static T GetObjectFromResponse<T>(Uri uri, IWebProxy proxy, Dictionary<string, string> headers) { string json = GetContents(uri, proxy, headers); return JsonMapper.ToObject<T>(json); } protected static void ValidateResponse(SecurityBase response) { if (!string.Equals(response.Code, SuccessCode, StringComparison.OrdinalIgnoreCase)) { throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Unable to retrieve credentials. Code = \"{0}\". Message = \"{1}\".", response.Code, response.Message)); } } #region Private serialization classes protected class SecurityBase { public string Code { get; set; } public string Message { get; set; } public DateTime LastUpdated { get; set; } } protected class SecurityInfo : SecurityBase { public string InstanceProfileArn { get; set; } public string InstanceProfileId { get; set; } } protected class SecurityCredentials : SecurityBase { public string Type { get; set; } public string AccessKeyId { get; set; } public string SecretAccessKey { get; set; } public string Token { get; set; } public DateTime Expiration { get; set; } public string RoleArn { get; set; } } #endregion } }
104
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.Credentials.Internal { /// <summary> /// An <see cref="SsoToken"/> is used by the <see cref="SSOAWSCredentials"/> provider to request /// permission to get credentials and by the <see cref="SSOTokenProvider"/> when a Service is using /// <see cref="BearerTokenSigner"/>. /// <para /> /// <see cref="SsoToken"/>s are persisted using <see cref="SSOTokenManager"/>. /// </summary> /// <remarks> /// This class is meant to be used internally. It may be projected to a /// <see cref="AWSToken"/> /// </remarks> public class SsoToken { /// <summary> /// Token string returned by the SSOOIDC service (IAmazonSSOOIDC). /// </summary> public string AccessToken { get; set; } /// <summary> /// Expiration time of <see cref="AccessToken"/> /// </summary> public DateTime ExpiresAt { get; set; } /// <summary> /// An opaque string returned by the sso-oidc service. /// </summary> public string RefreshToken { get; set; } /// <summary> /// The client ID generated when performing the registration portion of the OIDC authorization flow. /// The clientId is used alongside the <see cref="RefreshToken"/> to refresh the <see cref="AccessToken"/>. /// </summary> public string ClientId { get; set; } /// <summary> /// he client secret generated when performing the registration portion of the OIDC authorization flow. /// The <see cref="ClientSecret"/> is used alongside the <see cref="RefreshToken"/> to refresh the <see cref="AccessToken"/>. /// </summary> public string ClientSecret { get; set; } /// <summary> /// The expiration time of the client registration (<see cref="ClientId"/> and <see cref="ClientSecret"/>) as /// an RFC 3339 formatted timestamp. /// </summary> public string RegistrationExpiresAt { get; set; } /// <summary> /// The configured sso_region for the profile that credentials are being resolved for. /// </summary> public string Region { get; set; } /// <summary> /// The configured sso_start_url for the profile that credentials are being resolved for. /// </summary> public string StartUrl { get; set; } /// <summary> /// The configured sso_session for the profile that credentials are being resolved for. /// </summary> public string Session { get; set; } } }
81
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; using System.IO; using System.Text; using Amazon.Runtime.CredentialManagement; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif using Amazon.Runtime.Internal.Util; using Amazon.Util; using Amazon.Util.Internal; namespace Amazon.Runtime.Credentials.Internal { public interface ISSOTokenFileCache { /// <summary> /// Returns true if a cache entry exists for the <see cref="SsoToken"/> represented by /// <paramref name="options"/>. /// </summary> bool Exists(CredentialProfileOptions options); /// <inheritdoc cref="TryGetSsoTokenAsync"/> bool TryGetSsoToken(SSOTokenManagerGetTokenOptions getSsoTokenOptions, string ssoCacheDirectory, out SsoToken ssoToken); /// <inheritdoc cref="SaveSsoTokenAsync"/> void SaveSsoToken(SsoToken token, string ssoCacheDirectory); #if AWS_ASYNC_API /// <summary> /// Tries to load a <see cref="SsoToken"/> from the SSO File Cache. /// </summary> /// <param name="getSsoTokenOptions"> /// Options containing details needed to lookup the <see cref="SsoToken"/> in cache. /// </param> /// <param name="ssoCacheDirectory"> /// Optional: Leave null/empty to default to (user profile)/.aws/sso/cache/ /// </param> /// <param name="cancellationToken"> /// Cancels the operation /// </param> /// <returns> /// A <see cref="TryResponse{T}"/> indicating if a <see cref="SsoToken"/> was retrieved from cache. /// </returns> Task<TryResponse<SsoToken>> TryGetSsoTokenAsync(SSOTokenManagerGetTokenOptions getSsoTokenOptions, string ssoCacheDirectory, CancellationToken cancellationToken = default); /// <summary> /// Saves <paramref name="token"/> to the SSO File Cache. /// </summary> /// <param name="token"> /// <see cref="SsoToken"/> to persist to disk. /// </param> /// <param name="ssoCacheDirectory"> /// Optional: Leave null/empty to default to (user profile)/.aws/sso/cache/ /// </param> /// <param name="cancellationToken"> /// Cancels the operation /// </param> Task SaveSsoTokenAsync(SsoToken token, string ssoCacheDirectory, CancellationToken cancellationToken = default); #endif } [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Try methods intentionally suppress all Exceptions")] public class SSOTokenFileCache : ISSOTokenFileCache { private readonly Logger _logger = Logger.GetLogger(typeof(SSOTokenFileCache)); private readonly ICryptoUtil _cryptoUtil; private readonly IFile _file; private readonly IDirectory _directory; public SSOTokenFileCache( ICryptoUtil cryptoUtil, IFile file, IDirectory directory) { _cryptoUtil = cryptoUtil; _file = file; _directory = directory; } public bool Exists(CredentialProfileOptions options) { var mappedOptions = new SSOTokenManagerGetTokenOptions { StartUrl = options.SsoStartUrl, Session = options.SsoSession }; return TryGetSsoToken(mappedOptions, ssoCacheDirectory: null, out var _); } public bool TryGetSsoToken(SSOTokenManagerGetTokenOptions getSsoTokenOptions, string ssoCacheDirectory, out SsoToken ssoToken) { ssoToken = null; var cacheFilePath = BuildCacheFileFullPath(getSsoTokenOptions, ssoCacheDirectory); try { if (string.IsNullOrWhiteSpace(cacheFilePath) || !_file.Exists(cacheFilePath)) { _logger.InfoFormat("No SSO Token cache to load from"); return false; } var json = _file.ReadAllText(cacheFilePath); ssoToken = SsoTokenUtils.FromJson(json); _logger.InfoFormat("SSO Token loaded from cache"); return true; } catch (Exception e) { _logger.Error(e, "Unable to load token cache for start url: {0}", getSsoTokenOptions?.StartUrl); return false; } } public async Task<TryResponse<SsoToken>> TryGetSsoTokenAsync(SSOTokenManagerGetTokenOptions getSsoTokenOptions, string ssoCacheDirectory, CancellationToken cancellationToken = default) { var cacheFilePath = BuildCacheFileFullPath(getSsoTokenOptions, ssoCacheDirectory); var result = new TryResponse<SsoToken> { Success = false }; try { if (string.IsNullOrWhiteSpace(cacheFilePath) || !_file.Exists(cacheFilePath)) { _logger.InfoFormat("No SSO Token cache to load from"); return result; } var json = await _file.ReadAllTextAsync(cacheFilePath, cancellationToken).ConfigureAwait(false); result.Value = SsoTokenUtils.FromJson(json); result.Success = true; _logger.InfoFormat("SSO Token loaded from cache"); return result; } catch (Exception e) { _logger.Error(e, "Unable to load token cache for start url: {0}", getSsoTokenOptions?.StartUrl); return result; } } public void SaveSsoToken(SsoToken token, string ssoCacheDirectory) { if (null == token) return; var cacheFilePath = BuildCacheFileFullPath(token, ssoCacheDirectory); try { if (string.IsNullOrWhiteSpace(cacheFilePath)) { return; } var json = SsoTokenUtils.ToJson(token); _directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); _file.WriteAllText(cacheFilePath, json); } catch (Exception e) { _logger.Error(e, "Warning: Unable to save SSO Token Cache. Future retrieval will have to produce a token."); } } public async Task SaveSsoTokenAsync(SsoToken token, string ssoCacheDirectory, CancellationToken cancellationToken = default) { if (null == token) return; var cacheFilePath = BuildCacheFileFullPath(token, ssoCacheDirectory); try { if (string.IsNullOrWhiteSpace(cacheFilePath)) { return; } var json = SsoTokenUtils.ToJson(token); _directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); await _file.WriteAllTextAsync(cacheFilePath, json, cancellationToken).ConfigureAwait(false); } catch (Exception e) { _logger.Error(e, "Warning: Unable to save SSO Token Cache. Future retrieval will have to produce a token."); } } private string BuildCacheFileFullPath(SsoToken token, string ssoCacheDirectory) { return BuildCacheFileFullPath(token.StartUrl, token.Session, ssoCacheDirectory); } private string BuildCacheFileFullPath(SSOTokenManagerGetTokenOptions getSsoTokenOptions, string ssoCacheDirectory) { return BuildCacheFileFullPath(getSsoTokenOptions.StartUrl, getSsoTokenOptions.Session, ssoCacheDirectory); } private string BuildCacheFileFullPath(string startUrl, string session, string ssoCacheDirectory) { if (string.IsNullOrWhiteSpace(ssoCacheDirectory)) { ssoCacheDirectory = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".aws", "sso", "cache"); } var cacheFile = GetCacheFilename(startUrl, session); return Path.Combine(ssoCacheDirectory, cacheFile); } /// <summary> /// Determines the file name of the Token Cache, regardless of folder. /// If <see cref="SsoToken.Session"/> is set, than that will be used to calculate the filename, /// otherwise <see cref="SsoToken.StartUrl"/> is used. /// </summary> /// <returns> /// The filename to be used for a <see cref="SsoToken"/> /// </returns> private string GetCacheFilename(string startUrl, string session) { var fileSha = !string.IsNullOrEmpty(session) ? GenerateSha1Hash(session) : GenerateSha1Hash(startUrl); var filename = $"{fileSha}.json"; return filename; } /// <summary> /// Generate a SHA1 hash for the given text /// </summary> /// <param name="text">Text to generate a hash for</param> /// <returns> /// SHA1 hash for <paramref name="text"/> /// </returns> private string GenerateSha1Hash(string text) { var hash = _cryptoUtil.ComputeSHA1Hash(Encoding.UTF8.GetBytes(text ?? "")); return AWSSDKUtils.ToHex(hash, true); } } }
274
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.Concurrent; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime.Internal.Util; using Amazon.Runtime.SharedInterfaces; using Amazon.Util; namespace Amazon.Runtime.Credentials.Internal { public interface ISSOTokenManager { #if BCL SsoToken GetToken(SSOTokenManagerGetTokenOptions options); #endif #if AWS_ASYNC_API Task<SsoToken> GetTokenAsync(SSOTokenManagerGetTokenOptions options, CancellationToken cancellationToken = default); #endif } public class SSOTokenManager : ISSOTokenManager { private readonly ILogger _logger = Logger.GetLogger(typeof(SSOTokenManager)); private readonly ICoreAmazonSSOOIDC _ssooidcClient; private readonly ISSOTokenFileCache _ssoTokenFileCache; private readonly InMemoryCache _inMemoryCache; public SSOTokenManager( ICoreAmazonSSOOIDC ssooidcClient, ISSOTokenFileCache ssoTokenFileCache) { _ssooidcClient = ssooidcClient; _ssoTokenFileCache = ssoTokenFileCache; _inMemoryCache = new InMemoryCache(); } private class InMemoryCache { private readonly ConcurrentDictionary<string, SSOTokenManager.CacheState> _inMemoryCache = new ConcurrentDictionary<string, CacheState>(); public bool TryGetValue(SSOTokenManagerGetTokenOptions options, out CacheState inMemoryToken) { var cacheKey = BuildCacheKey(options); return _inMemoryCache.TryGetValue(cacheKey, out inMemoryToken); } public void AddOrUpdate(SSOTokenManagerGetTokenOptions options, CacheState newInMemoryToken) { var cacheKey = BuildCacheKey(options); _inMemoryCache.AddOrUpdate(cacheKey, newInMemoryToken, (x, y) => newInMemoryToken); } private static string BuildCacheKey(SSOTokenManagerGetTokenOptions options) { return !string.IsNullOrEmpty(options.Session) ? options.Session : options.StartUrl; } } #if BCL || AWS_ASYNC_API private class RefreshState { public bool FailedLastRefreshAttempt { get; set; } public DateTime? BlockRefreshUntil { get; set; } public bool IsInRefreshCoolDown() { if (!BlockRefreshUntil.HasValue) return false; #pragma warning disable CS0618 // Type or member is obsolete return BlockRefreshUntil.Value < AWSSDKUtils.CorrectedUtcNow; #pragma warning restore CS0618 // Type or member is obsolete } } private class CacheState { public SsoToken Token { get; set; } public RefreshState RefreshState { get; set; } } #endif #if BCL public SsoToken GetToken(SSOTokenManagerGetTokenOptions options) { CacheState inMemoryToken = null; if (AWSConfigs.UseSdkCache && _inMemoryCache.TryGetValue(options, out inMemoryToken) && !inMemoryToken.Token.NeedsRefresh()) { _logger.InfoFormat($"In Memory cache has SSOToken for [{options.StartUrl}]"); return inMemoryToken.Token; } if (_ssoTokenFileCache.TryGetSsoToken(options, options.CacheFolderLocation, out var ssoToken)) { _logger.InfoFormat($"File cache has SSOToken for [{options.StartUrl}]"); // token is not expired and doesn't need a refresh if (!ssoToken.NeedsRefresh()) { var newInMemoryToken = new CacheState { Token = ssoToken, RefreshState = new RefreshState() }; if (AWSConfigs.UseSdkCache) _inMemoryCache.AddOrUpdate(options, newInMemoryToken); return ssoToken; } // refresh token? else if (ssoToken.CanRefresh()) { _logger.InfoFormat($"File cache SSOToken for [{options.StartUrl}] needs refresh"); // only try and refresh an expired token once. if we've already failed, // don't try again. if (true == inMemoryToken?.RefreshState.FailedLastRefreshAttempt && ssoToken.IsExpired()) { throw new AmazonClientException("SSO Token has expired and can not be refreshed"); } // did we recently try to refresh the token? if (true == inMemoryToken?.RefreshState.IsInRefreshCoolDown()) { // if we can't refresh, but have a valid token, return the valid token if (!ssoToken.IsExpired()) { return ssoToken; } // if we can't refresh, but can generate a new token, do that else if (options.SupportsGettingNewToken) { return GenerateNewToken(options); } // we've already tried to refresh and failed, nothing more can be done. else { throw new AmazonClientException("SSO Token has expired and can not be refreshed"); } } try { _logger.InfoFormat($"Refreshing SSOToken for [{options.StartUrl}]"); var response = _ssooidcClient.RefreshToken(MapSsoTokenToGetSsoTokenResponse(ssoToken)); var newToken = MapGetSsoTokenResponseToSsoToken(response, options.Session); _ssoTokenFileCache.SaveSsoToken(newToken, options.CacheFolderLocation); var newInMemoryToken = new CacheState { Token = newToken, RefreshState = new RefreshState() }; if (AWSConfigs.UseSdkCache) _inMemoryCache.AddOrUpdate(options, newInMemoryToken); return newToken; } catch (Exception ex) { _logger.Error(ex, $"Refreshing SSOToken for [{options.StartUrl}] failed: {ex.Message}"); //if refreshing the token failed that means the refresh token was expired. //if the refresh token is expired and access token is expired and if the user specifies a callback with //option.SupportsGettingNewToken is true then we will generate a new token. if (ssoToken.IsExpired() && options.SupportsGettingNewToken) { return GenerateNewToken(options); } else if (!ssoToken.IsExpired()) { var newInMemoryToken = new CacheState { Token = ssoToken, RefreshState = new RefreshState { FailedLastRefreshAttempt = true, BlockRefreshUntil = AWSSDKUtils.CorrectedUtcNow.AddSeconds(30) } }; if (AWSConfigs.UseSdkCache) _inMemoryCache.AddOrUpdate(options, newInMemoryToken); return ssoToken; } else { throw new AmazonClientException("SSO Token has expired and failed to refresh", ex); } } } else if (ssoToken.IsExpired()) { if (options.SupportsGettingNewToken) { return GenerateNewToken(options); } else { throw new AmazonClientException("SSO Token has expired and can not be refreshed"); } } else { // Token was not refreshed, continue to use until it expires return ssoToken; } } // if no token found on disk, create one if we can else if (options.SupportsGettingNewToken) { return GenerateNewToken(options); } // can't find a token and can't create one else { throw new AmazonClientException("No valid SSO Token could be found."); } } private SsoToken GenerateNewToken(SSOTokenManagerGetTokenOptions options) { if (string.IsNullOrEmpty(options.ClientName)) { throw new ArgumentNullException($"Options property cannot be empty: {nameof(options.ClientName)}"); } if (options.SsoVerificationCallback == null) { throw new ArgumentNullException($"Options property cannot be empty: {nameof(options.SsoVerificationCallback)}"); } var request = new GetSsoTokenRequest { ClientName = GetSsoClientName(options.ClientName), ClientType = options.ClientType, StartUrl = options.StartUrl, SsoVerificationCallback = options.SsoVerificationCallback, Scopes = options.Scopes }; var response = _ssooidcClient.GetSsoToken(request); var token = MapGetSsoTokenResponseToSsoToken(response, options.Session); _ssoTokenFileCache.SaveSsoToken(token, options.CacheFolderLocation); return token; } #endif #if AWS_ASYNC_API public async Task<SsoToken> GetTokenAsync(SSOTokenManagerGetTokenOptions options, CancellationToken cancellationToken = default) { CacheState inMemoryToken = null; if (AWSConfigs.UseSdkCache && _inMemoryCache.TryGetValue(options, out inMemoryToken) && !inMemoryToken.Token.NeedsRefresh()) { _logger.InfoFormat($"In Memory cache has SSOToken for [{options.StartUrl}]"); return inMemoryToken.Token; } var cachedToken = await _ssoTokenFileCache.TryGetSsoTokenAsync( options, options.CacheFolderLocation, cancellationToken) .ConfigureAwait(false); if (cachedToken.Success) { _logger.InfoFormat($"File cache has SSOToken for [{options.StartUrl}]"); var ssoToken = cachedToken.Value; // token is not expired and doesn't need a refresh if (!ssoToken.NeedsRefresh()) { var newInMemoryToken = new CacheState { Token = ssoToken, RefreshState = new RefreshState() }; if (AWSConfigs.UseSdkCache) _inMemoryCache.AddOrUpdate(options, newInMemoryToken); return ssoToken; } // refresh token? else if (ssoToken.CanRefresh()) { _logger.InfoFormat($"File cache SSOToken for [{options.StartUrl}] needs refresh"); // only try and refresh an expired token once. if we've already failed, // don't try again. if (true == inMemoryToken?.RefreshState.FailedLastRefreshAttempt && ssoToken.IsExpired()) { throw new AmazonClientException("SSO Token has expired and can not be refreshed"); } // did we recently try to refresh the token? if (true == inMemoryToken?.RefreshState.IsInRefreshCoolDown()) { // if we can't refresh, but have a valid token, return the valid token if (!ssoToken.IsExpired()) { return ssoToken; } // if we can't refresh, but can generate a new token, do that else if (options.SupportsGettingNewToken) { return await GenerateNewTokenAsync(options, cancellationToken).ConfigureAwait(false); } // we've already tried to refresh and failed, nothing more can be done. else { throw new AmazonClientException("SSO Token has expired and can not be refreshed"); } } try { _logger.InfoFormat($"Refreshing SSOToken for [{options.Session}]"); var response = await _ssooidcClient.RefreshTokenAsync(MapSsoTokenToGetSsoTokenResponse(ssoToken)).ConfigureAwait(false); var newToken = MapGetSsoTokenResponseToSsoToken(response, options.Session); await _ssoTokenFileCache.SaveSsoTokenAsync(newToken, options.CacheFolderLocation, cancellationToken).ConfigureAwait(false); var newInMemoryToken = new CacheState { Token = newToken, RefreshState = new RefreshState() }; if (AWSConfigs.UseSdkCache) _inMemoryCache.AddOrUpdate(options, newInMemoryToken); return newToken; } catch (Exception ex) { _logger.Error(ex, $"Refreshing SSOToken for [{options.Session}] failed: {ex.Message}"); if (ssoToken.IsExpired() && options.SupportsGettingNewToken) { return await GenerateNewTokenAsync(options, cancellationToken).ConfigureAwait(false); } else if (!ssoToken.IsExpired()) { var newInMemoryToken = new CacheState { Token = ssoToken, RefreshState = new RefreshState { FailedLastRefreshAttempt = true, BlockRefreshUntil = AWSSDKUtils.CorrectedUtcNow.AddSeconds(30) } }; if (AWSConfigs.UseSdkCache) _inMemoryCache.AddOrUpdate(options, newInMemoryToken); return ssoToken; } else { throw new AmazonClientException("SSO Token has expired and failed to refresh", ex); } } } else if (ssoToken.IsExpired()) { if (options.SupportsGettingNewToken) { return await GenerateNewTokenAsync(options, cancellationToken).ConfigureAwait(false); } else { throw new AmazonClientException("SSO Token has expired and can not be refreshed"); } } else { // Token was not refreshed, continue to use until it expires return ssoToken; } } // if no token found on disk, create one if we can else if (options.SupportsGettingNewToken) { return await GenerateNewTokenAsync(options, cancellationToken).ConfigureAwait(false); } // can't find a token and can't create one else { throw new AmazonClientException("No valid SSO Token could be found."); } } private async Task<SsoToken> GenerateNewTokenAsync(SSOTokenManagerGetTokenOptions options, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(options.ClientName)) { throw new ArgumentNullException($"Options property cannot be empty: {nameof(options.ClientName)}"); } if (options.SsoVerificationCallback == null) { throw new ArgumentNullException($"Options property cannot be empty: {nameof(options.SsoVerificationCallback)}"); } var request = new GetSsoTokenRequest { ClientName = GetSsoClientName(options.ClientName), ClientType = options.ClientType, StartUrl = options.StartUrl, SsoVerificationCallback = options.SsoVerificationCallback, Scopes = options.Scopes }; var response = await _ssooidcClient.GetSsoTokenAsync(request).ConfigureAwait(false); var token = MapGetSsoTokenResponseToSsoToken(response, options.Session); await _ssoTokenFileCache.SaveSsoTokenAsync(token, options.CacheFolderLocation, cancellationToken).ConfigureAwait(false); return token; } #endif private static SsoToken MapGetSsoTokenResponseToSsoToken(GetSsoTokenResponse response, string session) { return new SsoToken { AccessToken = response.AccessToken, Region = response.Region, RefreshToken = response.RefreshToken, ClientId = response.ClientId, ClientSecret = response.ClientSecret, RegistrationExpiresAt = response.RegistrationExpiresAt, ExpiresAt = response.ExpiresAt, StartUrl = response.StartUrl, Session = session }; } private static GetSsoTokenResponse MapSsoTokenToGetSsoTokenResponse(SsoToken token) { return new GetSsoTokenResponse { AccessToken = token.AccessToken, Region = token.Region, RefreshToken = token.RefreshToken, ClientId = token.ClientId, ClientSecret = token.ClientSecret, RegistrationExpiresAt = token.RegistrationExpiresAt, ExpiresAt = token.ExpiresAt, StartUrl = token.StartUrl }; } /// <summary> /// Produces a client name watermarked with a timestamp for use in this provider's SSO Flow. /// </summary> /// <example> /// "sometool" -> "sometool-1599153467" /// </example> /// <returns>A Client Name to use in the internal SSO flow</returns> private static string GetSsoClientName(string clientName) { #pragma warning disable CS0618 // Type or member is obsolete var dateStamp = AWSSDKUtils.ConvertToUnixEpochSecondsString(AWSSDKUtils.CorrectedUtcNow); #pragma warning restore CS0618 // Type or member is obsolete return $"{clientName}-{dateStamp}"; } } }
513
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 Amazon.Runtime.SharedInterfaces; namespace Amazon.Runtime.Credentials.Internal { public class SSOTokenManagerGetTokenOptions { private const string SsoClientTypePublic = "public"; /// <inheritdoc cref="SsoToken.StartUrl"/> public string StartUrl { get; set; } /// <inheritdoc cref="SsoToken.Session"/> public string Session { get; set; } /// <inheritdoc cref="SsoToken.Region"/> public string Region { get; set; } /// <summary> /// Set to override the sso cache location. Leave null /// to use the Default /// </summary> public string CacheFolderLocation { get; set; } /// <inheritdoc cref="SSOAWSCredentialsOptions.ClientName"/> public string ClientName { get; set; } /// <inheritdoc cref="GetSsoTokenRequest.ClientType"/> public string ClientType { get; set; } = SsoClientTypePublic; public IList<string> Scopes { get; set; } /// <inheritdoc cref="SSOAWSCredentialsOptions.SsoVerificationCallback"/> public Action<SsoVerificationArguments> SsoVerificationCallback { get; set; } /// <summary> /// This field controls how <see cref="SSOTokenManager"/> should behave if it does not find a valid or /// refreshable token. /// <para /> /// If <c>true</c>, then <see cref="SSOTokenManager"/> will use <see cref="ICoreAmazonSSOOIDC.GetSsoToken"/> /// to start an authorization flow and mint a new token and cache the result. /// If <c>false</c> <see cref="SSOTokenManager"/> will throw an exception if it finds /// an expired token. It will take no action if finds no cached token. /// <para /> /// NOTE: If setting to <c>true</c>, <see cref="SsoVerificationCallback"/> must also be set /// for authorization flow to succeed. /// </summary> public bool SupportsGettingNewToken { get; set; } = true; } }
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 System.Linq; using System.Text; using System.Xml; using Amazon.Util; using ThirdParty.Json.LitJson; namespace Amazon.Runtime.Credentials.Internal { public static class SsoTokenUtils { private static class JsonPropertyNames { public const string AccessToken = "accessToken"; public const string Region = "region"; public const string RefreshToken = "refreshToken"; public const string ClientId = "clientId"; public const string ClientSecret = "clientSecret"; public const string RegistrationExpiresAt = "registrationExpiresAt"; public const string ExpiresAt = "expiresAt"; public const string StartUrl = "startUrl"; } #region Extension Methods /// <summary> /// True if <see cref="SsoToken.ExpiresAt"/> is less than the current time /// </summary> public static bool IsExpired(this SsoToken token) { if (null == token) throw new ArgumentNullException(nameof(token)); #pragma warning disable CS0618 // Type or member is obsolete var currentTime = AWSSDKUtils.CorrectedUtcNow; #pragma warning restore CS0618 // Type or member is obsolete return token.ExpiresAt < currentTime; } /// <summary> /// True if either the <paramref name="token"/> will expire in 6 minutes or /// has already expired. /// <para /> /// Per Spec: Always try and refresh an expired token. /// </summary> public static bool NeedsRefresh(this SsoToken token) { #pragma warning disable CS0618 // Type or member is obsolete var currentTime = AWSSDKUtils.CorrectedUtcNow; #pragma warning restore CS0618 // Type or member is obsolete return token.ExpiresAt <= currentTime.AddMinutes(6); } /// <summary> /// Indicates if <paramref name="token"/> has the necessary data properties /// to facilitate a refresh attempt. /// <para /> /// NOTE: This does NOT check if the <paramref name="token"/> is within a refresh /// time window. For that, use <see cref="NeedsRefresh"/>/ /// </summary> public static bool CanRefresh(this SsoToken token) { return !string.IsNullOrEmpty(token.RefreshToken) && !string.IsNullOrEmpty(token.ClientId) && !string.IsNullOrEmpty(token.ClientSecret); } /// <summary> /// Serializes the SSO Token to JSON /// </summary> /// <param name="token">Token to serialize</param> public static string AsJson(this SsoToken token) { return ToJson(token); } #endregion /// <summary> /// Serializes the SSO Token to JSON /// </summary> /// <param name="token">Token to serialize</param> public static string ToJson(SsoToken token) { var json = new StringBuilder(); var writer = new JsonWriter(json) { PrettyPrint = true, }; var jsonData = new JsonData { [JsonPropertyNames.AccessToken] = new JsonData(token.AccessToken), [JsonPropertyNames.ExpiresAt] = new JsonData(XmlConvert.ToString(token.ExpiresAt, XmlDateTimeSerializationMode.Utc)), [JsonPropertyNames.RefreshToken] = new JsonData(token.RefreshToken), [JsonPropertyNames.ClientId] = new JsonData(token.ClientId), [JsonPropertyNames.ClientSecret] = new JsonData(token.ClientSecret), [JsonPropertyNames.RegistrationExpiresAt] = new JsonData(token.RegistrationExpiresAt), [JsonPropertyNames.Region] = new JsonData(token.Region), [JsonPropertyNames.StartUrl] = new JsonData(token.StartUrl) }; JsonMapper.ToJson(jsonData, writer); return json.ToString(); } /// <summary> /// Deserializes the SSO Token from JSON /// </summary> /// <param name="json">JSON (string) to deserialize</param> public static SsoToken FromJson(string json) { var jsonData = JsonMapper.ToObject(json); var token = new SsoToken(); if (jsonData.PropertyNames.Contains(JsonPropertyNames.AccessToken)) token.AccessToken = jsonData[JsonPropertyNames.AccessToken].ToString(); else throw new AmazonClientException($"Token is invalid: missing required field [{JsonPropertyNames.AccessToken}]"); if (jsonData.PropertyNames.Contains(JsonPropertyNames.ExpiresAt)) token.ExpiresAt = XmlConvert.ToDateTime(jsonData[JsonPropertyNames.ExpiresAt].ToString(), XmlDateTimeSerializationMode.Utc); else throw new AmazonClientException($"Token is invalid: missing required field [{JsonPropertyNames.ExpiresAt}]"); if (jsonData.PropertyNames.Contains(JsonPropertyNames.RefreshToken)) token.RefreshToken = jsonData[JsonPropertyNames.RefreshToken]?.ToString(); if (jsonData.PropertyNames.Contains(JsonPropertyNames.ClientId)) token.ClientId = jsonData[JsonPropertyNames.ClientId]?.ToString(); if (jsonData.PropertyNames.Contains(JsonPropertyNames.ClientSecret)) token.ClientSecret = jsonData[JsonPropertyNames.ClientSecret]?.ToString(); if (jsonData.PropertyNames.Contains(JsonPropertyNames.RegistrationExpiresAt)) token.RegistrationExpiresAt = jsonData[JsonPropertyNames.RegistrationExpiresAt]?.ToString(); if (jsonData.PropertyNames.Contains(JsonPropertyNames.Region)) token.Region = jsonData[JsonPropertyNames.Region]?.ToString(); if (jsonData.PropertyNames.Contains(JsonPropertyNames.StartUrl)) token.StartUrl = jsonData[JsonPropertyNames.StartUrl]?.ToString(); return token; } } }
167