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-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class DecryptMaterialsOutput { private AWS.EncryptionSDK.Core.DecryptionMaterials _decryptionMaterials; public AWS.EncryptionSDK.Core.DecryptionMaterials DecryptionMaterials { get { return this._decryptionMaterials; } set { this._decryptionMaterials = value; } } internal bool IsSetDecryptionMaterials() { return this._decryptionMaterials != null; } public void Validate() { if (!IsSetDecryptionMaterials()) throw new System.ArgumentException("Missing value for required property 'DecryptionMaterials'"); } } }
32
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class DiscoveryFilter { private System.Collections.Generic.List<string> _accountIds; private string _partition; public System.Collections.Generic.List<string> AccountIds { get { return this._accountIds; } set { this._accountIds = value; } } internal bool IsSetAccountIds() { return this._accountIds != null; } public string Partition { get { return this._partition; } set { this._partition = value; } } internal bool IsSetPartition() { return this._partition != null; } public void Validate() { if (!IsSetAccountIds()) throw new System.ArgumentException("Missing value for required property 'AccountIds'"); if (!IsSetPartition()) throw new System.ArgumentException("Missing value for required property 'Partition'"); } } }
46
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class EncryptedDataKey { private string _keyProviderId; private System.IO.MemoryStream _keyProviderInfo; private System.IO.MemoryStream _ciphertext; public string KeyProviderId { get { return this._keyProviderId; } set { this._keyProviderId = value; } } internal bool IsSetKeyProviderId() { return this._keyProviderId != null; } public System.IO.MemoryStream KeyProviderInfo { get { return this._keyProviderInfo; } set { this._keyProviderInfo = value; } } internal bool IsSetKeyProviderInfo() { return this._keyProviderInfo != null; } public System.IO.MemoryStream Ciphertext { get { return this._ciphertext; } set { this._ciphertext = value; } } internal bool IsSetCiphertext() { return this._ciphertext != null; } public void Validate() { if (!IsSetKeyProviderId()) throw new System.ArgumentException("Missing value for required property 'KeyProviderId'"); if (!IsSetKeyProviderInfo()) throw new System.ArgumentException("Missing value for required property 'KeyProviderInfo'"); if (!IsSetCiphertext()) throw new System.ArgumentException("Missing value for required property 'Ciphertext'"); } } }
60
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class EncryptionMaterials { private AWS.EncryptionSDK.Core.AlgorithmSuiteId _algorithmSuiteId; private System.Collections.Generic.Dictionary<string, string> _encryptionContext; private System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> _encryptedDataKeys; private System.IO.MemoryStream _plaintextDataKey; private System.IO.MemoryStream _signingKey; public AWS.EncryptionSDK.Core.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } internal bool IsSetAlgorithmSuiteId() { return this._algorithmSuiteId != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } internal bool IsSetEncryptionContext() { return this._encryptionContext != null; } public System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> EncryptedDataKeys { get { return this._encryptedDataKeys; } set { this._encryptedDataKeys = value; } } internal bool IsSetEncryptedDataKeys() { return this._encryptedDataKeys != null; } public System.IO.MemoryStream PlaintextDataKey { get { return this._plaintextDataKey; } set { this._plaintextDataKey = value; } } internal bool IsSetPlaintextDataKey() { return this._plaintextDataKey != null; } public System.IO.MemoryStream SigningKey { get { return this._signingKey; } set { this._signingKey = value; } } internal bool IsSetSigningKey() { return this._signingKey != null; } public void Validate() { if (!IsSetAlgorithmSuiteId()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuiteId'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetEncryptedDataKeys()) throw new System.ArgumentException("Missing value for required property 'EncryptedDataKeys'"); } } }
84
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class GetClientInput { private string _region; public string Region { get { return this._region; } set { this._region = value; } } internal bool IsSetRegion() { return this._region != null; } public void Validate() { if (!IsSetRegion()) throw new System.ArgumentException("Missing value for required property 'Region'"); } } }
31
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class GetEncryptionMaterialsInput { private System.Collections.Generic.Dictionary<string, string> _encryptionContext; private AWS.EncryptionSDK.Core.CommitmentPolicy _commitmentPolicy; private AWS.EncryptionSDK.Core.AlgorithmSuiteId _algorithmSuiteId; private long? _maxPlaintextLength; public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } internal bool IsSetEncryptionContext() { return this._encryptionContext != null; } public AWS.EncryptionSDK.Core.CommitmentPolicy CommitmentPolicy { get { return this._commitmentPolicy; } set { this._commitmentPolicy = value; } } internal bool IsSetCommitmentPolicy() { return this._commitmentPolicy != null; } public AWS.EncryptionSDK.Core.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } internal bool IsSetAlgorithmSuiteId() { return this._algorithmSuiteId != null; } public long MaxPlaintextLength { get { return this._maxPlaintextLength.GetValueOrDefault(); } set { this._maxPlaintextLength = value; } } internal bool IsSetMaxPlaintextLength() { return this._maxPlaintextLength.HasValue; } public void Validate() { if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetCommitmentPolicy()) throw new System.ArgumentException("Missing value for required property 'CommitmentPolicy'"); } } }
70
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class GetEncryptionMaterialsOutput { private AWS.EncryptionSDK.Core.EncryptionMaterials _encryptionMaterials; public AWS.EncryptionSDK.Core.EncryptionMaterials EncryptionMaterials { get { return this._encryptionMaterials; } set { this._encryptionMaterials = value; } } internal bool IsSetEncryptionMaterials() { return this._encryptionMaterials != null; } public void Validate() { if (!IsSetEncryptionMaterials()) throw new System.ArgumentException("Missing value for required property 'EncryptionMaterials'"); } } }
32
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public interface IAwsCryptographicMaterialProviders { AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsKeyring(AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkKeyring(AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateMultiKeyring(AWS.EncryptionSDK.Core.CreateMultiKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateRawAesKeyring(AWS.EncryptionSDK.Core.CreateRawAesKeyringInput input); AWS.EncryptionSDK.Core.IKeyring CreateRawRsaKeyring(AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput input); AWS.EncryptionSDK.Core.ICryptographicMaterialsManager CreateDefaultCryptographicMaterialsManager( AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput input); AWS.EncryptionSDK.Core.IClientSupplier CreateDefaultClientSupplier( AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput input); } }
46
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public interface IClientSupplier { Amazon.KeyManagementService.IAmazonKeyManagementService GetClient(AWS.EncryptionSDK.Core.GetClientInput input); } }
15
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public interface ICryptographicMaterialsManager { AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput GetEncryptionMaterials( AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput input); AWS.EncryptionSDK.Core.DecryptMaterialsOutput DecryptMaterials( AWS.EncryptionSDK.Core.DecryptMaterialsInput input); } }
19
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public interface IKeyring { AWS.EncryptionSDK.Core.OnEncryptOutput OnEncrypt(AWS.EncryptionSDK.Core.OnEncryptInput input); AWS.EncryptionSDK.Core.OnDecryptOutput OnDecrypt(AWS.EncryptionSDK.Core.OnDecryptInput input); } }
16
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { internal class Keyring : KeyringBase { internal readonly Dafny.Aws.EncryptionSdk.Core.IKeyring _impl; internal Keyring(Dafny.Aws.EncryptionSdk.Core.IKeyring impl) { this._impl = impl; } protected override AWS.EncryptionSDK.Core.OnDecryptOutput _OnDecrypt( AWS.EncryptionSDK.Core.OnDecryptInput input) { Dafny.Aws.EncryptionSdk.Core._IOnDecryptInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IOnDecryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.OnDecrypt(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput(result.dtor_value); } protected override AWS.EncryptionSDK.Core.OnEncryptOutput _OnEncrypt( AWS.EncryptionSDK.Core.OnEncryptInput input) { Dafny.Aws.EncryptionSdk.Core._IOnEncryptInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IOnEncryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.OnEncrypt(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput(result.dtor_value); } } }
50
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public abstract class KeyringBase : IKeyring { public AWS.EncryptionSDK.Core.OnEncryptOutput OnEncrypt(AWS.EncryptionSDK.Core.OnEncryptInput input) { input.Validate(); return _OnEncrypt(input); } protected abstract AWS.EncryptionSDK.Core.OnEncryptOutput _OnEncrypt( AWS.EncryptionSDK.Core.OnEncryptInput input); public AWS.EncryptionSDK.Core.OnDecryptOutput OnDecrypt(AWS.EncryptionSDK.Core.OnDecryptInput input) { input.Validate(); return _OnDecrypt(input); } protected abstract AWS.EncryptionSDK.Core.OnDecryptOutput _OnDecrypt( AWS.EncryptionSDK.Core.OnDecryptInput input); } }
31
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. // ReSharper disable RedundantUsingDirective // ReSharper disable RedundantNameQualifier // ReSharper disable SuggestVarOrType_SimpleTypes using System; using AWS.EncryptionSDK.Core; using Wrappers_Compile; namespace AWS.EncryptionSDK.Core { internal class NativeWrapper_ClientSupplier : Dafny.Aws.EncryptionSdk.Core.IClientSupplier { internal readonly ClientSupplierBase _impl; public NativeWrapper_ClientSupplier(ClientSupplierBase nativeImpl) { _impl = nativeImpl; } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> GetClient( Dafny.Aws.EncryptionSdk.Core._IGetClientInput input) { AWS.EncryptionSDK.Core.GetClientInput nativeInput = TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput(input); AwsCryptographicMaterialProvidersBaseException finalException = null; try { Amazon.KeyManagementService.IAmazonKeyManagementService nativeOutput = _impl.GetClient(nativeInput); _ = nativeOutput ?? throw new AwsCryptographicMaterialProvidersException( $"{_impl}._GetClient returned null, should be {typeof(Amazon.KeyManagementService.IAmazonKeyManagementService)}"); return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Success( TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput(nativeOutput)); } catch (AwsCryptographicMaterialProvidersBaseException e) { finalException = e; } catch (Exception e) { var message = $"{_impl}._GetClient threw unexpected: {e.GetType()}: \"{e.Message}\""; finalException = new AwsCryptographicMaterialProvidersBaseException(message); } return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Failure(TypeConversion.ToDafny_CommonError(finalException)); } } }
59
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. // ReSharper disable RedundantUsingDirective // ReSharper disable RedundantNameQualifier // ReSharper disable SuggestVarOrType_SimpleTypes using System; using AWS.EncryptionSDK.Core; using Wrappers_Compile; namespace AWS.EncryptionSDK.Core { internal class NativeWrapper_CryptographicMaterialsManager : Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager { internal readonly CryptographicMaterialsManagerBase _impl; public NativeWrapper_CryptographicMaterialsManager(CryptographicMaterialsManagerBase nativeImpl) { _impl = nativeImpl; } public Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> DecryptMaterials( Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsInput input) { void validateOutput(AWS.EncryptionSDK.Core.DecryptMaterialsOutput nativeOutput) { try { nativeOutput.Validate(); } catch (ArgumentException e) { var message = $"Output of {_impl}._DecryptMaterials is invalid. {e.Message}"; throw new AwsCryptographicMaterialProvidersException(message); } } AWS.EncryptionSDK.Core.DecryptMaterialsInput nativeInput = TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput(input); AwsCryptographicMaterialProvidersBaseException finalException = null; try { AWS.EncryptionSDK.Core.DecryptMaterialsOutput nativeOutput = _impl.DecryptMaterials(nativeInput); _ = nativeOutput ?? throw new AwsCryptographicMaterialProvidersException( $"{_impl}._DecryptMaterials returned null, should be {typeof(AWS.EncryptionSDK.Core.DecryptMaterialsOutput)}"); validateOutput(nativeOutput); return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Success( TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput( nativeOutput)); } catch (AwsCryptographicMaterialProvidersBaseException e) { finalException = e; } catch (Exception e) { var message = $"{_impl}._DecryptMaterials threw unexpected: {e.GetType()}: \"{e.Message}\""; finalException = new AwsCryptographicMaterialProvidersBaseException(message); } return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Failure(TypeConversion.ToDafny_CommonError(finalException)); } public Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> GetEncryptionMaterials( Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsInput input) { void validateOutput(AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput nativeOutput) { try { nativeOutput.Validate(); } catch (ArgumentException e) { var message = $"Output of {_impl}._GetEncryptionMaterials is invalid. {e.Message}"; throw new AwsCryptographicMaterialProvidersException(message); } } AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput nativeInput = TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput(input); AwsCryptographicMaterialProvidersBaseException finalException = null; try { AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput nativeOutput = _impl.GetEncryptionMaterials(nativeInput); _ = nativeOutput ?? throw new AwsCryptographicMaterialProvidersException( $"{_impl}._GetEncryptionMaterials returned null, should be {typeof(AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput)}"); validateOutput(nativeOutput); return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Success(TypeConversion .ToDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput(nativeOutput)); } catch (AwsCryptographicMaterialProvidersBaseException e) { finalException = e; } catch (Exception e) { var message = $"{_impl}._GetEncryptionMaterials threw unexpected: {e.GetType()}: \"{e.Message}\""; finalException = new AwsCryptographicMaterialProvidersBaseException(message); } return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Failure(TypeConversion.ToDafny_CommonError(finalException)); } } }
123
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. // ReSharper disable RedundantUsingDirective // ReSharper disable RedundantNameQualifier // ReSharper disable SuggestVarOrType_SimpleTypes using System; using AWS.EncryptionSDK.Core; using Wrappers_Compile; namespace AWS.EncryptionSDK.Core { internal class NativeWrapper_Keyring : Dafny.Aws.EncryptionSdk.Core.IKeyring { internal readonly KeyringBase _impl; public NativeWrapper_Keyring(KeyringBase nativeImpl) { _impl = nativeImpl; } public Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IOnDecryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> OnDecrypt( Dafny.Aws.EncryptionSdk.Core._IOnDecryptInput input) { void validateOutput(AWS.EncryptionSDK.Core.OnDecryptOutput nativeOutput) { try { nativeOutput.Validate(); } catch (ArgumentException e) { var message = $"Output of {_impl}._OnDecrypt is invalid. {e.Message}"; throw new AwsCryptographicMaterialProvidersException(message); } } AWS.EncryptionSDK.Core.OnDecryptInput nativeInput = TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput(input); AwsCryptographicMaterialProvidersBaseException finalException = null; try { AWS.EncryptionSDK.Core.OnDecryptOutput nativeOutput = _impl.OnDecrypt(nativeInput); _ = nativeOutput ?? throw new AwsCryptographicMaterialProvidersException( $"{_impl}._OnDecrypt returned null, should be {typeof(AWS.EncryptionSDK.Core.OnDecryptOutput)}"); validateOutput(nativeOutput); return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IOnDecryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Success( TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput(nativeOutput)); } catch (AwsCryptographicMaterialProvidersBaseException e) { finalException = e; } catch (Exception e) { var message = $"{_impl}._OnDecrypt threw unexpected: {e.GetType()}: \"{e.Message}\""; finalException = new AwsCryptographicMaterialProvidersBaseException(message); } return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IOnDecryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Failure(TypeConversion.ToDafny_CommonError(finalException)); } public Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IOnEncryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> OnEncrypt( Dafny.Aws.EncryptionSdk.Core._IOnEncryptInput input) { void validateOutput(AWS.EncryptionSDK.Core.OnEncryptOutput nativeOutput) { try { nativeOutput.Validate(); } catch (ArgumentException e) { var message = $"Output of {_impl}._OnEncrypt is invalid. {e.Message}"; throw new AwsCryptographicMaterialProvidersException(message); } } AWS.EncryptionSDK.Core.OnEncryptInput nativeInput = TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput(input); AwsCryptographicMaterialProvidersBaseException finalException = null; try { AWS.EncryptionSDK.Core.OnEncryptOutput nativeOutput = _impl.OnEncrypt(nativeInput); _ = nativeOutput ?? throw new AwsCryptographicMaterialProvidersException( $"{_impl}._OnEncrypt returned null, should be {typeof(AWS.EncryptionSDK.Core.OnEncryptOutput)}"); validateOutput(nativeOutput); return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IOnEncryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Success( TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput(nativeOutput)); } catch (AwsCryptographicMaterialProvidersBaseException e) { finalException = e; } catch (Exception e) { var message = $"{_impl}._OnEncrypt threw unexpected: {e.GetType()}: \"{e.Message}\""; finalException = new AwsCryptographicMaterialProvidersBaseException(message); } return Wrappers_Compile .Result<Dafny.Aws.EncryptionSdk.Core._IOnEncryptOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> .create_Failure(TypeConversion.ToDafny_CommonError(finalException)); } } }
120
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class OnDecryptInput { private AWS.EncryptionSDK.Core.DecryptionMaterials _materials; private System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> _encryptedDataKeys; public AWS.EncryptionSDK.Core.DecryptionMaterials Materials { get { return this._materials; } set { this._materials = value; } } internal bool IsSetMaterials() { return this._materials != null; } public System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> EncryptedDataKeys { get { return this._encryptedDataKeys; } set { this._encryptedDataKeys = value; } } internal bool IsSetEncryptedDataKeys() { return this._encryptedDataKeys != null; } public void Validate() { if (!IsSetMaterials()) throw new System.ArgumentException("Missing value for required property 'Materials'"); if (!IsSetEncryptedDataKeys()) throw new System.ArgumentException("Missing value for required property 'EncryptedDataKeys'"); } } }
46
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class OnDecryptOutput { private AWS.EncryptionSDK.Core.DecryptionMaterials _materials; public AWS.EncryptionSDK.Core.DecryptionMaterials Materials { get { return this._materials; } set { this._materials = value; } } internal bool IsSetMaterials() { return this._materials != null; } public void Validate() { if (!IsSetMaterials()) throw new System.ArgumentException("Missing value for required property 'Materials'"); } } }
32
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class OnEncryptInput { private AWS.EncryptionSDK.Core.EncryptionMaterials _materials; public AWS.EncryptionSDK.Core.EncryptionMaterials Materials { get { return this._materials; } set { this._materials = value; } } internal bool IsSetMaterials() { return this._materials != null; } public void Validate() { if (!IsSetMaterials()) throw new System.ArgumentException("Missing value for required property 'Materials'"); } } }
32
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class OnEncryptOutput { private AWS.EncryptionSDK.Core.EncryptionMaterials _materials; public AWS.EncryptionSDK.Core.EncryptionMaterials Materials { get { return this._materials; } set { this._materials = value; } } internal bool IsSetMaterials() { return this._materials != null; } public void Validate() { if (!IsSetMaterials()) throw new System.ArgumentException("Missing value for required property 'Materials'"); } } }
32
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { using Amazon.Runtime; public class PaddingScheme : ConstantClass { public static readonly PaddingScheme PKCS1 = new PaddingScheme("PKCS1"); public static readonly PaddingScheme OAEP_SHA1_MGF1 = new PaddingScheme("OAEP_SHA1_MGF1"); public static readonly PaddingScheme OAEP_SHA256_MGF1 = new PaddingScheme("OAEP_SHA256_MGF1"); public static readonly PaddingScheme OAEP_SHA384_MGF1 = new PaddingScheme("OAEP_SHA384_MGF1"); public static readonly PaddingScheme OAEP_SHA512_MGF1 = new PaddingScheme("OAEP_SHA512_MGF1"); public static readonly PaddingScheme[] Values = { OAEP_SHA1_MGF1, OAEP_SHA256_MGF1, OAEP_SHA384_MGF1, OAEP_SHA512_MGF1, PKCS1 }; public PaddingScheme(string value) : base(value) { } } }
34
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System.Linq; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { internal static class TypeConversion { public static System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M13_childKeyrings( Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core.IKeyring> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList(value); } public static Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core.IKeyring> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M13_childKeyrings( System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList(value); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_algorithmSuiteId( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId> value) { return value.is_None ? (AWS.EncryptionSDK.Core.AlgorithmSuiteId)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_algorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId( (AWS.EncryptionSDK.Core.AlgorithmSuiteId)value)); } public static System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList( Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core.IKeyring> value) { return new System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring>( value.Elements.Select(FromDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList__M6_member)); } public static Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core.IKeyring> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList( System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring> value) { return Dafny.Sequence<Dafny.Aws.EncryptionSdk.Core.IKeyring>.FromArray(value .Select(ToDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList__M6_member).ToArray()); } public static System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptedDataKeys( Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList(value); } public static Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptedDataKeys( System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList(value); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput__M7_keyring( Dafny.Aws.EncryptionSdk.Core.IKeyring value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value); } public static Dafny.Aws.EncryptionSdk.Core.IKeyring ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput__M7_keyring( AWS.EncryptionSDK.Core.IKeyring value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput__M6_region( Dafny.ISequence<char> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput__M6_region( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(value); } public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M9_kmsClient( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M9_kmsClient( Amazon.KeyManagementService.IAmazonKeyManagementService value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static AWS.EncryptionSDK.Core.IClientSupplier FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M14_clientSupplier( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> value) { return value.is_None ? (AWS.EncryptionSDK.Core.IClientSupplier)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M14_clientSupplier( AWS.EncryptionSDK.Core.IClientSupplier value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference( (AWS.EncryptionSDK.Core.IClientSupplier)value)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value( Dafny.ISequence<byte> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput__M6_client( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput__M6_client( Amazon.KeyManagementService.IAmazonKeyManagementService value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingKey( Dafny.ISequence<byte> value) { return FromDafny_N6_smithy__N3_api__S4_Blob(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingKey( System.IO.MemoryStream value) { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M10_privateKey( Wrappers_Compile._IOption<Dafny.ISequence<byte>> value) { return value.is_None ? (System.IO.MemoryStream)null : FromDafny_N6_smithy__N3_api__S4_Blob(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M10_privateKey( System.IO.MemoryStream value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_Some( ToDafny_N6_smithy__N3_api__S4_Blob((System.IO.MemoryStream)value)); } public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient value) { if (value is Com.Amazonaws.Kms.KeyManagementServiceShim shim) { return shim._impl; } throw new System.ArgumentException( "Custom implementations of Amazon.KeyManagementService.IAmazonKeyManagementService are not supported yet"); } public static Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient ToDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference( Amazon.KeyManagementService.IAmazonKeyManagementService value) { if (value is Amazon.KeyManagementService.AmazonKeyManagementServiceClient impl) { return new Com.Amazonaws.Kms.KeyManagementServiceShim(impl); } throw new System.ArgumentException( "Custom implementations of Amazon.KeyManagementService.IAmazonKeyManagementService are not supported yet"); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static AWS.EncryptionSDK.Core.DecryptMaterialsOutput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput( Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsOutput value) { Dafny.Aws.EncryptionSdk.Core.DecryptMaterialsOutput concrete = (Dafny.Aws.EncryptionSdk.Core.DecryptMaterialsOutput)value; AWS.EncryptionSDK.Core.DecryptMaterialsOutput converted = new AWS.EncryptionSDK.Core.DecryptMaterialsOutput(); converted.DecryptionMaterials = (AWS.EncryptionSDK.Core.DecryptionMaterials) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput__M19_decryptionMaterials( concrete.decryptionMaterials); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsOutput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput( AWS.EncryptionSDK.Core.DecryptMaterialsOutput value) { return new Dafny.Aws.EncryptionSdk.Core.DecryptMaterialsOutput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput__M19_decryptionMaterials( value.DecryptionMaterials)); } public static AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkDiscoveryMultiKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput(); converted.Regions = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M7_regions( concrete.regions); if (concrete.discoveryFilter.is_Some) converted.DiscoveryFilter = (AWS.EncryptionSDK.Core.DiscoveryFilter) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M15_discoveryFilter( concrete.discoveryFilter); if (concrete.clientSupplier.is_Some) converted.ClientSupplier = (AWS.EncryptionSDK.Core.IClientSupplier) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M14_clientSupplier( concrete.clientSupplier); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M11_grantTokens( concrete.grantTokens); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkDiscoveryMultiKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput value) { AWS.EncryptionSDK.Core.DiscoveryFilter var_discoveryFilter = value.IsSetDiscoveryFilter() ? value.DiscoveryFilter : (AWS.EncryptionSDK.Core.DiscoveryFilter)null; AWS.EncryptionSDK.Core.IClientSupplier var_clientSupplier = value.IsSetClientSupplier() ? value.ClientSupplier : (AWS.EncryptionSDK.Core.IClientSupplier)null; System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M7_regions( value.Regions), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M15_discoveryFilter( var_discoveryFilter), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M14_clientSupplier( var_clientSupplier), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M11_grantTokens( var_grantTokens)); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_algorithmSuiteId( Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_algorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M12_keyNamespace( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M12_keyNamespace(string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList( Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> value) { return new System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey>( value.Elements.Select( FromDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList__M6_member)); } public static Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList( System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> value) { return Dafny.Sequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey>.FromArray(value .Select(ToDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList__M6_member).ToArray()); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M15_keyProviderInfo( Dafny.ISequence<byte> value) { return FromDafny_N6_smithy__N3_api__S4_Blob(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M15_keyProviderInfo( System.IO.MemoryStream value) { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M9_kmsClient( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M9_kmsClient( Amazon.KeyManagementService.IAmazonKeyManagementService value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M10_ciphertext( Dafny.ISequence<byte> value) { return FromDafny_N6_smithy__N3_api__S4_Blob(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M10_ciphertext( System.IO.MemoryStream value) { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } public static AWS.EncryptionSDK.Core.PaddingScheme FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M13_paddingScheme( Dafny.Aws.EncryptionSdk.Core._IPaddingScheme value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S13_PaddingScheme(value); } public static Dafny.Aws.EncryptionSdk.Core._IPaddingScheme ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M13_paddingScheme( AWS.EncryptionSDK.Core.PaddingScheme value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S13_PaddingScheme(value); } public static AWS.EncryptionSDK.Core.DecryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials( Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials value) { Dafny.Aws.EncryptionSdk.Core.DecryptionMaterials concrete = (Dafny.Aws.EncryptionSdk.Core.DecryptionMaterials)value; AWS.EncryptionSDK.Core.DecryptionMaterials converted = new AWS.EncryptionSDK.Core.DecryptionMaterials(); converted.AlgorithmSuiteId = (AWS.EncryptionSDK.Core.AlgorithmSuiteId) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_algorithmSuiteId( concrete.algorithmSuiteId); converted.EncryptionContext = (System.Collections.Generic.Dictionary<string, string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M17_encryptionContext( concrete.encryptionContext); if (concrete.plaintextDataKey.is_Some) converted.PlaintextDataKey = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_plaintextDataKey( concrete.plaintextDataKey); if (concrete.verificationKey.is_Some) converted.VerificationKey = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M15_verificationKey( concrete.verificationKey); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials( AWS.EncryptionSDK.Core.DecryptionMaterials value) { System.IO.MemoryStream var_plaintextDataKey = value.IsSetPlaintextDataKey() ? value.PlaintextDataKey : (System.IO.MemoryStream)null; System.IO.MemoryStream var_verificationKey = value.IsSetVerificationKey() ? value.VerificationKey : (System.IO.MemoryStream)null; return new Dafny.Aws.EncryptionSdk.Core.DecryptionMaterials( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_algorithmSuiteId( value.AlgorithmSuiteId), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M17_encryptionContext( value.EncryptionContext), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_plaintextDataKey( var_plaintextDataKey), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M15_verificationKey( var_verificationKey)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(Dafny.ISequence<byte> value) { System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); return utf8.GetString(value.Elements); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(string value) { System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); return Dafny.Sequence<byte>.FromArray(utf8.GetBytes(value)); } public static AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsDiscoveryMultiKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsDiscoveryMultiKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsDiscoveryMultiKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput(); converted.Regions = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M7_regions( concrete.regions); if (concrete.discoveryFilter.is_Some) converted.DiscoveryFilter = (AWS.EncryptionSDK.Core.DiscoveryFilter) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M15_discoveryFilter( concrete.discoveryFilter); if (concrete.clientSupplier.is_Some) converted.ClientSupplier = (AWS.EncryptionSDK.Core.IClientSupplier) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M14_clientSupplier( concrete.clientSupplier); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M11_grantTokens( concrete.grantTokens); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsDiscoveryMultiKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput value) { AWS.EncryptionSDK.Core.DiscoveryFilter var_discoveryFilter = value.IsSetDiscoveryFilter() ? value.DiscoveryFilter : (AWS.EncryptionSDK.Core.DiscoveryFilter)null; AWS.EncryptionSDK.Core.IClientSupplier var_clientSupplier = value.IsSetClientSupplier() ? value.ClientSupplier : (AWS.EncryptionSDK.Core.IClientSupplier)null; System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsDiscoveryMultiKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M7_regions( value.Regions), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M15_discoveryFilter( var_discoveryFilter), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M14_clientSupplier( var_clientSupplier), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M11_grantTokens( var_grantTokens)); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M10_signingKey( Wrappers_Compile._IOption<Dafny.ISequence<byte>> value) { return value.is_None ? (System.IO.MemoryStream)null : FromDafny_N6_smithy__N3_api__S4_Blob(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M10_signingKey( System.IO.MemoryStream value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_Some( ToDafny_N6_smithy__N3_api__S4_Blob((System.IO.MemoryStream)value)); } public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput__M6_client(value); } public static Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput( Amazon.KeyManagementService.IAmazonKeyManagementService value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput__M6_client(value); } public static AWS.EncryptionSDK.Core.OnEncryptInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput( Dafny.Aws.EncryptionSdk.Core._IOnEncryptInput value) { Dafny.Aws.EncryptionSdk.Core.OnEncryptInput concrete = (Dafny.Aws.EncryptionSdk.Core.OnEncryptInput)value; AWS.EncryptionSDK.Core.OnEncryptInput converted = new AWS.EncryptionSDK.Core.OnEncryptInput(); converted.Materials = (AWS.EncryptionSDK.Core.EncryptionMaterials) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput__M9_materials(concrete.materials); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IOnEncryptInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput(AWS.EncryptionSDK.Core.OnEncryptInput value) { return new Dafny.Aws.EncryptionSdk.Core.OnEncryptInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput__M9_materials(value.Materials)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(Dafny.ISequence<char> value) { return new string(value.Elements); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(string value) { return Dafny.Sequence<char>.FromString(value); } public static AWS.EncryptionSDK.Core.IClientSupplier FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference( Dafny.Aws.EncryptionSdk.Core.IClientSupplier value) { if (value is NativeWrapper_ClientSupplier nativeWrapper) return nativeWrapper._impl; return new ClientSupplier(value); } public static Dafny.Aws.EncryptionSdk.Core.IClientSupplier ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference( AWS.EncryptionSDK.Core.IClientSupplier value) { switch (value) { case ClientSupplier valueWithImpl: return valueWithImpl._impl; case ClientSupplierBase nativeImpl: return new NativeWrapper_ClientSupplier(nativeImpl); default: throw new System.ArgumentException( "Custom implementations of ClientSupplier must extend ClientSupplierBase."); } } public static AWS.EncryptionSDK.Core.EncryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials( Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials value) { Dafny.Aws.EncryptionSdk.Core.EncryptionMaterials concrete = (Dafny.Aws.EncryptionSdk.Core.EncryptionMaterials)value; AWS.EncryptionSDK.Core.EncryptionMaterials converted = new AWS.EncryptionSDK.Core.EncryptionMaterials(); converted.AlgorithmSuiteId = (AWS.EncryptionSDK.Core.AlgorithmSuiteId) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_algorithmSuiteId( concrete.algorithmSuiteId); converted.EncryptionContext = (System.Collections.Generic.Dictionary<string, string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptionContext( concrete.encryptionContext); converted.EncryptedDataKeys = (System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptedDataKeys( concrete.encryptedDataKeys); if (concrete.plaintextDataKey.is_Some) converted.PlaintextDataKey = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_plaintextDataKey( concrete.plaintextDataKey); if (concrete.signingKey.is_Some) converted.SigningKey = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M10_signingKey( concrete.signingKey); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials( AWS.EncryptionSDK.Core.EncryptionMaterials value) { System.IO.MemoryStream var_plaintextDataKey = value.IsSetPlaintextDataKey() ? value.PlaintextDataKey : (System.IO.MemoryStream)null; System.IO.MemoryStream var_signingKey = value.IsSetSigningKey() ? value.SigningKey : (System.IO.MemoryStream)null; return new Dafny.Aws.EncryptionSdk.Core.EncryptionMaterials( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_algorithmSuiteId( value.AlgorithmSuiteId), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptionContext( value.EncryptionContext), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptedDataKeys( value.EncryptedDataKeys), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_plaintextDataKey( var_plaintextDataKey), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M10_signingKey(var_signingKey)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList__M6_member( Dafny.ISequence<char> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList__M6_member( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M10_accountIds( Dafny.ISequence<Dafny.ISequence<char>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList(value); } public static Dafny.ISequence<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M10_accountIds( System.Collections.Generic.List<string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList(value); } public static AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput(); converted.KmsKeyId = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M8_kmsKeyId( concrete.kmsKeyId); converted.KmsClient = (Amazon.KeyManagementService.IAmazonKeyManagementService) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M9_kmsClient( concrete.kmsClient); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M11_grantTokens( concrete.grantTokens); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput value) { System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M8_kmsKeyId(value.KmsKeyId), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M9_kmsClient(value.KmsClient), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M11_grantTokens( var_grantTokens)); } public static AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput( Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsInput value) { Dafny.Aws.EncryptionSdk.Core.GetEncryptionMaterialsInput concrete = (Dafny.Aws.EncryptionSdk.Core.GetEncryptionMaterialsInput)value; AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput converted = new AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput(); converted.EncryptionContext = (System.Collections.Generic.Dictionary<string, string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M17_encryptionContext( concrete.encryptionContext); converted.CommitmentPolicy = (AWS.EncryptionSDK.Core.CommitmentPolicy) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_commitmentPolicy( concrete.commitmentPolicy); if (concrete.algorithmSuiteId.is_Some) converted.AlgorithmSuiteId = (AWS.EncryptionSDK.Core.AlgorithmSuiteId) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_algorithmSuiteId( concrete.algorithmSuiteId); if (concrete.maxPlaintextLength.is_Some) converted.MaxPlaintextLength = (long) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M18_maxPlaintextLength( concrete.maxPlaintextLength); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput( AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput value) { AWS.EncryptionSDK.Core.AlgorithmSuiteId var_algorithmSuiteId = value.IsSetAlgorithmSuiteId() ? value.AlgorithmSuiteId : (AWS.EncryptionSDK.Core.AlgorithmSuiteId)null; long? var_maxPlaintextLength = value.IsSetMaxPlaintextLength() ? value.MaxPlaintextLength : (long?)null; return new Dafny.Aws.EncryptionSdk.Core.GetEncryptionMaterialsInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M17_encryptionContext( value.EncryptionContext), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_commitmentPolicy( value.CommitmentPolicy), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_algorithmSuiteId( var_algorithmSuiteId), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M18_maxPlaintextLength( var_maxPlaintextLength)); } public static AWS.EncryptionSDK.Core.IAwsCryptographicMaterialProviders FromDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersReference( Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProviders value) { return new AwsCryptographicMaterialProviders(value); } public static Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProviders ToDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersReference( AWS.EncryptionSDK.Core.IAwsCryptographicMaterialProviders value) { if (value is AwsCryptographicMaterialProviders valueWithImpl) { return valueWithImpl._impl; } throw new System.ArgumentException( "Custom implementations of AWS.EncryptionSDK.Core.IAwsCryptographicMaterialProviders are not supported"); } public static AWS.EncryptionSDK.Core.DiscoveryFilter FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M15_discoveryFilter( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> value) { return value.is_None ? (AWS.EncryptionSDK.Core.DiscoveryFilter)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M15_discoveryFilter( AWS.EncryptionSDK.Core.DiscoveryFilter value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter( (AWS.EncryptionSDK.Core.DiscoveryFilter)value)); } public static AWS.EncryptionSDK.Core.AwsCryptographicMaterialProvidersException FromDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException( Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersException value) { return new AWS.EncryptionSDK.Core.AwsCryptographicMaterialProvidersException( FromDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException__M7_message( value.message)); } public static Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersException ToDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException( AWS.EncryptionSDK.Core.AwsCryptographicMaterialProvidersException value) { Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersException converted = new Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersException(); converted.message = ToDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException__M7_message( value.Message); return converted; } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M9_partition( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M9_partition(string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static AWS.EncryptionSDK.Core.EncryptedDataKey FromDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList__M6_member( Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey(value); } public static Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey ToDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList__M6_member( AWS.EncryptionSDK.Core.EncryptedDataKey value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey(value); } public static string FromDafny_N6_smithy__N3_api__S6_String(Dafny.ISequence<char> value) { return new string(value.Elements); } public static Dafny.ISequence<char> ToDafny_N6_smithy__N3_api__S6_String(string value) { return Dafny.Sequence<char>.FromString(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( Dafny.ISequence<Dafny.ISequence<char>> value) { return new System.Collections.Generic.List<string>( value.Elements.Select(FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList__M6_member)); } public static Dafny.ISequence<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( System.Collections.Generic.List<string> value) { return Dafny.Sequence<Dafny.ISequence<char>>.FromArray(value .Select(ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList__M6_member).ToArray()); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_plaintextDataKey( Wrappers_Compile._IOption<Dafny.ISequence<byte>> value) { return value.is_None ? (System.IO.MemoryStream)null : FromDafny_N6_smithy__N3_api__S4_Blob(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_plaintextDataKey( System.IO.MemoryStream value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_Some( ToDafny_N6_smithy__N3_api__S4_Blob((System.IO.MemoryStream)value)); } public static AWS.EncryptionSDK.Core.ICryptographicMaterialsManager FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateCryptographicMaterialsManagerOutput__M16_materialsManager( Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference(value); } public static Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateCryptographicMaterialsManagerOutput__M16_materialsManager( AWS.EncryptionSDK.Core.ICryptographicMaterialsManager value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference(value); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static AWS.EncryptionSDK.Core.AesWrappingAlg FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingAlg( Dafny.Aws.EncryptionSdk.Core._IAesWrappingAlg value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_AesWrappingAlg(value); } public static Dafny.Aws.EncryptionSdk.Core._IAesWrappingAlg ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingAlg( AWS.EncryptionSDK.Core.AesWrappingAlg value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_AesWrappingAlg(value); } public static AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput( Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsOutput value) { Dafny.Aws.EncryptionSdk.Core.GetEncryptionMaterialsOutput concrete = (Dafny.Aws.EncryptionSdk.Core.GetEncryptionMaterialsOutput)value; AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput converted = new AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput(); converted.EncryptionMaterials = (AWS.EncryptionSDK.Core.EncryptionMaterials) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput__M19_encryptionMaterials( concrete.encryptionMaterials); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsOutput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput( AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput value) { return new Dafny.Aws.EncryptionSdk.Core.GetEncryptionMaterialsOutput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput__M19_encryptionMaterials( value.EncryptionMaterials)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException__M7_message( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException__M7_message( string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M9_kmsClient( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M9_kmsClient( Amazon.KeyManagementService.IAmazonKeyManagementService value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M17_encryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M17_encryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static AWS.EncryptionSDK.Core.IClientSupplier FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M14_clientSupplier( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> value) { return value.is_None ? (AWS.EncryptionSDK.Core.IClientSupplier)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M14_clientSupplier( AWS.EncryptionSDK.Core.IClientSupplier value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference( (AWS.EncryptionSDK.Core.IClientSupplier)value)); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_algorithmSuiteId( Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M16_algorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static AWS.EncryptionSDK.Core.CommitmentPolicy FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_commitmentPolicy( Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy(value); } public static Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_commitmentPolicy( AWS.EncryptionSDK.Core.CommitmentPolicy value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy(value); } public static AWS.EncryptionSDK.Core.CreateRawAesKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateRawAesKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateRawAesKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateRawAesKeyringInput)value; AWS.EncryptionSDK.Core.CreateRawAesKeyringInput converted = new AWS.EncryptionSDK.Core.CreateRawAesKeyringInput(); converted.KeyNamespace = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M12_keyNamespace( concrete.keyNamespace); converted.KeyName = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M7_keyName( concrete.keyName); converted.WrappingKey = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingKey( concrete.wrappingKey); converted.WrappingAlg = (AWS.EncryptionSDK.Core.AesWrappingAlg) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingAlg( concrete.wrappingAlg); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateRawAesKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput( AWS.EncryptionSDK.Core.CreateRawAesKeyringInput value) { return new Dafny.Aws.EncryptionSdk.Core.CreateRawAesKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M12_keyNamespace( value.KeyNamespace), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M7_keyName(value.KeyName), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingKey( value.WrappingKey), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M11_wrappingAlg( value.WrappingAlg)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(Dafny.ISequence<char> value) { return new string(value.Elements); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(string value) { return Dafny.Sequence<char>.FromString(value); } public static AWS.EncryptionSDK.Core.EncryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput__M19_encryptionMaterials( Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials(value); } public static Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput__M19_encryptionMaterials( AWS.EncryptionSDK.Core.EncryptionMaterials value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials(value); } public static AWS.EncryptionSDK.Core.AesWrappingAlg FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_AesWrappingAlg( Dafny.Aws.EncryptionSdk.Core._IAesWrappingAlg value) { if (value.is_ALG__AES128__GCM__IV12__TAG16) return AWS.EncryptionSDK.Core.AesWrappingAlg.ALG_AES128_GCM_IV12_TAG16; if (value.is_ALG__AES192__GCM__IV12__TAG16) return AWS.EncryptionSDK.Core.AesWrappingAlg.ALG_AES192_GCM_IV12_TAG16; if (value.is_ALG__AES256__GCM__IV12__TAG16) return AWS.EncryptionSDK.Core.AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16; throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.AesWrappingAlg value"); } public static Dafny.Aws.EncryptionSdk.Core._IAesWrappingAlg ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_AesWrappingAlg(AWS.EncryptionSDK.Core.AesWrappingAlg value) { if (AWS.EncryptionSDK.Core.AesWrappingAlg.ALG_AES128_GCM_IV12_TAG16.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AesWrappingAlg.create_ALG__AES128__GCM__IV12__TAG16(); if (AWS.EncryptionSDK.Core.AesWrappingAlg.ALG_AES192_GCM_IV12_TAG16.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AesWrappingAlg.create_ALG__AES192__GCM__IV12__TAG16(); if (AWS.EncryptionSDK.Core.AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AesWrappingAlg.create_ALG__AES256__GCM__IV12__TAG16(); throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.AesWrappingAlg value"); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M12_keyNamespace( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M12_keyNamespace(string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static AWS.EncryptionSDK.Core.DecryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput__M19_decryptionMaterials( Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials(value); } public static Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput__M19_decryptionMaterials( AWS.EncryptionSDK.Core.DecryptionMaterials value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key( Dafny.ISequence<byte> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_plaintextDataKey( Wrappers_Compile._IOption<Dafny.ISequence<byte>> value) { return value.is_None ? (System.IO.MemoryStream)null : FromDafny_N6_smithy__N3_api__S4_Blob(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_plaintextDataKey( System.IO.MemoryStream value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_Some( ToDafny_N6_smithy__N3_api__S4_Blob((System.IO.MemoryStream)value)); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList( Dafny.ISequence<Dafny.ISequence<char>> value) { return new System.Collections.Generic.List<string>( value.Elements.Select(FromDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList__M6_member)); } public static Dafny.ISequence<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList(System.Collections.Generic.List<string> value) { return Dafny.Sequence<Dafny.ISequence<char>>.FromArray(value .Select(ToDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList__M6_member).ToArray()); } public static AWS.EncryptionSDK.Core.ICryptographicMaterialsManager FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateCryptographicMaterialsManagerOutput( Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateCryptographicMaterialsManagerOutput__M16_materialsManager( value); } public static Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateCryptographicMaterialsManagerOutput( AWS.EncryptionSDK.Core.ICryptographicMaterialsManager value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateCryptographicMaterialsManagerOutput__M16_materialsManager( value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M7_keyName( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput__M7_keyName(string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkDiscoveryKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkDiscoveryKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkDiscoveryKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput(); converted.KmsClient = (Amazon.KeyManagementService.IAmazonKeyManagementService) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M9_kmsClient( concrete.kmsClient); if (concrete.discoveryFilter.is_Some) converted.DiscoveryFilter = (AWS.EncryptionSDK.Core.DiscoveryFilter) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M15_discoveryFilter( concrete.discoveryFilter); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M11_grantTokens( concrete.grantTokens); converted.Region = (string) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M6_region( concrete.region); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkDiscoveryKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput value) { AWS.EncryptionSDK.Core.DiscoveryFilter var_discoveryFilter = value.IsSetDiscoveryFilter() ? value.DiscoveryFilter : (AWS.EncryptionSDK.Core.DiscoveryFilter)null; System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkDiscoveryKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M9_kmsClient( value.KmsClient), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M15_discoveryFilter( var_discoveryFilter), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M11_grantTokens( var_grantTokens), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M6_region( value.Region)); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_kmsKeyIds( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_kmsKeyIds( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList( (System.Collections.Generic.List<string>)value)); } public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M9_kmsClient( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M9_kmsClient( Amazon.KeyManagementService.IAmazonKeyManagementService value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(value); } public static System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M17_encryptedDataKeys( Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList(value); } public static Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M17_encryptedDataKeys( System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList(value); } public static AWS.EncryptionSDK.Core.OnEncryptOutput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput( Dafny.Aws.EncryptionSdk.Core._IOnEncryptOutput value) { Dafny.Aws.EncryptionSdk.Core.OnEncryptOutput concrete = (Dafny.Aws.EncryptionSdk.Core.OnEncryptOutput)value; AWS.EncryptionSDK.Core.OnEncryptOutput converted = new AWS.EncryptionSDK.Core.OnEncryptOutput(); converted.Materials = (AWS.EncryptionSDK.Core.EncryptionMaterials) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput__M9_materials(concrete.materials); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IOnEncryptOutput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput( AWS.EncryptionSDK.Core.OnEncryptOutput value) { return new Dafny.Aws.EncryptionSdk.Core.OnEncryptOutput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput__M9_materials(value.Materials)); } public static AWS.EncryptionSDK.Core.DecryptMaterialsInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput( Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsInput value) { Dafny.Aws.EncryptionSdk.Core.DecryptMaterialsInput concrete = (Dafny.Aws.EncryptionSdk.Core.DecryptMaterialsInput)value; AWS.EncryptionSDK.Core.DecryptMaterialsInput converted = new AWS.EncryptionSDK.Core.DecryptMaterialsInput(); converted.AlgorithmSuiteId = (AWS.EncryptionSDK.Core.AlgorithmSuiteId) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_algorithmSuiteId( concrete.algorithmSuiteId); converted.CommitmentPolicy = (AWS.EncryptionSDK.Core.CommitmentPolicy) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_commitmentPolicy( concrete.commitmentPolicy); converted.EncryptedDataKeys = (System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptedDataKeys( concrete.encryptedDataKeys); converted.EncryptionContext = (System.Collections.Generic.Dictionary<string, string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptionContext( concrete.encryptionContext); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput( AWS.EncryptionSDK.Core.DecryptMaterialsInput value) { return new Dafny.Aws.EncryptionSdk.Core.DecryptMaterialsInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_algorithmSuiteId( value.AlgorithmSuiteId), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M16_commitmentPolicy( value.CommitmentPolicy), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptedDataKeys( value.EncryptedDataKeys), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptionContext( value.EncryptionContext)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList__M6_member( Dafny.ISequence<char> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList__M6_member( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(value); } public static AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkMultiKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkMultiKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkMultiKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput(); if (concrete.generator.is_Some) converted.Generator = (string) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_generator( concrete.generator); if (concrete.kmsKeyIds.is_Some) converted.KmsKeyIds = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_kmsKeyIds( concrete.kmsKeyIds); if (concrete.clientSupplier.is_Some) converted.ClientSupplier = (AWS.EncryptionSDK.Core.IClientSupplier) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M14_clientSupplier( concrete.clientSupplier); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M11_grantTokens( concrete.grantTokens); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkMultiKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput value) { string var_generator = value.IsSetGenerator() ? value.Generator : (string)null; System.Collections.Generic.List<string> var_kmsKeyIds = value.IsSetKmsKeyIds() ? value.KmsKeyIds : (System.Collections.Generic.List<string>)null; AWS.EncryptionSDK.Core.IClientSupplier var_clientSupplier = value.IsSetClientSupplier() ? value.ClientSupplier : (AWS.EncryptionSDK.Core.IClientSupplier)null; System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkMultiKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_generator( var_generator), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_kmsKeyIds( var_kmsKeyIds), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M14_clientSupplier( var_clientSupplier), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M11_grantTokens( var_grantTokens)); } public static AWS.EncryptionSDK.Core.CommitmentPolicy FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_commitmentPolicy( Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy(value); } public static Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M16_commitmentPolicy( AWS.EncryptionSDK.Core.CommitmentPolicy value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy(value); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M15_verificationKey( Wrappers_Compile._IOption<Dafny.ISequence<byte>> value) { return value.is_None ? (System.IO.MemoryStream)null : FromDafny_N6_smithy__N3_api__S4_Blob(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M15_verificationKey( System.IO.MemoryStream value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_Some( ToDafny_N6_smithy__N3_api__S4_Blob((System.IO.MemoryStream)value)); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M17_encryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials__M17_encryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList__M6_member( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList__M6_member( string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static AWS.EncryptionSDK.Core.DiscoveryFilter FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M15_discoveryFilter( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> value) { return value.is_None ? (AWS.EncryptionSDK.Core.DiscoveryFilter)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M15_discoveryFilter( AWS.EncryptionSDK.Core.DiscoveryFilter value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter( (AWS.EncryptionSDK.Core.DiscoveryFilter)value)); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_algorithmSuiteId( Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M16_algorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M13_keyProviderId( Dafny.ISequence<byte> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M13_keyProviderId(string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static AWS.EncryptionSDK.Core.PaddingScheme FromDafny_N3_aws__N13_encryptionSdk__N4_core__S13_PaddingScheme( Dafny.Aws.EncryptionSdk.Core._IPaddingScheme value) { if (value.is_PKCS1) return AWS.EncryptionSDK.Core.PaddingScheme.PKCS1; if (value.is_OAEP__SHA1__MGF1) return AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA1_MGF1; if (value.is_OAEP__SHA256__MGF1) return AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA256_MGF1; if (value.is_OAEP__SHA384__MGF1) return AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA384_MGF1; if (value.is_OAEP__SHA512__MGF1) return AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA512_MGF1; throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.PaddingScheme value"); } public static Dafny.Aws.EncryptionSdk.Core._IPaddingScheme ToDafny_N3_aws__N13_encryptionSdk__N4_core__S13_PaddingScheme(AWS.EncryptionSDK.Core.PaddingScheme value) { if (AWS.EncryptionSDK.Core.PaddingScheme.PKCS1.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.PaddingScheme.create_PKCS1(); if (AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA1_MGF1.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.PaddingScheme.create_OAEP__SHA1__MGF1(); if (AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA256_MGF1.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.PaddingScheme.create_OAEP__SHA256__MGF1(); if (AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA384_MGF1.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.PaddingScheme.create_OAEP__SHA384__MGF1(); if (AWS.EncryptionSDK.Core.PaddingScheme.OAEP_SHA512_MGF1.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.PaddingScheme.create_OAEP__SHA512__MGF1(); throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.PaddingScheme value"); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( Dafny.Aws.EncryptionSdk.Core.IKeyring value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput__M7_keyring(value); } public static Dafny.Aws.EncryptionSdk.Core.IKeyring ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput(AWS.EncryptionSDK.Core.IKeyring value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput__M7_keyring(value); } public static AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateDefaultClientSupplierInput( Dafny.Aws.EncryptionSdk.Core._ICreateDefaultClientSupplierInput value) { Dafny.Aws.EncryptionSdk.Core.CreateDefaultClientSupplierInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateDefaultClientSupplierInput)value; AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput converted = new AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput(); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateDefaultClientSupplierInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateDefaultClientSupplierInput( AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput value) { return new Dafny.Aws.EncryptionSdk.Core.CreateDefaultClientSupplierInput(); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M8_kmsKeyId( Dafny.ISequence<char> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M8_kmsKeyId(string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList(Dafny.ISequence<Dafny.ISequence<char>> value) { return new System.Collections.Generic.List<string>( value.Elements.Select(FromDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList__M6_member)); } public static Dafny.ISequence<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList( System.Collections.Generic.List<string> value) { return Dafny.Sequence<Dafny.ISequence<char>>.FromArray(value .Select(ToDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList__M6_member).ToArray()); } public static AWS.EncryptionSDK.Core.DecryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M9_materials( Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials(value); } public static Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M9_materials( AWS.EncryptionSDK.Core.DecryptionMaterials value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials(value); } public static System.IO.MemoryStream FromDafny_N6_smithy__N3_api__S4_Blob(Dafny.ISequence<byte> value) { return new System.IO.MemoryStream(value.Elements); } public static Dafny.ISequence<byte> ToDafny_N6_smithy__N3_api__S4_Blob(System.IO.MemoryStream value) { return Dafny.Sequence<byte>.FromArray(value.ToArray()); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_kmsKeyIds( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_kmsKeyIds( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList( (System.Collections.Generic.List<string>)value)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_generator( Wrappers_Compile._IOption<Dafny.ISequence<char>> value) { return value.is_None ? (string)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_generator(string value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<char>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<char>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId((string)value)); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__N4_core__S47_CreateDefaultCryptographicMaterialsManagerInput__M7_keyring( Dafny.Aws.EncryptionSdk.Core.IKeyring value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value); } public static Dafny.Aws.EncryptionSdk.Core.IKeyring ToDafny_N3_aws__N13_encryptionSdk__N4_core__S47_CreateDefaultCryptographicMaterialsManagerInput__M7_keyring( AWS.EncryptionSDK.Core.IKeyring value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value); } public static AWS.EncryptionSDK.Core.OnDecryptOutput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput( Dafny.Aws.EncryptionSdk.Core._IOnDecryptOutput value) { Dafny.Aws.EncryptionSdk.Core.OnDecryptOutput concrete = (Dafny.Aws.EncryptionSdk.Core.OnDecryptOutput)value; AWS.EncryptionSDK.Core.OnDecryptOutput converted = new AWS.EncryptionSDK.Core.OnDecryptOutput(); converted.Materials = (AWS.EncryptionSDK.Core.DecryptionMaterials) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput__M9_materials(concrete.materials); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IOnDecryptOutput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput( AWS.EncryptionSDK.Core.OnDecryptOutput value) { return new Dafny.Aws.EncryptionSdk.Core.OnDecryptOutput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput__M9_materials(value.Materials)); } public static AWS.EncryptionSDK.Core.CreateMultiKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateMultiKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateMultiKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateMultiKeyringInput)value; AWS.EncryptionSDK.Core.CreateMultiKeyringInput converted = new AWS.EncryptionSDK.Core.CreateMultiKeyringInput(); if (concrete.generator.is_Some) converted.Generator = (AWS.EncryptionSDK.Core.IKeyring) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M9_generator( concrete.generator); converted.ChildKeyrings = (System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M13_childKeyrings( concrete.childKeyrings); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateMultiKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput( AWS.EncryptionSDK.Core.CreateMultiKeyringInput value) { AWS.EncryptionSDK.Core.IKeyring var_generator = value.IsSetGenerator() ? value.Generator : (AWS.EncryptionSDK.Core.IKeyring)null; return new Dafny.Aws.EncryptionSdk.Core.CreateMultiKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M9_generator(var_generator), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M13_childKeyrings( value.ChildKeyrings)); } public static long? FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M18_maxPlaintextLength( Wrappers_Compile._IOption<long> value) { return value.is_None ? (long?)null : FromDafny_N6_smithy__N3_api__S4_Long(value.Extract()); } public static Wrappers_Compile._IOption<long> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput__M18_maxPlaintextLength( long? value) { return value == null ? Wrappers_Compile.Option<long>.create_None() : Wrappers_Compile.Option<long>.create_Some(ToDafny_N6_smithy__N3_api__S4_Long((long)value)); } public static AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateRawRsaKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateRawRsaKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateRawRsaKeyringInput)value; AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput converted = new AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput(); converted.KeyNamespace = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M12_keyNamespace( concrete.keyNamespace); converted.KeyName = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M7_keyName( concrete.keyName); converted.PaddingScheme = (AWS.EncryptionSDK.Core.PaddingScheme) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M13_paddingScheme( concrete.paddingScheme); if (concrete.publicKey.is_Some) converted.PublicKey = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M9_publicKey( concrete.publicKey); if (concrete.privateKey.is_Some) converted.PrivateKey = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M10_privateKey( concrete.privateKey); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateRawRsaKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput( AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput value) { System.IO.MemoryStream var_publicKey = value.IsSetPublicKey() ? value.PublicKey : (System.IO.MemoryStream)null; System.IO.MemoryStream var_privateKey = value.IsSetPrivateKey() ? value.PrivateKey : (System.IO.MemoryStream)null; return new Dafny.Aws.EncryptionSdk.Core.CreateRawRsaKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M12_keyNamespace( value.KeyNamespace), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M7_keyName(value.KeyName), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M13_paddingScheme( value.PaddingScheme), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M9_publicKey(var_publicKey), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M10_privateKey( var_privateKey)); } public static AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMultiKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMultiKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMultiKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput(); if (concrete.generator.is_Some) converted.Generator = (string) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_generator( concrete.generator); if (concrete.kmsKeyIds.is_Some) converted.KmsKeyIds = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_kmsKeyIds( concrete.kmsKeyIds); if (concrete.clientSupplier.is_Some) converted.ClientSupplier = (AWS.EncryptionSDK.Core.IClientSupplier) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M14_clientSupplier( concrete.clientSupplier); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M11_grantTokens( concrete.grantTokens); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMultiKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput value) { string var_generator = value.IsSetGenerator() ? value.Generator : (string)null; System.Collections.Generic.List<string> var_kmsKeyIds = value.IsSetKmsKeyIds() ? value.KmsKeyIds : (System.Collections.Generic.List<string>)null; AWS.EncryptionSDK.Core.IClientSupplier var_clientSupplier = value.IsSetClientSupplier() ? value.ClientSupplier : (AWS.EncryptionSDK.Core.IClientSupplier)null; System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMultiKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_generator( var_generator), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M9_kmsKeyIds( var_kmsKeyIds), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M14_clientSupplier( var_clientSupplier), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput__M11_grantTokens( var_grantTokens)); } public static AWS.EncryptionSDK.Core.DiscoveryFilter FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M15_discoveryFilter( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> value) { return value.is_None ? (AWS.EncryptionSDK.Core.DiscoveryFilter)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M15_discoveryFilter( AWS.EncryptionSDK.Core.DiscoveryFilter value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter( (AWS.EncryptionSDK.Core.DiscoveryFilter)value)); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M9_generator( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IKeyring> value) { return value.is_None ? (AWS.EncryptionSDK.Core.IKeyring)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IKeyring> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput__M9_generator( AWS.EncryptionSDK.Core.IKeyring value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IKeyring>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IKeyring>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference( (AWS.EncryptionSDK.Core.IKeyring)value)); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static AWS.EncryptionSDK.Core.EncryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput__M9_materials( Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials(value); } public static Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnEncryptOutput__M9_materials( AWS.EncryptionSDK.Core.EncryptionMaterials value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M7_keyName( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M7_keyName(string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M9_publicKey( Wrappers_Compile._IOption<Dafny.ISequence<byte>> value) { return value.is_None ? (System.IO.MemoryStream)null : FromDafny_N6_smithy__N3_api__S4_Blob(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput__M9_publicKey( System.IO.MemoryStream value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<byte>>.create_Some( ToDafny_N6_smithy__N3_api__S4_Blob((System.IO.MemoryStream)value)); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput__M17_encryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static AWS.EncryptionSDK.Core.IClientSupplier FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M14_clientSupplier( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> value) { return value.is_None ? (AWS.EncryptionSDK.Core.IClientSupplier)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M14_clientSupplier( AWS.EncryptionSDK.Core.IClientSupplier value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference( (AWS.EncryptionSDK.Core.IClientSupplier)value)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M6_region( Dafny.ISequence<char> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput__M6_region( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S6_Region(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_AccountId(Dafny.ISequence<char> value) { return new string(value.Elements); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_AccountId(string value) { return Dafny.Sequence<char>.FromString(value); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId( Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId value) { if (value.is_ALG__AES__128__GCM__IV12__TAG16__NO__KDF) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_NO_KDF; if (value.is_ALG__AES__192__GCM__IV12__TAG16__NO__KDF) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_NO_KDF; if (value.is_ALG__AES__256__GCM__IV12__TAG16__NO__KDF) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_NO_KDF; if (value.is_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256; if (value.is_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256; if (value.is_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; if (value.is_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256; if (value.is_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; if (value.is_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; if (value.is_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; if (value.is_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.AlgorithmSuiteId value"); } public static Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_NO_KDF.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId.create_ALG__AES__128__GCM__IV12__TAG16__NO__KDF(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_NO_KDF.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId.create_ALG__AES__192__GCM__IV12__TAG16__NO__KDF(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId.create_ALG__AES__256__GCM__IV12__TAG16__NO__KDF(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384(); throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.AlgorithmSuiteId value"); } public static AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S47_CreateDefaultCryptographicMaterialsManagerInput( Dafny.Aws.EncryptionSdk.Core._ICreateDefaultCryptographicMaterialsManagerInput value) { Dafny.Aws.EncryptionSdk.Core.CreateDefaultCryptographicMaterialsManagerInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateDefaultCryptographicMaterialsManagerInput)value; AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput converted = new AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput(); converted.Keyring = (AWS.EncryptionSDK.Core.IKeyring) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S47_CreateDefaultCryptographicMaterialsManagerInput__M7_keyring( concrete.keyring); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateDefaultCryptographicMaterialsManagerInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S47_CreateDefaultCryptographicMaterialsManagerInput( AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput value) { return new Dafny.Aws.EncryptionSdk.Core.CreateDefaultCryptographicMaterialsManagerInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S47_CreateDefaultCryptographicMaterialsManagerInput__M7_keyring( value.Keyring)); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return value.ItemEnumerable.ToDictionary( pair => FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key(pair.Car), pair => FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value(pair.Cdr)); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return Dafny.Map<Dafny.ISequence<byte>, Dafny.ISequence<byte>>.FromCollection(value.Select(pair => new Dafny.Pair<Dafny.ISequence<byte>, Dafny.ISequence<byte>>( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key(pair.Key), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value(pair.Value)) )); } public static AWS.EncryptionSDK.Core.IClientSupplier FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M14_clientSupplier( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> value) { return value.is_None ? (AWS.EncryptionSDK.Core.IClientSupplier)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IClientSupplier> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M14_clientSupplier( AWS.EncryptionSDK.Core.IClientSupplier value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IClientSupplier>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference( (AWS.EncryptionSDK.Core.IClientSupplier)value)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList__M6_member( Dafny.ISequence<char> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_AccountId(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S13_AccountIdList__M6_member( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_AccountId(value); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M8_kmsKeyId( Dafny.ISequence<char> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M8_kmsKeyId(string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value); } public static AWS.EncryptionSDK.Core.DecryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput__M9_materials( Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials(value); } public static Dafny.Aws.EncryptionSdk.Core._IDecryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_OnDecryptOutput__M9_materials( AWS.EncryptionSDK.Core.DecryptionMaterials value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_DecryptionMaterials(value); } public static AWS.EncryptionSDK.Core.GetClientInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput( Dafny.Aws.EncryptionSdk.Core._IGetClientInput value) { Dafny.Aws.EncryptionSdk.Core.GetClientInput concrete = (Dafny.Aws.EncryptionSdk.Core.GetClientInput)value; AWS.EncryptionSDK.Core.GetClientInput converted = new AWS.EncryptionSDK.Core.GetClientInput(); converted.Region = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput__M6_region(concrete.region); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IGetClientInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput(AWS.EncryptionSDK.Core.GetClientInput value) { return new Dafny.Aws.EncryptionSdk.Core.GetClientInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput__M6_region(value.Region)); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference( Dafny.Aws.EncryptionSdk.Core.IKeyring value) { if (value is NativeWrapper_Keyring nativeWrapper) return nativeWrapper._impl; return new Keyring(value); } public static Dafny.Aws.EncryptionSdk.Core.IKeyring ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(AWS.EncryptionSDK.Core.IKeyring value) { switch (value) { case Keyring valueWithImpl: return valueWithImpl._impl; case KeyringBase nativeImpl: return new NativeWrapper_Keyring(nativeImpl); default: throw new System.ArgumentException( "Custom implementations of Keyring must extend KeyringBase."); } } public static AWS.EncryptionSDK.Core.OnDecryptInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput( Dafny.Aws.EncryptionSdk.Core._IOnDecryptInput value) { Dafny.Aws.EncryptionSdk.Core.OnDecryptInput concrete = (Dafny.Aws.EncryptionSdk.Core.OnDecryptInput)value; AWS.EncryptionSDK.Core.OnDecryptInput converted = new AWS.EncryptionSDK.Core.OnDecryptInput(); converted.Materials = (AWS.EncryptionSDK.Core.DecryptionMaterials) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M9_materials(concrete.materials); converted.EncryptedDataKeys = (System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M17_encryptedDataKeys( concrete.encryptedDataKeys); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IOnDecryptInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput(AWS.EncryptionSDK.Core.OnDecryptInput value) { return new Dafny.Aws.EncryptionSdk.Core.OnDecryptInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M9_materials(value.Materials), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput__M17_encryptedDataKeys( value.EncryptedDataKeys)); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static AWS.EncryptionSDK.Core.EncryptedDataKey FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey( Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey value) { Dafny.Aws.EncryptionSdk.Core.EncryptedDataKey concrete = (Dafny.Aws.EncryptionSdk.Core.EncryptedDataKey)value; AWS.EncryptionSDK.Core.EncryptedDataKey converted = new AWS.EncryptionSDK.Core.EncryptedDataKey(); converted.KeyProviderId = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M13_keyProviderId( concrete.keyProviderId); converted.KeyProviderInfo = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M15_keyProviderInfo( concrete.keyProviderInfo); converted.Ciphertext = (System.IO.MemoryStream) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M10_ciphertext(concrete.ciphertext); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey( AWS.EncryptionSDK.Core.EncryptedDataKey value) { return new Dafny.Aws.EncryptionSdk.Core.EncryptedDataKey( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M13_keyProviderId( value.KeyProviderId), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M15_keyProviderInfo( value.KeyProviderInfo), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_EncryptedDataKey__M10_ciphertext(value.Ciphertext)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_generator( Wrappers_Compile._IOption<Dafny.ISequence<char>> value) { return value.is_None ? (string)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput__M9_generator(string value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<char>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<char>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S8_KmsKeyId((string)value)); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M7_regions( Dafny.ISequence<Dafny.ISequence<char>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList(value); } public static Dafny.ISequence<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput__M7_regions( System.Collections.Generic.List<string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M11_grantTokens( Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> value) { return value.is_None ? (System.Collections.Generic.List<string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.ISequence<Dafny.ISequence<char>>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput__M11_grantTokens( System.Collections.Generic.List<string> value) { return value == null ? Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_None() : Wrappers_Compile.Option<Dafny.ISequence<Dafny.ISequence<char>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GrantTokenList( (System.Collections.Generic.List<string>)value)); } public static AWS.EncryptionSDK.Core.ICryptographicMaterialsManager FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager value) { if (value is NativeWrapper_CryptographicMaterialsManager nativeWrapper) return nativeWrapper._impl; return new CryptographicMaterialsManager(value); } public static Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( AWS.EncryptionSDK.Core.ICryptographicMaterialsManager value) { switch (value) { case CryptographicMaterialsManager valueWithImpl: return valueWithImpl._impl; case CryptographicMaterialsManagerBase nativeImpl: return new NativeWrapper_CryptographicMaterialsManager(nativeImpl); default: throw new System.ArgumentException( "Custom implementations of CryptographicMaterialsManager must extend CryptographicMaterialsManagerBase."); } } public static AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput(); converted.KmsKeyId = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M8_kmsKeyId( concrete.kmsKeyId); converted.KmsClient = (Amazon.KeyManagementService.IAmazonKeyManagementService) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M9_kmsClient( concrete.kmsClient); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M11_grantTokens( concrete.grantTokens); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput value) { System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsMrkKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M8_kmsKeyId( value.KmsKeyId), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M9_kmsClient( value.KmsClient), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput__M11_grantTokens( var_grantTokens)); } public static long FromDafny_N6_smithy__N3_api__S4_Long(long value) { return value; } public static long ToDafny_N6_smithy__N3_api__S4_Long(long value) { return value; } public static AWS.EncryptionSDK.Core.CommitmentPolicy FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy( Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy value) { if (value.is_FORBID__ENCRYPT__ALLOW__DECRYPT) return AWS.EncryptionSDK.Core.CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT; if (value.is_REQUIRE__ENCRYPT__ALLOW__DECRYPT) return AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT; if (value.is_REQUIRE__ENCRYPT__REQUIRE__DECRYPT) return AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT; throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.CommitmentPolicy value"); } public static Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy( AWS.EncryptionSDK.Core.CommitmentPolicy value) { if (AWS.EncryptionSDK.Core.CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.CommitmentPolicy.create_FORBID__ENCRYPT__ALLOW__DECRYPT(); if (AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.CommitmentPolicy.create_REQUIRE__ENCRYPT__ALLOW__DECRYPT(); if (AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.CommitmentPolicy.create_REQUIRE__ENCRYPT__REQUIRE__DECRYPT(); throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.CommitmentPolicy value"); } public static System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptedDataKeys( Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList(value); } public static Dafny.ISequence<Dafny.Aws.EncryptionSdk.Core._IEncryptedDataKey> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials__M17_encryptedDataKeys( System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S20_EncryptedDataKeyList(value); } public static AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput FromDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput( Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsDiscoveryKeyringInput value) { Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsDiscoveryKeyringInput concrete = (Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsDiscoveryKeyringInput)value; AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput converted = new AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput(); converted.KmsClient = (Amazon.KeyManagementService.IAmazonKeyManagementService) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M9_kmsClient( concrete.kmsClient); if (concrete.discoveryFilter.is_Some) converted.DiscoveryFilter = (AWS.EncryptionSDK.Core.DiscoveryFilter) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M15_discoveryFilter( concrete.discoveryFilter); if (concrete.grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M11_grantTokens( concrete.grantTokens); return converted; } public static Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsDiscoveryKeyringInput ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput value) { AWS.EncryptionSDK.Core.DiscoveryFilter var_discoveryFilter = value.IsSetDiscoveryFilter() ? value.DiscoveryFilter : (AWS.EncryptionSDK.Core.DiscoveryFilter)null; System.Collections.Generic.List<string> var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List<string>)null; return new Dafny.Aws.EncryptionSdk.Core.CreateAwsKmsDiscoveryKeyringInput( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M9_kmsClient( value.KmsClient), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M15_discoveryFilter( var_discoveryFilter), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M11_grantTokens( var_grantTokens)); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList(Dafny.ISequence<Dafny.ISequence<char>> value) { return new System.Collections.Generic.List<string>( value.Elements.Select(FromDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList__M6_member)); } public static Dafny.ISequence<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList(System.Collections.Generic.List<string> value) { return Dafny.Sequence<Dafny.ISequence<char>>.FromArray(value .Select(ToDafny_N3_aws__N13_encryptionSdk__N4_core__S12_KmsKeyIdList__M6_member).ToArray()); } public static AWS.EncryptionSDK.Core.DiscoveryFilter FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter( Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter value) { Dafny.Aws.EncryptionSdk.Core.DiscoveryFilter concrete = (Dafny.Aws.EncryptionSdk.Core.DiscoveryFilter)value; AWS.EncryptionSDK.Core.DiscoveryFilter converted = new AWS.EncryptionSDK.Core.DiscoveryFilter(); converted.AccountIds = (System.Collections.Generic.List<string>) FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M10_accountIds(concrete.accountIds); converted.Partition = (string)FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M9_partition( concrete.partition); return converted; } public static Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter( AWS.EncryptionSDK.Core.DiscoveryFilter value) { return new Dafny.Aws.EncryptionSdk.Core.DiscoveryFilter( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M10_accountIds(value.AccountIds), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter__M9_partition(value.Partition)); } public static AWS.EncryptionSDK.Core.EncryptionMaterials FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput__M9_materials( Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials(value); } public static Dafny.Aws.EncryptionSdk.Core._IEncryptionMaterials ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput__M9_materials( AWS.EncryptionSDK.Core.EncryptionMaterials value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S19_EncryptionMaterials(value); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList__M6_member( Dafny.Aws.EncryptionSdk.Core.IKeyring value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value); } public static Dafny.Aws.EncryptionSdk.Core.IKeyring ToDafny_N3_aws__N13_encryptionSdk__N4_core__S11_KeyringList__M6_member( AWS.EncryptionSDK.Core.IKeyring value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value); } public static System.Collections.Generic.List<string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M7_regions( Dafny.ISequence<Dafny.ISequence<char>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList(value); } public static Dafny.ISequence<Dafny.ISequence<char>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput__M7_regions( System.Collections.Generic.List<string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S10_RegionList(value); } public static AWS.EncryptionSDK.Core.DiscoveryFilter FromDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M15_discoveryFilter( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> value) { return value.is_None ? (AWS.EncryptionSDK.Core.DiscoveryFilter)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput__M15_discoveryFilter( AWS.EncryptionSDK.Core.DiscoveryFilter value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IDiscoveryFilter>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_DiscoveryFilter( (AWS.EncryptionSDK.Core.DiscoveryFilter)value)); } public static AWS.EncryptionSDK.Core.AwsCryptographicMaterialProvidersBaseException FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException value) { switch (value) { case Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersException dafnyVal: return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException( dafnyVal); default: return new AWS.EncryptionSDK.Core.AwsCryptographicMaterialProvidersBaseException( FromDafny_N6_smithy__N3_api__S6_String(value.GetMessage())); } } public static Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException ToDafny_CommonError( System.Exception value) { Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersBaseException rtn; switch (value) { case AWS.EncryptionSDK.Core.AwsCryptographicMaterialProvidersException exception: return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersException( exception); case AWS.EncryptionSDK.Core.AwsCryptographicMaterialProvidersBaseException exception: rtn = new Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersBaseException(); rtn.message = ToDafny_N6_smithy__N3_api__S6_String(exception.Message); return rtn; default: var message = $"AwsCryptographicMaterialProviders encountered unexpected: {value.GetType()}: \"{value.Message}\""; rtn = new Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersBaseException(); rtn.message = ToDafny_N6_smithy__N3_api__S6_String(message); return rtn; } } } }
2,789
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { internal class AwsEncryptionSdk : AwsEncryptionSdkBase { internal readonly Dafny.Aws.EncryptionSdk.IAwsEncryptionSdk _impl; internal AwsEncryptionSdk(Dafny.Aws.EncryptionSdk.IAwsEncryptionSdk impl) { this._impl = impl; } protected override AWS.EncryptionSDK.DecryptOutput _Decrypt(AWS.EncryptionSDK.DecryptInput input) { Dafny.Aws.EncryptionSdk._IDecryptInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk._IDecryptOutput, Dafny.Aws.EncryptionSdk.IAwsEncryptionSdkException> result = this._impl.Decrypt(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsEncryptionSdkBaseException(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput(result.dtor_value); } protected override AWS.EncryptionSDK.EncryptOutput _Encrypt(AWS.EncryptionSDK.EncryptInput input) { Dafny.Aws.EncryptionSdk._IEncryptInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk._IEncryptOutput, Dafny.Aws.EncryptionSdk.IAwsEncryptionSdkException> result = this._impl.Encrypt(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsEncryptionSdkBaseException(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput(result.dtor_value); } } }
45
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public abstract class AwsEncryptionSdkBase : IAwsEncryptionSdk { public AWS.EncryptionSDK.EncryptOutput Encrypt(AWS.EncryptionSDK.EncryptInput input) { input.Validate(); return _Encrypt(input); } protected abstract AWS.EncryptionSDK.EncryptOutput _Encrypt(AWS.EncryptionSDK.EncryptInput input); public AWS.EncryptionSDK.DecryptOutput Decrypt(AWS.EncryptionSDK.DecryptInput input) { input.Validate(); return _Decrypt(input); } protected abstract AWS.EncryptionSDK.DecryptOutput _Decrypt(AWS.EncryptionSDK.DecryptInput input); } }
30
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public class AwsEncryptionSdkBaseException : Exception { public AwsEncryptionSdkBaseException() : base() { } public AwsEncryptionSdkBaseException(string message) : base(message) { } } }
22
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public class AwsEncryptionSdkConfig { private AWS.EncryptionSDK.Core.CommitmentPolicy _commitmentPolicy; private long? _maxEncryptedDataKeys; public AWS.EncryptionSDK.Core.CommitmentPolicy CommitmentPolicy { get { return this._commitmentPolicy; } set { this._commitmentPolicy = value; } } internal bool IsSetCommitmentPolicy() { return this._commitmentPolicy != null; } public long MaxEncryptedDataKeys { get { return this._maxEncryptedDataKeys.GetValueOrDefault(); } set { this._maxEncryptedDataKeys = value; } } internal bool IsSetMaxEncryptedDataKeys() { return this._maxEncryptedDataKeys.HasValue; } public void Validate() { } } }
43
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public class AwsEncryptionSdkException : AwsEncryptionSdkBaseException { public AwsEncryptionSdkException(string message) : base(message) { } } }
18
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public static class AwsEncryptionSdkFactory { static readonly Dafny.Aws.EncryptionSdk.AwsEncryptionSdkFactory.AwsEncryptionSdkFactory _impl = new Dafny.Aws.EncryptionSdk.AwsEncryptionSdkFactory.AwsEncryptionSdkFactory(); public static AWS.EncryptionSDK.IAwsEncryptionSdk CreateDefaultAwsEncryptionSdk() { Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.IAwsEncryptionSdk, Dafny.Aws.EncryptionSdk.IAwsEncryptionSdkException> result = _impl.CreateDefaultAwsEncryptionSdk(); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsEncryptionSdkBaseException(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkReference(result.dtor_value); } public static AWS.EncryptionSDK.IAwsEncryptionSdk CreateAwsEncryptionSdk( AWS.EncryptionSDK.AwsEncryptionSdkConfig input) { Dafny.Aws.EncryptionSdk._IAwsEncryptionSdkConfig internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.IAwsEncryptionSdk, Dafny.Aws.EncryptionSdk.IAwsEncryptionSdkException> result = _impl.CreateAwsEncryptionSdk(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsEncryptionSdkBaseException(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkReference(result.dtor_value); } } }
41
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public class DecryptInput { private System.IO.MemoryStream _ciphertext; private AWS.EncryptionSDK.Core.ICryptographicMaterialsManager _materialsManager; private AWS.EncryptionSDK.Core.IKeyring _keyring; public System.IO.MemoryStream Ciphertext { get { return this._ciphertext; } set { this._ciphertext = value; } } internal bool IsSetCiphertext() { return this._ciphertext != null; } public AWS.EncryptionSDK.Core.ICryptographicMaterialsManager MaterialsManager { get { return this._materialsManager; } set { this._materialsManager = value; } } internal bool IsSetMaterialsManager() { return this._materialsManager != null; } public AWS.EncryptionSDK.Core.IKeyring Keyring { get { return this._keyring; } set { this._keyring = value; } } internal bool IsSetKeyring() { return this._keyring != null; } public void Validate() { if (!IsSetCiphertext()) throw new System.ArgumentException("Missing value for required property 'Ciphertext'"); } } }
57
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public class DecryptOutput { private System.IO.MemoryStream _plaintext; private System.Collections.Generic.Dictionary<string, string> _encryptionContext; private AWS.EncryptionSDK.Core.AlgorithmSuiteId _algorithmSuiteId; public System.IO.MemoryStream Plaintext { get { return this._plaintext; } set { this._plaintext = value; } } internal bool IsSetPlaintext() { return this._plaintext != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } internal bool IsSetEncryptionContext() { return this._encryptionContext != null; } public AWS.EncryptionSDK.Core.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } internal bool IsSetAlgorithmSuiteId() { return this._algorithmSuiteId != null; } public void Validate() { if (!IsSetPlaintext()) throw new System.ArgumentException("Missing value for required property 'Plaintext'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetAlgorithmSuiteId()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuiteId'"); } } }
61
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public class EncryptInput { private System.IO.MemoryStream _plaintext; private System.Collections.Generic.Dictionary<string, string> _encryptionContext; private AWS.EncryptionSDK.Core.ICryptographicMaterialsManager _materialsManager; private AWS.EncryptionSDK.Core.IKeyring _keyring; private AWS.EncryptionSDK.Core.AlgorithmSuiteId _algorithmSuiteId; private long? _frameLength; public System.IO.MemoryStream Plaintext { get { return this._plaintext; } set { this._plaintext = value; } } internal bool IsSetPlaintext() { return this._plaintext != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } internal bool IsSetEncryptionContext() { return this._encryptionContext != null; } public AWS.EncryptionSDK.Core.ICryptographicMaterialsManager MaterialsManager { get { return this._materialsManager; } set { this._materialsManager = value; } } internal bool IsSetMaterialsManager() { return this._materialsManager != null; } public AWS.EncryptionSDK.Core.IKeyring Keyring { get { return this._keyring; } set { this._keyring = value; } } internal bool IsSetKeyring() { return this._keyring != null; } public AWS.EncryptionSDK.Core.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } internal bool IsSetAlgorithmSuiteId() { return this._algorithmSuiteId != null; } public long FrameLength { get { return this._frameLength.GetValueOrDefault(); } set { this._frameLength = value; } } internal bool IsSetFrameLength() { return this._frameLength.HasValue; } public void Validate() { if (!IsSetPlaintext()) throw new System.ArgumentException("Missing value for required property 'Plaintext'"); } } }
93
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public class EncryptOutput { private System.IO.MemoryStream _ciphertext; private System.Collections.Generic.Dictionary<string, string> _encryptionContext; private AWS.EncryptionSDK.Core.AlgorithmSuiteId _algorithmSuiteId; public System.IO.MemoryStream Ciphertext { get { return this._ciphertext; } set { this._ciphertext = value; } } internal bool IsSetCiphertext() { return this._ciphertext != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } internal bool IsSetEncryptionContext() { return this._encryptionContext != null; } public AWS.EncryptionSDK.Core.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } internal bool IsSetAlgorithmSuiteId() { return this._algorithmSuiteId != null; } public void Validate() { if (!IsSetCiphertext()) throw new System.ArgumentException("Missing value for required property 'Ciphertext'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetAlgorithmSuiteId()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuiteId'"); } } }
61
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace AWS.EncryptionSDK { public interface IAwsEncryptionSdk { AWS.EncryptionSDK.EncryptOutput Encrypt(AWS.EncryptionSDK.EncryptInput input); AWS.EncryptionSDK.DecryptOutput Decrypt(AWS.EncryptionSDK.DecryptInput input); } }
17
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System.Linq; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK { internal static class TypeConversion { public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId( Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId value) { if (value.is_ALG__AES__128__GCM__IV12__TAG16__NO__KDF) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_NO_KDF; if (value.is_ALG__AES__192__GCM__IV12__TAG16__NO__KDF) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_NO_KDF; if (value.is_ALG__AES__256__GCM__IV12__TAG16__NO__KDF) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_NO_KDF; if (value.is_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256; if (value.is_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256; if (value.is_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; if (value.is_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256; if (value.is_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; if (value.is_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; if (value.is_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; if (value.is_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384) return AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.AlgorithmSuiteId value"); } public static Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_NO_KDF.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId.create_ALG__AES__128__GCM__IV12__TAG16__NO__KDF(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_NO_KDF.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId.create_ALG__AES__192__GCM__IV12__TAG16__NO__KDF(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId.create_ALG__AES__256__GCM__IV12__TAG16__NO__KDF(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY(); if (AWS.EncryptionSDK.Core.AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.AlgorithmSuiteId .create_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384(); throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.AlgorithmSuiteId value"); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M16_algorithmSuiteId( Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId ToDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M16_algorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static AWS.EncryptionSDK.EncryptOutput FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput( Dafny.Aws.EncryptionSdk._IEncryptOutput value) { Dafny.Aws.EncryptionSdk.EncryptOutput concrete = (Dafny.Aws.EncryptionSdk.EncryptOutput)value; AWS.EncryptionSDK.EncryptOutput converted = new AWS.EncryptionSDK.EncryptOutput(); converted.Ciphertext = (System.IO.MemoryStream)FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M10_ciphertext( concrete.ciphertext); converted.EncryptionContext = (System.Collections.Generic.Dictionary<string, string>) FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M17_encryptionContext( concrete.encryptionContext); converted.AlgorithmSuiteId = (AWS.EncryptionSDK.Core.AlgorithmSuiteId) FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M16_algorithmSuiteId(concrete.algorithmSuiteId); return converted; } public static Dafny.Aws.EncryptionSdk._IEncryptOutput ToDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput( AWS.EncryptionSDK.EncryptOutput value) { return new Dafny.Aws.EncryptionSdk.EncryptOutput( ToDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M10_ciphertext(value.Ciphertext), ToDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M17_encryptionContext(value.EncryptionContext), ToDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M16_algorithmSuiteId(value.AlgorithmSuiteId)); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M16_algorithmSuiteId( Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId ToDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M16_algorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value); } public static AWS.EncryptionSDK.Core.ICryptographicMaterialsManager FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_materialsManager( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager> value) { return value.is_None ? (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager> ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_materialsManager( AWS.EncryptionSDK.Core.ICryptographicMaterialsManager value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager)value)); } public static AWS.EncryptionSDK.IAwsEncryptionSdk FromDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkReference( Dafny.Aws.EncryptionSdk.IAwsEncryptionSdk value) { return new AwsEncryptionSdk(value); } public static Dafny.Aws.EncryptionSdk.IAwsEncryptionSdk ToDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkReference(AWS.EncryptionSDK.IAwsEncryptionSdk value) { if (value is AwsEncryptionSdk valueWithImpl) { return valueWithImpl._impl; } throw new System.ArgumentException( "Custom implementations of AWS.EncryptionSDK.IAwsEncryptionSdk are not supported"); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M10_ciphertext( Dafny.ISequence<byte> value) { return FromDafny_N6_smithy__N3_api__S4_Blob(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M10_ciphertext( System.IO.MemoryStream value) { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return value.ItemEnumerable.ToDictionary( pair => FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key(pair.Car), pair => FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value(pair.Cdr)); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return Dafny.Map<Dafny.ISequence<byte>, Dafny.ISequence<byte>>.FromCollection(value.Select(pair => new Dafny.Pair<Dafny.ISequence<byte>, Dafny.ISequence<byte>>( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key(pair.Key), ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value(pair.Value)) )); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value( Dafny.ISequence<byte> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M5_value( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static AWS.EncryptionSDK.Core.AlgorithmSuiteId FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_algorithmSuiteId( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId> value) { return value.is_None ? (AWS.EncryptionSDK.Core.AlgorithmSuiteId)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId> ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_algorithmSuiteId( AWS.EncryptionSDK.Core.AlgorithmSuiteId value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._IAlgorithmSuiteId>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_AlgorithmSuiteId( (AWS.EncryptionSDK.Core.AlgorithmSuiteId)value)); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference( Dafny.Aws.EncryptionSdk.Core.IKeyring value) { if (value is NativeWrapper_Keyring nativeWrapper) return nativeWrapper._impl; return new Keyring(value); } public static Dafny.Aws.EncryptionSdk.Core.IKeyring ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(AWS.EncryptionSDK.Core.IKeyring value) { switch (value) { case Keyring valueWithImpl: return valueWithImpl._impl; case KeyringBase nativeImpl: return new NativeWrapper_Keyring(nativeImpl); default: throw new System.ArgumentException( "Custom implementations of Keyring must extend KeyringBase."); } } public static string FromDafny_N6_smithy__N3_api__S6_String(Dafny.ISequence<char> value) { return new string(value.Elements); } public static Dafny.ISequence<char> ToDafny_N6_smithy__N3_api__S6_String(string value) { return Dafny.Sequence<char>.FromString(value); } public static AWS.EncryptionSDK.AwsEncryptionSdkException FromDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException( Dafny.Aws.EncryptionSdk.AwsEncryptionSdkException value) { return new AWS.EncryptionSDK.AwsEncryptionSdkException( FromDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException__M7_message(value.message)); } public static Dafny.Aws.EncryptionSdk.AwsEncryptionSdkException ToDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException( AWS.EncryptionSDK.AwsEncryptionSdkException value) { Dafny.Aws.EncryptionSdk.AwsEncryptionSdkException converted = new Dafny.Aws.EncryptionSdk.AwsEncryptionSdkException(); converted.message = ToDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException__M7_message(value.Message); return converted; } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M9_plaintext( Dafny.ISequence<byte> value) { return FromDafny_N6_smithy__N3_api__S4_Blob(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M9_plaintext( System.IO.MemoryStream value) { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } public static AWS.EncryptionSDK.DecryptInput FromDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput( Dafny.Aws.EncryptionSdk._IDecryptInput value) { Dafny.Aws.EncryptionSdk.DecryptInput concrete = (Dafny.Aws.EncryptionSdk.DecryptInput)value; AWS.EncryptionSDK.DecryptInput converted = new AWS.EncryptionSDK.DecryptInput(); converted.Ciphertext = (System.IO.MemoryStream)FromDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M10_ciphertext( concrete.ciphertext); if (concrete.materialsManager.is_Some) converted.MaterialsManager = (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager) FromDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M16_materialsManager( concrete.materialsManager); if (concrete.keyring.is_Some) converted.Keyring = (AWS.EncryptionSDK.Core.IKeyring)FromDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M7_keyring( concrete.keyring); return converted; } public static Dafny.Aws.EncryptionSdk._IDecryptInput ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput( AWS.EncryptionSDK.DecryptInput value) { AWS.EncryptionSDK.Core.ICryptographicMaterialsManager var_materialsManager = value.IsSetMaterialsManager() ? value.MaterialsManager : (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager)null; AWS.EncryptionSDK.Core.IKeyring var_keyring = value.IsSetKeyring() ? value.Keyring : (AWS.EncryptionSDK.Core.IKeyring)null; return new Dafny.Aws.EncryptionSdk.DecryptInput( ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M10_ciphertext(value.Ciphertext), ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M16_materialsManager(var_materialsManager), ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M7_keyring(var_keyring)); } public static string FromDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException__M7_message( Dafny.ISequence<char> value) { return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence<char> ToDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException__M7_message(string value) { return ToDafny_N6_smithy__N3_api__S6_String(value); } public static AWS.EncryptionSDK.Core.CommitmentPolicy FromDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M16_commitmentPolicy( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy> value) { return value.is_None ? (AWS.EncryptionSDK.Core.CommitmentPolicy)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy> ToDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M16_commitmentPolicy( AWS.EncryptionSDK.Core.CommitmentPolicy value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy( (AWS.EncryptionSDK.Core.CommitmentPolicy)value)); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M7_keyring( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IKeyring> value) { return value.is_None ? (AWS.EncryptionSDK.Core.IKeyring)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IKeyring> ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M7_keyring(AWS.EncryptionSDK.Core.IKeyring value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IKeyring>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IKeyring>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference( (AWS.EncryptionSDK.Core.IKeyring)value)); } public static AWS.EncryptionSDK.Core.ICryptographicMaterialsManager FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager value) { if (value is NativeWrapper_CryptographicMaterialsManager nativeWrapper) return nativeWrapper._impl; return new CryptographicMaterialsManager(value); } public static Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( AWS.EncryptionSDK.Core.ICryptographicMaterialsManager value) { switch (value) { case CryptographicMaterialsManager valueWithImpl: return valueWithImpl._impl; case CryptographicMaterialsManagerBase nativeImpl: return new NativeWrapper_CryptographicMaterialsManager(nativeImpl); default: throw new System.ArgumentException( "Custom implementations of CryptographicMaterialsManager must extend CryptographicMaterialsManagerBase."); } } public static long? FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M11_frameLength( Wrappers_Compile._IOption<long> value) { return value.is_None ? (long?)null : FromDafny_N6_smithy__N3_api__S4_Long(value.Extract()); } public static Wrappers_Compile._IOption<long> ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M11_frameLength(long? value) { return value == null ? Wrappers_Compile.Option<long>.create_None() : Wrappers_Compile.Option<long>.create_Some(ToDafny_N6_smithy__N3_api__S4_Long((long)value)); } public static System.IO.MemoryStream FromDafny_N6_smithy__N3_api__S4_Blob(Dafny.ISequence<byte> value) { return new System.IO.MemoryStream(value.Elements); } public static Dafny.ISequence<byte> ToDafny_N6_smithy__N3_api__S4_Blob(System.IO.MemoryStream value) { return Dafny.Sequence<byte>.FromArray(value.ToArray()); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M9_plaintext( Dafny.ISequence<byte> value) { return FromDafny_N6_smithy__N3_api__S4_Blob(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M9_plaintext( System.IO.MemoryStream value) { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } public static AWS.EncryptionSDK.AwsEncryptionSdkConfig FromDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig( Dafny.Aws.EncryptionSdk._IAwsEncryptionSdkConfig value) { Dafny.Aws.EncryptionSdk.AwsEncryptionSdkConfig concrete = (Dafny.Aws.EncryptionSdk.AwsEncryptionSdkConfig)value; AWS.EncryptionSDK.AwsEncryptionSdkConfig converted = new AWS.EncryptionSDK.AwsEncryptionSdkConfig(); if (concrete.commitmentPolicy.is_Some) converted.CommitmentPolicy = (AWS.EncryptionSDK.Core.CommitmentPolicy) FromDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M16_commitmentPolicy( concrete.commitmentPolicy); if (concrete.maxEncryptedDataKeys.is_Some) converted.MaxEncryptedDataKeys = (long)FromDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M20_maxEncryptedDataKeys( concrete.maxEncryptedDataKeys); return converted; } public static Dafny.Aws.EncryptionSdk._IAwsEncryptionSdkConfig ToDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig( AWS.EncryptionSDK.AwsEncryptionSdkConfig value) { AWS.EncryptionSDK.Core.CommitmentPolicy var_commitmentPolicy = value.IsSetCommitmentPolicy() ? value.CommitmentPolicy : (AWS.EncryptionSDK.Core.CommitmentPolicy)null; long? var_maxEncryptedDataKeys = value.IsSetMaxEncryptedDataKeys() ? value.MaxEncryptedDataKeys : (long?)null; return new Dafny.Aws.EncryptionSdk.AwsEncryptionSdkConfig( ToDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M16_commitmentPolicy( var_commitmentPolicy), ToDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M20_maxEncryptedDataKeys( var_maxEncryptedDataKeys)); } public static long FromDafny_N6_smithy__N3_api__S4_Long(long value) { return value; } public static long ToDafny_N6_smithy__N3_api__S4_Long(long value) { return value; } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M17_encryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M17_encryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static long? FromDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M20_maxEncryptedDataKeys( Wrappers_Compile._IOption<long> value) { return value.is_None ? (long?)null : FromDafny_N6_smithy__N3_api__S4_Long(value.Extract()); } public static Wrappers_Compile._IOption<long> ToDafny_N3_aws__N13_encryptionSdk__S22_AwsEncryptionSdkConfig__M20_maxEncryptedDataKeys(long? value) { return value == null ? Wrappers_Compile.Option<long>.create_None() : Wrappers_Compile.Option<long>.create_Some(ToDafny_N6_smithy__N3_api__S4_Long((long)value)); } public static AWS.EncryptionSDK.Core.CommitmentPolicy FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy( Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy value) { if (value.is_FORBID__ENCRYPT__ALLOW__DECRYPT) return AWS.EncryptionSDK.Core.CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT; if (value.is_REQUIRE__ENCRYPT__ALLOW__DECRYPT) return AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT; if (value.is_REQUIRE__ENCRYPT__REQUIRE__DECRYPT) return AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT; throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.CommitmentPolicy value"); } public static Dafny.Aws.EncryptionSdk.Core._ICommitmentPolicy ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_CommitmentPolicy( AWS.EncryptionSDK.Core.CommitmentPolicy value) { if (AWS.EncryptionSDK.Core.CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.CommitmentPolicy.create_FORBID__ENCRYPT__ALLOW__DECRYPT(); if (AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.CommitmentPolicy.create_REQUIRE__ENCRYPT__ALLOW__DECRYPT(); if (AWS.EncryptionSDK.Core.CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT.Equals(value)) return Dafny.Aws.EncryptionSdk.Core.CommitmentPolicy.create_REQUIRE__ENCRYPT__REQUIRE__DECRYPT(); throw new System.ArgumentException("Invalid AWS.EncryptionSDK.Core.CommitmentPolicy value"); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key( Dafny.ISequence<byte> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext__M3_key( string value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(value); } public static System.IO.MemoryStream FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M10_ciphertext( Dafny.ISequence<byte> value) { return FromDafny_N6_smithy__N3_api__S4_Blob(value); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M10_ciphertext( System.IO.MemoryStream value) { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M17_encryptionContext( Wrappers_Compile._IOption<Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>>> value) { return value.is_None ? (System.Collections.Generic.Dictionary<string, string>)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>>> ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M17_encryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return value == null ? Wrappers_Compile.Option<Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>>>.create_None() : Wrappers_Compile.Option<Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>>>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext( (System.Collections.Generic.Dictionary<string, string>)value)); } public static AWS.EncryptionSDK.Core.IKeyring FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M7_keyring( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IKeyring> value) { return value.is_None ? (AWS.EncryptionSDK.Core.IKeyring)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference(value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.IKeyring> ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M7_keyring(AWS.EncryptionSDK.Core.IKeyring value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IKeyring>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.IKeyring>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference( (AWS.EncryptionSDK.Core.IKeyring)value)); } public static AWS.EncryptionSDK.Core.ICryptographicMaterialsManager FromDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M16_materialsManager( Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager> value) { return value.is_None ? (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager)null : FromDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( value.Extract()); } public static Wrappers_Compile._IOption<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager> ToDafny_N3_aws__N13_encryptionSdk__S12_DecryptInput__M16_materialsManager( AWS.EncryptionSDK.Core.ICryptographicMaterialsManager value) { return value == null ? Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager>.create_None() : Wrappers_Compile.Option<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager>.create_Some( ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CryptographicMaterialsManagerReference( (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager)value)); } public static string FromDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(Dafny.ISequence<byte> value) { System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); return utf8.GetString(value.Elements); } public static Dafny.ISequence<byte> ToDafny_N3_aws__N13_encryptionSdk__N4_core__S9_Utf8Bytes(string value) { System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); return Dafny.Sequence<byte>.FromArray(utf8.GetBytes(value)); } public static AWS.EncryptionSDK.DecryptOutput FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput( Dafny.Aws.EncryptionSdk._IDecryptOutput value) { Dafny.Aws.EncryptionSdk.DecryptOutput concrete = (Dafny.Aws.EncryptionSdk.DecryptOutput)value; AWS.EncryptionSDK.DecryptOutput converted = new AWS.EncryptionSDK.DecryptOutput(); converted.Plaintext = (System.IO.MemoryStream)FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M9_plaintext( concrete.plaintext); converted.EncryptionContext = (System.Collections.Generic.Dictionary<string, string>) FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M17_encryptionContext( concrete.encryptionContext); converted.AlgorithmSuiteId = (AWS.EncryptionSDK.Core.AlgorithmSuiteId) FromDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M16_algorithmSuiteId(concrete.algorithmSuiteId); return converted; } public static Dafny.Aws.EncryptionSdk._IDecryptOutput ToDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput( AWS.EncryptionSDK.DecryptOutput value) { return new Dafny.Aws.EncryptionSdk.DecryptOutput( ToDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M9_plaintext(value.Plaintext), ToDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M17_encryptionContext(value.EncryptionContext), ToDafny_N3_aws__N13_encryptionSdk__S13_DecryptOutput__M16_algorithmSuiteId(value.AlgorithmSuiteId)); } public static AWS.EncryptionSDK.EncryptInput FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput( Dafny.Aws.EncryptionSdk._IEncryptInput value) { Dafny.Aws.EncryptionSdk.EncryptInput concrete = (Dafny.Aws.EncryptionSdk.EncryptInput)value; AWS.EncryptionSDK.EncryptInput converted = new AWS.EncryptionSDK.EncryptInput(); converted.Plaintext = (System.IO.MemoryStream)FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M9_plaintext( concrete.plaintext); if (concrete.encryptionContext.is_Some) converted.EncryptionContext = (System.Collections.Generic.Dictionary<string, string>) FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M17_encryptionContext( concrete.encryptionContext); if (concrete.materialsManager.is_Some) converted.MaterialsManager = (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager) FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_materialsManager( concrete.materialsManager); if (concrete.keyring.is_Some) converted.Keyring = (AWS.EncryptionSDK.Core.IKeyring)FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M7_keyring( concrete.keyring); if (concrete.algorithmSuiteId.is_Some) converted.AlgorithmSuiteId = (AWS.EncryptionSDK.Core.AlgorithmSuiteId) FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_algorithmSuiteId( concrete.algorithmSuiteId); if (concrete.frameLength.is_Some) converted.FrameLength = (long)FromDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M11_frameLength(concrete.frameLength); return converted; } public static Dafny.Aws.EncryptionSdk._IEncryptInput ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput( AWS.EncryptionSDK.EncryptInput value) { System.Collections.Generic.Dictionary<string, string> var_encryptionContext = value.IsSetEncryptionContext() ? value.EncryptionContext : (System.Collections.Generic.Dictionary<string, string>)null; AWS.EncryptionSDK.Core.ICryptographicMaterialsManager var_materialsManager = value.IsSetMaterialsManager() ? value.MaterialsManager : (AWS.EncryptionSDK.Core.ICryptographicMaterialsManager)null; AWS.EncryptionSDK.Core.IKeyring var_keyring = value.IsSetKeyring() ? value.Keyring : (AWS.EncryptionSDK.Core.IKeyring)null; AWS.EncryptionSDK.Core.AlgorithmSuiteId var_algorithmSuiteId = value.IsSetAlgorithmSuiteId() ? value.AlgorithmSuiteId : (AWS.EncryptionSDK.Core.AlgorithmSuiteId)null; long? var_frameLength = value.IsSetFrameLength() ? value.FrameLength : (long?)null; return new Dafny.Aws.EncryptionSdk.EncryptInput( ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M9_plaintext(value.Plaintext), ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M17_encryptionContext(var_encryptionContext), ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_materialsManager(var_materialsManager), ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M7_keyring(var_keyring), ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M16_algorithmSuiteId(var_algorithmSuiteId), ToDafny_N3_aws__N13_encryptionSdk__S12_EncryptInput__M11_frameLength(var_frameLength)); } public static System.Collections.Generic.Dictionary<string, string> FromDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M17_encryptionContext( Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> value) { return FromDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static Dafny.IMap<Dafny.ISequence<byte>, Dafny.ISequence<byte>> ToDafny_N3_aws__N13_encryptionSdk__S13_EncryptOutput__M17_encryptionContext( System.Collections.Generic.Dictionary<string, string> value) { return ToDafny_N3_aws__N13_encryptionSdk__N4_core__S17_EncryptionContext(value); } public static AWS.EncryptionSDK.AwsEncryptionSdkBaseException FromDafny_CommonError_AwsEncryptionSdkBaseException( Dafny.Aws.EncryptionSdk.IAwsEncryptionSdkException value) { switch (value) { case Dafny.Aws.EncryptionSdk.AwsEncryptionSdkException dafnyVal: return FromDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException(dafnyVal); default: return new AWS.EncryptionSDK.AwsEncryptionSdkBaseException( FromDafny_N6_smithy__N3_api__S6_String(value.GetMessage())); } } public static Dafny.Aws.EncryptionSdk.IAwsEncryptionSdkException ToDafny_CommonError(System.Exception value) { Dafny.Aws.EncryptionSdk.AwsEncryptionSdkBaseException rtn; switch (value) { case AWS.EncryptionSDK.AwsEncryptionSdkException exception: return ToDafny_N3_aws__N13_encryptionSdk__S25_AwsEncryptionSdkException(exception); case AWS.EncryptionSDK.AwsEncryptionSdkBaseException exception: rtn = new Dafny.Aws.EncryptionSdk.AwsEncryptionSdkBaseException(); rtn.message = ToDafny_N6_smithy__N3_api__S6_String(exception.Message); return rtn; default: var message = $"AwsEncryptionSdk encountered unexpected: {value.GetType()}: \"{value.Message}\""; rtn = new Dafny.Aws.EncryptionSdk.AwsEncryptionSdkBaseException(); rtn.message = ToDafny_N6_smithy__N3_api__S6_String(message); return rtn; } } } }
771
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; namespace Com.Amazonaws.Kms { internal class KeyManagementServiceShim : Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient { internal Amazon.KeyManagementService.AmazonKeyManagementServiceClient _impl; internal KeyManagementServiceShim(Amazon.KeyManagementService.AmazonKeyManagementServiceClient impl) { this._impl = impl; } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._ICancelKeyDeletionResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> CancelKeyDeletion( Dafny.Com.Amazonaws.Kms._ICancelKeyDeletionRequest request) { Amazon.KeyManagementService.Model.CancelKeyDeletionRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S24_CancelKeyDeletionRequest(request); try { Amazon.KeyManagementService.Model.CancelKeyDeletionResponse sdkResponse = this._impl.CancelKeyDeletionAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICancelKeyDeletionResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S25_CancelKeyDeletionResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICancelKeyDeletionResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IConnectCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ConnectCustomKeyStore( Dafny.Com.Amazonaws.Kms._IConnectCustomKeyStoreRequest request) { Amazon.KeyManagementService.Model.ConnectCustomKeyStoreRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S28_ConnectCustomKeyStoreRequest(request); try { Amazon.KeyManagementService.Model.ConnectCustomKeyStoreResponse sdkResponse = this._impl.ConnectCustomKeyStoreAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IConnectCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S29_ConnectCustomKeyStoreResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IConnectCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> CreateAlias(Dafny.Com.Amazonaws.Kms._ICreateAliasRequest request) { Amazon.KeyManagementService.Model.CreateAliasRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_CreateAliasRequest(request); try { this._impl.CreateAliasAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._ICreateCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> CreateCustomKeyStore( Dafny.Com.Amazonaws.Kms._ICreateCustomKeyStoreRequest request) { Amazon.KeyManagementService.Model.CreateCustomKeyStoreRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S27_CreateCustomKeyStoreRequest(request); try { Amazon.KeyManagementService.Model.CreateCustomKeyStoreResponse sdkResponse = this._impl.CreateCustomKeyStoreAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICreateCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S28_CreateCustomKeyStoreResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICreateCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._ICreateGrantResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> CreateGrant( Dafny.Com.Amazonaws.Kms._ICreateGrantRequest request) { Amazon.KeyManagementService.Model.CreateGrantRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_CreateGrantRequest(request); try { Amazon.KeyManagementService.Model.CreateGrantResponse sdkResponse = this._impl.CreateGrantAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICreateGrantResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S19_CreateGrantResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICreateGrantResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._ICreateKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> CreateKey( Dafny.Com.Amazonaws.Kms._ICreateKeyRequest request) { Amazon.KeyManagementService.Model.CreateKeyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S16_CreateKeyRequest(request); try { Amazon.KeyManagementService.Model.CreateKeyResponse sdkResponse = this._impl.CreateKeyAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICreateKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S17_CreateKeyResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ICreateKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IDecryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> Decrypt( Dafny.Com.Amazonaws.Kms._IDecryptRequest request) { Amazon.KeyManagementService.Model.DecryptRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S14_DecryptRequest(request); try { Amazon.KeyManagementService.Model.DecryptResponse sdkResponse = this._impl.DecryptAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDecryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S15_DecryptResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDecryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DeleteAlias(Dafny.Com.Amazonaws.Kms._IDeleteAliasRequest request) { Amazon.KeyManagementService.Model.DeleteAliasRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_DeleteAliasRequest(request); try { this._impl.DeleteAliasAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IDeleteCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DeleteCustomKeyStore( Dafny.Com.Amazonaws.Kms._IDeleteCustomKeyStoreRequest request) { Amazon.KeyManagementService.Model.DeleteCustomKeyStoreRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S27_DeleteCustomKeyStoreRequest(request); try { Amazon.KeyManagementService.Model.DeleteCustomKeyStoreResponse sdkResponse = this._impl.DeleteCustomKeyStoreAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDeleteCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S28_DeleteCustomKeyStoreResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDeleteCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DeleteImportedKeyMaterial(Dafny.Com.Amazonaws.Kms._IDeleteImportedKeyMaterialRequest request) { Amazon.KeyManagementService.Model.DeleteImportedKeyMaterialRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S32_DeleteImportedKeyMaterialRequest(request); try { this._impl.DeleteImportedKeyMaterialAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IDescribeCustomKeyStoresResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DescribeCustomKeyStores( Dafny.Com.Amazonaws.Kms._IDescribeCustomKeyStoresRequest request) { Amazon.KeyManagementService.Model.DescribeCustomKeyStoresRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S30_DescribeCustomKeyStoresRequest(request); try { Amazon.KeyManagementService.Model.DescribeCustomKeyStoresResponse sdkResponse = this._impl.DescribeCustomKeyStoresAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDescribeCustomKeyStoresResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S31_DescribeCustomKeyStoresResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDescribeCustomKeyStoresResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IDescribeKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DescribeKey( Dafny.Com.Amazonaws.Kms._IDescribeKeyRequest request) { Amazon.KeyManagementService.Model.DescribeKeyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_DescribeKeyRequest(request); try { Amazon.KeyManagementService.Model.DescribeKeyResponse sdkResponse = this._impl.DescribeKeyAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDescribeKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S19_DescribeKeyResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDescribeKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DisableKey(Dafny.Com.Amazonaws.Kms._IDisableKeyRequest request) { Amazon.KeyManagementService.Model.DisableKeyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S17_DisableKeyRequest(request); try { this._impl.DisableKeyAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DisableKeyRotation(Dafny.Com.Amazonaws.Kms._IDisableKeyRotationRequest request) { Amazon.KeyManagementService.Model.DisableKeyRotationRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S25_DisableKeyRotationRequest(request); try { this._impl.DisableKeyRotationAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IDisconnectCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> DisconnectCustomKeyStore( Dafny.Com.Amazonaws.Kms._IDisconnectCustomKeyStoreRequest request) { Amazon.KeyManagementService.Model.DisconnectCustomKeyStoreRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S31_DisconnectCustomKeyStoreRequest(request); try { Amazon.KeyManagementService.Model.DisconnectCustomKeyStoreResponse sdkResponse = this._impl.DisconnectCustomKeyStoreAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDisconnectCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S32_DisconnectCustomKeyStoreResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IDisconnectCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> EnableKey(Dafny.Com.Amazonaws.Kms._IEnableKeyRequest request) { Amazon.KeyManagementService.Model.EnableKeyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S16_EnableKeyRequest(request); try { this._impl.EnableKeyAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> EnableKeyRotation(Dafny.Com.Amazonaws.Kms._IEnableKeyRotationRequest request) { Amazon.KeyManagementService.Model.EnableKeyRotationRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S24_EnableKeyRotationRequest(request); try { this._impl.EnableKeyRotationAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IEncryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> Encrypt( Dafny.Com.Amazonaws.Kms._IEncryptRequest request) { Amazon.KeyManagementService.Model.EncryptRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S14_EncryptRequest(request); try { Amazon.KeyManagementService.Model.EncryptResponse sdkResponse = this._impl.EncryptAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IEncryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S15_EncryptResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IEncryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GenerateDataKey( Dafny.Com.Amazonaws.Kms._IGenerateDataKeyRequest request) { Amazon.KeyManagementService.Model.GenerateDataKeyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S22_GenerateDataKeyRequest(request); try { Amazon.KeyManagementService.Model.GenerateDataKeyResponse sdkResponse = this._impl.GenerateDataKeyAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S23_GenerateDataKeyResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GenerateDataKeyPair( Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairRequest request) { Amazon.KeyManagementService.Model.GenerateDataKeyPairRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S26_GenerateDataKeyPairRequest(request); try { Amazon.KeyManagementService.Model.GenerateDataKeyPairResponse sdkResponse = this._impl.GenerateDataKeyPairAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S27_GenerateDataKeyPairResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairWithoutPlaintextResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GenerateDataKeyPairWithoutPlaintext( Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairWithoutPlaintextRequest request) { Amazon.KeyManagementService.Model.GenerateDataKeyPairWithoutPlaintextRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S42_GenerateDataKeyPairWithoutPlaintextRequest( request); try { Amazon.KeyManagementService.Model.GenerateDataKeyPairWithoutPlaintextResponse sdkResponse = this._impl.GenerateDataKeyPairWithoutPlaintextAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairWithoutPlaintextResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S43_GenerateDataKeyPairWithoutPlaintextResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyPairWithoutPlaintextResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyWithoutPlaintextResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GenerateDataKeyWithoutPlaintext( Dafny.Com.Amazonaws.Kms._IGenerateDataKeyWithoutPlaintextRequest request) { Amazon.KeyManagementService.Model.GenerateDataKeyWithoutPlaintextRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S38_GenerateDataKeyWithoutPlaintextRequest( request); try { Amazon.KeyManagementService.Model.GenerateDataKeyWithoutPlaintextResponse sdkResponse = this._impl.GenerateDataKeyWithoutPlaintextAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyWithoutPlaintextResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S39_GenerateDataKeyWithoutPlaintextResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateDataKeyWithoutPlaintextResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGenerateRandomResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GenerateRandom( Dafny.Com.Amazonaws.Kms._IGenerateRandomRequest request) { Amazon.KeyManagementService.Model.GenerateRandomRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S21_GenerateRandomRequest(request); try { Amazon.KeyManagementService.Model.GenerateRandomResponse sdkResponse = this._impl.GenerateRandomAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateRandomResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S22_GenerateRandomResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGenerateRandomResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGetKeyPolicyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GetKeyPolicy( Dafny.Com.Amazonaws.Kms._IGetKeyPolicyRequest request) { Amazon.KeyManagementService.Model.GetKeyPolicyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S19_GetKeyPolicyRequest(request); try { Amazon.KeyManagementService.Model.GetKeyPolicyResponse sdkResponse = this._impl.GetKeyPolicyAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetKeyPolicyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S20_GetKeyPolicyResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetKeyPolicyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGetKeyRotationStatusResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GetKeyRotationStatus( Dafny.Com.Amazonaws.Kms._IGetKeyRotationStatusRequest request) { Amazon.KeyManagementService.Model.GetKeyRotationStatusRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S27_GetKeyRotationStatusRequest(request); try { Amazon.KeyManagementService.Model.GetKeyRotationStatusResponse sdkResponse = this._impl.GetKeyRotationStatusAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetKeyRotationStatusResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S28_GetKeyRotationStatusResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetKeyRotationStatusResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGetParametersForImportResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GetParametersForImport( Dafny.Com.Amazonaws.Kms._IGetParametersForImportRequest request) { Amazon.KeyManagementService.Model.GetParametersForImportRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S29_GetParametersForImportRequest(request); try { Amazon.KeyManagementService.Model.GetParametersForImportResponse sdkResponse = this._impl.GetParametersForImportAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetParametersForImportResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S30_GetParametersForImportResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetParametersForImportResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IGetPublicKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> GetPublicKey( Dafny.Com.Amazonaws.Kms._IGetPublicKeyRequest request) { Amazon.KeyManagementService.Model.GetPublicKeyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S19_GetPublicKeyRequest(request); try { Amazon.KeyManagementService.Model.GetPublicKeyResponse sdkResponse = this._impl.GetPublicKeyAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetPublicKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S20_GetPublicKeyResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IGetPublicKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IImportKeyMaterialResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ImportKeyMaterial( Dafny.Com.Amazonaws.Kms._IImportKeyMaterialRequest request) { Amazon.KeyManagementService.Model.ImportKeyMaterialRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S24_ImportKeyMaterialRequest(request); try { Amazon.KeyManagementService.Model.ImportKeyMaterialResponse sdkResponse = this._impl.ImportKeyMaterialAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IImportKeyMaterialResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S25_ImportKeyMaterialResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IImportKeyMaterialResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IListAliasesResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ListAliases( Dafny.Com.Amazonaws.Kms._IListAliasesRequest request) { Amazon.KeyManagementService.Model.ListAliasesRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_ListAliasesRequest(request); try { Amazon.KeyManagementService.Model.ListAliasesResponse sdkResponse = this._impl.ListAliasesAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListAliasesResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S19_ListAliasesResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListAliasesResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IListGrantsResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ListGrants( Dafny.Com.Amazonaws.Kms._IListGrantsRequest request) { Amazon.KeyManagementService.Model.ListGrantsRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S17_ListGrantsRequest(request); try { Amazon.KeyManagementService.Model.ListGrantsResponse sdkResponse = this._impl.ListGrantsAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListGrantsResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S18_ListGrantsResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListGrantsResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IListKeyPoliciesResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ListKeyPolicies( Dafny.Com.Amazonaws.Kms._IListKeyPoliciesRequest request) { Amazon.KeyManagementService.Model.ListKeyPoliciesRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S22_ListKeyPoliciesRequest(request); try { Amazon.KeyManagementService.Model.ListKeyPoliciesResponse sdkResponse = this._impl.ListKeyPoliciesAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListKeyPoliciesResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S23_ListKeyPoliciesResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListKeyPoliciesResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IListResourceTagsResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ListResourceTags( Dafny.Com.Amazonaws.Kms._IListResourceTagsRequest request) { Amazon.KeyManagementService.Model.ListResourceTagsRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S23_ListResourceTagsRequest(request); try { Amazon.KeyManagementService.Model.ListResourceTagsResponse sdkResponse = this._impl.ListResourceTagsAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListResourceTagsResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S24_ListResourceTagsResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IListResourceTagsResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> PutKeyPolicy(Dafny.Com.Amazonaws.Kms._IPutKeyPolicyRequest request) { Amazon.KeyManagementService.Model.PutKeyPolicyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S19_PutKeyPolicyRequest(request); try { this._impl.PutKeyPolicyAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IReEncryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ReEncrypt( Dafny.Com.Amazonaws.Kms._IReEncryptRequest request) { Amazon.KeyManagementService.Model.ReEncryptRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S16_ReEncryptRequest(request); try { Amazon.KeyManagementService.Model.ReEncryptResponse sdkResponse = this._impl.ReEncryptAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IReEncryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S17_ReEncryptResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IReEncryptResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IReplicateKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ReplicateKey( Dafny.Com.Amazonaws.Kms._IReplicateKeyRequest request) { Amazon.KeyManagementService.Model.ReplicateKeyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S19_ReplicateKeyRequest(request); try { Amazon.KeyManagementService.Model.ReplicateKeyResponse sdkResponse = this._impl.ReplicateKeyAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IReplicateKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S20_ReplicateKeyResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IReplicateKeyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> RetireGrant(Dafny.Com.Amazonaws.Kms._IRetireGrantRequest request) { Amazon.KeyManagementService.Model.RetireGrantRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_RetireGrantRequest(request); try { this._impl.RetireGrantAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> RevokeGrant(Dafny.Com.Amazonaws.Kms._IRevokeGrantRequest request) { Amazon.KeyManagementService.Model.RevokeGrantRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_RevokeGrantRequest(request); try { this._impl.RevokeGrantAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IScheduleKeyDeletionResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> ScheduleKeyDeletion( Dafny.Com.Amazonaws.Kms._IScheduleKeyDeletionRequest request) { Amazon.KeyManagementService.Model.ScheduleKeyDeletionRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S26_ScheduleKeyDeletionRequest(request); try { Amazon.KeyManagementService.Model.ScheduleKeyDeletionResponse sdkResponse = this._impl.ScheduleKeyDeletionAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IScheduleKeyDeletionResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S27_ScheduleKeyDeletionResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IScheduleKeyDeletionResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._ISignResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> Sign(Dafny.Com.Amazonaws.Kms._ISignRequest request) { Amazon.KeyManagementService.Model.SignRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S11_SignRequest(request); try { Amazon.KeyManagementService.Model.SignResponse sdkResponse = this._impl.SignAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ISignResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S12_SignResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._ISignResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> TagResource(Dafny.Com.Amazonaws.Kms._ITagResourceRequest request) { Amazon.KeyManagementService.Model.TagResourceRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_TagResourceRequest(request); try { this._impl.TagResourceAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> UntagResource(Dafny.Com.Amazonaws.Kms._IUntagResourceRequest request) { Amazon.KeyManagementService.Model.UntagResourceRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S20_UntagResourceRequest(request); try { this._impl.UntagResourceAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> UpdateAlias(Dafny.Com.Amazonaws.Kms._IUpdateAliasRequest request) { Amazon.KeyManagementService.Model.UpdateAliasRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S18_UpdateAliasRequest(request); try { this._impl.UpdateAliasAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IUpdateCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> UpdateCustomKeyStore( Dafny.Com.Amazonaws.Kms._IUpdateCustomKeyStoreRequest request) { Amazon.KeyManagementService.Model.UpdateCustomKeyStoreRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S27_UpdateCustomKeyStoreRequest(request); try { Amazon.KeyManagementService.Model.UpdateCustomKeyStoreResponse sdkResponse = this._impl.UpdateCustomKeyStoreAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IUpdateCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S28_UpdateCustomKeyStoreResponse( sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IUpdateCustomKeyStoreResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> UpdateKeyDescription(Dafny.Com.Amazonaws.Kms._IUpdateKeyDescriptionRequest request) { Amazon.KeyManagementService.Model.UpdateKeyDescriptionRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S27_UpdateKeyDescriptionRequest(request); try { this._impl.UpdateKeyDescriptionAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> UpdatePrimaryRegion(Dafny.Com.Amazonaws.Kms._IUpdatePrimaryRegionRequest request) { Amazon.KeyManagementService.Model.UpdatePrimaryRegionRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S26_UpdatePrimaryRegionRequest(request); try { this._impl.UpdatePrimaryRegionAsync(sdkRequest).Wait(); return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Success(_System.Tuple0.Default()); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile.Result<_System._ITuple0, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> .create_Failure(this.ConvertError(ex)); } } public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms._IVerifyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException> Verify( Dafny.Com.Amazonaws.Kms._IVerifyRequest request) { Amazon.KeyManagementService.Model.VerifyRequest sdkRequest = TypeConversion.FromDafny_N3_com__N9_amazonaws__N3_kms__S13_VerifyRequest(request); try { Amazon.KeyManagementService.Model.VerifyResponse sdkResponse = this._impl.VerifyAsync(sdkRequest).Result; return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IVerifyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Success( TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S14_VerifyResponse(sdkResponse)); } catch (System.AggregateException aggregate) when (aggregate.InnerException is Amazon.KeyManagementService.AmazonKeyManagementServiceException ex) { return Wrappers_Compile .Result<Dafny.Com.Amazonaws.Kms._IVerifyResponse, Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException>.create_Failure(this.ConvertError(ex)); } } private Dafny.Com.Amazonaws.Kms.IKeyManagementServiceException ConvertError( Amazon.KeyManagementService.AmazonKeyManagementServiceException error) { switch (error) { case Amazon.KeyManagementService.Model.AlreadyExistsException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S22_AlreadyExistsException(e); case Amazon.KeyManagementService.Model.CloudHsmClusterInUseException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S29_CloudHsmClusterInUseException(e); case Amazon.KeyManagementService.Model.CloudHsmClusterInvalidConfigurationException e: return TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S44_CloudHsmClusterInvalidConfigurationException(e); case Amazon.KeyManagementService.Model.CloudHsmClusterNotActiveException e: return TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S33_CloudHsmClusterNotActiveException(e); case Amazon.KeyManagementService.Model.CloudHsmClusterNotFoundException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S32_CloudHsmClusterNotFoundException(e); case Amazon.KeyManagementService.Model.CloudHsmClusterNotRelatedException e: return TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S34_CloudHsmClusterNotRelatedException(e); case Amazon.KeyManagementService.Model.CustomKeyStoreHasCMKsException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S30_CustomKeyStoreHasCMKsException(e); case Amazon.KeyManagementService.Model.CustomKeyStoreInvalidStateException e: return TypeConversion .ToDafny_N3_com__N9_amazonaws__N3_kms__S35_CustomKeyStoreInvalidStateException(e); case Amazon.KeyManagementService.Model.CustomKeyStoreNameInUseException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S32_CustomKeyStoreNameInUseException(e); case Amazon.KeyManagementService.Model.CustomKeyStoreNotFoundException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S31_CustomKeyStoreNotFoundException(e); case Amazon.KeyManagementService.Model.DependencyTimeoutException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S26_DependencyTimeoutException(e); case Amazon.KeyManagementService.Model.DisabledException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S17_DisabledException(e); case Amazon.KeyManagementService.Model.ExpiredImportTokenException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S27_ExpiredImportTokenException(e); case Amazon.KeyManagementService.Model.IncorrectKeyException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S21_IncorrectKeyException(e); case Amazon.KeyManagementService.Model.IncorrectKeyMaterialException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S29_IncorrectKeyMaterialException(e); case Amazon.KeyManagementService.Model.IncorrectTrustAnchorException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S29_IncorrectTrustAnchorException(e); case Amazon.KeyManagementService.Model.InvalidAliasNameException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S25_InvalidAliasNameException(e); case Amazon.KeyManagementService.Model.InvalidArnException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S19_InvalidArnException(e); case Amazon.KeyManagementService.Model.InvalidCiphertextException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S26_InvalidCiphertextException(e); case Amazon.KeyManagementService.Model.InvalidGrantIdException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S23_InvalidGrantIdException(e); case Amazon.KeyManagementService.Model.InvalidGrantTokenException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S26_InvalidGrantTokenException(e); case Amazon.KeyManagementService.Model.InvalidImportTokenException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S27_InvalidImportTokenException(e); case Amazon.KeyManagementService.Model.InvalidKeyUsageException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S24_InvalidKeyUsageException(e); case Amazon.KeyManagementService.Model.InvalidMarkerException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S22_InvalidMarkerException(e); case Amazon.KeyManagementService.Model.KeyUnavailableException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S23_KeyUnavailableException(e); case Amazon.KeyManagementService.Model.KMSInternalException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S20_KMSInternalException(e); case Amazon.KeyManagementService.Model.KMSInvalidSignatureException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S28_KMSInvalidSignatureException(e); case Amazon.KeyManagementService.Model.KMSInvalidStateException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S24_KMSInvalidStateException(e); case Amazon.KeyManagementService.Model.LimitExceededException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S22_LimitExceededException(e); case Amazon.KeyManagementService.Model.MalformedPolicyDocumentException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S32_MalformedPolicyDocumentException(e); case Amazon.KeyManagementService.Model.NotFoundException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S17_NotFoundException(e); case Amazon.KeyManagementService.Model.TagException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S12_TagException(e); case Amazon.KeyManagementService.Model.UnsupportedOperationException e: return TypeConversion.ToDafny_N3_com__N9_amazonaws__N3_kms__S29_UnsupportedOperationException(e); default: return new Dafny.Com.Amazonaws.Kms.UnknownKeyManagementServiceError { message = TypeConversion.ToDafny_N6_smithy__N3_api__S6_String(error.Message ?? "") }; } } } }
1,183
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Linq; using System.Security.Cryptography; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Wrappers_Compile; using ibyteseq = Dafny.ISequence<byte>; using byteseq = Dafny.Sequence<byte>; using icharseq = Dafny.ISequence<char>; using charseq = Dafny.Sequence<char>; namespace AESEncryption { public partial class AES_GCM { public static _IResult<_IEncryptionOutput, icharseq> AESEncryptExtern( AESEncryption._IAES__GCM encAlg, ibyteseq iv, ibyteseq key, ibyteseq msg, ibyteseq aad ) { var keyBytes = key.Elements; var nonceBytes = iv.Elements; var plaintextBytes = msg.Elements; var aadBytes = aad.Elements; var ciphertext = new byte[plaintextBytes.Length + encAlg.dtor_tagLength]; try { // System.Security.Cryptography.AesGcm is absent in .NET Framework #if NETFRAMEWORK var param = new AeadParameters( new KeyParameter(keyBytes), encAlg.dtor_tagLength * 8, nonceBytes, aadBytes); var cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); cipher.Init(true, param); var len = cipher.ProcessBytes(msg.Elements, 0, msg.Elements.Length, ciphertext, 0); cipher.DoFinal(ciphertext, len); // Append authentication tag #else var aesCiphertext = new Span<byte>(ciphertext, 0, plaintextBytes.Length); var tag = new Span<byte>(ciphertext, plaintextBytes.Length, encAlg.dtor_tagLength); var cipher = new AesGcm(keyBytes); cipher.Encrypt(nonceBytes, plaintextBytes, aesCiphertext, tag, aadBytes); #endif return Result<_IEncryptionOutput, icharseq>.create_Success( __default.EncryptionOutputFromByteSeq(byteseq.FromArray(ciphertext), encAlg)); } catch (Exception ex) { var message = string.IsNullOrEmpty(ex.Message) ? "" : $": {ex.Message}"; return DafnyFFI.CreateFailure<EncryptionOutput>("AES encrypt error" + message); } } public static _IResult<ibyteseq, icharseq> AESDecryptExtern( AESEncryption._IAES__GCM encAlg, ibyteseq key, ibyteseq cipherText, ibyteseq authTag, ibyteseq iv, ibyteseq aad ) { var keyBytes = key.Elements; var nonceBytes = iv.Elements; var ciphertextBytes = cipherText.Elements; var aadBytes = aad.Elements; var tagBytes = authTag.Elements; var plaintext = new byte[ciphertextBytes.Length]; try { #if NETFRAMEWORK var ciphertextAndTag = ciphertextBytes.Concat(tagBytes).ToArray(); var param = new AeadParameters( new KeyParameter(keyBytes), encAlg.dtor_tagLength * 8, nonceBytes, aadBytes); var cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); cipher.Init(false, param); cipher.DoFinal(ciphertextAndTag, plaintext, 0); #else var cipher = new AesGcm(keyBytes); cipher.Decrypt(nonceBytes, ciphertextBytes, tagBytes, plaintext, aadBytes); #endif return Result<ibyteseq, icharseq>.create_Success(byteseq.FromArray(plaintext)); } catch (Exception ex) { var message = string.IsNullOrEmpty(ex.Message) ? "" : $": {ex.Message}"; return DafnyFFI.CreateFailure<ibyteseq>("AES decrypt error" + message); } } } }
103
aws-encryption-sdk-dafny
aws
C#
using Amazon.KeyManagementService; using Wrappers_Compile; namespace AwsKmsUtils { public partial class __default { public static _IOption<bool> RegionMatch( Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient client, Dafny.ISequence<char> region) { string regionStr = AWS.EncryptionSDK.Core.TypeConversion.FromDafny_N6_smithy__N3_api__S6_String(region); IAmazonKeyManagementService nativeClient = AWS.EncryptionSDK.Core.TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S18_KmsClientReference(client); return new Option_Some<bool>(nativeClient.Config.RegionEndpoint.SystemName.Equals(regionStr)); } } }
18
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon; using Amazon.KeyManagementService; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Util; // ReSharper disable once RedundantUsingDirective using AWS.EncryptionSDK.Core; // ReSharper disable once RedundantUsingDirective using Wrappers_Compile; namespace DefaultClientSupplier { // ReSharper disable once RedundantExtendsListEntry public partial class DefaultClientSupplier : Dafny.Aws.EncryptionSdk.Core.IClientSupplier { // ReSharper disable once RedundantNameQualifier public Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> GetClient( Dafny.Aws.EncryptionSdk.Core._IGetClientInput input) { GetClientInput convertedInput = AWS.EncryptionSDK.Core.TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput(input); try { var regionEndpoint = string.IsNullOrEmpty(convertedInput.Region) ? null : RegionEndpoint.GetBySystemName(convertedInput.Region); var clientConfig = new AmazonKeyManagementServiceConfig { RegionEndpoint = regionEndpoint }; var client = new DefaultKmsClient(clientConfig); // ReSharper disable once RedundantNameQualifier return Wrappers_Compile.Result<Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException>.create_Success( AWS.EncryptionSDK.Core.TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput__M6_client(client) ); } catch (AmazonServiceException e) { return Result<Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException>.create_Failure( AWS.EncryptionSDK.Core.TypeConversion.ToDafny_CommonError(e) ); } } } /// <summary> /// A KMS client that adds the Encryption SDK version to the user agent. /// </summary> internal class DefaultKmsClient : AmazonKeyManagementServiceClient { public DefaultKmsClient(AmazonKeyManagementServiceConfig config) : base(config) { } protected override void CustomizeRuntimePipeline(RuntimePipeline pipeline) { base.CustomizeRuntimePipeline(pipeline); pipeline.AddHandlerAfter<Marshaller>(new UserAgentHandler()); } } /// <summary> /// Adds the Encryption SDK version to the user agent. /// </summary> internal class UserAgentHandler : PipelineHandler { private static readonly string UserAgentSuffix; static UserAgentHandler() { var version = typeof(UserAgentHandler).Assembly.GetName().Version; var semver = $"{version.Major}.{version.Minor}.{version.Build}"; UserAgentSuffix = $" AwsEncryptionSdkNet/{semver}"; } /// <inheritdoc /> public override void InvokeSync(IExecutionContext executionContext) { AddUserAgent(executionContext); base.InvokeSync(executionContext); } /// <inheritdoc /> public override Task<T> InvokeAsync<T>(IExecutionContext executionContext) { AddUserAgent(executionContext); return base.InvokeAsync<T>(executionContext); } private static void AddUserAgent(IExecutionContext executionContext) { var request = executionContext.RequestContext.Request; request.Headers[AWSSDKUtils.UserAgentHeader] += UserAgentSuffix; } } }
106
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using AWS.EncryptionSDK; using Wrappers_Compile; using icharseq = Dafny.ISequence<char>; using ibyteseq = Dafny.ISequence<byte>; using byteseq = Dafny.Sequence<byte>; namespace ExternDigest { public class UnsupportedDigestException : AwsEncryptionSdkBaseException { public UnsupportedDigestException(CryptoDatatypes_Compile.DigestAlgorithm alg) : base(String.Format("Unsupported digest parameter: {0}", alg)) { } public UnsupportedDigestException(HMAC.Digests digest) : base(String.Format("Unsupported digest: {0}", digest.ToString())) { } } public partial class __default { public static _IResult<ibyteseq, icharseq> Digest(CryptoDatatypes_Compile._IDigestAlgorithm alg, ibyteseq msg) { try { System.Security.Cryptography.HashAlgorithm hashAlgorithm; if (alg.is_SHA__512) { hashAlgorithm = System.Security.Cryptography.SHA512.Create(); } else { throw new UnsupportedDigestException((CryptoDatatypes_Compile.DigestAlgorithm)alg); } byte[] digest = hashAlgorithm.ComputeHash(msg.Elements); return Result<ibyteseq, icharseq>.create_Success(byteseq.FromArray(digest)); } catch (Exception e) { return DafnyFFI.CreateFailure<ibyteseq>(e.ToString()); } } } }
43
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Linq; using System.Collections.Generic; using ibyteseq = Dafny.ISequence<byte>; using byteseq = Dafny.Sequence<byte>; namespace EncryptionContext { public partial class __default { public static Dafny.Map<ibyteseq,ibyteseq> LinearToMap(Dafny.ISequence<_System._ITuple2<ibyteseq,ibyteseq>> kvPairs) { Dictionary<ibyteseq, ibyteseq> dict = kvPairs.Elements.ToDictionary( item => ((_System.Tuple2<ibyteseq, ibyteseq>)item)._0, item => ((_System.Tuple2<ibyteseq, ibyteseq>)item)._1); List<Dafny.Pair<ibyteseq, ibyteseq>> pairs = new List<Dafny.Pair<ibyteseq, ibyteseq>>(); foreach(KeyValuePair<ibyteseq, ibyteseq> entry in dict) { pairs.Add(new Dafny.Pair<ibyteseq, ibyteseq>(entry.Key, entry.Value)); } return Dafny.Map<ibyteseq,ibyteseq>.FromCollection(pairs); } } }
27
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using ibyteseq = Dafny.ISequence<byte>; using byteseq = Dafny.Sequence<byte>; namespace HMAC { public partial class HMac { private Org.BouncyCastle.Crypto.Macs.HMac hmac; public HMac(_IDigests digest) { Org.BouncyCastle.Crypto.IDigest bouncyCastleDigest; if(digest.is_SHA__256) { bouncyCastleDigest = new Org.BouncyCastle.Crypto.Digests.Sha256Digest(); } else if(digest.is_SHA__384) { bouncyCastleDigest = new Org.BouncyCastle.Crypto.Digests.Sha384Digest(); } else if(digest.is_SHA__512) { bouncyCastleDigest = new Org.BouncyCastle.Crypto.Digests.Sha512Digest(); } else { throw new ExternDigest.UnsupportedDigestException((Digests)digest); } hmac = new Org.BouncyCastle.Crypto.Macs.HMac(bouncyCastleDigest); } public void Init(ibyteseq input) { // KeyParameter/ Init should not mutate input, but this is safer than using input.Elements directly byte[] elemCopy = (byte[]) input.Elements.Clone(); var keyParams = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(elemCopy); hmac.Init(keyParams); // elemCopy may contain sensitive info; zeroize it to reduce time this lives in memory Array.Clear(elemCopy, 0, elemCopy.Length); elemCopy = null; } public void BlockUpdate(ibyteseq input) { // BlockUpdate should not mutate input, but this is safer than using input.Elements directly byte[] elemCopy = (byte[]) input.Elements.Clone(); hmac.BlockUpdate(elemCopy, 0, elemCopy.Length); // elemCopy may contain sensitive info; zeroize it to reduce time this lives in memory Array.Clear(elemCopy, 0, elemCopy.Length); elemCopy = null; } public ibyteseq GetResult() { byte[] output = new byte[hmac.GetMacSize()]; hmac.DoFinal(output, 0); return byteseq.FromArray(output); } } }
55
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Security.Cryptography; using icharseq = Dafny.ISequence<char>; using ibyteseq = Dafny.ISequence<byte>; namespace ExternRandom { public partial class __default { public static Wrappers_Compile._IResult<ibyteseq, icharseq> GenerateBytes(int i) { try { //= compliance/data-format/message-header.txt#2.5.1.6 //# While //# implementations cannot guarantee complete uniqueness, implementations //# MUST use a good source of randomness when generating messages IDs in //# order to make the chance of duplicate IDs negligible. RandomNumberGenerator rng = RandomNumberGenerator.Create(); byte[] z = new byte[i]; rng.GetBytes(z); return Wrappers_Compile.Result<ibyteseq, icharseq>.create_Success(Dafny.Sequence<byte>.FromArray(z)); } catch (Exception e) { return DafnyFFI.CreateFailure<ibyteseq>(e.ToString()); } } } }
29
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Diagnostics; using System.Text; using System.IO; using AWS.EncryptionSDK; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Security; using Wrappers_Compile; using icharseq = Dafny.ISequence<char>; using ibyteseq = Dafny.ISequence<byte>; using byteseq = Dafny.Sequence<byte>; namespace RSAEncryption { public class RSAUnsupportedPaddingSchemeException : AwsEncryptionSdkBaseException { public RSAUnsupportedPaddingSchemeException(string paddingScheme) : base(String.Format("Invalid RSA Padding Scheme: {0}", paddingScheme)) { } } public partial class RSA { // The following represent common, recommended RSA constants const int RSA_PUBLIC_EXPONENT = (65537); const int RSA_CERTAINTY = 256; public static byte[] ParsePEMString(string pem) { AsymmetricKeyParameter key = (AsymmetricKeyParameter) new PemReader(new StringReader(pem)).ReadObject(); using (StringWriter stringWriter = new StringWriter()) { PemWriter pemWriter = new PemWriter(stringWriter); pemWriter.WriteObject(key); return Encoding.UTF8.GetBytes(stringWriter.ToString()); } } // GetPemBytes represents a helper method that takes an AsymmetricCipherKeyPair and returns the corresponding // private and public keys as UTF-8 byte arrays private static void GetPemBytes(AsymmetricCipherKeyPair keyPair, out byte[] publicKeyBytes, out byte[] privateKeyBytes) { using (var stringWriter = new StringWriter()) { var pemWriter = new PemWriter(stringWriter); pemWriter.WriteObject(keyPair.Public); publicKeyBytes = Encoding.UTF8.GetBytes(stringWriter.ToString()); } using (var stringWriter = new StringWriter()) { var pemWriter = new PemWriter(stringWriter); pemWriter.WriteObject(keyPair.Private); privateKeyBytes = Encoding.UTF8.GetBytes(stringWriter.ToString()); } } // GetEngineForPadding represents a helper method that takes in an PaddingMode and returns a // IAsymmetricBlockCipher for the RsaBlindedEngine that uses the appropriate digest or throws a // RSAUnsupportedPaddingSchemeException if no valid padding exists private static IAsymmetricBlockCipher GetEngineForPadding(_IPaddingMode padding) { if (padding.is_PKCS1) { return new Pkcs1Encoding(new RsaBlindedEngine()); } else if (padding.is_OAEP__SHA1) { return new OaepEncoding(new RsaBlindedEngine(), new Sha1Digest()); } else if (padding.is_OAEP__SHA256) { return new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest()); } else if (padding.is_OAEP__SHA384) { return new OaepEncoding(new RsaBlindedEngine(), new Sha384Digest()); } else if (padding.is_OAEP__SHA512) { return new OaepEncoding(new RsaBlindedEngine(), new Sha512Digest()); } else { throw new RSAUnsupportedPaddingSchemeException(padding.ToString()); } } // GetPublicKeyFromByteSeq represents a helper method that takes in a byteseq representing a public // key and returns the AsymmetricKeyParameter for that public key, encoded using UTF-8 private static AsymmetricKeyParameter GetPublicKeyFromByteSeq(ibyteseq key) { AsymmetricKeyParameter keyParam; using (var stringReader = new StringReader(Encoding.UTF8.GetString(key.Elements))) { return (AsymmetricKeyParameter) new PemReader(stringReader).ReadObject(); } } /// <summary> /// Reads the given PEM-encoded RSA private key, and returns the corresponding PEM-encoded public key. /// </summary> public static byte[] GetPublicKeyFromPrivateKeyPemString(string pem) { RsaPrivateCrtKeyParameters privateKeyParams; using (var stringReader = new StringReader(pem)) { var pemObject = new PemReader(stringReader).ReadObject(); try { privateKeyParams = (RsaPrivateCrtKeyParameters)pemObject; } catch (InvalidCastException ex) { throw new ArgumentException("Expected RSA private key", nameof(pem), ex); } } Debug.Assert(privateKeyParams != null); RsaKeyParameters publicKeyParams = new RsaKeyParameters(false, privateKeyParams.Modulus, privateKeyParams.PublicExponent); using (var stringWriter = new StringWriter()) { new PemWriter(stringWriter).WriteObject(publicKeyParams); return Encoding.UTF8.GetBytes(stringWriter.ToString()); } } public static void GenerateKeyPairBytes(int strength, out byte[] publicKeyBytes, out byte[] privateKeyBytes) { if (strength > 4096) { throw new ArgumentException("AWS Crypto will not generate an RSA Key greater than 4096."); } RsaKeyPairGenerator keygen = new RsaKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(); keygen.Init(new RsaKeyGenerationParameters( BigInteger.ValueOf(RSA_PUBLIC_EXPONENT), secureRandom, strength, RSA_CERTAINTY)); AsymmetricCipherKeyPair keygenPair = keygen.GenerateKeyPair(); GetPemBytes(keygenPair, out publicKeyBytes, out privateKeyBytes); } public static void GenerateKeyPairExtern(int strength, out ibyteseq publicKey, out ibyteseq privateKey) { byte[] publicKeyBytes; byte[] privateKeyBytes; GenerateKeyPairBytes(strength, out publicKeyBytes, out privateKeyBytes); publicKey = byteseq.FromArray(publicKeyBytes); privateKey = byteseq.FromArray(privateKeyBytes); } public static _IResult<ibyteseq, icharseq> EncryptExtern(_IPaddingMode padding, ibyteseq publicKey, ibyteseq plaintextMessage) { try { IAsymmetricBlockCipher engine = GetEngineForPadding(padding); AsymmetricKeyParameter publicKeyParam = GetPublicKeyFromByteSeq(publicKey); engine.Init(true, publicKeyParam); return Result<ibyteseq, icharseq>.create_Success(byteseq.FromArray( engine.ProcessBlock(plaintextMessage.Elements, 0, plaintextMessage.Elements.Length))); } catch (Exception encryptEx) { return DafnyFFI.CreateFailure<ibyteseq>(encryptEx.ToString()); } } public static _IResult<ibyteseq, icharseq> DecryptExtern(_IPaddingMode padding, ibyteseq privateKey, ibyteseq cipherText) { try { IAsymmetricBlockCipher engine = GetEngineForPadding(padding); AsymmetricCipherKeyPair keyPair; using ( var stringReader = new StringReader(Encoding.UTF8.GetString(privateKey.Elements))) { // This needs to be read as an AsymmetricCipherKeyPair and cannot be read directly as a // AsymmetricKeyParameter like the public key can keyPair = (AsymmetricCipherKeyPair) new PemReader(stringReader).ReadObject(); } engine.Init(false, keyPair.Private); return Result<ibyteseq, icharseq>.create_Success(byteseq.FromArray( engine.ProcessBlock(cipherText.Elements, 0, cipherText.Elements.Length))); } catch (Exception decryptEx) { return DafnyFFI.CreateFailure<ibyteseq>(decryptEx.ToString()); } } } }
176
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Linq; using System.Collections.Generic; namespace Sets { public partial class __default { public static Dafny.ISequence<Dafny.ISequence<T>> SetToOrderedSequence<T>(Dafny.ISet<Dafny.ISequence<T>> set, Func<T,T,bool> less) { Dafny.ISequence<T>[] itemArray = set.Elements.ToArray(); IComparer<Dafny.ISequence<T>> lexicographicComapre = new LexicographicComparer<T>(less); Array.Sort(itemArray, lexicographicComapre); return Dafny.Sequence<Dafny.ISequence<T>>.FromElements(itemArray); } // This is to facilitate moving the above from a `method` to a `function method` in Dafny. public static Dafny.ISequence<Dafny.ISequence<T>> SetToOrderedSequence2<T>(Dafny.ISet<Dafny.ISequence<T>> set, Func<T,T,bool> less) { return SetToOrderedSequence(set, less); } } // Lexicographically compares two dafny sequences according to a given // isLessThan function public class LexicographicComparer<T> : Comparer<Dafny.ISequence<T>> { private Func<T,T,bool> isLessThan; public LexicographicComparer(Func<T,T,bool> isLessThan) { this.isLessThan = isLessThan; } public override int Compare(Dafny.ISequence<T> x, Dafny.ISequence<T> y) { if (x == null || y == null) return Default.Compare(x, y); T[] xArr = x.Elements; T[] yArr = y.Elements; for (int i = 0; i < xArr.Length && i < yArr.Length; i++) { bool xLessThanAtIndex = isLessThan(xArr[i], yArr[i]); if (xLessThanAtIndex) { return -1; } bool yLessThanAtIndex = isLessThan(yArr[i], xArr[i]); if (yLessThanAtIndex) { return 1; } } // Reached the end of one array. Either they are equal, or the // one which is shorter should be considered "less than" return xArr.Length.CompareTo(yArr.Length); } } }
56
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using AWS.EncryptionSDK; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Security; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Asn1; using Wrappers_Compile; using icharseq = Dafny.ISequence<char>; using ibyteseq = Dafny.ISequence<byte>; using byteseq = Dafny.Sequence<byte>; namespace Signature { public class ECDSAUnsupportedParametersException : AwsEncryptionSdkBaseException { public ECDSAUnsupportedParametersException(ECDSAParams parameters) : base(String.Format("Unsupported ECDSA parameters: {0}", parameters)) { } } public partial class ECDSA { public static _IResult<SignatureKeyPair, icharseq> ExternKeyGen(_IECDSAParams x) { try { ECKeyPairGenerator generator = new ECKeyPairGenerator(); SecureRandom rng = new SecureRandom(); X9ECParameters p; if (x.is_ECDSA__P384) { p = ECNamedCurveTable.GetByName("secp384r1"); } else if (x.is_ECDSA__P256) { p = ECNamedCurveTable.GetByName("secp256r1"); } else { throw new ECDSAUnsupportedParametersException((ECDSAParams)x); } generator.Init(new ECKeyGenerationParameters(new ECDomainParameters(p.Curve, p.G, p.N, p.H), rng)); AsymmetricCipherKeyPair kp = generator.GenerateKeyPair(); ECPoint pt = ((ECPublicKeyParameters)kp.Public).Q; // serialize the public and private keys, and then return them var vk = SerializePublicKey((ECPublicKeyParameters)kp.Public); var sk = byteseq.FromArray(((ECPrivateKeyParameters)kp.Private).D.ToByteArray()); return Result<SignatureKeyPair, icharseq>.create_Success(new SignatureKeyPair(vk, sk)); } catch (Exception e) { return DafnyFFI.CreateFailure<SignatureKeyPair>(e.ToString()); } } /// <summary> /// Compresses and encodes the elliptic curve point corresponding to the given public key. /// See SEC-1 v2 (http://www.secg.org/sec1-v2.pdf), sections 2.3.3 and 2.3.5. For /// example, note: /// the compressed y-coordinate is placed in the leftmost octet of the octet string /// along with an indication that point compression is on, and the x-coordinate is /// placed in the remainder of the octet string /// Requires: keyParams.Parameters.Curve is a prime curve (if not, a cast exception will be thrown) /// </summary> public static ibyteseq SerializePublicKey(ECPublicKeyParameters keyParams) { ECPoint pt = keyParams.Q; // zero-pad x coordinate var xBytes = pt.AffineXCoord.GetEncoded(); var curve = (FpCurve)keyParams.Parameters.Curve; int fieldByteSize = (curve.FieldSize + 7) / 8; if (xBytes.Length < fieldByteSize) { var paddingLength = fieldByteSize - xBytes.Length; var paddedX = new byte[fieldByteSize]; System.Array.Clear(paddedX, 0, paddingLength); xBytes.CopyTo(paddedX, paddingLength); xBytes = paddedX; } // compress y coordinate var y = pt.AffineYCoord.ToBigInteger(); byte compressedY = y.Mod(BigInteger.ValueOf(2)).Equals(BigInteger.ValueOf(0)) ? (byte)2 : (byte)3; var yBytes = new byte[] { compressedY }; // return yBytes + xBytes: return byteseq.Concat(byteseq.FromArray(yBytes), (byteseq.FromArray(xBytes))); } public static _IResult<bool, icharseq> Verify(_IECDSAParams x, ibyteseq vk, ibyteseq msg, ibyteseq sig) { try { byte[] digest = InternalDigest(x, msg); X9ECParameters parameters; if (x.is_ECDSA__P384) { parameters = ECNamedCurveTable.GetByName("secp384r1"); } else if (x.is_ECDSA__P256) { parameters = ECNamedCurveTable.GetByName("secp256r1"); } else { throw new ECDSAUnsupportedParametersException((ECDSAParams)x); } ECDomainParameters dp = new ECDomainParameters(parameters.Curve, parameters.G, parameters.N, parameters.H); ECPoint pt = parameters.Curve.DecodePoint((byte[])vk.Elements.Clone()); ECPublicKeyParameters vkp = new ECPublicKeyParameters(pt, dp); ECDsaSigner sign = new ECDsaSigner(); sign.Init(false, vkp); BigInteger r, s; DERDeserialize(sig.Elements, out r, out s); return Result<bool, icharseq>.create_Success(sign.VerifySignature(digest, r, s)); } catch (Exception e) { return Result<bool, icharseq>.create_Failure(Dafny.Sequence<char>.FromString(e.ToString())); } } public static _IResult<ibyteseq, icharseq> Sign(_IECDSAParams x, ibyteseq sk, ibyteseq msg) { try { byte[] digest = InternalDigest(x, msg); X9ECParameters parameters; if (x.is_ECDSA__P384) { parameters = ECNamedCurveTable.GetByName("secp384r1"); } else if (x.is_ECDSA__P256) { parameters = ECNamedCurveTable.GetByName("secp256r1"); } else { throw new ECDSAUnsupportedParametersException((ECDSAParams)x); } ECDomainParameters dp = new ECDomainParameters(parameters.Curve, parameters.G, parameters.N, parameters.H); ECPrivateKeyParameters skp = new ECPrivateKeyParameters(new BigInteger(sk.Elements), dp); ECDsaSigner sign = new ECDsaSigner(); sign.Init(true, skp); byte[] serializedSignature; // This loop can in theory run forever, but the chances of that are negligible. // We may want to consider failing, after some number of loops, if we can do so in a way consistent with other ESDKs. do { // sig is array of two integers: r and s BigInteger[] sig = sign.GenerateSignature(digest); serializedSignature = DERSerialize(sig[0], sig[1]); if (serializedSignature.Length != x.SignatureLength()) { // Most of the time, a signature of the wrong length can be fixed // by negating s in the signature relative to the group order. serializedSignature = DERSerialize(sig[0], parameters.N.Subtract(sig[1])); } } while (serializedSignature.Length != x.SignatureLength()); return Result<ibyteseq, icharseq>.create_Success(byteseq.FromArray(serializedSignature)); } catch (Exception e) { return DafnyFFI.CreateFailure<ibyteseq>(e.ToString()); } } private static byte[] InternalDigest(_IECDSAParams x, ibyteseq msg) { System.Security.Cryptography.HashAlgorithm alg; if (x.is_ECDSA__P384) { alg = System.Security.Cryptography.SHA384.Create(); } else if (x.is_ECDSA__P256) { alg = System.Security.Cryptography.SHA256.Create(); } else { throw new ECDSAUnsupportedParametersException((ECDSAParams)x); } return alg.ComputeHash(msg.Elements); } private static byte[] DERSerialize(BigInteger r, BigInteger s) { DerSequence derSeq = new DerSequence(new DerInteger(r), new DerInteger(s)); return derSeq.GetEncoded(); } private static void DERDeserialize(byte[] bytes, out BigInteger r, out BigInteger s) { Asn1InputStream asn1 = new Asn1InputStream(bytes); var seq = (Asn1Sequence)asn1.ReadObject(); var dr = (DerInteger)seq[0]; var ds = (DerInteger)seq[1]; r = new BigInteger(dr.ToString()); s = new BigInteger(ds.ToString()); } } }
175
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Numerics; namespace TimeUtil { public class Time { public static ulong CurrentRelativeTime() { var timespan = DateTime.Now - DateTime.MinValue; return (ulong)timespan.TotalSeconds; } } }
15
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Text; using Wrappers_Compile; using ibyteseq = Dafny.ISequence<byte>; using byteseq = Dafny.Sequence<byte>; using icharseq = Dafny.ISequence<char>; using charseq = Dafny.Sequence<char>; namespace UTF8 { public partial class __default { public static _IResult<ibyteseq, icharseq> Encode(icharseq str) { UTF8Encoding utf8 = new UTF8Encoding(false, true); try { byte[] utf8Bytes = utf8.GetBytes(str.Elements); return Result<ibyteseq, icharseq>.create_Success(byteseq.FromArray(utf8Bytes)); } catch(EncoderFallbackException e) { return DafnyFFI.CreateFailure<ibyteseq>( "Input contains invalid Unicode characters"); } catch(ArgumentNullException e) { return DafnyFFI.CreateFailure<ibyteseq>("Input is null"); } } public static _IResult<icharseq, icharseq> Decode(ibyteseq bytes) { UTF8Encoding utf8 = new UTF8Encoding(false, true); try { string decoded = utf8.GetString(bytes.Elements); return Result<icharseq, icharseq>.create_Success(charseq.FromString(decoded)); } catch(ArgumentException e) { // GetString is defined as returning ArgumentException, ArgumentNullException, DecoderFallbackException // Both ArgumentNullException and DecoderFallbackException are children of ArgumentException return DafnyFFI.CreateFailure<icharseq>("Input contains an invalid Unicode code point"); } } } }
40
aws-encryption-sdk-dafny
aws
C#
using System; using System.IO; using Wrappers_Compile; using icharseq = Dafny.ISequence<char>; using ibyteseq = Dafny.ISequence<byte>; namespace TestUtils { public partial class __default { public static _IOutcome<icharseq> WriteFile(icharseq path, ibyteseq contents) { try { var pathString = DafnyFFI.StringFromDafnyString(path); var bytes = DafnyFFI.ByteArrayFromSequence(contents); File.WriteAllBytes(pathString, bytes); return Outcome<icharseq>.create_Pass(); } catch (Exception e) { return DafnyFFI.CreateFail(e.Message); } } public static _IResult<ibyteseq, icharseq> ReadFile(icharseq path) { try { var pathString = DafnyFFI.StringFromDafnyString(path); var bytes = File.ReadAllBytes(pathString); var byteseq = DafnyFFI.SequenceFromByteArray(bytes); return Result<ibyteseq, icharseq>.create_Success(byteseq); } catch (Exception e) { return DafnyFFI.CreateFailure<ibyteseq>(e.Message); } } } }
33
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using AWS.EncryptionSDK.Core; // ReSharper disable once RedundantUsingDirective using Wrappers_Compile; using Xunit; using Xunit.Sdk; using static AWSEncryptionSDKTests.NativeWrappers.Utils; namespace AWSEncryptionSDKTests.NativeWrappers { public class OutputValidationTests { private const string EXPECTED_FAILURE = "Wrappers_Compile.Result.Failure(Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersException)"; [Fact] public void TestInvalidRejected() { var underTest = new NativeWrapper_Keyring(new BadKeyring()); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IOnEncryptOutput, // ReSharper disable once RedundantAssignment Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> output = null; try { output = underTest.OnEncrypt(GetDafnyOnEncryptInput()); } catch (Exception e) { throw new XunitException( $"{underTest}.OnEncrypt threw an exception: {e.GetType()} with message: \"{e.Message}\"." + $"Should have returned: \"{EXPECTED_FAILURE}\"" ); } if (output != null) { // Weird way of checking that the class is right, I know, but this is what I can figure out Assert.Equal(EXPECTED_FAILURE, $"{output}"); var e = output.dtor_error; const string expectedMessage = "Output of AWSEncryptionSDKTests.NativeWrappers.BadKeyring._OnEncrypt is invalid." + " Missing value for required property 'Materials'"; var actualMessage = TypeConversion.FromDafny_N6_smithy__N3_api__S6_String(e.GetMessage()); Assert.Equal(expectedMessage, actualMessage); } else { throw new XunitException($"{underTest}.OnEncrypt returned null." + $"Should have returned: \"{EXPECTED_FAILURE}\""); } } [Fact] public void TestNullRejected() { var underTest = new NativeWrapper_Keyring(new BadKeyring()); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IOnDecryptOutput, // ReSharper disable once RedundantAssignment Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> output = null; try { output = underTest.OnDecrypt(GetDafnyOnDecryptInput()); } catch (Exception e) { throw new XunitException( $"{underTest}.OnDecrypt threw an exception: {e.GetType()} with message: \"{e.Message}\"." + $"Should have returned: \"{EXPECTED_FAILURE}\"" ); } if (output != null) { Assert.Equal(EXPECTED_FAILURE, $"{output}"); var e = output.dtor_error; const string expectedMessage = "AWSEncryptionSDKTests.NativeWrappers.BadKeyring._OnDecrypt returned null, should be AWS.EncryptionSDK.Core.OnDecryptOutput"; var actualMessage = TypeConversion.FromDafny_N6_smithy__N3_api__S6_String(e.GetMessage()); /*Console.Out.WriteLine($"actual is: \"{actualMessage}\"");*/ Assert.Equal(expectedMessage, actualMessage); } else { throw new XunitException($"{underTest}.OnDecrypt returned null." + $"Should have returned: \"{EXPECTED_FAILURE}\""); } } } class BadKeyring : KeyringBase { protected override OnEncryptOutput _OnEncrypt(OnEncryptInput input) { return new OnEncryptOutput(); } protected override OnDecryptOutput _OnDecrypt(OnDecryptInput input) { return null; } } internal static class Utils { internal static Dafny.Aws.EncryptionSdk.Core._IOnEncryptInput GetDafnyOnEncryptInput() { return TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnEncryptInput(GetOnEncryptInput()); } internal static Dafny.Aws.EncryptionSdk.Core._IOnDecryptInput GetDafnyOnDecryptInput() { return TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_OnDecryptInput(GetOnDecryptInput()); } static OnEncryptInput GetOnEncryptInput() { var materials = new EncryptionMaterials() { AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, EncryptionContext = new Dictionary<string, string>() {{"test", "test"}}, EncryptedDataKeys = new List<EncryptedDataKey>() }; return new OnEncryptInput {Materials = materials}; } static OnDecryptInput GetOnDecryptInput() { var materials = new DecryptionMaterials() { AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, EncryptionContext = new Dictionary<string, string>() {{"test", "test"}} }; return new OnDecryptInput() { EncryptedDataKeys = new List<EncryptedDataKey>(), Materials = materials }; } } }
143
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using AWS.EncryptionSDK.Core; using Xunit; using Xunit.Sdk; namespace AWSEncryptionSDKTests.NativeWrappers { public class TypeConversionToDafnyWrapperTest { [Fact] public void TestInterfaceThrowsException() { const string expectedMessage = "Custom implementations of Keyring must extend KeyringBase."; var expected = new ArgumentException(expectedMessage); Dafny.Aws.EncryptionSdk.Core.IKeyring output = null; try { output = TypeConversion .ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference( new KeyringInterface()); } catch (ArgumentException e) { Assert.Equal(expectedMessage, e.Message); return; } catch (Exception e) { throw new XunitException( nameof(TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference) + $" threw an exception: {e.GetType()} with message: \"{e.Message}\"." + $"Should have thrown: \"{expected}\"" ); } throw new XunitException( nameof(TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S16_KeyringReference) + $" returned {output}. Should have thrown: \"{expected}\""); } } class KeyringInterface : IKeyring { public OnEncryptOutput OnEncrypt(OnEncryptInput input) { throw new System.NotImplementedException(); } public OnDecryptOutput OnDecrypt(OnDecryptInput input) { throw new System.NotImplementedException(); } } }
53
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.CommandLine; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using AWS.EncryptionSDK.Core; using AWS.EncryptionSDK; namespace TestVectors { class Generator { private const string OutputKeysManifestUri = "file://keys.json"; static void Main(string[] args) { var encryptManifestFileOpt = new Option<FileInfo>(name: "--encrypt-manifest") { IsRequired = true }; var outputDirOpt = new Option<DirectoryInfo>(name: "--output-dir") { IsRequired = true }; var quietOpt = new Option<bool>(name: "--quiet"); var rootCommand = new RootCommand { encryptManifestFileOpt, outputDirOpt, quietOpt }; rootCommand.SetHandler((FileInfo encryptManifestFile, DirectoryInfo outputDir, bool quiet) => { new Generator(encryptManifestFile, outputDir, quiet).Run(); }, encryptManifestFileOpt, outputDirOpt, quietOpt); rootCommand.Invoke(args); } private readonly EncryptManifest _encryptManifest; private readonly KeyManifest _keyManifest; private readonly DirectoryInfo _outputDir; private readonly DirectoryInfo _plaintextDir; private readonly DirectoryInfo _ciphertextDir; private readonly bool _quiet; private Generator(FileInfo encryptManifestFile, DirectoryInfo outputDir, bool quiet) { _encryptManifest = Utils.LoadObjectFromPath<EncryptManifest>(encryptManifestFile.FullName); Console.Error.WriteLine( $"Loaded {_encryptManifest.VectorMap.Count} vectors from {encryptManifestFile.FullName}"); string keysPath = Utils.ManifestUriToPath(_encryptManifest.KeysUri, encryptManifestFile.FullName); _keyManifest = Utils.LoadObjectFromPath<KeyManifest>(keysPath); if (!outputDir.Exists) { outputDir.Create(); } if (outputDir.GetFileSystemInfos().Length != 0) { throw new ArgumentException("Output directory not empty"); } _outputDir = outputDir; _plaintextDir = outputDir.CreateSubdirectory("plaintexts"); _ciphertextDir = outputDir.CreateSubdirectory("ciphertexts"); _quiet = quiet; } private void Run() { var plaintexts = GeneratePlaintexts(_encryptManifest.PlaintextSizes); Utils.WriteNamedDataMap(_plaintextDir, plaintexts); Console.Error.WriteLine($"Wrote {plaintexts.Count} plaintext files"); var targetedVectors = _encryptManifest.VectorMap .Where(pair => ShouldTargetVector(pair.Key, pair.Value)) .ToList(); var totalVectorCount = _encryptManifest.VectorMap.Count; Console.Error.WriteLine($"Targeting {targetedVectors.Count} out of {totalVectorCount} vectors"); GenerateAndWriteVectors(targetedVectors, plaintexts); Console.Error.WriteLine($"Wrote {targetedVectors.Count} ciphertexts"); DecryptManifest decryptManifest = GenerateDecryptManifest(targetedVectors, plaintexts); string decryptManifestPath = Path.Join(_outputDir.FullName, "manifest.json"); Utils.WriteObjectToPath(decryptManifest, decryptManifestPath); Console.Error.WriteLine("Wrote decrypt vector manifest"); // TODO resolve KMS aliases to ARNs, instead of copying them over var keysPath = Utils.ManifestUriToPath(OutputKeysManifestUri, decryptManifestPath); Utils.WriteObjectToPath(_keyManifest, keysPath); Console.Error.WriteLine("Wrote key manifest"); } private static Dictionary<string, MemoryStream> GeneratePlaintexts(Dictionary<string, uint> sizes) { var plaintexts = new Dictionary<string, MemoryStream>(); foreach (var (name, size) in sizes) { if (size > int.MaxValue) { throw new ArgumentException($"Can't generate a {size}-byte plaintext"); } var buffer = new MemoryStream((int)size); RandomNumberGenerator.Fill(buffer.GetBuffer()); plaintexts.Add(name, buffer); } return plaintexts; } // We don't have a better way to query this information right now. // This could be a use case for Smithy enums' "tags" property, that we'd need to support in codegen. // https://awslabs.github.io/smithy/1.0/spec/core/constraint-traits.html#enum-trait private static readonly AlgorithmSuiteId[] COMMITTING_ALGORITHM_SUITES = { AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, }; /// <summary> /// Returns whether the generator should attempt to encrypt the given vector. /// Useful for selecting particular vectors when debugging. /// </summary> private bool ShouldTargetVector(string id, EncryptVector vector) { // We don't support encrypting unframed messages. return vector.Scenario.FrameSize != 0; } private void GenerateAndWriteVectors( IList<KeyValuePair<string, EncryptVector>> targetedVectors, Dictionary<string, MemoryStream> plaintexts) { foreach (var (id, vector) in targetedVectors) { try { var ciphertext = GenerateDecryptVector(vector, plaintexts); Utils.WriteBinaryFile(_ciphertextDir, id, ciphertext); if (!_quiet) { Console.Error.WriteLine($"Wrote ciphertext file for vector {id}"); } } catch (AwsEncryptionSdkException ex) { throw new ApplicationException($"Failed to encrypt vector {id}", ex); } } } private DecryptManifest GenerateDecryptManifest( IList<KeyValuePair<string, EncryptVector>> targetedVectors, Dictionary<string, MemoryStream> plaintexts) { var decryptVectors = new Dictionary<string, DecryptVector>(); foreach (var (id, encryptVector) in targetedVectors) { var plaintextPath = "file://" + Path.Join(_plaintextDir.Name, encryptVector.Scenario.PlaintextName); var ciphertextPath = "file://" + Path.Join(_ciphertextDir.Name, id); decryptVectors[id] = new DecryptVector { Ciphertext = ciphertextPath, MasterKeys = encryptVector.Scenario.MasterKeys, Result = new DecryptResult { Output = new DecryptOutput { Plaintext = plaintextPath } } }; } return new DecryptManifest { Meta = new ManifestMeta { Type = "awses-decrypt", // This manifest format is described by version 3 of "AWS Encryption SDK Message Decryption": // https://github.com/awslabs/aws-crypto-tools-test-vector-framework/blob/master/features/0004-awses-message-decryption.md // // Although the Python ESDK's test vector handler would correctly handle/decrypt the vectors, // it incorrectly rejects the version "3" during manifest loading, // so for expedience we'll just advertise what Python can handle. // TODO: fix Python's vector handler version validation, and change this value to 3 Version = 2 }, Client = new Client { Name = "awslabs/aws-encryption-sdk-dafny", // TODO pass this by env var Version = "0.1.0-alpha" }, KeysUri = OutputKeysManifestUri, VectorMap = decryptVectors }; } private MemoryStream GenerateDecryptVector( EncryptVector vector, Dictionary<string, MemoryStream> plaintexts) { EncryptScenario scenario = vector.Scenario; AlgorithmSuiteId algSuiteId = new AlgorithmSuiteId("0x" + scenario.Algorithm); Debug.Assert(AlgorithmSuiteId.Values.Contains(algSuiteId)); CommitmentPolicy commitmentPolicy = COMMITTING_ALGORITHM_SUITES.Contains(algSuiteId) ? CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT : CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT; AwsEncryptionSdkConfig config = new AwsEncryptionSdkConfig { CommitmentPolicy = commitmentPolicy }; IAwsEncryptionSdk client = AwsEncryptionSdkFactory.CreateAwsEncryptionSdk(config); ICryptographicMaterialsManager cmm = MaterialProviderFactory.CreateEncryptCmm(vector, _keyManifest.Keys); EncryptInput encryptInput = new EncryptInput { AlgorithmSuiteId = algSuiteId, EncryptionContext = scenario.EncryptionContext, FrameLength = scenario.FrameSize, MaterialsManager = cmm, Plaintext = plaintexts[scenario.PlaintextName] }; return client.Encrypt(encryptInput).Ciphertext; } } }
227
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Amazon; using Amazon.KeyManagementService; using AWS.EncryptionSDK.Core; using RSAEncryption; namespace TestVectors { public enum CryptoOperation { ENCRYPT, DECRYPT } public static class MaterialProviderFactory { public static IAwsCryptographicMaterialProviders materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); public static ICryptographicMaterialsManager CreateDecryptCmm(DecryptVector vector, Dictionary<string, Key> keys) { CreateDefaultCryptographicMaterialsManagerInput input = new CreateDefaultCryptographicMaterialsManagerInput { Keyring = CreateDecryptKeyring(vector, keys) }; return materialProviders.CreateDefaultCryptographicMaterialsManager(input); } private static IKeyring CreateDecryptKeyring(DecryptVector vector, Dictionary<string, Key> keys) { List<IKeyring> children = new List<IKeyring>(); foreach (MasterKey keyInfo in vector.MasterKeys) { // Some keyrings, like discovery KMS keyrings, do not specify keys Key key = keyInfo.Key == null ? null : keys[keyInfo.Key]; children.Add(CreateKeyring(keyInfo, key, CryptoOperation.DECRYPT)); } CreateMultiKeyringInput createMultiKeyringInput = new CreateMultiKeyringInput { Generator = null, ChildKeyrings = children }; return materialProviders.CreateMultiKeyring(createMultiKeyringInput); } public static ICryptographicMaterialsManager CreateEncryptCmm(EncryptVector vector, Dictionary<string, Key> keys) { CreateDefaultCryptographicMaterialsManagerInput input = new CreateDefaultCryptographicMaterialsManagerInput { Keyring = CreateEncryptKeyring(vector, keys) }; return materialProviders.CreateDefaultCryptographicMaterialsManager(input); } private static IKeyring CreateEncryptKeyring(EncryptVector vector, Dictionary<string, Key> keys) { IList<MasterKey> masterKeys = vector.Scenario.MasterKeys; Debug.Assert(masterKeys.Count >= 1); Key generatorKey = keys[masterKeys[0].Key]; IKeyring generatorKeyring = CreateKeyring(masterKeys[0], generatorKey, CryptoOperation.ENCRYPT); List<IKeyring> children = masterKeys .Skip(1) .Select(masterKey => { Key key = keys[masterKey.Key]; return CreateKeyring(masterKey, key, CryptoOperation.ENCRYPT); }) .ToList(); CreateMultiKeyringInput createMultiKeyringInput = new CreateMultiKeyringInput { Generator = generatorKeyring, ChildKeyrings = children }; return materialProviders.CreateMultiKeyring(createMultiKeyringInput); } private static IKeyring CreateKeyring(MasterKey keyInfo, Key key, CryptoOperation operation) { if (keyInfo.Type == "aws-kms") { CreateAwsKmsKeyringInput createKeyringInput = new CreateAwsKmsKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(GetRegionForArn(key.Id)), KmsKeyId = key.Id, }; return materialProviders.CreateAwsKmsKeyring(createKeyringInput); } if (keyInfo.Type == "aws-kms-mrk-aware") { CreateAwsKmsMrkKeyringInput createKeyringInput = new CreateAwsKmsMrkKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(GetRegionForArn(key.Id)), KmsKeyId = key.Id, }; return materialProviders.CreateAwsKmsMrkKeyring(createKeyringInput); } if (keyInfo.Type == "aws-kms-mrk-aware-discovery" && operation == CryptoOperation.DECRYPT) { AWS.EncryptionSDK.Core.DiscoveryFilter filter = null; if (keyInfo.AwsKmsDiscoveryFilter != null) { filter = new AWS.EncryptionSDK.Core.DiscoveryFilter { AccountIds = (List<string>)keyInfo.AwsKmsDiscoveryFilter.AccountIds, Partition = keyInfo.AwsKmsDiscoveryFilter.Partition, }; } CreateAwsKmsMrkDiscoveryKeyringInput createKeyringInput = new CreateAwsKmsMrkDiscoveryKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.GetBySystemName(keyInfo.DefaultMrkRegion)), Region = keyInfo.DefaultMrkRegion, DiscoveryFilter = filter, }; return materialProviders.CreateAwsKmsMrkDiscoveryKeyring(createKeyringInput); } if (keyInfo.Type == "raw" && keyInfo.EncryptionAlgorithm == "aes") { CreateRawAesKeyringInput createKeyringInput = new CreateRawAesKeyringInput { KeyNamespace = keyInfo.ProviderId, KeyName = key.Id, WrappingKey = new MemoryStream(Convert.FromBase64String(key.Material)), WrappingAlg = AesAlgorithmFromBits(key.Bits), }; return materialProviders.CreateRawAesKeyring(createKeyringInput); } if (keyInfo.Type == "raw" && keyInfo.EncryptionAlgorithm == "rsa" && key.Type == "private") { PaddingScheme padding = RSAPaddingFromStrings(keyInfo.PaddingAlgorithm, keyInfo.PaddingHash); byte[] privateKey = RSA.ParsePEMString(key.Material); CreateRawRsaKeyringInput createKeyringInput = new CreateRawRsaKeyringInput { KeyNamespace = keyInfo.ProviderId, KeyName = key.Id, PaddingScheme = padding, PrivateKey = new MemoryStream(privateKey) }; // Extract the public key if we need to encrypt if (operation == CryptoOperation.ENCRYPT) { byte[] publicKey = RSA.GetPublicKeyFromPrivateKeyPemString(key.Material); createKeyringInput.PublicKey = new MemoryStream(publicKey); } return materialProviders.CreateRawRsaKeyring(createKeyringInput); } if (keyInfo.Type == "raw" && keyInfo.EncryptionAlgorithm == "rsa" && key.Type == "public") { PaddingScheme padding = RSAPaddingFromStrings(keyInfo.PaddingAlgorithm, keyInfo.PaddingHash); byte[] publicKey = RSA.ParsePEMString(key.Material); CreateRawRsaKeyringInput createKeyringInput = new CreateRawRsaKeyringInput { KeyNamespace = keyInfo.ProviderId, KeyName = key.Id, PaddingScheme = padding, PublicKey = new MemoryStream(publicKey) }; return materialProviders.CreateRawRsaKeyring(createKeyringInput); } string operationStr = operation == CryptoOperation.ENCRYPT ? "encryption" : "decryption"; throw new Exception($"Unsupported keyring type for {operation}"); } private static AesWrappingAlg AesAlgorithmFromBits(ushort bits) { switch (bits) { case 128: return AesWrappingAlg.ALG_AES128_GCM_IV12_TAG16; case 192: return AesWrappingAlg.ALG_AES192_GCM_IV12_TAG16; case 256: return AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16; default: throw new Exception("Unsupported AES wrapping algorithm"); }; } private static PaddingScheme RSAPaddingFromStrings(string strAlg, string strHash) { switch (strAlg) { case "pkcs1": return PaddingScheme.PKCS1; case "oaep-mgf1": switch (strHash) { case "sha1": return PaddingScheme.OAEP_SHA1_MGF1; case "sha256": return PaddingScheme.OAEP_SHA256_MGF1; case "sha384": return PaddingScheme.OAEP_SHA384_MGF1; case "sha512": return PaddingScheme.OAEP_SHA512_MGF1; } break; }; throw new Exception("Unsupported RSA Padding " + strAlg + strHash); } private static RegionEndpoint GetRegionForArn(string keyId) { try { Arn arn = Arn.Parse(keyId); return RegionEndpoint.GetBySystemName(arn.Region); } catch (ArgumentException e) { // Some of our test vector key definitions use a variety of // malformed key ids. // These are usually meant to fail (since decryption requires // matching configured key arns to ciphertext key arns), // but in order for them to fail correctly // we need to at least be able to create our client, // so we choose a default region return RegionEndpoint.GetBySystemName("us-west-2"); } } } }
226
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using Newtonsoft.Json; namespace TestVectors { // TODO Need to use some enums for various fields, possibly subtypes to represent RSA vs AES having different params? public class Key { [JsonProperty("decrypt")] public bool Decrypt { get; set; } [JsonProperty("encrypt")] public bool Encrypt { get; set; } [JsonRequired] [JsonProperty("type")] public string Type { get; set; } [JsonRequired] [JsonProperty("key-id")] public string Id { get; set; } [JsonProperty("algorithm")] public string Algorithm { get; set; } [JsonProperty("bits")] public ushort Bits { get; set; } [JsonProperty("encoding")] public string Encoding { get; set; } [JsonProperty("material")] public string Material { get; set; } } public class KeyManifest { [JsonRequired] [JsonProperty("manifest")] public ManifestMeta Meta { get; set; } [JsonRequired] [JsonProperty("keys")] public Dictionary<string, Key> Keys { get; set; } } // TODO Rename? Need to use some enums for various fields, possibly subtypes to represent RSA vs AES having different params? public class MasterKey { [JsonProperty("type")] public string Type { get; set; } [JsonProperty("key")] public string Key { get; set; } [JsonProperty("provider-id")] public string ProviderId { get; set; } [JsonProperty("encryption-algorithm")] public string EncryptionAlgorithm { get; set; } [JsonProperty("padding-algorithm")] public string PaddingAlgorithm { get; set; } [JsonProperty("padding-hash")] public string PaddingHash { get; set; } [JsonProperty("default-mrk-region")] public string DefaultMrkRegion { get; set; } [JsonProperty("aws-kms-discovery-filter")] public DiscoveryFilter AwsKmsDiscoveryFilter { get; set; } } public class DiscoveryFilter { [JsonProperty("partition")] public string Partition { get; set; } [JsonProperty("account-ids")] public IList<string> AccountIds { get; set; } } public class DecryptVector { [JsonProperty("description")] public string Description { get; set; } [JsonRequired] [JsonProperty("ciphertext")] public string Ciphertext { get; set; } [JsonProperty("master-keys")] public IList<MasterKey> MasterKeys { get; set; } [JsonProperty("result")] public DecryptResult Result { get; set; } [JsonProperty("decryption-method")] public string DecryptionMethod { get; set; } } public class DecryptResult { [JsonProperty("output")] public DecryptOutput Output { get; set; } [JsonProperty("error")] public DecryptError Error { get; set; } } public class DecryptOutput { [JsonProperty("plaintext")] public string Plaintext { get; set; } } public class DecryptError { [JsonProperty("error-description")] public string ErrorMessage { get; set; } } public class DecryptManifest { [JsonRequired] [JsonProperty("manifest")] public ManifestMeta Meta { get; set; } [JsonRequired] [JsonProperty("client")] public Client Client { get; set; } [JsonRequired] [JsonProperty("keys")] public string KeysUri { get; set; } [JsonRequired] [JsonProperty("tests")] public Dictionary<string, DecryptVector> VectorMap { get; set; } } public class EncryptScenario { [JsonRequired] [JsonProperty("plaintext")] public string PlaintextName { get; set; } /// <summary> /// Hex string of algorithm suite ID /// </summary> [JsonRequired] [JsonProperty("algorithm")] public string Algorithm { get; set; } [JsonRequired] [JsonProperty("frame-size")] public uint FrameSize { get; set; } [JsonRequired] [JsonProperty("encryption-context")] public Dictionary<string, string> EncryptionContext { get; set; } [JsonRequired] [JsonProperty("master-keys")] public IList<MasterKey> MasterKeys { get; set; } } public class EncryptVector { [JsonRequired] [JsonProperty("encryption-scenario")] public EncryptScenario Scenario { get; set; } // TODO: each of these three are currently unused, but we need to model them // so that we can successfully parse the manifest [JsonProperty("decryption-method")] public string DecryptionMethod { get; set; } [JsonProperty("result")] public DecryptResult Result { get; set; } [JsonProperty("decryption-master-keys")] public IList<MasterKey> DecryptionMasterKeys { get; set; } // TODO create tampered messages // 'dynamic' type because we sometimes set this as a string // and sometimes set it as an object. Will need to figure this // out when we support tampered messages [JsonProperty("tampering")] public dynamic Tampering { get; set; } } public class EncryptManifest { [JsonRequired] [JsonProperty("manifest")] public ManifestMeta Meta { get; set; } [JsonRequired] [JsonProperty("keys")] public string KeysUri { get; set; } [JsonRequired] [JsonProperty("plaintexts")] public Dictionary<string, uint> PlaintextSizes { get; set; } [JsonRequired] [JsonProperty("tests")] public Dictionary<string, EncryptVector> VectorMap { get; set; } } public class ManifestMeta { [JsonRequired] [JsonProperty("type")] public string Type { get; set; } [JsonRequired] [JsonProperty("version")] public int Version { get; set; } } public class Client { [JsonRequired] [JsonProperty("name")] public string Name { get; set; } [JsonRequired] [JsonProperty("version")] public string Version { get; set; } } }
198
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace TestVectors { public static class Utils { public static string GetEnvironmentVariableOrError(string key) { string nullableResult = Environment.GetEnvironmentVariable(key); if (nullableResult == null) { throw new ArgumentException($"Environment Variable {key} must be set"); } return nullableResult; } public static T LoadObjectFromPath<T>(string path) { if (!File.Exists(path)) { throw new ArgumentException($"File not found: {path}"); } string contents = File.ReadAllText(path); // As a safe-guard against not fully implementing the test vector spec, // explicitly fail if the file contains any keys we were not expecting JsonSerializerSettings settings = new JsonSerializerSettings(); settings.MissingMemberHandling = MissingMemberHandling.Error; return JsonConvert.DeserializeObject<T>(contents, settings); } /// <summary> /// Serializes the given object as JSON and writes it to the given path. /// Throws if the file already exists. /// <para> /// Note that NO exception will be thrown if the object has a null value on a required property. /// </para> /// </summary> public static void WriteObjectToPath<T>(T obj, string path) { var serializer = new JsonSerializer { Formatting = Formatting.Indented, // WARNING: We set this option in order to omit null optional values. // But it "overrides" the `JsonRequired` behavior on serialization - // if the object has a null required value, // the serializer will just ignore it without throwing an exception. NullValueHandling = NullValueHandling.Ignore, }; // Do this first in order to avoid serializing if opening the file fails anyway using (var fs = new FileStream(path, FileMode.CreateNew)) { using (var stringWriter = new StringWriter()) { serializer.Serialize(stringWriter, obj); var bytes = Encoding.UTF8.GetBytes(stringWriter.ToString()); fs.Write(bytes, 0, bytes.Length); } } } public static string ManifestUriToPath(string uri, string manifestPath) { // Assumes files referenced in manifests starts with 'file://' if (!string.Equals(uri.Substring(0, 7), "file://")) { throw new ArgumentException($"Malformed filepath in manifest (needs to start with 'file://'): {uri}"); } DirectoryInfo parentDir = Directory.GetParent(manifestPath); if (parentDir == null) { throw new ArgumentException($"Couldn't find parent directory of {manifestPath}"); } return Path.Combine(parentDir.ToString(), uri.Substring(7)); } /// <summary> /// Writes the data of each name-data pair into a new, correspondingly-named file. /// Throws if any file already exists. /// </summary> /// <param name="dir">the directory in which to create new files</param> /// <param name="namedData">the collection of name-data pairs</param> public static void WriteNamedDataMap(DirectoryInfo dir, Dictionary<string, MemoryStream> namedData) { foreach (var nameDataPair in namedData) { WriteBinaryFile(dir, nameDataPair.Key, nameDataPair.Value); } } /// <summary> /// Writes the given data into a new file. /// Throws if the file already exists. /// </summary> /// <param name="dir">the directory in which to create the new file</param> /// <param name="name">the name of the file</param> /// <param name="data">the data to be written</param> public static void WriteBinaryFile(DirectoryInfo dir, string name, MemoryStream data) { var path = dir.FullName + Path.DirectorySeparatorChar + name; using (var fs = new FileStream(path, FileMode.CreateNew)) { using (var writer = new BinaryWriter(fs)) { writer.Write(data.ToArray()); } } } } }
118
aws-encryption-sdk-dafny
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; namespace TestVectors.Runner { public abstract class TestVectorData : IEnumerable<object[]> { protected readonly Dictionary<string, DecryptVector> VectorMap; protected readonly Dictionary<string, Key> KeyMap; protected readonly string VectorRoot; protected TestVectorData() { this.VectorRoot = Utils.GetEnvironmentVariableOrError("DAFNY_AWS_ESDK_TEST_VECTOR_MANIFEST_PATH"); DecryptManifest manifest = Utils.LoadObjectFromPath<DecryptManifest>(VectorRoot); this.VectorMap = manifest.VectorMap; string keysPath = Utils.ManifestUriToPath(manifest.KeysUri, VectorRoot); this.KeyMap = Utils.LoadObjectFromPath<KeyManifest>(keysPath).Keys; } protected static bool VectorContainsMasterKeyOfType(DecryptVector vector, string typeOfKey) { return vector.MasterKeys.Any(masterKey => masterKey.Type == typeOfKey); } public abstract IEnumerator<object[]> GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // Simplistic method for narrowing down which vectors to target. Add any permanent skips // here (e.g. for unsupported features) or temporarily update if you want to // test certain vectors protected static bool TargetVector(KeyValuePair<string, DecryptVector> entry) { if (entry.Value.DecryptionMethod != null && entry.Value.DecryptionMethod.Equals("streaming-unsigned-only")) { // These vectors specifically target streaming APIs. Since we do not // yet support streaming, we cannot test against these. return false; } return true; } } public class DecryptTestVectors : TestVectorData { public override IEnumerator<object[]> GetEnumerator() { long count = 0; foreach(var vectorEntry in VectorMap) { if (!TargetVector(vectorEntry)) { continue; } DecryptVector vector = vectorEntry.Value; byte[] plaintext = null; if (vector.Result.Output != null) { string plaintextPath = Utils.ManifestUriToPath(vector.Result.Output.Plaintext, VectorRoot); if (!File.Exists(plaintextPath)) { throw new ArgumentException($"Could not find plaintext file at path: {plaintextPath}"); } plaintext = File.ReadAllBytes(plaintextPath); } string errorMessage = null; if (vector.Result.Error != null) { errorMessage = vector.Result.Error.ErrorMessage; } string ciphertextPath = Utils.ManifestUriToPath(vector.Ciphertext, VectorRoot); if (!File.Exists(ciphertextPath)) { throw new ArgumentException($"Could not find ciphertext file at path: {ciphertextPath}"); } byte[] ciphertext = File.ReadAllBytes(Utils.ManifestUriToPath(vector.Ciphertext, VectorRoot)); MemoryStream ciphertextStream = new MemoryStream(ciphertext); yield return new object[] { vectorEntry.Key, vector, KeyMap, plaintext, errorMessage, ciphertextStream }; count++; } // If nothing gets `yield return`-ed, xUnit gives an unclear error message. This error is better. if (count == 0) { throw new Exception("No targeted vectors found"); } } } public class TestVectorDecryptTests { [SkippableTheory] [ClassData (typeof(DecryptTestVectors))] public void CanDecryptTestVector( string vectorId, DecryptVector vector, Dictionary<string, Key> keyMap, byte[] expectedPlaintext, string expectedError, MemoryStream ciphertextStream ) { if (expectedPlaintext != null && expectedError != null) { throw new ArgumentException( $"Test vector {vectorId} has both plaintext and error in its expected result, this is not possible" ); } try { AwsEncryptionSdkConfig config = new AwsEncryptionSdkConfig { CommitmentPolicy = CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT }; IAwsEncryptionSdk encryptionSdk = AwsEncryptionSdkFactory.CreateAwsEncryptionSdk(config); ICryptographicMaterialsManager cmm = MaterialProviderFactory.CreateDecryptCmm(vector, keyMap); DecryptInput decryptInput = new DecryptInput { Ciphertext = ciphertextStream, MaterialsManager = cmm, }; AWS.EncryptionSDK.DecryptOutput decryptOutput = encryptionSdk.Decrypt(decryptInput); if (expectedError != null) { throw new Exception( $"Test vector {vectorId} succeeded when it shouldn't have" ); } byte[] result = decryptOutput.Plaintext.ToArray(); Assert.Equal(expectedPlaintext, result); } catch (Exception e) when ( e is AwsEncryptionSdkException || e is AwsCryptographicMaterialProvidersException ) { if (expectedPlaintext != null) { // Test was not expected to fail throw; } } } } }
160
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; #if NETCOREAPP3_1_OR_GREATER using System.Runtime.InteropServices; #endif namespace Amazon.Common.DotNetCli.Tools { public abstract class AbstractCLIWrapper { protected string _workingDirectory; protected IToolLogger _logger; public AbstractCLIWrapper(IToolLogger logger, string workingDirectory) { this._logger = logger; this._workingDirectory = workingDirectory; } protected int ExecuteCommand(ProcessStartInfo startInfo, string loggerLabel) { var handler = (DataReceivedEventHandler)((o, e) => { if (string.IsNullOrEmpty(e.Data)) return; _logger?.WriteLine($"... {loggerLabel}: " + e.Data); }); int exitCode; using (var proc = new Process()) { proc.StartInfo = startInfo; proc.Start(); if(startInfo.RedirectStandardOutput) { proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; } proc.WaitForExit(); exitCode = proc.ExitCode; } return exitCode; } /// <summary> /// A collection of known paths for common utilities that are usually not found in the path /// </summary> static readonly IDictionary<string, string> KNOWN_LOCATIONS = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { {"dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe" }, {"chmod", @"/bin/chmod" }, {"zip", @"/usr/bin/zip" }, {"docker.exe", @"C:\Program Files\Docker\Docker\Resources\bin\docker.exe" } }; /// <summary> /// Search the path environment variable for the command given. /// </summary> /// <param name="command">The command to search for in the path</param> /// <returns>The full path to the command if found otherwise it will return null</returns> public static string FindExecutableInPath(string command) { if (File.Exists(command)) return Path.GetFullPath(command); #if NETCOREAPP3_1_OR_GREATER if (string.Equals(command, "dotnet.exe")) { if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { command = "dotnet"; } var mainModule = Process.GetCurrentProcess().MainModule; if (!string.IsNullOrEmpty(mainModule?.FileName) && Path.GetFileName(mainModule.FileName).Equals(command, StringComparison.OrdinalIgnoreCase)) { return mainModule.FileName; } } #endif Func<string, string> quoteRemover = x => { if (x.StartsWith("\"")) x = x.Substring(1); if (x.EndsWith("\"")) x = x.Substring(0, x.Length - 1); return x; }; var envPath = Environment.GetEnvironmentVariable("PATH"); foreach (var path in envPath.Split(Path.PathSeparator)) { try { var fullPath = Path.Combine(quoteRemover(path), command); if (File.Exists(fullPath)) return fullPath; } catch (Exception) { // Catch exceptions and continue if there are invalid characters in the user's path. } } if (KNOWN_LOCATIONS.ContainsKey(command) && File.Exists(KNOWN_LOCATIONS[command])) return KNOWN_LOCATIONS[command]; return null; } } }
127
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using Amazon.Runtime; namespace Amazon.Common.DotNetCli.Tools { /// <summary> /// Handle the callback from AWSCredentials when an MFA token code is required. /// </summary> internal class AssumeRoleMfaTokenCodeCallback { private AssumeRoleAWSCredentialsOptions Options { get; set; } internal AssumeRoleMfaTokenCodeCallback(AssumeRoleAWSCredentialsOptions options) { this.Options = options; } internal string Execute() { Console.Write($"Enter MFA code for {this.Options.MfaSerialNumber}: "); var code = Utilities.ReadSecretFromConsole(); Console.WriteLine(); return code; } } }
30
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Amazon.Common.DotNetCli.Tools { public static class Constants { public const string DEFAULT_DOCKERFILE = "Dockerfile"; public const int MAX_ECR_REPOSITORY_NAME_LENGTH = 256; public static readonly string CWE_ASSUME_ROLE_POLICY = @" { ""Version"": ""2012-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""events.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"" } ] } ".Trim(); public static readonly string ECS_ASSUME_ROLE_POLICY = @" { ""Version"": ""2012-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""ecs.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"" } ] } ".Trim(); public static readonly string EC2_ASSUME_ROLE_POLICY = @" { ""Version"": ""2008-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""ec2.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"" } ] } ".Trim(); public static readonly string ELASTICBEANSTALK_ASSUME_ROLE_POLICY = @" { ""Version"": ""2008-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""elasticbeanstalk.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"", ""Condition"": { ""StringEquals"": { ""sts:ExternalId"": ""elasticbeanstalk"" } } } ] } ".Trim(); public static readonly string ECS_TASKS_ASSUME_ROLE_POLICY = @" { ""Version"": ""2008-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""ecs-tasks.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"" } ] } ".Trim(); public static readonly string LAMBDA_PRINCIPAL = "lambda.amazonaws.com"; public static readonly string LAMBDA_ASSUME_ROLE_POLICY = @" { ""Version"": ""2012-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""lambda.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"" } ] } ".Trim(); public static readonly Dictionary<string, string> COMMON_KNOWN_MANAGED_POLICY_DESCRIPTIONS = new Dictionary<string, string> { {"PowerUserAccess","Provides full access to AWS services and resources, but does not allow management of users and groups."}, {"AmazonS3FullAccess","Provides full access to all buckets via the AWS Management Console."}, {"AmazonDynamoDBFullAccess","Provides full access to Amazon DynamoDB via the AWS Management Console."}, {"CloudWatchLogsFullAccess","Provides full access to CloudWatch Logs"} }; } }
137
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.IO; using System.Text; using ThirdParty.Json.LitJson; namespace Amazon.Common.DotNetCli.Tools { public abstract class DefaultConfigFile { JsonData _rootData; public DefaultConfigFile() : this(new JsonData(), string.Empty) { } public DefaultConfigFile(string sourceFile) : this(new JsonData(), sourceFile) { } public DefaultConfigFile(JsonData data, string sourceFile) { this._rootData = data ?? new JsonData(); this.SourceFile = sourceFile; } /// <summary> /// The file the default values were read from. /// </summary> public string SourceFile { get; private set; } public abstract string DefaultConfigFileName { get; } public void LoadDefaults(string projectLocation, string configFile) { string path = Path.Combine(projectLocation, configFile); this.SourceFile = path; if (!File.Exists(path)) return; using (var reader = new StreamReader(File.OpenRead(path))) { try { this._rootData = JsonMapper.ToObject(reader) as JsonData; this.SourceFile = path; } catch (Exception e) { throw new ToolsException($"Error parsing default config {path}: {e.Message}", ToolsException.CommonErrorCode.DefaultsParseFail, e); } } } /// <summary> /// Gets the default value for the CommandOption with the CommandOption's switch string. /// </summary> /// <param name="fullSwitchName"></param> /// <returns></returns> public object this[string fullSwitchName] { get { if (fullSwitchName.StartsWith("--")) fullSwitchName = fullSwitchName.Substring(2); if (this._rootData[fullSwitchName] == null) return null; if (this._rootData[fullSwitchName].IsString) return this._rootData[fullSwitchName].ToString(); if (this._rootData[fullSwitchName].IsInt) return (int)this._rootData[fullSwitchName]; if (this._rootData[fullSwitchName].IsBoolean) return (bool)this._rootData[fullSwitchName]; if (this._rootData[fullSwitchName].IsArray) { var items = new string[this._rootData[fullSwitchName].Count]; for (int i = 0; i < items.Length; i++) { items[i] = this._rootData[fullSwitchName][i].ToString(); } return items; } if (this._rootData[fullSwitchName].IsObject) { var obj = new Dictionary<string, string>(); foreach (var key in this._rootData[fullSwitchName].PropertyNames) { obj[key] = this._rootData[key]?.ToString(); } return obj; } return null; } } protected JsonData GetValue(CommandOption option) { var key = option.Switch.Substring(2); return this._rootData[key]; } /// <summary> /// Gets the default if it exists as a string. This is used for display purpose. /// </summary> /// <param name="option"></param> /// <returns></returns> public string GetValueAsString(CommandOption option) { var key = option.Switch.Substring(2); var data = this._rootData[key]; if (data == null) return null; if (data.IsString) return data.ToString(); else if (data.IsBoolean) return ((bool)data).ToString(); else if (data.IsInt) return ((int)data).ToString(); return null; } public static string FormatCommaDelimitedList(string[] values) { return values == null ? null : string.Join(",", values); } public static string FormatKeyValue(IDictionary<string, string> values) { if (values == null) return null; StringBuilder sb = new StringBuilder(); foreach (var kvp in values) { if (sb.Length > 0) sb.Append(";"); sb.Append($"\"{kvp.Key}\"=\"{kvp.Value}\""); } return sb.ToString(); } public string GetRawString(string key) { var data = this._rootData[key]; if (data == null || !data.IsString) return null; return data.ToString(); } } }
170
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Amazon.Common.DotNetCli.Tools { public class DockerCLIWrapper : AbstractCLIWrapper { public static readonly string WorkingDirectoryMountLocation = "/tmp/source/"; string _dockerCLI; public DockerCLIWrapper(IToolLogger logger, string workingDirectory) : base(logger, workingDirectory) { this._dockerCLI = FindExecutableInPath("docker.exe"); if (this._dockerCLI == null) this._dockerCLI = FindExecutableInPath("docker"); if (string.IsNullOrEmpty(this._dockerCLI)) throw new Exception("Failed to locate docker CLI executable. Make sure the docker CLI is installed in the environment PATH."); } public int Build(string workingDirectory, string dockerFile, string imageTag, string additionalBuildOptions, bool arm64Build = false) { _logger?.WriteLine($"... invoking 'docker build', working folder '{workingDirectory}, docker file {dockerFile}, image name {imageTag}'"); var arguments = new StringBuilder(); #if NETCOREAPP3_1_OR_GREATER var runningOnLinuxArm64 = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && RuntimeInformation.ProcessArchitecture == Architecture.Arm64; #else var runningOnLinuxArm64 = false; #endif if (arm64Build && !runningOnLinuxArm64) { _logger?.WriteLine("The docker CLI \"buildx\" command is used to build ARM64 images. This requires version 20 or later of the docker CLI."); arguments.Append($"buildx build --platform linux/arm64 "); } else { arguments.Append($"build "); } arguments.Append($" -f \"{dockerFile}\" -t {imageTag}"); if(!string.IsNullOrEmpty(additionalBuildOptions)) { arguments.Append($" {additionalBuildOptions}"); } arguments.Append(" ."); _logger?.WriteLine($"... docker {arguments.ToString()}"); var psi = new ProcessStartInfo { FileName = this._dockerCLI, Arguments = arguments.ToString(), WorkingDirectory = workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; return base.ExecuteCommand(psi, "docker build"); } public string GetImageId(string imageTag) { var psi = new ProcessStartInfo { FileName = this._dockerCLI, // Make sure to have the space after the "{{.ID}}" and the closing quote. Arguments = "images --format \"{{.ID}}\" " + imageTag, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; var process = Process.Start(psi); var imageId = process.StandardOutput.ReadToEnd()?.Trim(); // To prevent a unlikely hang give 10 seconds as max for waiting for the docker CLI to execute and return back the image id. process.WaitForExit(10000); if (imageId.Length != 12) return null; return imageId; } public int Login(string username, string password, string proxy) { _logger?.WriteLine($"... invoking 'docker login'"); var arguments = $"login --username {username} --password {password} {proxy}"; var psi = new ProcessStartInfo { FileName = this._dockerCLI, Arguments = arguments.ToString(), WorkingDirectory = this._workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; return base.ExecuteCommand(psi, "docker login"); } public int Tag(string sourceTagName, string targetTagName) { _logger?.WriteLine($"... invoking 'docker tag'"); var arguments = $"tag {sourceTagName} {targetTagName}"; var psi = new ProcessStartInfo { FileName = this._dockerCLI, Arguments = arguments.ToString(), WorkingDirectory = this._workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; return base.ExecuteCommand(psi, "docker tag"); } public int Push(string targetTagName) { _logger?.WriteLine($"... invoking 'docker push'"); var arguments = $"push {targetTagName}"; var psi = new ProcessStartInfo { FileName = this._dockerCLI, Arguments = arguments.ToString(), WorkingDirectory = this._workingDirectory }; return base.ExecuteCommand(psi, "docker push"); } /// <summary> /// Executes the Docker run command on the given image locally /// </summary> /// <param name="imageId">Tells Docker which pre-built image to run. Can be local or remote.</param> /// <param name="containerName">A custom name to give the generated container. This is useful so the caller of this method knows what container to look for after.</param> /// <param name="commandToRun">Tells Docker what commands to invoke on the container once it is running. Can be left blank.</param> /// <returns></returns> public int Run(string imageId, string containerName, string commandToRun = "") { var argumentList = new List<string>() { "run", "--name", containerName, // Automatically remove the container once it's done running "--rm", // This allows the container access to the working directory in a virtual mapped path located at /tmp/source // That means that when the container is finished running, anything it leaves in /tmp/source (e.g. the binaries), // will just exist in the working directory "--volume", $"\"{this._workingDirectory}\":{WorkingDirectoryMountLocation}", "-i" }; // For Linux or MacOS, running a .NET image as non-root requires some special // handling. We have to pass the user's UID and GID, but we also have to specify // the location of where .NET and Nuget put their files, because by default, they // go to the /.dotnet and /.local, which a non-root user can't write to in a container if (PosixUserHelper.IsRunningInPosix) { var posixUser = PosixUserHelper.GetEffectiveUser(_logger); if (posixUser != null && (posixUser?.UserID > 0 || posixUser.Value.GroupID > 0)) { argumentList.AddRange(new [] { // Set Docker user and group IDs "-u", $"{posixUser.Value.UserID}:{posixUser.Value.GroupID}", // Set .NET CLI home directory "-e", "DOTNET_CLI_HOME=/tmp/dotnet", // Set NuGet data home directory to non-root directory "-e", "XDG_DATA_HOME=/tmp/xdg" }); } } argumentList.Add(imageId); var arguments = string.Join(" ", argumentList); if (!string.IsNullOrEmpty(commandToRun)) { arguments += $" {commandToRun}"; } var psi = new ProcessStartInfo { FileName = this._dockerCLI, Arguments = arguments, WorkingDirectory = this._workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; _logger?.WriteLine($"... invoking 'docker {arguments}' from directory {this._workingDirectory}"); return base.ExecuteCommand(psi, "docker run"); } } }
234
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; namespace Amazon.Common.DotNetCli.Tools { /// <summary> /// Wrapper around the dotnet cli used to execute the publish command. /// </summary> public class DotNetCLIWrapper : AbstractCLIWrapper { public DotNetCLIWrapper(IToolLogger logger, string workingDirectory) : base(logger, workingDirectory) { } /// <summary> /// Generates deployment manifest for staged content /// </summary> /// <param name="projectLocation"></param> /// <param name="outputLocation"></param> /// <param name="targetFramework"></param> /// <param name="configuration"></param> public int Publish(string projectLocation, string outputLocation, string targetFramework, string configuration, string additionalPublishOptions) { if (Directory.Exists(outputLocation)) { try { Directory.Delete(outputLocation, true); _logger?.WriteLine("Deleted previous publish folder"); } catch (Exception e) { _logger?.WriteLine($"Warning unable to delete previous publish folder: {e.Message}"); } } _logger?.WriteLine($"... invoking 'dotnet publish'"); var dotnetCLI = FindExecutableInPath("dotnet.exe"); if (dotnetCLI == null) dotnetCLI = FindExecutableInPath("dotnet"); if (string.IsNullOrEmpty(dotnetCLI)) throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH."); StringBuilder arguments = new StringBuilder("publish"); if (!string.IsNullOrEmpty(projectLocation)) { arguments.Append($" \"{Utilities.DetermineProjectLocation(this._workingDirectory, projectLocation)}\""); } if (!string.IsNullOrEmpty(outputLocation)) { arguments.Append($" --output \"{outputLocation}\""); } if (!string.IsNullOrEmpty(configuration)) { arguments.Append($" --configuration \"{configuration}\""); } if (!string.IsNullOrEmpty(targetFramework)) { arguments.Append($" --framework \"{targetFramework}\""); } if (!string.IsNullOrEmpty(additionalPublishOptions)) { arguments.Append($" {additionalPublishOptions}"); } var psi = new ProcessStartInfo { FileName = dotnetCLI, Arguments = arguments.ToString(), WorkingDirectory = this._workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; this._logger?.WriteLine($"Executing: dotnet {psi.Arguments}"); int exitCode = base.ExecuteCommand(psi, "dotnet publish"); if (exitCode != 0) return exitCode; var chmodPath = FindExecutableInPath("chmod"); if (!string.IsNullOrEmpty(chmodPath) && File.Exists(chmodPath)) { // as we are not invoking through a shell, which would handle // wildcard expansion for us, we need to invoke per-file var dllFiles = Directory.GetFiles(outputLocation, "*.dll", SearchOption.TopDirectoryOnly); foreach (var dllFile in dllFiles) { var dllFilename = Path.GetFileName(dllFile); var psiChmod = new ProcessStartInfo { FileName = chmodPath, Arguments = "+r \"" + dllFilename + "\"", WorkingDirectory = outputLocation, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; if(base.ExecuteCommand(psiChmod, "dotnet publish") == 0) { this._logger?.WriteLine($"Changed permissions on published dll (chmod +r {dllFilename})."); } } } return 0; } public static Version GetSdkVersion() { var dotnetCLI = FindExecutableInPath("dotnet.exe"); if (dotnetCLI == null) dotnetCLI = FindExecutableInPath("dotnet"); if (string.IsNullOrEmpty(dotnetCLI)) throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH."); var results = Utilities.ExecuteShellCommand(null, dotnetCLI, "--list-sdks"); if(results.ExitCode != 0) throw new Exception("Command \"dotnet --list-sdks\" failed, captured output: \n" + results.Stdout); var maxSdkVersion = ParseListSdkOutput(results.Stdout); if (maxSdkVersion == null) { throw new Exception("Failed to parse latest SDK version from captured output:\n" + results.Stdout); } return maxSdkVersion; } public static Version ParseListSdkOutput(string listSdkOutput) { var outputLines = listSdkOutput.Split('\n'); for (int i = outputLines.Length - 1; i >= 0; i--) { var line = outputLines[i].Trim(); if (string.IsNullOrEmpty(line)) continue; var tokens = line.Split(' '); // There should be at least 2 tokens, the version and the path to the SDK. There might be more than 2 tokens if the path to the SDK contained spaces. if (tokens.Length < 2) continue; if(Version.TryParse(tokens[0], out var version)) { return version; } } return null; } } }
169
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.IO; using System.Collections.Generic; using System.Text; using ThirdParty.Json.LitJson; namespace Amazon.Common.DotNetCli.Tools { public static class ExtensionMethods { public static void SetIfNotNull(this JsonData data, string key, string value) { if (value == null) return; data[key] = value; } public static void SetFilePathIfNotNull(this JsonData data, string key, string filepath, string rootPath) { if (string.IsNullOrEmpty(filepath)) return; if(Path.IsPathRooted(filepath) && !string.IsNullOrEmpty(rootPath)) { var fileName = Path.GetFileName(filepath); var parentDirectory = Directory.GetParent(filepath).FullName; filepath = Path.Combine(Utilities.RelativePathTo(rootPath, parentDirectory), fileName); } data[key] = filepath; } public static void SetIfNotNull(this JsonData data, string key, bool? value) { if (!value.HasValue) return; data[key] = value.Value; } public static void SetIfNotNull(this JsonData data, string key, int? value) { if (!value.HasValue) return; data[key] = value.Value; } } }
49
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace Amazon.Common.DotNetCli.Tools { /// <summary> /// The logger is used to write all status messages. When executing CLI commands they are written to the console. /// When the Visual Studio Toolkit calls the commands it passes its logger to redirect the output /// to the VS windows. /// </summary> public interface IToolLogger { void WriteLine(string message); void WriteLine(string message, params object[] args); } /// <summary> /// Default console implementation /// </summary> public class ConsoleToolLogger : IToolLogger { public void WriteLine(string message) { Console.WriteLine(message); #if DEBUG Debugger.Log(0, "console", message + "\n"); #endif } public void WriteLine(string message, params object[] args) { var str = string.Format(message, args); Console.WriteLine(str); #if DEBUG Debugger.Log(0, "console", str + "\n"); #endif } } }
44
aws-extensions-for-dotnet-cli
aws
C#
using System.Diagnostics; #if NETCOREAPP3_1_OR_GREATER using System.Runtime.InteropServices; #endif namespace Amazon.Common.DotNetCli.Tools { public struct PosixUserInfo { public int UserID; public int GroupID; public bool UserIDSet; public bool GroupIDSet; } /// <summary> /// Helper class to retrieve current Linux/Mac user and group information /// </summary> public static class PosixUserHelper { /// <summary> /// Return True if running under Unix or Mac, requires running on .NET Core 3.1 or greater /// </summary> public static readonly bool IsRunningInPosix = #if NETCOREAPP3_1_OR_GREATER RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); #else false; #endif /// <summary> /// Return the effective user's UID and GID under Linux and Mac by calling the "id" command. /// This will fault if running on Windows (by design), check IsRunningInPosix before calling this method. /// </summary> /// <returns>PosixUserInfo struct with UID and GID, or NULL if not detected</returns> public static PosixUserInfo? GetEffectiveUser(IToolLogger logger, IProcessFactory processFactory = null) { if (processFactory == null) processFactory = ProcessFactory.Default; var values = new int?[] {null, null}; // Call `id` twice, once to get the user, // once to get the group for(var loop = 0; loop < values.Length; loop++) { var arg = loop == 0 ? "-u" : "-g"; var results = processFactory.RunProcess(new ProcessStartInfo { FileName = "id", Arguments = arg }); if (!results.Executed) { logger?.WriteLine($"Error executing \"id {arg}\" {results.Error}"); } else if (results.ExitCode != 0) { logger?.WriteLine($"Error executing \"id {arg}\" - exit code {results.ExitCode} {results.Error}"); } else if (! int.TryParse(results.Output, out var value)) { logger?.WriteLine($"Error parsing output \"id {arg}\" (\"{results.Output}\")"); } else { values[loop] = value; } } if (! values[0].HasValue) { logger?.WriteLine("Warning: Unable to get effective user from \"id -u\""); return null; } if (! values[1].HasValue) { logger?.WriteLine("Warning: Unable to get effective group from \"id -g\""); return null; } return new PosixUserInfo { UserID = values[0].Value, GroupID = values[1].Value }; } } }
95
aws-extensions-for-dotnet-cli
aws
C#
using System.Diagnostics; using System.Text; namespace Amazon.Common.DotNetCli.Tools { /// <summary> /// This class represents an instance of a process being executed, set up to capture /// STDOUT and STDERR and expose as properties. Once it's created, you can execute /// Run multiple times. /// </summary> public class ProcessInstance { /// <summary> /// Results of process execution /// </summary> public struct ProcessResults { /// <summary> /// True if process executed within timout /// </summary> public bool Executed { get; set; } /// <summary> /// Non-zero upon success /// </summary> public int? ExitCode { get; set; } /// <summary> /// Output captured from STDOUT /// </summary> public string Output { get; set; } /// <summary> /// Output captured from STDERR or other error information /// </summary> public string Error { get; set; } } private readonly ProcessStartInfo _info; /// <summary> /// Set up ProcessStartInfo, forcing values required to capture STDOUT and STDERR /// </summary> /// <param name="info"></param> public ProcessInstance(ProcessStartInfo info) { _info = info; _info.RedirectStandardOutput = true; _info.RedirectStandardError = true; _info.UseShellExecute = false; } /// <summary> /// Run the process /// </summary> /// <param name="timeoutInMilliseconds"></param> /// <returns>Process instance execution results</returns> public ProcessResults Run(int timeoutInMilliseconds = 60000) { var stdout = new StringBuilder(); var stderr = new StringBuilder(); using (var proc = new Process()) { proc.StartInfo = _info; proc.EnableRaisingEvents = true; proc.OutputDataReceived += (_, e) => { if (!string.IsNullOrEmpty(e.Data)) stdout.Append(e.Data); }; proc.ErrorDataReceived += (_, e) => { if (!string.IsNullOrEmpty(e.Data)) stderr.Append(e.Data); }; bool executed; int? exitCode; string output; string error; if (proc.Start()) { proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); executed = proc.WaitForExit(timeoutInMilliseconds); if (executed) proc.WaitForExit(); // this ensures STDOUT is completely captured else stderr.Append($"{(stderr.Length > 0 ? "\n" : "")}Timeout waiting for process"); exitCode = proc.ExitCode; output = stdout.ToString(); error = stderr.ToString(); } else { executed = false; exitCode = null; output = ""; error = "Unable to launch process"; } return new ProcessResults() { Executed = executed, ExitCode = exitCode, Output = output, Error = error }; } } } /// <summary> /// This class is a factory that generates executed Processes /// </summary> public class ProcessFactory: IProcessFactory { public static readonly IProcessFactory Default = new ProcessFactory(); /// <summary> /// Launch the process described by "info" and return the execution results. /// </summary> /// <param name="info"></param> /// <param name="timeout"></param> /// <returns></returns> public ProcessInstance.ProcessResults RunProcess(ProcessStartInfo info, int timeout = 60000) { return new ProcessInstance(info).Run(timeout); } } public interface IProcessFactory { ProcessInstance.ProcessResults RunProcess(ProcessStartInfo info, int timeout = 60000); } }
133
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Auth.AccessControlPolicy; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; namespace Amazon.Common.DotNetCli.Tools { /// <summary> /// Utility class for interacting with console user to select or create an IAM role /// </summary> public static class RoleHelper { public const string EC2_ASSUME_ROLE_PRINCIPAL = "ec2.amazonaws.com"; public const string ECS_TASK_ASSUME_ROLE_PRINCIPAL = "ecs-tasks.amazonaws.com"; public const int DEFAULT_ITEM_MAX = 20; private const int MAX_LINE_LENGTH_FOR_MANAGED_ROLE = 95; public static readonly TimeSpan SLEEP_TIME_FOR_ROLE_PROPOGATION = TimeSpan.FromSeconds(15); public static string GenerateUniqueIAMRoleName(IAmazonIdentityManagementService iamClient, string baseName) { var existingRoleNames = new HashSet<string>(); var response = new ListRolesResponse(); do { var roles = iamClient.ListRolesAsync(new ListRolesRequest { Marker = response.Marker }).Result.Roles; roles.ForEach(x => existingRoleNames.Add(x.RoleName)); } while (response.IsTruncated); if (!existingRoleNames.Contains(baseName)) return baseName; for (int i = 1; true; i++) { var name = baseName + "-" + i; if (!existingRoleNames.Contains(name)) return name; } } public static string ExpandInstanceProfile(IAmazonIdentityManagementService iamClient, string instanceProfile) { if (instanceProfile.StartsWith("arn:aws")) return instanceProfile; // Wrapping this in a task to avoid dealing with aggregate exception. var task = Task.Run<string>(async () => { try { var request = new GetInstanceProfileRequest { InstanceProfileName = instanceProfile }; var response = await iamClient.GetInstanceProfileAsync(request).ConfigureAwait(false); return response.InstanceProfile.Arn; } catch (NoSuchEntityException) { return null; } }); if (task.Result == null) { throw new ToolsException($"Instance Profile \"{instanceProfile}\" can not be found.", ToolsException.CommonErrorCode.RoleNotFound); } return task.Result; } public static string ExpandRoleName(IAmazonIdentityManagementService iamClient, string roleName) { if (roleName.StartsWith("arn:aws")) return roleName; // Wrapping this in a task to avoid dealing with aggregate exception. var task = Task.Run<string>(async () => { try { var request = new GetRoleRequest { RoleName = roleName }; var response = await iamClient.GetRoleAsync(request).ConfigureAwait(false); return response.Role.Arn; } catch (NoSuchEntityException) { return null; } }); if(task.Result == null) { throw new ToolsException($"Role \"{roleName}\" can not be found.", ToolsException.CommonErrorCode.RoleNotFound); } return task.Result; } public static string ExpandManagedPolicyName(IAmazonIdentityManagementService iamClient, string managedPolicy) { if (managedPolicy.StartsWith("arn:aws")) return managedPolicy; // Wrapping this in a task to avoid dealing with aggregate exception. var task = Task.Run<string>(async () => { var listResponse = new ListPoliciesResponse(); do { var listRequest = new ListPoliciesRequest { Marker = listResponse.Marker, Scope = PolicyScopeType.All }; listResponse = await iamClient.ListPoliciesAsync(listRequest).ConfigureAwait(false); var policy = listResponse.Policies.FirstOrDefault(x => string.Equals(managedPolicy, x.PolicyName)); if (policy != null) return policy.Arn; } while (listResponse.IsTruncated); return null; }); if (task.Result == null) { throw new ToolsException($"Policy \"{managedPolicy}\" can not be found.", ToolsException.CommonErrorCode.PolicyNotFound); } return task.Result; } public static string CreateRole(IAmazonIdentityManagementService iamClient, string roleName, string assumeRolePolicy, params string[] managedPolicies) { if (managedPolicies != null && managedPolicies.Length > 0) { for(int i = 0; i < managedPolicies.Length; i++) { if (managedPolicies[i] != null) { managedPolicies[i] = ExpandManagedPolicyName(iamClient, managedPolicies[i]); } } } string roleArn; try { CreateRoleRequest request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = assumeRolePolicy }; var response = iamClient.CreateRoleAsync(request).Result; roleArn = response.Role.Arn; } catch (Exception e) { throw new ToolsException($"Error creating IAM Role: {e.Message}", ToolsException.CommonErrorCode.IAMCreateRole, e); } if (managedPolicies != null && managedPolicies.Length > 0) { try { foreach (var managedPolicy in managedPolicies) { if (managedPolicy != null) { var request = new AttachRolePolicyRequest { RoleName = roleName, PolicyArn = managedPolicy }; iamClient.AttachRolePolicyAsync(request).Wait(); } } } catch (Exception e) { throw new ToolsException($"Error assigning managed IAM Policy: {e.Message}", ToolsException.CommonErrorCode.IAMAttachRole, e); } } bool found = false; do { // There is no way check if the role has propagated yet so to // avoid error during deployment creation do a generous sleep. Console.WriteLine("Waiting for new IAM Role to propagate to AWS regions"); long start = DateTime.Now.Ticks; while (TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds < SLEEP_TIME_FOR_ROLE_PROPOGATION.TotalSeconds) { Thread.Sleep(TimeSpan.FromSeconds(1)); Console.Write("."); Console.Out.Flush(); } Console.WriteLine("\t Done"); try { var getResponse = iamClient.GetRoleAsync(new GetRoleRequest { RoleName = roleName }).Result; if (getResponse.Role != null) found = true; } catch (NoSuchEntityException) { } catch (Exception e) { throw new ToolsException("Error confirming new role was created: " + e.Message, ToolsException.CommonErrorCode.IAMGetRole, e); } } while (!found); return roleArn; } public static async Task<IList<ManagedPolicy>> FindManagedPoliciesAsync(IAmazonIdentityManagementService iamClient, PromptRoleInfo promptInfo, int maxPolicies) { ListPoliciesRequest request = new ListPoliciesRequest { Scope = PolicyScopeType.AWS, }; ListPoliciesResponse response = null; IList<ManagedPolicy> policies = new List<ManagedPolicy>(); do { request.Marker = response?.Marker; response = await iamClient.ListPoliciesAsync(request).ConfigureAwait(false); foreach (var policy in response.Policies) { if (policy.IsAttachable && (promptInfo.KnownManagedPolicyDescription.ContainsKey(policy.PolicyName) || (promptInfo.AWSManagedPolicyNamePrefix != null && policy.PolicyName.StartsWith(promptInfo.AWSManagedPolicyNamePrefix))) ) { policies.Add(policy); } if (policies.Count == maxPolicies) return policies; } } while (response.IsTruncated); response = await iamClient.ListPoliciesAsync(new ListPoliciesRequest { Scope = PolicyScopeType.Local }); foreach (var policy in response.Policies) { if (policy.IsAttachable) policies.Add(policy); if (policies.Count == maxPolicies) return policies; } return policies; } public static async Task<IList<Role>> FindExistingRolesAsync(IAmazonIdentityManagementService iamClient, string assumeRolePrincpal, int maxRoles) { List<Role> roles = new List<Role>(); ListRolesRequest request = new ListRolesRequest(); ListRolesResponse response = null; do { if (response != null) request.Marker = response.Marker; response = await iamClient.ListRolesAsync(request).ConfigureAwait(false); foreach (var role in response.Roles) { if (AssumeRoleServicePrincipalSelector(role, assumeRolePrincpal)) { roles.Add(role); if (roles.Count == maxRoles) { break; } } } } while (response.IsTruncated && roles.Count < maxRoles); return roles; } private static IList<Role> FindExistingRoles(IAmazonIdentityManagementService iamClient, string assumeRolePrincpal, int maxRoles) { var task = Task.Run<IList<Role>>(async () => { return await FindExistingRolesAsync(iamClient, assumeRolePrincpal, maxRoles); }); return task.Result; } private static bool AssumeRoleServicePrincipalSelector(Role r, string servicePrincipal) { if (string.IsNullOrEmpty(r.AssumeRolePolicyDocument)) return false; try { var decode = WebUtility.UrlDecode(r.AssumeRolePolicyDocument); var policy = Policy.FromJson(decode); foreach (var statement in policy.Statements) { if (statement.Actions.Contains(new ActionIdentifier("sts:AssumeRole")) && statement.Principals.Contains(new Principal("Service", servicePrincipal))) { return true; } } return r.AssumeRolePolicyDocument.Contains(servicePrincipal); } catch (Exception) { return false; } } public static async Task<IList<InstanceProfile>> FindExistingInstanceProfilesAsync(IAmazonIdentityManagementService iamClient, int maxRoles) { var profiles = new List<InstanceProfile>(); ListInstanceProfilesRequest request = new ListInstanceProfilesRequest(); ListInstanceProfilesResponse response = null; do { if (response != null) request.Marker = response.Marker; response = await iamClient.ListInstanceProfilesAsync(request).ConfigureAwait(false); foreach (var profile in response.InstanceProfiles) { profiles.Add(profile); } } while (response.IsTruncated && profiles.Count < maxRoles); return profiles; } public static string PromptForRole(IAmazonIdentityManagementService iamClient, PromptRoleInfo promptInfo) { var existingRoles = FindExistingRoles(iamClient, promptInfo.AssumeRolePrincipal, DEFAULT_ITEM_MAX); if (existingRoles.Count == 0) { return PromptToCreateRole(iamClient, promptInfo); } var roleArn = SelectFromExisting(iamClient, promptInfo, existingRoles); return roleArn; } private static string SelectFromExisting(IAmazonIdentityManagementService iamClient, PromptRoleInfo promptInfo, IList<Role> existingRoles) { Console.Out.WriteLine("Select IAM Role that to provide AWS credentials to your code:"); for (int i = 0; i < existingRoles.Count; i++) { Console.Out.WriteLine($" {(i + 1).ToString().PadLeft(2)}) {existingRoles[i].RoleName}"); } Console.Out.WriteLine($" {(existingRoles.Count + 1).ToString().PadLeft(2)}) *** Create new IAM Role ***"); Console.Out.Flush(); int chosenIndex = Utilities.WaitForPromptResponseByIndex(1, existingRoles.Count + 1); if (chosenIndex - 1 < existingRoles.Count) { return existingRoles[chosenIndex - 1].Arn; } else { return PromptToCreateRole(iamClient, promptInfo); } } private static string PromptToCreateRole(IAmazonIdentityManagementService iamClient, PromptRoleInfo promptInfo) { Console.Out.WriteLine($"Enter name of the new IAM Role:"); var roleName = Console.ReadLine(); if (string.IsNullOrWhiteSpace(roleName)) return null; roleName = roleName.Trim(); Console.Out.WriteLine("Select IAM Policy to attach to the new role and grant permissions"); var managedPolices = FindManagedPoliciesAsync(iamClient, promptInfo, DEFAULT_ITEM_MAX).Result; for (int i = 0; i < managedPolices.Count; i++) { var line = $" {(i + 1).ToString().PadLeft(2)}) {managedPolices[i].PolicyName}"; var description = AttemptToGetPolicyDescription(managedPolices[i].Arn, promptInfo.KnownManagedPolicyDescription); if (!string.IsNullOrEmpty(description)) { if ((line.Length + description.Length) > MAX_LINE_LENGTH_FOR_MANAGED_ROLE) description = description.Substring(0, MAX_LINE_LENGTH_FOR_MANAGED_ROLE - line.Length) + " ..."; line += $" ({description})"; } Console.Out.WriteLine(line); } Console.Out.WriteLine($" {(managedPolices.Count + 1).ToString().PadLeft(2)}) *** No policy, add permissions later ***"); Console.Out.Flush(); int chosenIndex = Utilities.WaitForPromptResponseByIndex(1, managedPolices.Count + 1); string managedPolicyArn = null; if (chosenIndex < managedPolices.Count) { var selectedPolicy = managedPolices[chosenIndex - 1]; managedPolicyArn = selectedPolicy.Arn; } var roleArn = CreateRole(iamClient, roleName, Utilities.GetAssumeRolePolicy(promptInfo.AssumeRolePrincipal), managedPolicyArn); return roleArn; } /// <summary> /// Because description does not come back in the list policy operation cache known lambda policy descriptions to /// help users understand which role to pick. /// </summary> /// <param name="policyArn"></param> /// <param name="knownManagedPolicyDescription"></param> /// <returns></returns> private static string AttemptToGetPolicyDescription(string policyArn, Dictionary<string, string> knownManagedPolicyDescription) { string content; if (!knownManagedPolicyDescription.TryGetValue(policyArn, out content)) return null; return content; } public class PromptRoleInfo { /// <summary> /// The principal searched for in existing roles when displaying available roles to user to select. /// </summary> public string AssumeRolePrincipal { get; set; } /// <summary> /// If prompting to create a role based on a managed policy display any aws provided /// managed policies that start with this name. /// </summary> public string AWSManagedPolicyNamePrefix { get; set; } /// <summary> /// A list of known AWS managed policies to show along with their description. /// </summary> public Dictionary<string, string> KnownManagedPolicyDescription { get; set; } } } }
484
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Amazon.Common.DotNetCli.Tools { /// <summary> /// Utility class that pulls down configuration files from an S3 bucket that the AWS Toolkit for Visual Studio uses. /// </summary> public class ToolkitConfigFileFetcher { const string HOSTEDFILES_LOCATION = @"https://idetoolkits-hostedfiles.amazonaws.com/"; static ToolkitConfigFileFetcher INSTANCE = new ToolkitConfigFileFetcher(); private ToolkitConfigFileFetcher() { } public static ToolkitConfigFileFetcher Instance { get { return INSTANCE; } } /// <summary> /// Attempt to get the configuration file from the AWS Toolkit for Visual Studio config bucket. /// If there is an error retieving the file like a proxy issue then null is returned. /// </summary> /// <param name="logger"></param> /// <param name="filename"></param> /// <returns></returns> public async Task<string> GetFileContentAsync(IToolLogger logger, string filename) { using (var client = new HttpClient()) { try { var content = await client.GetStringAsync(HOSTEDFILES_LOCATION + filename); return content; } catch(Exception) { return null; } } } } }
50
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Runtime; using System; using System.Collections.Generic; using System.Text; namespace Amazon.Common.DotNetCli.Tools { public class ToolsException : Exception { public enum CommonErrorCode { DefaultsParseFail, CommandLineParseError, ProfileNotFound, ProfileNotCreateable, RegionNotConfigured, InvalidParameterValue, MissingRequiredParameter, MissingConfigFile, PersistConfigError, NoProjectFound, InvalidCredentialConfiguration, DotnetPublishFailed, ShellOutToDotnetPublishFailed, // Return for the specific shell out to dotnet publish DockerBuildFailed, FailedToFindSolutionDirectory, FailedToSetupECRRepository, GetECRAuthTokens, DockerCLILoginFail, DockerTagFail, DockerPushFail, IAMAttachRole, IAMCreateRole, IAMGetRole, RoleNotFound, PolicyNotFound, FailedToFindZipProgram, BucketInDifferentRegionThenClient, S3GetBucketLocation, S3UploadError } public ToolsException(string message, CommonErrorCode code) : this(message, code, null) { } public ToolsException(string message, CommonErrorCode code, Exception e) :this(message, code.ToString(), e) { } protected ToolsException(string message, string errorCode, Exception e) : base(message) { this.Code = errorCode; var ae = e as AmazonServiceException; if (ae != null) { this.ServiceCode = $"{ae.ErrorCode}-{ae.StatusCode}"; } } public string Code { get; } public string ServiceCode { get; } } }
81
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Transfer; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using System.Xml.XPath; using Amazon.Util; using System.Text.RegularExpressions; using System.Collections; using System.Xml; namespace Amazon.Common.DotNetCli.Tools { public static class Utilities { /// <summary> /// Compiled Regex for $(Variable) token searches /// </summary> private readonly static Regex EnvironmentVariableTokens = new Regex(@"[$][(].*?[)]", RegexOptions.Compiled); /// <summary> /// Replaces $(Variable) tokens with environment variables /// </summary> /// <param name="original">original string</param> /// <returns>string with environment variable replacements</returns> public static string ReplaceEnvironmentVariables(string original) { MatchCollection matches = EnvironmentVariableTokens.Matches(original); var modified = original; foreach (Match m in matches) { var withoutBrackets = m.Value.Substring(2, m.Value.Length - 3); var entry = FindEnvironmentVariable(withoutBrackets); if (entry == null) { continue; } var env = (string)entry.Value.Value; modified = modified.Replace(m.Value, env); } return modified; } /// <summary> /// Helper method to find an environment variable if it exists /// </summary> /// <param name="name">environennt variable name</param> /// <returns>DictionaryEntry containing environment variable key value</returns> private static DictionaryEntry? FindEnvironmentVariable(string name) { var allEnvironmentVariables = Environment.GetEnvironmentVariables(); foreach (DictionaryEntry de in allEnvironmentVariables) { if ((string)de.Key == name) { return de; } } return null; } public static string[] SplitByComma(this string str) { return str?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } /// <summary> /// Creates a relative path /// </summary> /// <param name="start"></param> /// <param name="relativeTo"></param> /// <returns></returns> public static string RelativePathTo(string start, string relativeTo) { start = Path.GetFullPath(start).Replace("\\", "/"); relativeTo = Path.GetFullPath(relativeTo).Replace("\\", "/"); string[] startDirs = start.Split('/'); string[] relativeToDirs = relativeTo.Split('/'); int len = startDirs.Length < relativeToDirs.Length ? startDirs.Length : relativeToDirs.Length; int lastCommonRoot = -1; int index; for (index = 0; index < len && string.Equals(startDirs[index], relativeToDirs[index], StringComparison.OrdinalIgnoreCase); index++) { lastCommonRoot = index; } // The 2 paths don't share a common ancestor. So the closest we can give is the absolute path to the target. if (lastCommonRoot == -1) { return relativeTo; } StringBuilder relativePath = new StringBuilder(); for (index = lastCommonRoot + 1; index < startDirs.Length; index++) { if (startDirs[index].Length > 0) relativePath.Append("../"); } for (index = lastCommonRoot + 1; index < relativeToDirs.Length; index++) { relativePath.Append(relativeToDirs[index]); if(index + 1 < relativeToDirs.Length) { relativePath.Append("/"); } } return relativePath.ToString(); } public static string GetSolutionDirectoryFullPath(string workingDirectory, string projectLocation, string givenSolutionDirectory) { // If we were given a path to the solution (relative, or full) use that. if (!string.IsNullOrWhiteSpace(givenSolutionDirectory)) { if (!Path.IsPathRooted(givenSolutionDirectory)) { return Path.Combine(workingDirectory, givenSolutionDirectory).TrimEnd('\\', '/'); } return givenSolutionDirectory.TrimEnd('\\', '/'); } // If we weren't given a solution path, try to find one looking up from the project file. var currentDirectory = projectLocation; while (currentDirectory != null) { if (Directory.EnumerateFiles(currentDirectory).Any(x => x.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))) { return currentDirectory.TrimEnd('\\', '/'); } DirectoryInfo dirInfo = Directory.GetParent(currentDirectory); if ((dirInfo == null) || !dirInfo.Exists) { break; } currentDirectory = dirInfo.FullName; } // Otherwise, we didn't find a solution file, so just default to the project directory. return (Path.IsPathRooted(projectLocation) ? projectLocation : Path.Combine(workingDirectory, projectLocation)).TrimEnd('\\', '/'); } /// <summary> /// Determine where the dotnet publish should put its artifacts at. /// </summary> /// <param name="workingDirectory"></param> /// <param name="projectLocation"></param> /// <param name="configuration"></param> /// <param name="targetFramework"></param> /// <returns></returns> public static string DeterminePublishLocation(string workingDirectory, string projectLocation, string configuration, string targetFramework) { var path = Path.Combine(DetermineProjectLocation(workingDirectory, projectLocation), "bin", configuration, targetFramework, "publish"); return path; } public static string LookupTargetFrameworkFromProjectFile(string projectLocation) { var projectFile = FindProjectFileInDirectory(projectLocation); var xdoc = XDocument.Load(projectFile); var element = xdoc.XPathSelectElement("//PropertyGroup/TargetFramework"); return element?.Value; } public static string LookupOutputTypeFromProjectFile(string projectLocation) { var projectFile = FindProjectFileInDirectory(projectLocation); var xdoc = XDocument.Load(projectFile); var element = xdoc.XPathSelectElement("//PropertyGroup/OutputType"); return element?.Value; } public static bool LookPublishAotFlag(string projectLocation, string msBuildParameters) { if (msBuildParameters != null) { string msBuildParametersTrimmed = string.Concat(msBuildParameters.Where(c => !char.IsWhiteSpace(c))); if (msBuildParametersTrimmed.ToLower().Contains("publishaot=true")) { return true; } else if (msBuildParametersTrimmed.ToLower().Contains("publishaot=false")) { return false; } } // If the property wasn't provided in msBuildParameters, fall back to searching project file var projectFile = FindProjectFileInDirectory(projectLocation); var xdoc = XDocument.Load(projectFile); var element = xdoc.XPathSelectElement("//PropertyGroup/PublishAot"); if (bool.TryParse(element?.Value, out bool result)) { return result; } return false; } public static bool HasExplicitSelfContainedFlag(string projectLocation, string msBuildParameters) { if (msBuildParameters != null && msBuildParameters.IndexOf("--self-contained", StringComparison.InvariantCultureIgnoreCase) != -1) { return true; } // If the property wasn't provided in msBuildParameters, fall back to searching project file var projectFile = FindProjectFileInDirectory(projectLocation); var xdoc = XDocument.Load(projectFile); var element = xdoc.XPathSelectElement("//PropertyGroup/SelfContained"); if (bool.TryParse(element?.Value, out _)) { return true; } return false; } public static string FindProjectFileInDirectory(string directory) { if (File.Exists(directory)) return directory; foreach (var ext in new [] { "*.csproj", "*.fsproj", "*.vbproj" }) { var files = Directory.GetFiles(directory, ext, SearchOption.TopDirectoryOnly); if (files.Length == 1) { return files[0]; } } return null; } /// <summary> /// Determines the location of the project root depending on how the workingDirectory and projectLocation /// fields are set. workingDir is the directory from where the CLI was called. ProjectLocation is optionally /// passed in as an argument by the user, but must be a directory, not a file. If a relative project loction /// is passed in (i.e. not rooted), the path relative to the workingDirectory is returned. /// </summary> /// <param name="workingDirectory"></param> /// <param name="projectLocation"></param> /// <returns>The full path to the project root directory (not project file, and not solution directory) without a trailing directory separator</returns> public static string DetermineProjectLocation(string workingDirectory, string projectLocation) { string location; if (string.IsNullOrEmpty(projectLocation)) { location = workingDirectory; } else if (string.IsNullOrEmpty(workingDirectory)) { location = projectLocation; } else { location = Path.IsPathRooted(projectLocation) ? projectLocation : Path.Combine(workingDirectory, projectLocation); } return location.TrimEnd('\\', '/'); } /// <summary> /// Determine where the dotnet build directory is. /// </summary> /// <param name="workingDirectory"></param> /// <param name="projectLocation"></param> /// <param name="configuration"></param> /// <param name="targetFramework"></param> /// <returns></returns> public static string DetermineBuildLocation(string workingDirectory, string projectLocation, string configuration, string targetFramework) { var path = Path.Combine( DetermineProjectLocation(workingDirectory, projectLocation), "bin", configuration, targetFramework); return path; } /// <summary> /// A utility method for parsing KeyValue pair CommandOptions. /// </summary> /// <param name="option"></param> /// <returns></returns> public static Dictionary<string, string> ParseKeyValueOption(string option) { var parameters = new Dictionary<string, string>(); if (string.IsNullOrWhiteSpace(option)) return parameters; try { var currentPos = 0; while (currentPos != -1 && currentPos < option.Length) { string name; GetNextToken(option, '=', ref currentPos, out name); string value; GetNextToken(option, ';', ref currentPos, out value); if (string.IsNullOrEmpty(name)) throw new ToolsException($"Error parsing option ({option}), format should be <key1>=<value1>;<key2>=<value2>", ToolsException.CommonErrorCode.CommandLineParseError); parameters[name] = value ?? string.Empty; } } catch (ToolsException) { throw; } catch (Exception e) { throw new ToolsException($"Error parsing option ({option}), format should be <key1>=<value1>;<key2>=<value2>: {e.Message}", ToolsException.CommonErrorCode.CommandLineParseError); } return parameters; } private static void GetNextToken(string option, char endToken, ref int currentPos, out string token) { if (option.Length <= currentPos) { token = string.Empty; return; } int tokenStart = currentPos; int tokenEnd = -1; bool inQuote = false; if (option[currentPos] == '"') { inQuote = true; tokenStart++; currentPos++; while (currentPos < option.Length && option[currentPos] != '"') { currentPos++; } if (option[currentPos] == '"') tokenEnd = currentPos; } while (currentPos < option.Length && option[currentPos] != endToken) { currentPos++; } if (!inQuote) { if (currentPos < option.Length && option[currentPos] == endToken) tokenEnd = currentPos; } if (tokenEnd == -1) token = option.Substring(tokenStart); else token = option.Substring(tokenStart, tokenEnd - tokenStart); currentPos++; } public static string DetermineToolVersion() { AssemblyInformationalVersionAttribute attribute = null; try { var assembly = Assembly.GetEntryAssembly(); if (assembly == null) return null; attribute = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>(); } catch (Exception) { // ignored } return attribute?.InformationalVersion; } public static void ZipDirectory(IToolLogger logger, string directory, string zipArchivePath) { zipArchivePath = Path.GetFullPath(zipArchivePath); if (File.Exists(zipArchivePath)) File.Delete(zipArchivePath); var zipArchiveParentDirectory = Path.GetDirectoryName(zipArchivePath); if (!Directory.Exists(zipArchiveParentDirectory)) { logger?.WriteLine($"Creating directory {zipArchiveParentDirectory}"); new DirectoryInfo(zipArchiveParentDirectory).Create(); } #if NETCOREAPP3_1_OR_GREATER if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { BundleWithDotNetCompression(zipArchivePath, directory, logger); } else { // Use the native zip utility if it exist which will maintain linux/osx file permissions var zipCLI = AbstractCLIWrapper.FindExecutableInPath("zip"); if (!string.IsNullOrEmpty(zipCLI)) { BundleWithZipCLI(zipCLI, zipArchivePath, directory, logger); } else { throw new ToolsException("Failed to find the \"zip\" utility program in path. This program is required to maintain Linux file permissions in the zip archive.", ToolsException.CommonErrorCode.FailedToFindZipProgram); } } #else BundleWithDotNetCompression(zipArchivePath, directory, logger); #endif } /// <summary> /// Get the list of files from the publish folder that should be added to the zip archive. /// This will skip all files in the runtimes folder because they have already been flatten to the root. /// </summary> /// <param name="publishLocation"></param> /// <returns></returns> private static IDictionary<string, string> GetFilesToIncludeInArchive(string publishLocation) { const char uniformDirectorySeparator = '/'; var includedFiles = new Dictionary<string, string>(); var allFiles = Directory.GetFiles(publishLocation, "*.*", SearchOption.AllDirectories); foreach (var file in allFiles) { var relativePath = file.Substring(publishLocation.Length) .Replace(Path.DirectorySeparatorChar.ToString(), uniformDirectorySeparator.ToString()); if (relativePath[0] == uniformDirectorySeparator) relativePath = relativePath.Substring(1); includedFiles[relativePath] = file; } return includedFiles; } /// <summary> /// Zip up the publish folder using the .NET compression libraries. This is what is used when run on Windows. /// </summary> /// <param name="zipArchivePath">The path and name of the zip archive to create.</param> /// <param name="publishLocation">The location to be bundled.</param> /// <param name="logger">Logger instance.</param> private static void BundleWithDotNetCompression(string zipArchivePath, string publishLocation, IToolLogger logger) { using (var zipArchive = ZipFile.Open(zipArchivePath, ZipArchiveMode.Create)) { var includedFiles = GetFilesToIncludeInArchive(publishLocation); foreach (var kvp in includedFiles) { zipArchive.CreateEntryFromFile(kvp.Value, kvp.Key); logger?.WriteLine($"... zipping: {kvp.Key}"); } } } /// <summary> /// Creates the deployment bundle using the native zip tool installed /// on the system (default /usr/bin/zip). This is what is typically used on Linux and OSX /// </summary> /// <param name="zipCLI">The path to the located zip binary.</param> /// <param name="zipArchivePath">The path and name of the zip archive to create.</param> /// <param name="publishLocation">The location to be bundled.</param> /// <param name="logger">Logger instance.</param> private static void BundleWithZipCLI(string zipCLI, string zipArchivePath, string publishLocation, IToolLogger logger) { var args = new StringBuilder("\"" + zipArchivePath + "\""); var allFiles = GetFilesToIncludeInArchive(publishLocation); foreach (var kvp in allFiles) { args.AppendFormat(" \"{0}\"", kvp.Key); } var psiZip = new ProcessStartInfo { FileName = zipCLI, Arguments = args.ToString(), WorkingDirectory = publishLocation, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; var handler = (DataReceivedEventHandler)((o, e) => { if (string.IsNullOrEmpty(e.Data)) return; logger?.WriteLine("... zipping: " + e.Data); }); using (var proc = new Process()) { proc.StartInfo = psiZip; proc.Start(); proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; proc.WaitForExit(); if (proc.ExitCode == 0) { logger?.WriteLine(string.Format("Created publish archive ({0}).", zipArchivePath)); } } } public static async Task ValidateBucketRegionAsync(IAmazonS3 s3Client, string s3Bucket) { string bucketRegion; try { bucketRegion = await Utilities.GetBucketRegionAsync(s3Client, s3Bucket); } catch(Exception e) { Console.Error.WriteLine($"Warning: Unable to determine region for bucket {s3Bucket}, assuming bucket is in correct region: {e.Message}", ToolsException.CommonErrorCode.S3GetBucketLocation, e); return; } var configuredRegion = s3Client.Config.RegionEndpoint?.SystemName; if(configuredRegion == null && !string.IsNullOrEmpty(s3Client.Config.ServiceURL)) { configuredRegion = AWSSDKUtils.DetermineRegion(s3Client.Config.ServiceURL); } // If we still don't know the region and assume we are running in a non standard way and assume the caller // knows what they are doing. if (configuredRegion == null) return; if (!string.Equals(bucketRegion, configuredRegion)) { throw new ToolsException($"Error: S3 bucket must be in the same region as the configured region {configuredRegion}. {s3Bucket} is in the region {bucketRegion}.", ToolsException.CommonErrorCode.BucketInDifferentRegionThenClient); } } private static async Task<string> GetBucketRegionAsync(IAmazonS3 s3Client, string bucket) { var request = new GetBucketLocationRequest { BucketName = bucket }; var response = await s3Client.GetBucketLocationAsync(request); // Handle the legacy naming conventions if (response.Location == S3Region.US) return "us-east-1"; if (response.Location == S3Region.EU) return "eu-west-1"; return response.Location.Value; } public static async Task<bool> EnsureBucketExistsAsync(IToolLogger logger, IAmazonS3 s3Client, string bucketName) { bool ret = false; logger?.WriteLine("Making sure bucket '" + bucketName + "' exists"); try { await s3Client.PutBucketAsync(new PutBucketRequest() { BucketName = bucketName, UseClientRegion = true }); ret = true; } catch (AmazonS3Exception exc) { if (System.Net.HttpStatusCode.Conflict != exc.StatusCode) { logger?.WriteLine("Attempt to create deployment upload bucket caught AmazonS3Exception, StatusCode '{0}', Message '{1}'", exc.StatusCode, exc.Message); } else { // conflict may occur if bucket belongs to another user or if bucket owned by this user but in a different region if (exc.ErrorCode != "BucketAlreadyOwnedByYou") logger?.WriteLine("Unable to use bucket name '{0}'; bucket exists but is not owned by you\r\n...S3 error was '{1}'.", bucketName, exc.Message); else { logger?.WriteLine("..a bucket with name '{0}' already exists and will be used for upload", bucketName); ret = true; } } } catch (Exception exc) { logger?.WriteLine("Attempt to create deployment upload bucket caught Exception, Message '{0}'", exc.Message); } return ret; } public static Task<string> UploadToS3Async(IToolLogger logger, IAmazonS3 s3Client, string bucket, string prefix, string rootName, Stream stream) { var extension = ".zip"; if (!string.IsNullOrEmpty(Path.GetExtension(rootName))) { extension = Path.GetExtension(rootName); rootName = Path.GetFileNameWithoutExtension(rootName); } var key = (prefix ?? "") + $"{rootName}-{DateTime.Now.Ticks}{extension}"; return UploadToS3Async(logger, s3Client, bucket, key, stream); } public static async Task<string> UploadToS3Async(IToolLogger logger, IAmazonS3 s3Client, string bucket, string key, Stream stream) { logger?.WriteLine($"Uploading to S3. (Bucket: {bucket} Key: {key})"); var request = new TransferUtilityUploadRequest() { BucketName = bucket, Key = key, InputStream = stream }; request.UploadProgressEvent += Utilities.CreateTransferUtilityProgressHandler(logger); try { await new TransferUtility(s3Client).UploadAsync(request); } catch (Exception e) { throw new ToolsException($"Error uploading to {key} in bucket {bucket}: {e.Message}", ToolsException.CommonErrorCode.S3UploadError, e); } return key; } const int UPLOAD_PROGRESS_INCREMENT = 10; private static EventHandler<StreamTransferProgressArgs> CreateProgressHandler(IToolLogger logger) { var percentToUpdateOn = UPLOAD_PROGRESS_INCREMENT; EventHandler<StreamTransferProgressArgs> handler = ((s, e) => { if (e.PercentDone != percentToUpdateOn && e.PercentDone <= percentToUpdateOn) return; var increment = e.PercentDone % UPLOAD_PROGRESS_INCREMENT; if (increment == 0) increment = UPLOAD_PROGRESS_INCREMENT; percentToUpdateOn = e.PercentDone + increment; logger?.WriteLine($"... Progress: {e.PercentDone}%"); }); return handler; } private static EventHandler<UploadProgressArgs> CreateTransferUtilityProgressHandler(IToolLogger logger) { var percentToUpdateOn = UPLOAD_PROGRESS_INCREMENT; EventHandler<UploadProgressArgs> handler = ((s, e) => { if (e.PercentDone != percentToUpdateOn && e.PercentDone <= percentToUpdateOn) return; var increment = e.PercentDone % UPLOAD_PROGRESS_INCREMENT; if (increment == 0) increment = UPLOAD_PROGRESS_INCREMENT; percentToUpdateOn = e.PercentDone + increment; logger?.WriteLine($"... Progress: {e.PercentDone}%"); }); return handler; } internal static int WaitForPromptResponseByIndex(int min, int max) { int chosenIndex = -1; while (chosenIndex == -1) { var indexInput = Console.ReadLine()?.Trim(); int parsedIndex; if (int.TryParse(indexInput, out parsedIndex) && parsedIndex >= min && parsedIndex <= max) { chosenIndex = parsedIndex; } else { Console.Out.WriteLine($"Invalid selection, must be a number between {min} and {max}"); } } return chosenIndex; } static readonly string GENERIC_ASSUME_ROLE_POLICY = @" { ""Version"": ""2012-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""{ASSUME_ROLE_PRINCIPAL}"" }, ""Action"": ""sts:AssumeRole"" } ] } ".Trim(); public static string GetAssumeRolePolicy(string assumeRolePrincipal) { return GENERIC_ASSUME_ROLE_POLICY.Replace("{ASSUME_ROLE_PRINCIPAL}", assumeRolePrincipal); } public class ExecuteShellCommandResult { public int ExitCode { get; } public string Stdout { get; } public ExecuteShellCommandResult(int exitCode, string stdout) { this.ExitCode = exitCode; this.Stdout = stdout; } } public static ExecuteShellCommandResult ExecuteShellCommand(string workingDirectory, string process, string arguments) { var startInfo = new ProcessStartInfo { FileName = process, Arguments = arguments, WorkingDirectory = workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; StringBuilder capturedOutput = new StringBuilder(); var handler = (DataReceivedEventHandler)((o, e) => { if (string.IsNullOrEmpty(e.Data)) return; capturedOutput.AppendLine(e.Data); }); using (var proc = new Process()) { proc.StartInfo = startInfo; proc.Start(); if (startInfo.RedirectStandardOutput) { proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; } proc.WaitForExit(); return new ExecuteShellCommandResult(proc.ExitCode, capturedOutput.ToString()); } } public static string ReadSecretFromConsole() { var code = new StringBuilder(); while (true) { ConsoleKeyInfo i = Console.ReadKey(true); if (i.Key == ConsoleKey.Enter) { break; } else if (i.Key == ConsoleKey.Backspace) { if (code.Length > 0) { code.Remove(code.Length - 1, 1); Console.Write("\b \b"); } } // i.Key > 31: Skip the initial ascii control characters like ESC and tab. The space character is 32. // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc else if ((int)i.Key > 31 && i.KeyChar != '\u0000') { code.Append(i.KeyChar); Console.Write("*"); } } return code.ToString().Trim(); } public static void CopyDirectory(string sourceDirectory, string destinationDirectory, bool copySubDirectories) { // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirectory); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirectory); } // If the destination directory doesn't exist, create it. if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string tempPath = Path.Combine(destinationDirectory, file.Name); file.CopyTo(tempPath, false); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirectories) { DirectoryInfo[] dirs = dir.GetDirectories(); foreach (DirectoryInfo subdirectory in dirs) { string temppath = Path.Combine(destinationDirectory, subdirectory.Name); CopyDirectory(subdirectory.FullName, temppath, copySubDirectories); } } } public static bool TryGenerateECRRepositoryName(string projectName, out string repositoryName) { repositoryName = null; if (Directory.Exists(projectName)) { projectName = new DirectoryInfo(projectName).Name; } else if(File.Exists(projectName)) { projectName = Path.GetFileNameWithoutExtension(projectName); } projectName = projectName.ToLower(); var sb = new StringBuilder(); foreach(var c in projectName) { if(char.IsLetterOrDigit(c)) { sb.Append(c); } else if(sb.Length > 0 && (c == '.' || c == '_' || c == '-')) { sb.Append(c); } } // Repository name must be at least 2 characters if(sb.Length > 1) { repositoryName = sb.ToString(); // Max length of repository name is 256 characters. if (Constants.MAX_ECR_REPOSITORY_NAME_LENGTH < repositoryName.Length) { repositoryName = repositoryName.Substring(0, Constants.MAX_ECR_REPOSITORY_NAME_LENGTH); } } return !string.IsNullOrEmpty(repositoryName); } } }
925
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using Amazon.Common.DotNetCli.Tools.Commands; using System.IO; using System.Linq; using Amazon.Common.DotNetCli.Tools.Options; namespace Amazon.Common.DotNetCli.Tools.CLi { public class Application { public string SubCommandName { get; } public string ToolDisplayName { get; } IList<ICommandInfo> CommandInfos { get; } public string ProjectHome { get; } public Application(string subCommandName, string toolDisplayName, string projectHome, IList<ICommandInfo> commands) { this.SubCommandName = subCommandName; this.ToolDisplayName = toolDisplayName; this.CommandInfos = commands; this.ProjectHome = projectHome; } public int Execute(string[] args) { try { PrintToolTitle(); if (args.Length == 0) { PrintUsage(); return -1; } if (IsHelpSwitch(args[0])) { if (args.Length > 1) PrintUsage(args[1]); else PrintUsage(); return 0; } else if(args.Length > 1 && IsHelpSwitch(args[1])) { PrintUsage(args[0]); return 0; } var commandInfo = FindCommandInfo(args[0]); if (commandInfo != null) { var command = commandInfo.CreateCommand(new ConsoleToolLogger(), Directory.GetCurrentDirectory(), args.Skip(1).ToArray()); var success = command.ExecuteAsync().Result; if (!success) { return -1; } } else { Console.Error.WriteLine($"Unknown command: {args[0]}\n"); PrintUsage(); return -1; } } catch (ToolsException e) { Console.Error.WriteLine(e.Message); return -1; } catch(TargetInvocationException e) when (e.InnerException is ToolsException) { Console.Error.WriteLine(e.InnerException.Message); return -1; } catch (Exception e) { Console.Error.WriteLine($"Unknown error:"); Console.Error.WriteLine(e); return -1; } return 0; } private bool IsHelpSwitch(string value) { if (value == "--help" || value == "--h" || value == "help") return true; return false; } private ICommandInfo FindCommandInfo(string name) { foreach (var commandInfo in this.CommandInfos) { if (commandInfo == null) continue; if (string.Equals(commandInfo.Name, name, StringComparison.OrdinalIgnoreCase)) { return commandInfo; } } return null; } private void PrintToolTitle() { var sb = new StringBuilder(this.ToolDisplayName); var version = Utilities.DetermineToolVersion(); if (!string.IsNullOrEmpty(version)) { sb.Append($" ({version})"); } Console.WriteLine(sb.ToString()); Console.WriteLine($"Project Home: {this.ProjectHome}"); Console.WriteLine("\t"); } private void PrintUsage() { const int NAME_WIDTH = 23; Console.WriteLine("\t"); foreach(var command in this.CommandInfos) { if (command == null) { Console.WriteLine("\t"); } else if (command is GroupHeaderInfo) { Console.WriteLine("\t"); Console.WriteLine(command.Name); Console.WriteLine("\t"); } else { Console.WriteLine($"\t{command.Name.PadRight(NAME_WIDTH)} {command.Description}"); } } Console.WriteLine("\t"); Console.WriteLine("To get help on individual commands execute:"); Console.WriteLine($"\tdotnet {this.SubCommandName} help <command>"); Console.WriteLine("\t"); } private void PrintUsage(string command) { var commandInfo = FindCommandInfo(command); if (commandInfo != null) PrintUsage(commandInfo.Name, commandInfo.Description, commandInfo.CommandOptions, commandInfo.Argument); else { Console.Error.WriteLine($"Unknown command {command}"); PrintUsage(); } } private void PrintUsage(string command, string description, IList<CommandOption> options, string argument) { const int INDENT = 3; Console.WriteLine($"{command}: "); Console.WriteLine($"{new string(' ', INDENT)}{description}"); Console.WriteLine("\t"); if (!string.IsNullOrEmpty(argument)) { Console.WriteLine($"{new string(' ', INDENT)}dotnet {this.SubCommandName} {command} [arguments] [options]"); Console.WriteLine($"{new string(' ', INDENT)}Arguments:"); Console.WriteLine($"{new string(' ', INDENT * 2)}{argument}"); } else { Console.WriteLine($"{new string(' ', INDENT)}dotnet {this.SubCommandName} {command} [options]"); } const int SWITCH_COLUMN_WIDTH = 40; Console.WriteLine($"{new string(' ', INDENT)}Options:"); foreach (var option in options) { StringBuilder sb = new StringBuilder(); if (option.ShortSwitch != null) sb.Append($"{option.ShortSwitch.PadRight(6)} | "); sb.Append($"{option.Switch}"); if (sb.Length < SWITCH_COLUMN_WIDTH) sb.Append(new string(' ', SWITCH_COLUMN_WIDTH - sb.Length)); sb.Append(option.Description); Console.WriteLine($"{new string(' ', INDENT * 2)}{sb.ToString()}"); } } } }
216
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using ThirdParty.Json.LitJson; using Amazon.ECR; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.S3; using Amazon.SecurityToken; namespace Amazon.Common.DotNetCli.Tools.Commands { public abstract class BaseCommand<TDefaultConfig> : ICommand where TDefaultConfig : DefaultConfigFile, new() { public ToolsException LastToolsException => LastException as ToolsException; public Exception LastException { get; private set; } public string[] OriginalCommandLineArguments { get; private set; } public BaseCommand(IToolLogger logger, string workingDirectory) { this.Logger = logger; this.WorkingDirectory = workingDirectory; } public BaseCommand(IToolLogger logger, string workingDirectory, IList<CommandOption> possibleOptions, string[] args) : this(logger, workingDirectory) { args = args ?? new string[0]; this.OriginalCommandLineArguments = args; var values = CommandLineParser.ParseArguments(possibleOptions, args); ParseCommandArguments(values); } public async Task<bool> ExecuteAsync() { try { var success = await PerformActionAsync(); if (!success) return false; if (this.GetBoolValueOrDefault(this.PersistConfigFile, CommonDefinedCommandOptions.ARGUMENT_PERSIST_CONFIG_FILE, false).GetValueOrDefault()) { this.SaveConfigFile(); } } catch (ToolsException e) { this.Logger?.WriteLine(e.Message); this.LastException = e; return false; } catch (Exception e) { this.Logger?.WriteLine($"Unknown error executing command: {e.Message}"); this.Logger?.WriteLine(e.StackTrace); this.LastException = e; return false; } return true; } protected abstract Task<bool> PerformActionAsync(); protected abstract string ToolName { get; } /// <summary> /// The common options used by every command /// </summary> protected static readonly IList<CommandOption> CommonOptions = new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_DISABLE_INTERACTIVE, CommonDefinedCommandOptions.ARGUMENT_AWS_REGION, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE_LOCATION, CommonDefinedCommandOptions.ARGUMENT_AWS_ACCESS_KEY_ID, CommonDefinedCommandOptions.ARGUMENT_AWS_SECRET_KEY, CommonDefinedCommandOptions.ARGUMENT_AWS_SESSION_TOKEN, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, CommonDefinedCommandOptions.ARGUMENT_CONFIG_FILE, CommonDefinedCommandOptions.ARGUMENT_PERSIST_CONFIG_FILE }; /// <summary> /// Used to combine the command specific command options with the common options. /// </summary> /// <param name="optionCollections"></param> /// <returns></returns> protected static IList<CommandOption> BuildLineOptions(params IList<CommandOption>[] optionCollections) { var list = new List<CommandOption>(); list.AddRange(CommonOptions); if (optionCollections != null) { foreach (var options in optionCollections) { if (options != null) { foreach (var option in options) { if (!list.Any(x => string.Equals(x.Switch, option.Switch))) { list.Add(option); } } } } } return list; } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected virtual void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DISABLE_INTERACTIVE.Switch)) != null) this.DisableInteractive = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE.Switch)) != null) this.Profile = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE_LOCATION.Switch)) != null) this.ProfileLocation = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_AWS_REGION.Switch)) != null) this.Region = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION.Switch)) != null) this.ProjectLocation = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIG_FILE.Switch)) != null) { this.ConfigFile = tuple.Item2.StringValue; var fullConfigPath = Path.Combine(Utilities.DetermineProjectLocation(this.WorkingDirectory, this.ProjectLocation), this.ConfigFile); if (!File.Exists(fullConfigPath)) { throw new ToolsException($"Config file {fullConfigPath} can not be found.", ToolsException.CommonErrorCode.MissingConfigFile); } } if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_PERSIST_CONFIG_FILE.Switch)) != null) this.PersistConfigFile = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_AWS_ACCESS_KEY_ID.Switch)) != null) this.AWSAccessKeyId = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_AWS_SECRET_KEY.Switch)) != null) this.AWSSecretKey = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_AWS_SESSION_TOKEN.Switch)) != null) this.AWSSessionToken = tuple.Item2.StringValue; if (string.IsNullOrEmpty(this.ConfigFile)) { this.ConfigFile = new TDefaultConfig().DefaultConfigFileName; } } TDefaultConfig _defaultConfig; public TDefaultConfig DefaultConfig { get { if (this._defaultConfig == null) { var config = new TDefaultConfig(); config.LoadDefaults(Utilities.DetermineProjectLocation(this.WorkingDirectory, this.ProjectLocation), this.ConfigFile); this._defaultConfig = config; } return this._defaultConfig; } } public string Region { get; set; } public string Profile { get; set; } public string ProfileLocation { get; set; } public string AWSAccessKeyId { get; set; } public string AWSSecretKey { get; set; } public string AWSSessionToken { get; set; } public AWSCredentials Credentials { get; set; } public string ProjectLocation { get; set; } public string ConfigFile { get; set; } public bool? PersistConfigFile { get; set; } /// <summary> /// Disable all Console.Read operations to make sure the command is never blocked waiting for input. This is /// used by the AWS Visual Studio Toolkit to make sure it never gets blocked. /// </summary> public bool DisableInteractive { get; set; } = false; private AWSCredentials _resolvedCredentials; protected AWSCredentials DetermineAWSCredentials() { if(this._resolvedCredentials != null) { return this._resolvedCredentials; } if (this.Credentials != null) { this._resolvedCredentials = this.Credentials; } else { var awsAccessKeyId = GetStringValueOrDefault(this.AWSAccessKeyId, CommonDefinedCommandOptions.ARGUMENT_AWS_ACCESS_KEY_ID, false); var profile = this.GetStringValueOrDefault(this.Profile, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE, false); if(!string.IsNullOrEmpty(awsAccessKeyId)) { var awsSecretKey = GetStringValueOrDefault(this.AWSSecretKey, CommonDefinedCommandOptions.ARGUMENT_AWS_SECRET_KEY, false); var awsSessionToken = GetStringValueOrDefault(this.AWSSessionToken, CommonDefinedCommandOptions.ARGUMENT_AWS_SESSION_TOKEN, false); if (string.IsNullOrEmpty(awsSecretKey)) throw new ToolsException("An AWS access key id was specified without a required AWS secret key. Either set an AWS secret key or remove the AWS access key id and use profiles for credentials.", ToolsException.CommonErrorCode.InvalidCredentialConfiguration); if(string.IsNullOrEmpty(awsSessionToken)) { this._resolvedCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretKey); } else { this._resolvedCredentials = new SessionAWSCredentials(awsAccessKeyId, awsSecretKey, awsSessionToken); } } else if (!string.IsNullOrEmpty(profile)) { var chain = new CredentialProfileStoreChain(this.ProfileLocation); if (!chain.TryGetAWSCredentials(profile, out this._resolvedCredentials)) { this._resolvedCredentials = FallbackCredentialsFactory.GetCredentials(); } } else { this._resolvedCredentials = FallbackCredentialsFactory.GetCredentials(); } if(this._resolvedCredentials is AssumeRoleAWSCredentials) { var assumeOptions = ((AssumeRoleAWSCredentials)this._resolvedCredentials).Options; assumeOptions.MfaTokenCodeCallback = new AssumeRoleMfaTokenCodeCallback(assumeOptions).Execute; } } return this._resolvedCredentials; } public RegionEndpoint DetermineAWSRegion() { // See if a region has been set but don't prompt if not set. var regionName = this.GetStringValueOrDefault(this.Region, CommonDefinedCommandOptions.ARGUMENT_AWS_REGION, false); if (!string.IsNullOrWhiteSpace(regionName)) { return RegionEndpoint.GetBySystemName(regionName); } // See if we can find a region using the region fallback logic. if (string.IsNullOrWhiteSpace(regionName)) { var region = FallbackRegionFactory.GetRegionEndpoint(true); if (region != null) { return region; } } // If we still don't have a region prompt the user for a region. regionName = this.GetStringValueOrDefault(this.Region, CommonDefinedCommandOptions.ARGUMENT_AWS_REGION, true); if (!string.IsNullOrWhiteSpace(regionName)) { return RegionEndpoint.GetBySystemName(regionName); } throw new ToolsException("Can not determine AWS region. Either configure a default region or use the --region option.", ToolsException.CommonErrorCode.RegionNotConfigured); } /// <summary> /// Gets the value for the CommandOption either through the property value which means the /// user explicity set the value or through defaults for the project. /// /// If no value is found in either the property value or the defaults and the value /// is required the user will be prompted for the value if we are running in interactive /// mode. /// </summary> /// <param name="propertyValue"></param> /// <param name="option"></param> /// <param name="required"></param> /// <returns></returns> public string GetStringValueOrDefault(string propertyValue, CommandOption option, bool required) { if (!string.IsNullOrEmpty(propertyValue)) { var expanded = Utilities.ReplaceEnvironmentVariables(propertyValue); return expanded; } else if (!string.IsNullOrEmpty(DefaultConfig[option.Switch] as string)) { var configDefault = DefaultConfig[option.Switch] as string; var expanded = Utilities.ReplaceEnvironmentVariables(configDefault); return expanded; } else if(DefaultConfig[option.Switch] is int) { var configDefault = (int)DefaultConfig[option.Switch]; return configDefault.ToString(); } else if (required && !this.DisableInteractive) { return PromptForValue(option); } else if (_cachedRequestedValues.ContainsKey(option)) { var cachedValue = _cachedRequestedValues[option]; return cachedValue; } if (required) { throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter); } return propertyValue; } public string GetRoleValueOrDefault(string propertyValue, CommandOption option, string assumeRolePrincipal, string awsManagedPolicyPrefix, Dictionary<string, string> knownManagedPolicyDescription, bool required) { if (!string.IsNullOrEmpty(propertyValue)) { return RoleHelper.ExpandRoleName(this.IAMClient, propertyValue); } else if (!string.IsNullOrEmpty(DefaultConfig[option.Switch] as string)) { var configDefault = DefaultConfig[option.Switch] as string; return RoleHelper.ExpandRoleName(this.IAMClient, configDefault); } else if (_cachedRequestedValues.ContainsKey(option)) { var cachedValue = _cachedRequestedValues[option]; return cachedValue; } else if (required && !this.DisableInteractive) { var promptInfo = new RoleHelper.PromptRoleInfo { AssumeRolePrincipal = assumeRolePrincipal, AWSManagedPolicyNamePrefix = awsManagedPolicyPrefix, KnownManagedPolicyDescription = knownManagedPolicyDescription }; var role = RoleHelper.PromptForRole(this.IAMClient, promptInfo); if(!string.IsNullOrEmpty(role)) { _cachedRequestedValues[option] = role; } return role; } return null; } /// <summary> /// Complex parameters are formatted as a JSON string. This method parses the string into the JsonData object /// </summary> /// <param name="propertyValue"></param> /// <param name="option"></param> /// <returns></returns> public JsonData GetJsonValueOrDefault(string propertyValue, CommandOption option) { string jsonContent = GetStringValueOrDefault(propertyValue, option, false); if (string.IsNullOrWhiteSpace(jsonContent)) return null; try { var data = JsonMapper.ToObject(jsonContent); return data; } catch(Exception e) { throw new ToolsException($"Error parsing JSON string for parameter {option.Switch}: {e.Message}", ToolsException.CommonErrorCode.CommandLineParseError); } } /// <summary> /// String[] version of GetStringValueOrDefault /// </summary> /// <param name="propertyValue"></param> /// <param name="option"></param> /// <param name="required"></param> /// <returns></returns> public string[] GetStringValuesOrDefault(string[] propertyValue, CommandOption option, bool required) { if (propertyValue != null) { return propertyValue; } else if (!string.IsNullOrEmpty(DefaultConfig[option.Switch] as string)) { var configDefault = DefaultConfig[option.Switch] as string; if (string.IsNullOrEmpty(configDefault)) return null; return configDefault.SplitByComma(); } else if (required && !this.DisableInteractive) { var response = PromptForValue(option); if (string.IsNullOrEmpty(response)) return null; return response.SplitByComma(); } else if (_cachedRequestedValues.ContainsKey(option)) { var cachedValue = _cachedRequestedValues[option]; return cachedValue?.SplitByComma(); } if (required) { throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter); } return null; } public Dictionary<string, string> GetKeyValuePairOrDefault(Dictionary<string, string> propertyValue, CommandOption option, bool required) { if (propertyValue != null) { return propertyValue; } else if (!string.IsNullOrEmpty(DefaultConfig[option.Switch] as string)) { var configDefault = DefaultConfig[option.Switch] as string; if (string.IsNullOrEmpty(configDefault)) return null; return Utilities.ParseKeyValueOption(configDefault); } else if (required && !this.DisableInteractive) { var response = PromptForValue(option); if (string.IsNullOrEmpty(response)) return null; return Utilities.ParseKeyValueOption(response); } else if (_cachedRequestedValues.ContainsKey(option)) { var cachedValue = _cachedRequestedValues[option]; return cachedValue == null ? null : Utilities.ParseKeyValueOption(cachedValue); } if (required) { throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter); } return null; } /// <summary> /// Int version of GetStringValueOrDefault /// </summary> /// <param name="propertyValue"></param> /// <param name="option"></param> /// <param name="required"></param> /// <returns></returns> public int? GetIntValueOrDefault(int? propertyValue, CommandOption option, bool required) { if (propertyValue.HasValue) { return propertyValue.Value; } else if (DefaultConfig[option.Switch] is int) { var configDefault = (int)DefaultConfig[option.Switch]; return configDefault; } else if (required && !this.DisableInteractive) { var userValue = PromptForValue(option); if (string.IsNullOrWhiteSpace(userValue)) return null; int i; if (!int.TryParse(userValue, out i)) { throw new ToolsException($"{userValue} cannot be parsed into an integer for {option.Name}", ToolsException.CommonErrorCode.CommandLineParseError); } return i; } else if (_cachedRequestedValues.ContainsKey(option)) { var cachedValue = _cachedRequestedValues[option]; int i; if (int.TryParse(cachedValue, out i)) { return i; } } if (required) { throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter); } return null; } /// <summary> /// bool version of GetStringValueOrDefault /// </summary> /// <param name="propertyValue"></param> /// <param name="option"></param> /// <param name="required"></param> /// <returns></returns> public bool? GetBoolValueOrDefault(bool? propertyValue, CommandOption option, bool required) { if (propertyValue.HasValue) { return propertyValue.Value; } else if (DefaultConfig[option.Switch] is bool) { var configDefault = (bool)DefaultConfig[option.Switch]; return configDefault; } else if (required && !this.DisableInteractive) { var userValue = PromptForValue(option); if (string.IsNullOrWhiteSpace(userValue)) return null; bool i; if (bool.TryParse(userValue, out i)) { throw new ToolsException($"{userValue} cannot be parsed into a boolean for {option.Name}", ToolsException.CommonErrorCode.CommandLineParseError); } return i; } else if (_cachedRequestedValues.ContainsKey(option)) { var cachedValue = _cachedRequestedValues[option]; bool i; if (bool.TryParse(cachedValue, out i)) { return i; } } if (required) { throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter); } return null; } public string GetInstanceProfileOrDefault(string propertyValue, CommandOption option, bool required, string newRoleName) { var value = GetStringValueOrDefault(propertyValue, option, false); if (!string.IsNullOrEmpty(value)) { value = RoleHelper.ExpandInstanceProfile(this.IAMClient, value); return value; } else if (required && !this.DisableInteractive) { var existingProfiles = RoleHelper.FindExistingInstanceProfilesAsync(this.IAMClient, 20).Result; var selections = new List<string>(); foreach (var profile in existingProfiles) selections.Add(profile.InstanceProfileName); selections.Add("*** Create new Instance Profile ***"); var chosenIndex = PromptForValue(option, selections); if(chosenIndex < selections.Count - 1) { var arn = existingProfiles[chosenIndex].Arn; _cachedRequestedValues[option] = arn; return arn; } else { var promptInfo = new RoleHelper.PromptRoleInfo { KnownManagedPolicyDescription = Constants.COMMON_KNOWN_MANAGED_POLICY_DESCRIPTIONS }; var managedPolices = RoleHelper.FindManagedPoliciesAsync(this.IAMClient, promptInfo, 20).Result; var profileSelection = new List<string>(); foreach (var profile in managedPolices) profileSelection.Add(profile.PolicyName); chosenIndex = PromptForValue("Select managed policy to assign to new instance profile: ", profileSelection); var uniqueRoleName = RoleHelper.GenerateUniqueIAMRoleName(this.IAMClient, newRoleName); this.Logger?.WriteLine("Creating role {0}", uniqueRoleName); RoleHelper.CreateRole(this.IAMClient, uniqueRoleName, Constants.EC2_ASSUME_ROLE_POLICY, managedPolices[chosenIndex].Arn); this.Logger?.WriteLine("Creating instance profile {0}", uniqueRoleName); var response = this.IAMClient.CreateInstanceProfileAsync(new IdentityManagement.Model.CreateInstanceProfileRequest { InstanceProfileName = uniqueRoleName }).Result; this.Logger?.WriteLine("Assigning role to instance profile"); this.IAMClient.AddRoleToInstanceProfileAsync(new IdentityManagement.Model.AddRoleToInstanceProfileRequest { InstanceProfileName = uniqueRoleName, RoleName = uniqueRoleName }).Wait(); var arn = response.InstanceProfile.Arn; _cachedRequestedValues[option] = arn; return arn; } } if (required) { throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter); } return null; } protected string GetServiceRoleOrCreateIt(string propertyValue, CommandOption option, string roleName, string assumeRolePolicy, string policy, params string[] managedPolicies) { var value = GetStringValueOrDefault(propertyValue, option, false); if (!string.IsNullOrEmpty(value)) { return value; } Role role = null; try { role = this.IAMClient.GetRoleAsync(new GetRoleRequest { RoleName = roleName }).Result.Role; } catch (AggregateException e) { if (!(e.InnerException is NoSuchEntityException)) throw e.InnerException; } if(role == null) { this.Logger?.WriteLine("Creating service role " + roleName); return RoleHelper.CreateRole(this.IAMClient, roleName, assumeRolePolicy, managedPolicies); } this.Logger?.WriteLine("Using service role " + role.RoleName); return role.Arn; } // Cache all prompted values so the user is never prompted for the same CommandOption later. protected Dictionary<CommandOption, string> _cachedRequestedValues = new Dictionary<CommandOption, string>(); protected string PromptForValue(CommandOption option) { if (_cachedRequestedValues.ContainsKey(option)) { var cachedValue = _cachedRequestedValues[option]; return cachedValue; } string input = null; Console.Out.WriteLine($"Enter {option.Name}: ({option.Description})"); Console.Out.Flush(); input = Console.ReadLine(); if (string.IsNullOrWhiteSpace(input)) return null; input = input.Trim(); _cachedRequestedValues[option] = input; return input; } protected int PromptForValue(CommandOption option, IList<string> items) { return PromptForValue("Select " + option.Name + ":", items); } protected int PromptForValue(string message, IList<string> items) { Console.Out.WriteLine(message); for (int i = 0; i < items.Count; i++) { Console.Out.WriteLine($" {(i + 1).ToString().PadLeft(2)}) {items[i]}"); } Console.Out.Flush(); int chosenIndex = WaitForIndexResponse(1, items.Count); return chosenIndex - 1; } private int WaitForIndexResponse(int min, int max) { int chosenIndex = -1; while (chosenIndex == -1) { var indexInput = Console.ReadLine()?.Trim(); int parsedIndex; if (int.TryParse(indexInput, out parsedIndex) && parsedIndex >= min && parsedIndex <= max) { chosenIndex = parsedIndex; } else { Console.Out.WriteLine($"Invalid selection, must be a number between {min} and {max}"); } } return chosenIndex; } public IToolLogger Logger { get; protected set; } public string WorkingDirectory { get; set; } protected void SetUserAgentString() { string version = this.GetType().GetTypeInfo().Assembly.GetName().Version.ToString(); Util.Internal.InternalSDKUtils.SetUserAgent(this.ToolName, version); } IAmazonSecurityTokenService _stsClient; public IAmazonSecurityTokenService STSClient { get { if (this._stsClient == null) { SetUserAgentString(); var config = new AmazonSecurityTokenServiceConfig(); config.RegionEndpoint = DetermineAWSRegion(); this._stsClient = new AmazonSecurityTokenServiceClient(DetermineAWSCredentials(), config); } return this._stsClient; } set { this._stsClient = value; } } IAmazonIdentityManagementService _iamClient; public IAmazonIdentityManagementService IAMClient { get { if (this._iamClient == null) { SetUserAgentString(); var config = new AmazonIdentityManagementServiceConfig(); config.RegionEndpoint = DetermineAWSRegion(); this._iamClient = new AmazonIdentityManagementServiceClient(DetermineAWSCredentials(), config); } return this._iamClient; } set { this._iamClient = value; } } IAmazonS3 _s3Client; public IAmazonS3 S3Client { get { if (this._s3Client == null) { SetUserAgentString(); var config = new AmazonS3Config(); config.RegionEndpoint = DetermineAWSRegion(); config.Timeout = TimeSpan.FromHours(1); this._s3Client = new AmazonS3Client(DetermineAWSCredentials(), config); } return this._s3Client; } set { this._s3Client = value; } } IAmazonECR _ecrClient; public IAmazonECR ECRClient { get { if (this._ecrClient == null) { SetUserAgentString(); var config = new AmazonECRConfig(); config.RegionEndpoint = DetermineAWSRegion(); this._ecrClient = new AmazonECRClient(DetermineAWSCredentials(), config); } return this._ecrClient; } set { this._ecrClient = value; } } protected void SaveConfigFile() { try { JsonData data; if (File.Exists(this.DefaultConfig.SourceFile)) { data = JsonMapper.ToObject(File.ReadAllText(this.DefaultConfig.SourceFile)); } else { data = new JsonData(); } data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_AWS_REGION.ConfigFileKey, this.GetStringValueOrDefault(this.Region, CommonDefinedCommandOptions.ARGUMENT_AWS_REGION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE.ConfigFileKey, this.GetStringValueOrDefault(this.Profile, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE_LOCATION.ConfigFileKey, this.GetStringValueOrDefault(this.ProfileLocation, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE_LOCATION, false)); SaveConfigFile(data); StringBuilder sb = new StringBuilder(); JsonWriter writer = new JsonWriter(sb); writer.PrettyPrint = true; JsonMapper.ToJson(data, writer); var json = sb.ToString(); File.WriteAllText(this.DefaultConfig.SourceFile, json); this.Logger?.WriteLine($"Config settings saved to {this.DefaultConfig.SourceFile}"); } catch (Exception e) { throw new ToolsException("Error persisting configuration file: " + e.Message, ToolsException.CommonErrorCode.PersistConfigError); } } protected abstract void SaveConfigFile(JsonData data); public bool ConfirmDeletion(string resource) { if (this.DisableInteractive) return true; Console.WriteLine("Are you sure you want to delete the {0}? [y/n]", resource); char input; do { input = Console.ReadKey().KeyChar; } while (input != 'y' && input != 'n'); return input == 'y'; } protected void EnsureInProjectDirectory() { var projectLocation = Utilities.DetermineProjectLocation(this.WorkingDirectory, this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false)); if (!Directory.Exists(projectLocation)) { throw new ToolsException($"Provided project location is not a directory.", ToolsException.CommonErrorCode.NoProjectFound); } if (Directory.GetFiles(projectLocation, "*.csproj", SearchOption.TopDirectoryOnly).Length == 1 || Directory.GetFiles(projectLocation, "*.fsproj", SearchOption.TopDirectoryOnly).Length == 1 || Directory.GetFiles(projectLocation, "*.vbproj", SearchOption.TopDirectoryOnly).Length == 1) { return; } throw new ToolsException($"No .NET project found in directory {projectLocation} to build.", ToolsException.CommonErrorCode.NoProjectFound); } } }
912
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Amazon.ECR.Model; using Amazon.ECR; using ThirdParty.Json.LitJson; using System.IO; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Common.DotNetCli.Tools; namespace Amazon.Common.DotNetCli.Tools.Commands { public abstract class BasePushDockerImageCommand<TDefaultConfig> : BaseCommand<TDefaultConfig>, ICommand where TDefaultConfig : DefaultConfigFile, new() { public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, CommonDefinedCommandOptions.ARGUMENT_LOCAL_DOCKER_IMAGE, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG_OBSOLETE, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS }); PushDockerImagePropertyContainer _pushProperties; public PushDockerImagePropertyContainer PushDockerImageProperties { get { if (this._pushProperties == null) { this._pushProperties = new PushDockerImagePropertyContainer(); } return this._pushProperties; } set { this._pushProperties = value; } } public string PushedImageUri { get; private set; } public bool SkipPushToECR { get; set; } /// <summary> /// If this is set then the tag used to push to ECR will be made unique. The value is a string giving /// a base known name by the user for the tag. This is typically the name of the CloudFormation resource. /// </summary> public string ImageTagUniqueSeed { get; set; } public BasePushDockerImageCommand(IToolLogger logger, string workingDirectory, string[] args) : this(logger, workingDirectory, CommandOptions, args) { } protected BasePushDockerImageCommand(IToolLogger logger, string workingDirectory, IList<CommandOption> commandOptions, string[] args) : base(logger, workingDirectory, commandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); this.PushDockerImageProperties.ParseCommandArguments(values); } protected override async Task<bool> PerformActionAsync() { var projectLocation = Utilities.DetermineProjectLocation(this.WorkingDirectory, this.ProjectLocation); var dockerCli = new DockerCLIWrapper(this.Logger, projectLocation); string sourceDockerTag; string destinationDockerTag; var localDockerImage = this.GetStringValueOrDefault(this.PushDockerImageProperties.LocalDockerImage, CommonDefinedCommandOptions.ARGUMENT_LOCAL_DOCKER_IMAGE, false); // If there is no local tag then build the image if(string.IsNullOrEmpty(localDockerImage)) { // In the case of building the image when we push the image the local image will have the same name as the ECR destionation tag. destinationDockerTag = DetermineDockerImageTag(true, projectLocation); sourceDockerTag = destinationDockerTag; BuildDockerImage(dockerCli, projectLocation, destinationDockerTag); } else { destinationDockerTag = DetermineDockerImageTag(false, projectLocation); sourceDockerTag = localDockerImage; // If an ECR destination tag was not given then use the same tag as the local. That way the user isn't required to specify the --image-tag switch. if (string.IsNullOrEmpty(destinationDockerTag)) { destinationDockerTag = sourceDockerTag; if (!destinationDockerTag.Contains(":")) destinationDockerTag += ":latest"; } } if (!this.SkipPushToECR) { string ecrTag; if(string.IsNullOrEmpty(ImageTagUniqueSeed)) { ecrTag = destinationDockerTag; } else { var imageId = dockerCli.GetImageId(sourceDockerTag); ecrTag = GenerateUniqueEcrTag(this.ImageTagUniqueSeed, destinationDockerTag, imageId); } await PushToECR(dockerCli, sourceDockerTag, ecrTag); } else { this.PushedImageUri = destinationDockerTag; } return true; } public static string GenerateUniqueEcrTag(string uniqueSeed, string destinationDockerTag, string imageId) { // If there is any problem getting the image ID from the CLI then default to Ticks to make sure the tag is unique. if (string.IsNullOrEmpty(imageId)) { imageId = DateTime.UtcNow.Ticks.ToString(); } var imageInfo = SplitImageTag(destinationDockerTag); var uniqueTag = $"{imageInfo.RepositoryName}:{uniqueSeed.ToLower()}-{imageId}-{imageInfo.Tag}"; return uniqueTag; } private string DetermineDockerImageTag(bool required, string projectLocation) { // Try to get the tag from the newer --image-tag switch. var dockerImageTag = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerImageTag, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG, false)?.ToLower(); if (string.IsNullOrEmpty(dockerImageTag)) { // Since the newer --image-tag switch was not set attempt to get the value from the old obsolete --tag switch. dockerImageTag = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerImageTag, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG_OBSOLETE, false)?.ToLower(); if (string.IsNullOrEmpty(dockerImageTag)) { // If docker tag is required and we still don't have then try and generate one. // If it is not required then the push command is reusing a local image tag. // If the generate fails then ask the user for the image tag. if(required) { string generatedRepositoryName; if (Utilities.TryGenerateECRRepositoryName(projectLocation, out generatedRepositoryName)) { dockerImageTag = generatedRepositoryName; Logger.WriteLine($"Creating image tag from project: {dockerImageTag}"); } else { // If we still don't have a value ask one more time for the --image-tag switch but this time make it required. dockerImageTag = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerImageTag, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG, required)?.ToLower(); } } } } if (string.IsNullOrEmpty(dockerImageTag)) return null; if (!dockerImageTag.Contains(":")) dockerImageTag += ":latest"; return dockerImageTag; } private void BuildDockerImage(DockerCLIWrapper dockerCli, string projectLocation, string dockerImageTag) { var dockerFile = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerFile, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, false); if (string.IsNullOrEmpty(dockerFile)) { dockerFile = Constants.DEFAULT_DOCKERFILE; } var hostBuildOutput = this.GetStringValueOrDefault(this.PushDockerImageProperties.HostBuildOutput, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, false); if (!string.IsNullOrEmpty(hostBuildOutput)) { var configuration = this.GetStringValueOrDefault(this.PushDockerImageProperties.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false) ?? "Release"; var targetFramework = this.GetStringValueOrDefault(this.PushDockerImageProperties.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false); string publishOptions = this.GetStringValueOrDefault(this.PushDockerImageProperties.PublishOptions, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, false); BuildProject(projectLocation, configuration, targetFramework, publishOptions, Path.Combine(projectLocation, hostBuildOutput)); } var dockerDetails = InspectDockerFile(this.Logger, projectLocation, dockerFile); this.Logger?.WriteLine("Executing docker build"); var dockerBuildWorkingDirectory = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerBuildWorkingDirectory, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, false); if (string.IsNullOrEmpty(dockerBuildWorkingDirectory)) { dockerBuildWorkingDirectory = dockerDetails.BuildFromSolutionDirectory ? DetermineSolutionDirectory(projectLocation) : projectLocation; } else { if (!Path.IsPathRooted(dockerBuildWorkingDirectory)) { dockerBuildWorkingDirectory = Path.GetFullPath(Path.Combine(projectLocation, dockerBuildWorkingDirectory)); } this.PushDockerImageProperties.DockerBuildWorkingDirectory = Utilities.RelativePathTo(projectLocation, dockerBuildWorkingDirectory); } var dockerBuildOptions = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerBuildOptions, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, false); var fullDockerfilePath = Path.Combine(projectLocation, dockerFile); if (!Path.IsPathRooted(fullDockerfilePath)) { fullDockerfilePath = Path.Combine(dockerBuildWorkingDirectory, fullDockerfilePath); } // The Docker CLI gives a poor error message if the Dockerfile does not exist. This does a preemptive check and gives a more // meaningful error message. if (!File.Exists(fullDockerfilePath)) { throw new ToolsException($"Error failed to find file \"{fullDockerfilePath}\" to build the Docker image", ToolsException.CommonErrorCode.DockerBuildFailed); } if (ExecuteDockerBuild(dockerCli, dockerBuildWorkingDirectory, fullDockerfilePath, dockerImageTag, dockerBuildOptions) != 0) { throw new ToolsException("Error executing \"docker build\"", ToolsException.CommonErrorCode.DockerBuildFailed); } } protected virtual int ExecuteDockerBuild(DockerCLIWrapper dockerCli, string dockerBuildWorkingDirectory, string fullDockerfilePath, string dockerImageTag, string dockerBuildOptions) { return dockerCli.Build(dockerBuildWorkingDirectory, fullDockerfilePath, dockerImageTag, dockerBuildOptions); } private async Task PushToECR(DockerCLIWrapper dockerCli, string sourceDockerImageTag, string destinationDockerImageTag) { var sourceRepoInfo = SplitImageTag(sourceDockerImageTag); await InitiateDockerLogin(dockerCli); var splitDestinationTag = SplitImageTag(destinationDockerImageTag); Repository repository = await SetupECRRepository(splitDestinationTag.RepositoryName); var targetTag = repository.RepositoryUri + ":" + splitDestinationTag.Tag; this.Logger?.WriteLine($"Taging image {sourceRepoInfo.FullTagName} with {destinationDockerImageTag}"); if (dockerCli.Tag(sourceRepoInfo.FullTagName, targetTag) != 0) { throw new ToolsException("Error executing \"docker tag\"", ToolsException.CommonErrorCode.DockerTagFail); } this.Logger?.WriteLine("Pushing image to ECR repository"); if (dockerCli.Push(targetTag) != 0) { throw new ToolsException("Error executing \"docker push\"", ToolsException.CommonErrorCode.DockerPushFail); } this.PushedImageUri = targetTag; this.Logger?.WriteLine($"Image {this.PushedImageUri} Push Complete. "); } public static RepoInfo SplitImageTag(string imageTag) { int pos = imageTag.IndexOf(':'); if(pos == -1) { return new RepoInfo(imageTag, "latest"); } string repo = imageTag.Substring(0, pos); string tag; // If the imageTag ended in a semicolon then use latest as the tag if (pos + 1 == imageTag.Length) { tag = "latest"; } else { tag = imageTag.Substring(pos + 1); } return new RepoInfo(repo, tag); } protected virtual void BuildProject(string projectLocation, string configuration, string targetFramework, string publishOptions, string publishLocation) { this.EnsureInProjectDirectory(); var dotnetCli = new DotNetCLIWrapper(this.Logger, projectLocation); this.Logger?.WriteLine("Executing publish command"); if (dotnetCli.Publish(projectLocation, publishLocation, targetFramework, configuration, publishOptions) != 0) { throw new ToolsException("Error executing \"dotnet publish\"", ToolsException.CommonErrorCode.DotnetPublishFailed); } } private async Task<Repository> SetupECRRepository(string ecrRepositoryName) { try { DescribeRepositoriesResponse describeResponse = null; try { describeResponse = await this.ECRClient.DescribeRepositoriesAsync(new DescribeRepositoriesRequest { RepositoryNames = new List<string> { ecrRepositoryName } }); } catch (Exception e) { if (!(e is RepositoryNotFoundException)) { throw; } } Repository repository; if (describeResponse != null && describeResponse.Repositories.Count == 1) { this.Logger?.WriteLine($"Found existing ECR Repository {ecrRepositoryName}"); repository = describeResponse.Repositories[0]; } else { this.Logger?.WriteLine($"Creating ECR Repository {ecrRepositoryName}"); repository = (await this.ECRClient.CreateRepositoryAsync(new CreateRepositoryRequest { RepositoryName = ecrRepositoryName })).Repository; } return repository; } catch (Exception e) { throw new ToolsException($"Error determining Amazon ECR repository: {e.Message}", ToolsException.CommonErrorCode.FailedToSetupECRRepository); } } private async Task InitiateDockerLogin(DockerCLIWrapper dockerCLI) { try { this.Logger?.WriteLine("Fetching ECR authorization token to use to login with the docker CLI"); var response = await this.ECRClient.GetAuthorizationTokenAsync(new GetAuthorizationTokenRequest()); var authTokenBytes = Convert.FromBase64String(response.AuthorizationData[0].AuthorizationToken); var authToken = Encoding.UTF8.GetString(authTokenBytes); var decodedTokens = authToken.Split(':'); this.Logger?.WriteLine("Executing docker CLI login command"); if (dockerCLI.Login(decodedTokens[0], decodedTokens[1], response.AuthorizationData[0].ProxyEndpoint) != 0) { throw new ToolsException($"Error executing the docker login command", ToolsException.CommonErrorCode.DockerCLILoginFail); } } catch (ToolsException) { throw; } catch (Exception e) { throw new ToolsException($"Error logging on with the docker CLI: {e.Message}", ToolsException.CommonErrorCode.GetECRAuthTokens); } } protected override void SaveConfigFile(JsonData data) { this.PushDockerImageProperties.PersistSettings(this, data); } public static DockerDetails InspectDockerFile(IToolLogger logger, string projectLocation, string dockerfile) { var details = new DockerDetails(); var projectFilename = DetermineProjectFile(projectLocation); var dockerFilePath = Path.Combine(projectLocation, dockerfile); if (File.Exists(dockerFilePath)) { logger?.WriteLine("Inspecting Dockerfile to figure how to build project and docker image"); using (var stream = File.OpenRead(dockerFilePath)) using (var reader = new StreamReader(stream)) { string line; while ((line = reader.ReadLine()) != null) { var noSpaceLine = line.Replace(" ", ""); if (noSpaceLine.StartsWith("COPY") && (noSpaceLine.EndsWith(".sln./") || (projectFilename != null && noSpaceLine.Contains("/" + projectFilename)))) { details.BuildFromSolutionDirectory = true; logger?.WriteLine("... Determined that docker build needs to be run from solution folder."); } } } } return details; } private static string DetermineProjectFile(string projectLocation) { var files = Directory.GetFiles(projectLocation, "*.csproj", SearchOption.TopDirectoryOnly); if (files.Length == 1) return Path.GetFileName(files[0]); files = Directory.GetFiles(projectLocation, "*.fsproj", SearchOption.TopDirectoryOnly); if (files.Length == 1) return Path.GetFileName(files[0]); return null; } public static string DetermineSolutionDirectory(string projectLocation) { if (Directory.GetFiles(projectLocation, "*.sln", SearchOption.TopDirectoryOnly).Length != 0) return projectLocation; var parent = Directory.GetParent(projectLocation)?.FullName; if (parent == null) throw new ToolsException("Unable to determine directory for the solution", ToolsException.CommonErrorCode.FailedToFindSolutionDirectory); return DetermineSolutionDirectory(parent); } public class DockerDetails { public bool BuildFromSolutionDirectory { get; set; } } public class PushDockerImagePropertyContainer { public string Configuration { get; set; } public string TargetFramework { get; set; } public string PublishOptions { get; set; } public string DockerImageTag { get; set; } public string DockerBuildWorkingDirectory { get; set; } public string DockerBuildOptions { get; set; } public string DockerFile { get; set; } public string HostBuildOutput { get; set; } public string LocalDockerImage { get; set; } public void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.Switch)) != null) this.Configuration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS.Switch)) != null) this.PublishOptions = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY.Switch)) != null) this.DockerBuildWorkingDirectory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS.Switch)) != null) this.DockerBuildOptions = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE.Switch)) != null) this.DockerFile = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT.Switch)) != null) this.HostBuildOutput = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_LOCAL_DOCKER_IMAGE.Switch)) != null) this.LocalDockerImage = tuple.Item2.StringValue; // Check the --image-tag or the old obsolete --tag for an ECR Image tag. if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG.Switch)) != null) this.DockerImageTag = tuple.Item2.StringValue; else if (string.IsNullOrEmpty(this.DockerImageTag) && (tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG_OBSOLETE.Switch)) != null) this.DockerImageTag = tuple.Item2.StringValue; } public void PersistSettings(BaseCommand<TDefaultConfig> command, JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.ConfigFileKey, command.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, command.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS.ConfigFileKey, command.GetStringValueOrDefault(this.PublishOptions, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE.ConfigFileKey, command.GetStringValueOrDefault(this.DockerFile, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, false)); var tag = command.GetStringValueOrDefault(this.DockerImageTag, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG, false); if (!string.IsNullOrEmpty(tag)) { // Strip the full ECR URL name of form - protocol://aws_account_id.dkr.ecr.region.amazonaws.domain/repository:tag // irrespective of domain int dkrPos = tag.IndexOf(".dkr.ecr"); if (dkrPos != -1) { tag = tag.Substring(dkrPos + 1); int pos = tag.IndexOf('/'); if (pos != -1) { tag = tag.Substring(pos + 1); } } data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG.ConfigFileKey, tag); } data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY.ConfigFileKey, command.GetStringValueOrDefault(this.DockerBuildWorkingDirectory, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS.ConfigFileKey, command.GetStringValueOrDefault(this.DockerBuildOptions, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT.ConfigFileKey, command.GetStringValueOrDefault(this.HostBuildOutput, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, false)); } } public class RepoInfo { public RepoInfo(string repositoryName, string tag) { this.RepositoryName = repositoryName; this.Tag = tag ?? "latest"; } public string RepositoryName { get; } public string Tag { get; set; } public string FullTagName { get { return $"{this.RepositoryName}:{this.Tag}"; } } } } }
547
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace Amazon.Common.DotNetCli.Tools.Commands { public interface ICommandInfo { string Name { get; } string Description { get; } string Argument { get; } IList<CommandOption> CommandOptions { get; } ICommand CreateCommand(IToolLogger logger, string workingDirectory, string[] args); }; public class GroupHeaderInfo : ICommandInfo { public GroupHeaderInfo(string name) { this.Name = name; } public string Name { get; } public string Description { get; } public string Argument { get; } public IList<CommandOption> CommandOptions { get; } public ICommand CreateCommand(IToolLogger logger, string workingDirectory, string[] args) { return null; } } public class CommandInfo<T> : ICommandInfo where T : class, ICommand { public CommandInfo(string name, string description, IList<CommandOption> commandOptions) { this.Name = name; this.Description = description; this.CommandOptions = commandOptions; } public CommandInfo(string name, string description, IList<CommandOption> commandOptions, string argument) : this(name, description, commandOptions) { this.Argument = argument; } public string Name { get; } public string Description { get; } public string Argument { get; } public IList<CommandOption> CommandOptions { get; } public ICommand CreateCommand(IToolLogger logger, string workingDirectory, string[] args) { var typeClient = typeof(T); var constructor = typeClient.GetConstructor(new Type[] { typeof(IToolLogger), typeof(string), typeof(string[]) }); if (constructor == null) throw new Exception($"Command Type {typeClient.FullName} is missing constructor"); return constructor.Invoke(new object[] { logger, workingDirectory, args }) as T; } } }
71
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.Common.DotNetCli.Tools.Commands { /// <summary> /// Interface for commands to implement. /// </summary> public interface ICommand { /// <summary> /// If enabled the tool will prompt for required fields if they are not already given. /// </summary> bool DisableInteractive { get; set; } Task<bool> ExecuteAsync(); } }
21
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; namespace Amazon.Common.DotNetCli.Tools.Options { public static class CommandLineParser { /// <summary> /// Parse all the command line arguments. /// </summary> /// <param name="options"></param> /// <param name="arguments"></param> /// <returns></returns> public static CommandOptions ParseArguments( IList<CommandOption> options, string[] arguments) { CommandOptions values = new CommandOptions(); for (int i = 0; i < arguments.Length; i++) { // Collect arguments that are not attached to a switch. This is currently always the function name. if (arguments[i].StartsWith("-")) { var option = FindCommandOption(options, arguments[i]); if (option != null) { var value = new CommandOptionValue(); if (option.ValueType != CommandOption.CommandOptionValueType.NoValue) { if (i + 1 >= arguments.Length) { throw new ToolsException($"Argument {arguments[i]} must be followed by a value", ToolsException.CommonErrorCode.CommandLineParseError); } switch (option.ValueType) { case CommandOption.CommandOptionValueType.StringValue: case CommandOption.CommandOptionValueType.JsonValue: value.StringValue = arguments[i + 1]; break; case CommandOption.CommandOptionValueType.CommaDelimitedList: value.StringValues = arguments[i + 1].SplitByComma(); break; case CommandOption.CommandOptionValueType.KeyValuePairs: value.KeyValuePairs = Utilities.ParseKeyValueOption(arguments[i + 1]); break; case CommandOption.CommandOptionValueType.IntValue: int iv; if (!int.TryParse(arguments[i + 1], out iv)) throw new Exception($"Argument {arguments[i]} expects an integer value but received an {arguments[i + 1]}"); value.IntValue = iv; break; case CommandOption.CommandOptionValueType.BoolValue: bool bv; if (!bool.TryParse(arguments[i + 1], out bv)) throw new Exception($"Argument {arguments[i]} expects either {bool.TrueString} or {bool.FalseString} value but received an {arguments[i + 1]}"); value.BoolValue = bv; break; } i++; } values.AddOption(option, value); } } // Arguments starting /p: are msbuild parameters that should be passed into the dotnet package command else if (arguments[i].StartsWith("/p:")) { if (string.IsNullOrEmpty(values.MSBuildParameters)) { values.MSBuildParameters = arguments[i]; } else { values.MSBuildParameters += " " + arguments[i]; } } else { values.Arguments.Add(arguments[i]); } } return values; } private static CommandOption FindCommandOption(IEnumerable<CommandOption> options, string argument) { var option = options.FirstOrDefault(x => { if (string.Equals(argument, x.ShortSwitch, StringComparison.OrdinalIgnoreCase) || string.Equals(argument, x.Switch, StringComparison.OrdinalIgnoreCase)) return true; return false; }); return option; } } }
107
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.Common.DotNetCli.Tools.Options { /// <summary> /// The definitionn of an option for a command. /// </summary> public class CommandOption { /// <summary> /// An enum for the possible values for an option /// </summary> public enum CommandOptionValueType { NoValue, StringValue, BoolValue, IntValue, CommaDelimitedList, KeyValuePairs, JsonValue } /// <summary> /// The name of the option. /// </summary> public string Name { get; set; } /// <summary> /// The short form of the command line switch. This will start with just one dash e.g. -f for framework /// </summary> public string ShortSwitch { get; set; } /// <summary> /// The full form of the command line switch. This will start with two dashes e.g. --framework /// </summary> public string Switch { get; set; } /// <summary> /// The description of the option /// </summary> public string Description { get; set; } /// <summary> /// The type of value that is expected with this command option /// </summary> public CommandOptionValueType ValueType { get; set; } /// <summary> /// The JSON key used in configuration file.` /// </summary> public string ConfigFileKey { get { var key = this.Switch; if (key.StartsWith("--")) key = key.Substring(2); return key; } } } }
60
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.Common.DotNetCli.Tools.Options { /// <summary> /// Container for all the command options /// </summary> public class CommandOptions { Dictionary<CommandOption, CommandOptionValue> _values = new Dictionary<CommandOption, CommandOptionValue>(); public int Count { get { return this._values.Count; } } /// <summary> /// Gets the list of command line arguments that are not associated with a command option. Currently /// the only valid value for this is function name. /// </summary> public IList<string> Arguments { get; } = new List<string>(); /// <summary> /// Adds a CommandOption along with its value /// </summary> /// <param name="option"></param> /// <param name="value"></param> public void AddOption(CommandOption option, CommandOptionValue value) { _values[option] = value; } /// <summary> /// Gets the command option along with its value. The argument is searched for using both the short switch and the full switch. /// </summary> /// <param name="argument"></param> /// <returns></returns> public Tuple<CommandOption, CommandOptionValue> FindCommandOption(string argument) { var option = _values.Keys.FirstOrDefault(x => { if (string.Equals(argument, x.ShortSwitch, StringComparison.OrdinalIgnoreCase) || string.Equals(argument, x.Switch, StringComparison.OrdinalIgnoreCase)) return true; return false; }); if (option == null) return null; return new Tuple<CommandOption, CommandOptionValue>(option, _values[option]); } /// <summary> /// MSBuild parameters that will be passed to the 'dotnet publish' command /// </summary> public string MSBuildParameters { get; set; } } }
65
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.Common.DotNetCli.Tools.Options { /// <summary> /// Container class for the actual value of the CommandOption /// </summary> public class CommandOptionValue { /// <summary> /// This will be set if the CommandOption is of type string /// </summary> public string StringValue { get; set; } /// <summary> /// This will be set if the CommandOption is of type CommaDelimitedList /// </summary> public string[] StringValues { get; set; } /// <summary> /// This will be set if the CommandOption is of type KeyValuePairs /// </summary> public Dictionary<string, string> KeyValuePairs { get;set; } /// <summary> /// This will be set if the CommandOption is of type bool /// </summary> public bool BoolValue { get; set; } /// <summary> /// This will be set if the CommandOption is of type int /// </summary> public int IntValue { get; set; } } }
38
aws-extensions-for-dotnet-cli
aws
C#
 using System; using System.Collections.Generic; using System.Text; namespace Amazon.Common.DotNetCli.Tools.Options { public static class CommonDefinedCommandOptions { public static readonly CommandOption ARGUMENT_CONFIGURATION = new CommandOption { Name = "Build Configuration", ShortSwitch = "-c", Switch = "--configuration", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Configuration to build with, for example Release or Debug.", }; public static readonly CommandOption ARGUMENT_FRAMEWORK = new CommandOption { Name = "Framework", ShortSwitch = "-f", Switch = "--framework", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Target framework to compile, for example netcoreapp3.1.", }; public static readonly CommandOption ARGUMENT_SELF_CONTAINED = new CommandOption { Name = "Self Contained", Switch = "--self-contained", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If true a self contained deployment bundle including the targeted .NET runtime will be created.", }; public static readonly CommandOption ARGUMENT_PUBLISH_OPTIONS = new CommandOption { Name = "Publish Options", ShortSwitch = "-po", Switch = "--publish-options", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Additional options passed to the \"dotnet publish\" command.", }; public static readonly CommandOption ARGUMENT_DISABLE_INTERACTIVE = new CommandOption { Name = "Disable Interactive", Switch = "--disable-interactive", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "When set to true missing required parameters will not be prompted for." }; public static readonly CommandOption ARGUMENT_AWS_PROFILE = new CommandOption { Name = "AWS Profile", Switch = "--profile", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Profile to use to look up AWS credentials, if not set environment credentials will be used." }; public static readonly CommandOption ARGUMENT_AWS_PROFILE_LOCATION = new CommandOption { Name = "AWS Profile Location", Switch = "--profile-location", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Optional override to the search location for Profiles, points at a shared credentials file." }; public static readonly CommandOption ARGUMENT_AWS_ACCESS_KEY_ID = new CommandOption { Name = "AWS Access Key ID", Switch = "--aws-access-key-id", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The AWS access key id. Used when setting credentials explicitly instead of using --profile." }; public static readonly CommandOption ARGUMENT_AWS_SECRET_KEY = new CommandOption { Name = "AWS Secret Key", Switch = "--aws-secret-key", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The AWS secret key. Used when setting credentials explicitly instead of using --profile." }; public static readonly CommandOption ARGUMENT_AWS_SESSION_TOKEN = new CommandOption { Name = "AWS Access Key ID", Switch = "--aws-session-token", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The AWS session token. Used when setting credentials explicitly instead of using --profile." }; public static readonly CommandOption ARGUMENT_AWS_REGION = new CommandOption { Name = "AWS Region", Switch = "--region", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The region to connect to AWS services, if not set region will be detected from the environment." }; public static readonly CommandOption ARGUMENT_PROJECT_LOCATION = new CommandOption { Name = "Project Location", ShortSwitch = "-pl", Switch = "--project-location", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The location of the project, if not set the current directory will be assumed." }; public static readonly CommandOption ARGUMENT_MSBUILD_PARAMETERS = new CommandOption { Name = "MSBuild Parameters", Switch = "--msbuild-parameters", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Additional msbuild parameters passed to the 'dotnet publish' command. Add quotes around the value if the value contains spaces.", }; public static readonly CommandOption ARGUMENT_CONFIG_FILE = new CommandOption { Name = "Config File", ShortSwitch = "-cfg", Switch = "--config-file", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"Configuration file storing default values for command line arguments." }; public static readonly CommandOption ARGUMENT_PERSIST_CONFIG_FILE = new CommandOption { Name = "Persist Config File", ShortSwitch = "-pcfg", Switch = "--persist-config-file", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = $"If true the arguments used for a successful deployment are persisted to a config file." }; public static readonly CommandOption ARGUMENT_DOCKER_TAG = new CommandOption { Name = "Docker Image Tag", ShortSwitch = "-it", Switch = "--image-tag", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Name and optionally a tag in the 'name:tag' format.", }; public static readonly CommandOption ARGUMENT_DOCKER_TAG_OBSOLETE = new CommandOption { Name = "Docker Image Tag", ShortSwitch = "-t", Switch = "--tag", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Obsolete. This has been replaced with the --image-tag switch.", }; public static readonly CommandOption ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY = new CommandOption { Name = "Docker Build Working Directory", ShortSwitch = "-dbwd", Switch = "--docker-build-working-dir", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The directory to execute the \"docker build\" command from.", }; public static readonly CommandOption ARGUMENT_DOCKER_BUILD_OPTIONS = new CommandOption { Name = "Docker Build Options", ShortSwitch = "-dbo", Switch = "--docker-build-options", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Additional options passed to the \"docker build\" command.", }; public static readonly CommandOption ARGUMENT_DOCKERFILE = new CommandOption { Name = "Dockerfile", ShortSwitch = "-df", Switch = "--dockerfile", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The docker file used to build the image. Default value is \"{Constants.DEFAULT_DOCKERFILE}\".", }; public static readonly CommandOption ARGUMENT_LOCAL_DOCKER_IMAGE = new CommandOption { Name = "Local Docker Image", ShortSwitch = "-ldi", Switch = "--local-docker-image", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "If set the docker build command is skipped and the indicated local image is pushed to ECR.", }; public static readonly CommandOption ARGUMENT_HOST_BUILD_OUTPUT = new CommandOption { Name = "Host Build Output Directory", Switch = "--docker-host-build-output-dir", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "If set a \"dotnet publish\" command is executed on the host machine before executing \"docker build\". The output can be copied into image being built.", }; } }
215
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Amazon.ECS.Tools { public static class Constants { public const string TOOLNAME = "AWSECSToolsDotnet"; public static readonly string ECS_DEFAULT_SERVICE_POLICY = @" { ""Version"": ""2012-10-17"", ""Statement"": [ { ""Effect"": ""Allow"", ""Action"": [ ""ec2:AuthorizeSecurityGroupIngress"", ""ec2:Describe*"", ""elasticloadbalancing:DeregisterInstancesFromLoadBalancer"", ""elasticloadbalancing:DeregisterTargets"", ""elasticloadbalancing:Describe*"", ""elasticloadbalancing:RegisterInstancesWithLoadBalancer"", ""elasticloadbalancing:RegisterTargets"" ], ""Resource"": ""*"" } ] } ".Trim(); } }
37
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.ECS.Tools { /// <summary> /// This class defines all the possible options across all the commands. The individual commands will then /// references the options that are appropiate. /// </summary> public static class ECSDefinedCommandOptions { public static readonly CommandOption ARGUMENT_DOCKER_TAG = new CommandOption { Name = "Docker Image Tag", ShortSwitch = "-t", Switch = "--tag", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Name and optionally a tag in the 'name:tag' format.", }; public static readonly CommandOption ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY = new CommandOption { Name = "Docker Build Working Directory", ShortSwitch = "-dbwd", Switch = "--docker-build-working-dir", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The directory to execute the \"docker build\" command from.", }; public static readonly CommandOption ARGUMENT_DOCKER_BUILD_OPTIONS = new CommandOption { Name = "Docker Build Options", ShortSwitch = "-dbo", Switch = "--docker-build-options", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Additional options passed to the \"docker build\" command.", }; public static readonly CommandOption ARGUMENT_SKIP_IMAGE_PUSH = new CommandOption { Name = "Skip Image Push", ShortSwitch = "-sip", Switch = "--skip-image-push", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "Skip building and push an image to Amazon ECR.", }; public static readonly CommandOption ARGUMENT_ECS_CLUSTER = new CommandOption { Name = "Cluster Name", ShortSwitch = "-ec", Switch = "--cluster", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Name of the ECS Cluster to run the docker image.", }; public static readonly CommandOption ARGUMENT_LAUNCH_TYPE = new CommandOption { Name = "Launch Type", ShortSwitch = "-lt", Switch = "--launch-type", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The launch type on which to run tasks. Valid values EC2 | FARGATE.", }; public static readonly CommandOption ARGUMENT_LAUNCH_SUBNETS = new CommandOption { Name = "Launch VPC Subnets", ShortSwitch = "-ls", Switch = "--launch-subnets", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Comma delimited list of subnet ids used when launch type is FARGATE", }; public static readonly CommandOption ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP = new CommandOption { Name = "Assign Public IP Address", Switch = "--assign-public-ip", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If true a public IP address is assigned to the task when launch type is FARGATE", }; public static readonly CommandOption ARGUMENT_LAUNCH_SECURITYGROUPS = new CommandOption { Name = "Launch Type", ShortSwitch = "-lsg", Switch = "--launch-security-groups", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Comma delimited list of security group ids used when launch type is FARGATE", }; public static readonly CommandOption ARGUMENT_ECS_SERVICE = new CommandOption { Name = "Service Name", ShortSwitch = "-cs", Switch = "--cluster-service", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Name of the service to run on the ECS Cluster.", }; public static readonly CommandOption ARGUMENT_ECS_DESIRED_COUNT = new CommandOption { Name = "Desired Count", ShortSwitch = "-dc", Switch = "--desired-count", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The number of instantiations of the task to place and keep running in your service. Default is 1.", }; public static readonly CommandOption ARGUMENT_ECS_TASK_COUNT = new CommandOption { Name = "Task Count", ShortSwitch = "-tc", Switch = "--task-count", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The number of instantiations of the task to place and keep running in your service. Default is 1.", }; public static readonly CommandOption ARGUMENT_TD_EXECUTION_ROLE = new CommandOption { Name = "Task Definition Execution Role", Switch = "--task-execution-role", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The IAM role ECS assumes to pull images from ECR and publish logs to CloudWatch Logs. Fargate only." }; public static readonly CommandOption ARGUMENT_TD_CPU = new CommandOption { Name = "Task Definition Allocated CPU", Switch = "--task-cpu", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The amount of cpu to allocate for the task definition. Fargate only." }; public static readonly CommandOption ARGUMENT_TD_MEMORY = new CommandOption { Name = "Task Definition Allocated Memory", Switch = "--task-memory", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The amount of memory to allocated for the task definition. Fargate only." }; public static readonly CommandOption ARGUMENT_ELB_TARGET_GROUP_ARN = new CommandOption { Name = "ELB Target ARN", ShortSwitch = "-etg", Switch = "--elb-target-group", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The full Amazon Resource Name (ARN) of the Elastic Load Balancing target group associated with a service. " }; public static readonly CommandOption ARGUMENT_TD_PLATFORM_VERSION = new CommandOption { Name = "Task Platform version", Switch = "--platform-version", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The platform version selected for the task. Fargate only." }; public static readonly CommandOption ARGUMENT_ELB_CONTAINER_PORT = new CommandOption { Name = "ELB Container Port", ShortSwitch = "-ecp", Switch = "--elb-container-port", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The port on the container to associate with the load balancer." }; public static readonly CommandOption ARGUMENT_DEPLOYMENT_MAXIMUM_PERCENT = new CommandOption { Name = "Deployment Maximum Percent", Switch = "--deployment-maximum-percent", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The upper limit of the number of tasks that are allowed in the RUNNING or PENDING state in a service during a deployment." }; public static readonly CommandOption ARGUMENT_DEPLOYMENT_MINIMUM_HEALTHY_PERCENT = new CommandOption { Name = "Deployment Minimum Healhy Percent", Switch = "--deployment-minimum-healthy-percent", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The lower limit of the number of running tasks that must remain in the RUNNING state in a service during a deployment." }; public static readonly CommandOption ARGUMENT_ELB_SERVICE_ROLE = new CommandOption { Name = "ELB Service Role", Switch = "--elb-service-role", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The name or (ARN) of the IAM role that allows ECS to make calls to the load balancer." }; public static readonly CommandOption ARGUMENT_SCHEDULED_RULE_NAME = new CommandOption { Name = "Scheduled Rule", Switch = "--rule", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The name of the CloudWatch Event Schedule rule." }; public static readonly CommandOption ARGUMENT_SCHEDULED_RULE_TARGET = new CommandOption { Name = "Schedule Rule Target", Switch = "--rule-target", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The name of the target that will be assigned to the rule and point to the ECS task definition." }; public static readonly CommandOption ARGUMENT_SCHEDULE_EXPRESSION = new CommandOption { Name = "Schedule Expression", Switch = "--schedule-expression", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The scheduling expression. For example, \"cron(0 20 * * ? *)\" or \"rate(5 minutes)\"." }; public static readonly CommandOption ARGUMENT_CLOUDWATCHEVENT_ROLE = new CommandOption { Name = "CloudWatch Event IAM Role", Switch = "--cloudwatch-event-role", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The role that IAM will assume to invoke the target." }; public static readonly CommandOption ARGUMENT_ECS_TASK_GROUP = new CommandOption { Name = "Task Group", Switch = "--task-group", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The task group to associate with the task. The default value is the family name of the task definition." }; public static readonly CommandOption ARGUMENT_PLACEMENT_CONSTRAINTS = new CommandOption { Name = "Placement Constraints", Switch = "--placement-constraints", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Placement constraint to use for tasks in service. Format is <type>=<optional expression>,...", }; public static readonly CommandOption ARGUMENT_PLACEMENT_STRATEGY = new CommandOption { Name = "Placement Strategy", Switch = "--placement-strategy", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Placement strategy to use for tasks in service. Format is <type>=<optional field>,...", }; // Properties for defining a task definition public static readonly CommandOption ARGUMENT_CONTAINER_COMMANDS = new CommandOption { Name = "Command", Switch = "--container-command", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "A comma delimited list of commands to pass to the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_CPU = new CommandOption { Name = "Container CPU", Switch = "--container-cpu", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The number of cpu units reserved for the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_DISABLE_NETWORKING = new CommandOption { Name = "Container Disable Networking", Switch = "--container-disable-networking", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "When this parameter is true, networking is disabled within the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_DNS_SEARCH_DOMAINS = new CommandOption { Name = "Container DNS Search-Domains", Switch = "--container-dns-search-domains", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "A comma delimited of DNS search domains that are presented to the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_DNS_SERVERS = new CommandOption { Name = "Container DNS Servers", Switch = "--container-dns-servers", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "A comma delimited of DNS servers that are presented to the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_DOCKER_LABELS = new CommandOption { Name = "Container Docker Labels", Switch = "--container-docker-labels", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "Labels to add to the container. Format is <key1>=<value1>;<key2>=<value2>.", }; public static readonly CommandOption ARGUMENT_CONTAINER_DOCKER_SECURITY_OPTIONS = new CommandOption { Name = "Container Docker Security Options", Switch = "--container-docker-security-options", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems.", }; public static readonly CommandOption ARGUMENT_CONTAINER_ENTRY_POINT = new CommandOption { Name = "Container Entry Point", Switch = "--container-entry-point", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "The entry point that is passed to the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_ENVIRONMENT_VARIABLES = new CommandOption { Name = "Container Environment Variables", Switch = "--container-environment-variables", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "Environment variables for a container definition. Format is <key1>=<value1>;<key2>=<value2>." }; public static readonly CommandOption ARGUMENT_CONTAINER_ESSENTIAL = new CommandOption { Name = "Container is Essential", Switch = "--container-is-essential", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If true, and that container fails, all other containers that are part of the task are stopped.", }; public static readonly CommandOption ARGUMENT_CONTAINER_EXTRA_HOSTS = new CommandOption { Name = "Container Extra Hosts", Switch = "--container-extra-hosts", ValueType = CommandOption.CommandOptionValueType.JsonValue, Description = "Hostnames and IP address entries that are added to the /etc/hosts file of a container. Format is JSON string." }; public static readonly CommandOption ARGUMENT_CONTAINER_HOSTNAME = new CommandOption { Name = "Container Hostname", Switch = "--container-hostname", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The hostname to use for your container." }; public static readonly CommandOption ARGUMENT_CONTAINER_LINKS = new CommandOption { Name = "Container Links", Switch = "--container-links", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Comma delimited list of container names to communicate without the need for port mapping." }; public static readonly CommandOption ARGUMENT_CONTAINER_LINUX_PARAMETERS = new CommandOption { Name = "Container Linux Parameters", Switch = "--container-linux-parameters", ValueType = CommandOption.CommandOptionValueType.JsonValue, Description = "The Linux capabilities for the container that are added to or dropped. Format is JSON string." }; public static readonly CommandOption ARGUMENT_CONTAINER_LOG_CONFIGURATION = new CommandOption { Name = "Container Log Configuration", Switch = "--container-log-configuration", ValueType = CommandOption.CommandOptionValueType.JsonValue, Description = "The log driver to use for the container. Format is JSON string." }; public static readonly CommandOption ARGUMENT_CONTAINER_MEMORY_HARD_LIMIT = new CommandOption { Name = "Container Memory Hard Limit", Switch = "--container-memory-hard-limit", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The hard limit (in MiB) of memory to present to the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_MEMORY_SOFT_LIMIT = new CommandOption { Name = "Container Memory Soft Limit", Switch = "--container-memory-soft-limit", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The soft limit (in MiB) of memory to reserve for the container.", }; public static readonly CommandOption ARGUMENT_CONTAINER_MOUNT_POINTS = new CommandOption { Name = "Container Mount Points", Switch = "--container-mount-points", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "The mount points for data volumes in your container. Format is JSON string." }; public static readonly CommandOption ARGUMENT_CONTAINER_NAME = new CommandOption { Name = "Container Name", Switch = "--container-name", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Name of the Container in a Task Definition to be created/updated.", }; public static readonly CommandOption ARGUMENT_CONTAINER_PORT_MAPPING = new CommandOption { Name = "Container Port Mapping", Switch = "--container-port-mapping", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "The mapping of ports. Format is <host-port>:<container-port>,...", }; public static readonly CommandOption ARGUMENT_CONTAINER_PRIVILEGED = new CommandOption { Name = "Container Privileged", Switch = "--container-privileged", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If true, the container is given elevated privileges on the host container instance" }; public static readonly CommandOption ARGUMENT_CONTAINER_READONLY_ROOT_FILESYSTEM = new CommandOption { Name = "Container Readonly Root Filesystem", Switch = "--container-readonly-root-filesystem", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If true, the container is given read-only access to its root file system." }; public static readonly CommandOption ARGUMENT_CONTAINER_ULIMITS = new CommandOption { Name = "Container ULimits", Switch = "--container-ulimits", ValueType = CommandOption.CommandOptionValueType.JsonValue, Description = "The ulimit settings to pass to the container. Format is JSON string." }; public static readonly CommandOption ARGUMENT_CONTAINER_USER = new CommandOption { Name = "Container User", Switch = "--container-user", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The user name to use inside the container." }; public static readonly CommandOption ARGUMENT_CONTAINER_VOLUMES_FROM = new CommandOption { Name = "Container Volumes From", Switch = "--container-ulimits", ValueType = CommandOption.CommandOptionValueType.JsonValue, Description = "Details on a data volume from another container in the same task definition. Format is JSON string." }; public static readonly CommandOption ARGUMENT_CONTAINER_WORKING_DIRECTORY = new CommandOption { Name = "Container Working Directory", Switch = "--container-working-directory", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The working directory in which to run commands inside the container." }; public static readonly CommandOption ARGUMENT_TD_NAME = new CommandOption { Name = "Task Definition Name", Switch = "--task-definition-name", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Name of the ECS Task Defintion to be created or updated.", }; public static readonly CommandOption ARGUMENT_TD_NETWORK_MODE = new CommandOption { Name = "Task Definition Network Mode", Switch = "--task-definition-network-mode", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The Docker networking mode to use for the containers in the task." }; public static readonly CommandOption ARGUMENT_TD_ROLE = new CommandOption { Name = "Task Definition Role", Switch = "--task-definition-task-role", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The IAM role that will provide AWS credentials for the containers in the Task Definition." }; public static readonly CommandOption ARGUMENT_TD_VOLUMES = new CommandOption { Name = "Task Definition Volumes", Switch = "--task-definition-volumes", ValueType = CommandOption.CommandOptionValueType.JsonValue, Description = "Volume definitions that containers in your task may use. Format is JSON string." }; } }
517
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; using System.Threading.Tasks; using Amazon.ECS.Tools.Commands; using ThirdParty.Json.LitJson; using Amazon.Common.DotNetCli.Tools; namespace Amazon.ECS.Tools { /// <summary> /// This class gives access to the default values for the CommandOptions defined in the project's default json file. /// </summary> public class ECSToolsDefaults : DefaultConfigFile { public const string DEFAULT_FILE_NAME = "aws-ecs-tools-defaults.json"; public ECSToolsDefaults() { } public ECSToolsDefaults(string sourceFile) : this(new JsonData(), sourceFile) { } public ECSToolsDefaults(JsonData data, string sourceFile) : base(data, sourceFile) { } public override string DefaultConfigFileName => DEFAULT_FILE_NAME; } }
41
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.ECR; using Amazon.ECR.Model; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Amazon.EC2.Model; using Amazon.ECS.Model; using Amazon.IdentityManagement.Model; using Amazon.ECS.Tools.Commands; using Amazon.CloudWatchLogs.Model; using Amazon.CloudWatchLogs; using ThirdParty.Json.LitJson; using System.Linq; using Task = System.Threading.Tasks.Task; namespace Amazon.ECS.Tools { public static class ECSUtilities { public static List<PlacementConstraint> ConvertPlacementConstraint(string[] values) { if (values == null || values.Length == 0) return null; var list = new List<PlacementConstraint>(); foreach(var value in values) { var tokens = value.Split('='); var constraint = new PlacementConstraint { Type = tokens[0] }; if (tokens.Length > 1) constraint.Expression = tokens[1]; list.Add(constraint); } return list; } public static List<PlacementStrategy> ConvertPlacementStrategy(string[] values) { if (values == null || values.Length == 0) return null; var list = new List<PlacementStrategy>(); foreach (var value in values) { var tokens = value.Split('='); var constraint = new PlacementStrategy { Type = tokens[0] }; if (tokens.Length > 1) constraint.Field = tokens[1]; list.Add(constraint); } return list; } public static async Task<string> ExpandImageTagIfNecessary(IToolLogger logger, IAmazonECR ecrClient, string dockerImageTag) { try { if (dockerImageTag.Contains(".amazonaws.")) return dockerImageTag; string repositoryName = dockerImageTag; if (repositoryName.Contains(":")) repositoryName = repositoryName.Substring(0, repositoryName.IndexOf(':')); DescribeRepositoriesResponse describeResponse = null; try { describeResponse = await ecrClient.DescribeRepositoriesAsync(new DescribeRepositoriesRequest { RepositoryNames = new List<string> { repositoryName } }); } catch (Exception e) { if (!(e is RepositoryNotFoundException)) { throw; } } // Not found in ECR, assume pulling Docker Hub if (describeResponse == null) { return dockerImageTag; } var fullPath = describeResponse.Repositories[0].RepositoryUri + dockerImageTag.Substring(dockerImageTag.IndexOf(':')); logger?.WriteLine($"Determined full image name to be {fullPath}"); return fullPath; } catch (DockerToolsException) { throw; } catch (Exception e) { throw new DockerToolsException($"Error determining full repository path for the image {dockerImageTag}: {e.Message}", DockerToolsException.ECSErrorCode.FailedToExpandImageTag); } } public static async System.Threading.Tasks.Task EnsureClusterExistsAsync(IToolLogger logger, IAmazonECS ecsClient, string clusterName) { try { logger.WriteLine($"Checking to see if cluster {clusterName} exists"); var response = await ecsClient.DescribeClustersAsync(new DescribeClustersRequest { Clusters = new List<string> { clusterName } }); if (response.Clusters.Count == 0 || string.Equals(response.Clusters[0].Status, "INACTIVE", StringComparison.OrdinalIgnoreCase)) { logger.WriteLine($"... Cluster does not exist, creating cluster {clusterName}"); await ecsClient.CreateClusterAsync(new CreateClusterRequest { ClusterName = clusterName }); } } catch (DockerToolsException) { throw; } catch (Exception e) { throw new DockerToolsException($"Error ensuring ECS cluster {clusterName} exists: {e.Message}", DockerToolsException.ECSErrorCode.EnsureClusterExistsFail); } } public static async Task<string> CreateOrUpdateTaskDefinition(IToolLogger logger, IAmazonECS ecsClient, ECSBaseCommand command, TaskDefinitionProperties properties, string dockerImageTag, bool isFargate) { var ecsContainer = command.GetStringValueOrDefault(properties.ContainerName, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME, true); var ecsTaskDefinition = command.GetStringValueOrDefault(properties.TaskDefinitionName, ECSDefinedCommandOptions.ARGUMENT_TD_NAME, true); try { DescribeTaskDefinitionResponse response = null; try { response = await ecsClient.DescribeTaskDefinitionAsync(new DescribeTaskDefinitionRequest { TaskDefinition = ecsTaskDefinition }); } catch (Exception e) { if (!(e is ClientException)) { throw; } } var registerRequest = new RegisterTaskDefinitionRequest() { Family = ecsTaskDefinition }; if (response == null || response.TaskDefinition == null) { logger?.WriteLine("Creating new task definition"); } else { logger?.WriteLine("Updating existing task definition"); registerRequest.ContainerDefinitions = response.TaskDefinition.ContainerDefinitions; registerRequest.Cpu = response.TaskDefinition.Cpu; registerRequest.ExecutionRoleArn = response.TaskDefinition.ExecutionRoleArn; registerRequest.Memory = response.TaskDefinition.Memory; registerRequest.NetworkMode = response.TaskDefinition.NetworkMode; registerRequest.PlacementConstraints = response.TaskDefinition.PlacementConstraints; registerRequest.RequiresCompatibilities = response.TaskDefinition.RequiresCompatibilities; registerRequest.TaskRoleArn = response.TaskDefinition.TaskRoleArn; registerRequest.Volumes = response.TaskDefinition.Volumes; } var networkMode = command.GetStringValueOrDefault(properties.TaskDefinitionNetworkMode, ECSDefinedCommandOptions.ARGUMENT_TD_NETWORK_MODE, false); if (!string.IsNullOrEmpty(networkMode)) { registerRequest.NetworkMode = networkMode; } { JsonData volumes = command.GetJsonValueOrDefault(properties.TaskDefinitionVolumes, ECSDefinedCommandOptions.ARGUMENT_TD_VOLUMES); if (volumes != null) { foreach (JsonData item in volumes) { var volume = new Amazon.ECS.Model.Volume(); if (item["host"] != null) { volume.Host = new HostVolumeProperties(); volume.Host.SourcePath = item["host"]["sourcePath"] != null ? item["host"]["sourcePath"].ToString() : null; } volume.Name = item["name"] != null ? item["name"].ToString() : null; } } } var taskIAMRole = command.GetStringValueOrDefault(properties.TaskDefinitionRole, ECSDefinedCommandOptions.ARGUMENT_TD_ROLE, false); if (!string.IsNullOrWhiteSpace(taskIAMRole)) { registerRequest.TaskRoleArn = taskIAMRole; } var containerDefinition = registerRequest.ContainerDefinitions.FirstOrDefault(x => string.Equals(x.Name, ecsContainer, StringComparison.Ordinal)); if (containerDefinition == null) { logger?.WriteLine("Creating new container definition"); containerDefinition = new ContainerDefinition { Name = ecsContainer }; registerRequest.ContainerDefinitions.Add(containerDefinition); } containerDefinition.Image = dockerImageTag; { var containerCommands = command.GetStringValuesOrDefault(properties.ContainerCommands, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_COMMANDS, false); if (containerCommands != null && containerCommands.Length > 0) { containerDefinition.Command = new List<string>(containerCommands); } } { var disableNetworking = command.GetBoolValueOrDefault(properties.ContainerDisableNetworking, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DISABLE_NETWORKING, false); if (disableNetworking.HasValue) { containerDefinition.DisableNetworking = disableNetworking.Value; } } { var dnsSearchServers = command.GetStringValuesOrDefault(properties.ContainerDNSSearchDomains, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SEARCH_DOMAINS, false); if (dnsSearchServers != null && dnsSearchServers.Length > 0) { containerDefinition.DnsSearchDomains = new List<string>(dnsSearchServers); } } { var dnsServers = command.GetStringValuesOrDefault(properties.ContainerDNSServers, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SERVERS, false); if (dnsServers != null && dnsServers.Length > 0) { containerDefinition.DnsServers = new List<string>(dnsServers); } } { var labels = command.GetKeyValuePairOrDefault(properties.ContainerDockerLabels, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_LABELS, false); if (labels != null && labels.Count > 0) { containerDefinition.DockerLabels = new Dictionary<string, string>(labels); } } { var options = command.GetStringValuesOrDefault(properties.ContainerDockerSecurityOptions, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_SECURITY_OPTIONS, false); if (options != null && options.Length > 0) { containerDefinition.DockerSecurityOptions = new List<string>(options); } } { var entrypoints = command.GetStringValuesOrDefault(properties.ContainerEntryPoint, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENTRY_POINT, false); if (entrypoints != null && entrypoints.Length > 0) { containerDefinition.EntryPoint = new List<string>(entrypoints); } } { var environmentVariables = command.GetKeyValuePairOrDefault(properties.ContainerEnvironmentVariables, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENVIRONMENT_VARIABLES, false); if (environmentVariables != null && environmentVariables.Count > 0) { var listEnv = new List<Amazon.ECS.Model.KeyValuePair>(); foreach (var e in environmentVariables) { listEnv.Add(new Amazon.ECS.Model.KeyValuePair { Name = e.Key, Value = e.Value }); } containerDefinition.Environment = listEnv; } } { var essential = command.GetBoolValueOrDefault(properties.ContainerEssential, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ESSENTIAL, false); if (essential.HasValue) { containerDefinition.Essential = essential.Value; } } { JsonData data = command.GetJsonValueOrDefault(properties.ContainerExtraHosts, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_EXTRA_HOSTS); if (data != null) { containerDefinition.ExtraHosts.Clear(); foreach (JsonData item in data) { var obj = new Amazon.ECS.Model.HostEntry(); obj.Hostname = item["hostname"] != null ? item["hostname"].ToString() : null; obj.IpAddress = item["ipAddress"] != null ? item["ipAddress"].ToString() : null; containerDefinition.ExtraHosts.Add(obj); } } } { var hostname = command.GetStringValueOrDefault(properties.ContainerHostname, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_HOSTNAME, false); if (!string.IsNullOrEmpty(hostname)) { containerDefinition.Hostname = hostname; } } { var links = command.GetStringValuesOrDefault(properties.ContainerLinks, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINKS, false); if (links != null && links.Length > 0) { containerDefinition.Links = new List<string>(links); } } { JsonData data = command.GetJsonValueOrDefault(properties.ContainerExtraHosts, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_EXTRA_HOSTS); if (data != null) { var linuxParameter = new LinuxParameters(); if (data["capabilities"] != null) { linuxParameter.Capabilities = new KernelCapabilities(); if (data["capabilities"]["drop"] != null) { foreach (var item in data["capabilities"]["drop"]) { linuxParameter.Capabilities.Drop.Add(item.ToString()); } } if (data["capabilities"]["add"] != null) { foreach (var item in data["capabilities"]["add"]) { linuxParameter.Capabilities.Add.Add(item.ToString()); } } } if (data["devices"] != null) { linuxParameter.Devices.Clear(); foreach (JsonData item in data["devices"]) { var device = new Device(); device.ContainerPath = item["containerPath"] != null ? item["containerPath"].ToString() : null; device.HostPath = item["hostPath"] != null ? item["hostPath"].ToString() : null; foreach (string permission in item["permissions"]) { device.Permissions.Add(permission); } linuxParameter.Devices.Add(device); } } if (data["initProcessEnabled"] != null && data["initProcessEnabled"].IsBoolean) linuxParameter.InitProcessEnabled = (bool)data["initProcessEnabled"]; containerDefinition.LinuxParameters = linuxParameter; } } { JsonData data = command.GetJsonValueOrDefault(properties.ContainerLogConfiguration, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LOG_CONFIGURATION); if (data != null) { containerDefinition.LogConfiguration = new LogConfiguration(); containerDefinition.LogConfiguration.LogDriver = null; // Added support for logDriver JSON key as fix for legacy bug where JSON key containerPath was used. if (data["logDriver"] != null) { containerDefinition.LogConfiguration.LogDriver = data["logDriver"].ToString(); } else if (data["containerPath"] != null) // Retained legacy containerPath JSON key support. Removing this would break existing customers. { containerDefinition.LogConfiguration.LogDriver = data["containerPath"].ToString(); } if (data["options"] != null) { foreach (var key in data["options"].PropertyNames) { containerDefinition.LogConfiguration.Options[key] = data["options"][key].ToString(); } } } } { var hardLimit = command.GetIntValueOrDefault(properties.ContainerMemoryHardLimit, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_HARD_LIMIT, false); if (hardLimit.HasValue) { logger?.WriteLine($"Setting container hard memory limit {hardLimit.Value}MiB"); containerDefinition.Memory = hardLimit.Value; } } { var softLimit = command.GetIntValueOrDefault(properties.ContainerMemorySoftLimit, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_SOFT_LIMIT, false); if (softLimit.HasValue) { logger?.WriteLine($"Setting container soft memory limit {softLimit.Value}MiB"); containerDefinition.MemoryReservation = softLimit.Value; } } { JsonData data = command.GetJsonValueOrDefault(properties.ContainerMountPoints, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MOUNT_POINTS); if (data != null) { containerDefinition.MountPoints.Clear(); foreach (JsonData item in data) { var mountPoint = new MountPoint(); mountPoint.ContainerPath = item["containerPath"] != null ? item["containerPath"].ToString() : null; mountPoint.ContainerPath = item["sourceVolume"] != null ? item["sourceVolume"].ToString() : null; if (item["readOnly"] != null && item["readOnly"].IsBoolean) { mountPoint.ReadOnly = (bool)item["readOnly"]; } containerDefinition.MountPoints.Add(mountPoint); } } } { var portMappings = command.GetStringValuesOrDefault(properties.ContainerPortMappings, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PORT_MAPPING, false); if (portMappings != null) { containerDefinition.PortMappings = new List<PortMapping>(); foreach (var mapping in portMappings) { var tokens = mapping.Split(':'); if (tokens.Length != 2) { throw new DockerToolsException($"Port mapping {mapping} is invalid. Format should be <host-port>:<container-port>,<host-port>:<container-port>,...", DockerToolsException.CommonErrorCode.CommandLineParseError); } int hostPort = !isFargate ? int.Parse(tokens[0]) : int.Parse(tokens[1]); logger?.WriteLine($"Adding port mapping host {hostPort} to container {tokens[1]}"); containerDefinition.PortMappings.Add(new PortMapping { HostPort = hostPort, ContainerPort = int.Parse(tokens[1]) }); } } } { var privileged = command.GetBoolValueOrDefault(properties.ContainerPrivileged, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PRIVILEGED, false); if (privileged.HasValue) { containerDefinition.Privileged = privileged.Value; } } { var readonlyFilesystem = command.GetBoolValueOrDefault(properties.ContainerReadonlyRootFilesystem, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_READONLY_ROOT_FILESYSTEM, false); if (readonlyFilesystem.HasValue) { containerDefinition.ReadonlyRootFilesystem = readonlyFilesystem.Value; } } { JsonData data = command.GetJsonValueOrDefault(properties.ContainerUlimits, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ULIMITS); if (data != null) { containerDefinition.Ulimits.Clear(); foreach (JsonData item in data) { var ulimit = new Ulimit(); ulimit.Name = item["name"] != null ? item["name"].ToString() : null; if (item["hardLimit"] != null && item["hardLimit"].IsInt) { ulimit.HardLimit = (int)item["hardLimit"]; } if (item["softLimit"] != null && item["softLimit"].IsInt) { ulimit.HardLimit = (int)item["softLimit"]; } containerDefinition.Ulimits.Add(ulimit); } } } { var containerUser = command.GetStringValueOrDefault(properties.ContainerUser, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_USER, false); if (!string.IsNullOrEmpty(containerUser)) { containerDefinition.User = containerUser; } } { JsonData data = command.GetJsonValueOrDefault(properties.ContainerVolumesFrom, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_VOLUMES_FROM); if (data != null) { containerDefinition.VolumesFrom.Clear(); foreach (JsonData item in data) { var volume = new VolumeFrom(); volume.SourceContainer = item["sourceContainer"] != null ? item["sourceContainer"].ToString() : null; if (item["readOnly"] != null && item["readOnly"].IsBoolean) { volume.ReadOnly = (bool)item["readOnly"]; } containerDefinition.VolumesFrom.Add(volume); } } } { var workingDirectory = command.GetStringValueOrDefault(properties.ContainerWorkingDirectory, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_WORKING_DIRECTORY, false); if (!string.IsNullOrEmpty(workingDirectory)) { containerDefinition.WorkingDirectory = workingDirectory; } } if (isFargate) { if (registerRequest.NetworkMode != null && registerRequest.NetworkMode != NetworkMode.Awsvpc) { logger?.WriteLine("Setting network mode to \"awsvpc\" which is required to launch fargate based tasks"); } registerRequest.NetworkMode = NetworkMode.Awsvpc; if (registerRequest.RequiresCompatibilities == null) registerRequest.RequiresCompatibilities = new List<string>(); if (!registerRequest.RequiresCompatibilities.Contains("FARGATE")) registerRequest.RequiresCompatibilities.Add("FARGATE"); registerRequest.Memory = command.GetStringValueOrDefault(properties.TaskMemory, ECSDefinedCommandOptions.ARGUMENT_TD_MEMORY, true); registerRequest.Cpu = command.GetStringValueOrDefault(properties.TaskCPU, ECSDefinedCommandOptions.ARGUMENT_TD_CPU, true); var taskExecutionRole = command.GetStringValueOrDefault(properties.TaskDefinitionExecutionRole, ECSDefinedCommandOptions.ARGUMENT_TD_EXECUTION_ROLE, false); if (!string.IsNullOrEmpty(taskExecutionRole)) { registerRequest.ExecutionRoleArn = taskExecutionRole; } else if (string.IsNullOrEmpty(registerRequest.ExecutionRoleArn)) // If this is a redeployment check to see if the role was already set in a previous deployment. { if (string.IsNullOrEmpty(registerRequest.ExecutionRoleArn)) { registerRequest.ExecutionRoleArn = await EnsureTaskExecutionRoleExists(logger, command); } } } else { registerRequest.ExecutionRoleArn = null; } if (registerRequest.NetworkMode != NetworkMode.Awsvpc) { registerRequest.RequiresCompatibilities.Clear(); } if (containerDefinition.LogConfiguration == null || containerDefinition.LogConfiguration.LogDriver == LogDriver.Awslogs) { string defaultLogGroup = "/ecs/" + ecsTaskDefinition + "/" + containerDefinition.Name; if (containerDefinition.LogConfiguration == null) containerDefinition.LogConfiguration = new LogConfiguration() { LogDriver = "awslogs" }; if (containerDefinition.LogConfiguration.Options == null) containerDefinition.LogConfiguration.Options = new Dictionary<string, string>(); var options = containerDefinition.LogConfiguration.Options; options["awslogs-group"] = (options.ContainsKey("awslogs-group") && !string.IsNullOrWhiteSpace(options["awslogs-group"]) ? options["awslogs-group"] : defaultLogGroup); options["awslogs-region"] = (options.ContainsKey("awslogs-region") && !string.IsNullOrWhiteSpace(options["awslogs-region"]) ? options["awslogs-region"] : command.DetermineAWSRegion().SystemName); options["awslogs-stream-prefix"] = (options.ContainsKey("awslogs-stream-prefix") && !string.IsNullOrWhiteSpace(options["awslogs-stream-prefix"]) ? options["awslogs-stream-prefix"] : "ecs"); await EnsureLogGroupExistsAsync(logger, command.CWLClient, options["awslogs-group"]); logger?.WriteLine("Configured ECS to log to the CloudWatch Log Group " + options["awslogs-group"]); } var registerResponse = await ecsClient.RegisterTaskDefinitionAsync(registerRequest); logger?.WriteLine($"Registered new task definition revision {registerResponse.TaskDefinition.Revision}"); return registerResponse.TaskDefinition.TaskDefinitionArn; } catch (DockerToolsException) { throw; } catch (Exception e) { throw new DockerToolsException($"Error updating ECS task definition {ecsTaskDefinition}: {e.Message}", DockerToolsException.ECSErrorCode.FailedToUpdateTaskDefinition); } } public static async System.Threading.Tasks.Task EnsureLogGroupExistsAsync(IToolLogger logger, IAmazonCloudWatchLogs cwlClient, string logGroup) { try { var response = await cwlClient.DescribeLogGroupsAsync(new DescribeLogGroupsRequest { LogGroupNamePrefix = logGroup }); if (response.LogGroups.FirstOrDefault(x => string.Equals(logGroup, x.LogGroupName, StringComparison.Ordinal)) != null) { logger?.WriteLine("Found existing log group " + logGroup + " for container"); return; } } catch (Exception e) { throw new DockerToolsException("Error checking log group " + logGroup + " existed for the container: " + e.Message, DockerToolsException.ECSErrorCode.LogGroupDescribeFailed); } try { await cwlClient.CreateLogGroupAsync(new CreateLogGroupRequest { LogGroupName = logGroup }); logger?.WriteLine("Created log group " + logGroup + " for the container"); } catch (Exception e) { throw new DockerToolsException("Failed to create log group " + logGroup + " for the container: " + e.Message, DockerToolsException.ECSErrorCode.LogGroupCreateFailed); } } private const string DEFAULT_ECS_TASK_EXECUTION_ROLE = "ecsTaskExecutionRole"; public static async Task<string> EnsureTaskExecutionRoleExists(IToolLogger logger, ECSBaseCommand command) { bool roleExists = false; try { var request = new GetRoleRequest { RoleName = DEFAULT_ECS_TASK_EXECUTION_ROLE }; var response = await command.IAMClient.GetRoleAsync(request).ConfigureAwait(false); roleExists = true; logger.WriteLine("Task Execution role \"{0}\" already exists.", DEFAULT_ECS_TASK_EXECUTION_ROLE); } catch (Amazon.IdentityManagement.Model.NoSuchEntityException) { roleExists = false; } catch (Exception e) { logger.WriteLine("Error checking to make sure role \"ecsTaskExecutionRole\" exists, continuing on assuming the role exists: " + e.Message); } if (roleExists) return DEFAULT_ECS_TASK_EXECUTION_ROLE; logger.WriteLine("Creating default \"{0}\" IAM role.", DEFAULT_ECS_TASK_EXECUTION_ROLE); RoleHelper.CreateRole(command.IAMClient, DEFAULT_ECS_TASK_EXECUTION_ROLE, Amazon.Common.DotNetCli.Tools.Constants.ECS_TASKS_ASSUME_ROLE_POLICY, "CloudWatchLogsFullAccess", "AmazonEC2ContainerRegistryReadOnly"); return DEFAULT_ECS_TASK_EXECUTION_ROLE; } public static async System.Threading.Tasks.Task SetupAwsVpcNetworkConfigurationAsync(ECSBaseDeployCommand command, NetworkConfiguration networkConfiguration) { if (networkConfiguration.AwsvpcConfiguration == null) networkConfiguration.AwsvpcConfiguration = new AwsVpcConfiguration(); string defaultVpcId = null; bool noExistingSubnets = networkConfiguration.AwsvpcConfiguration.Subnets.Count == 0; var vpcSubnetWrapper = await SetupAwsVpcNetworkConfigurationSubnets(command, defaultVpcId, noExistingSubnets); var subnets = vpcSubnetWrapper.Subnets; defaultVpcId = vpcSubnetWrapper.VpcId; if (subnets != null) { networkConfiguration.AwsvpcConfiguration.Subnets = new List<string>(subnets); } bool noExistingSecurityGroups = networkConfiguration.AwsvpcConfiguration.SecurityGroups.Count == 0; var securityGroups = await SetupAwsVpcNetworkConfigurationSecurityGroups(command, defaultVpcId, noExistingSecurityGroups); if (securityGroups != null) { networkConfiguration.AwsvpcConfiguration.SecurityGroups = new List<string>(securityGroups); } var assignPublicIp = command.GetBoolValueOrDefault(command.ClusterProperties.AssignPublicIpAddress, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP, false); if (assignPublicIp.HasValue) { networkConfiguration.AwsvpcConfiguration.AssignPublicIp = assignPublicIp.Value ? AssignPublicIp.ENABLED : AssignPublicIp.DISABLED; } else if (networkConfiguration?.AwsvpcConfiguration?.AssignPublicIp == null) { // Enable by default if not set to make the common case easier networkConfiguration.AwsvpcConfiguration.AssignPublicIp = AssignPublicIp.ENABLED; command.Logger?.WriteLine("Enabling \"Assign Public IP\" for tasks"); } } public static async System.Threading.Tasks.Task SetupAwsVpcNetworkConfigurationCloudwatchEventAsync( ECSBaseDeployCommand command, Amazon.CloudWatchEvents.Model.NetworkConfiguration networkConfiguration) { if (networkConfiguration.AwsvpcConfiguration == null) networkConfiguration.AwsvpcConfiguration = new Amazon.CloudWatchEvents.Model.AwsVpcConfiguration(); string defaultVpcId = null; bool noExistingSubnets = networkConfiguration.AwsvpcConfiguration.Subnets.Count == 0; var vpcSubnetWrapper = await SetupAwsVpcNetworkConfigurationSubnets(command, defaultVpcId, noExistingSubnets); var subnets = vpcSubnetWrapper.Subnets; defaultVpcId = vpcSubnetWrapper.VpcId; if (subnets != null) { networkConfiguration.AwsvpcConfiguration.Subnets = new List<string>(subnets); } bool noExistingSecurityGroups = networkConfiguration.AwsvpcConfiguration.SecurityGroups.Count == 0; var securityGroups = await SetupAwsVpcNetworkConfigurationSecurityGroups(command, defaultVpcId, noExistingSecurityGroups); if (securityGroups != null) { networkConfiguration.AwsvpcConfiguration.SecurityGroups = new List<string>(securityGroups); } var assignPublicIp = command.GetBoolValueOrDefault(command.ClusterProperties.AssignPublicIpAddress, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP, false); if (assignPublicIp.HasValue) { networkConfiguration.AwsvpcConfiguration.AssignPublicIp = assignPublicIp.Value ? Amazon.CloudWatchEvents.AssignPublicIp.ENABLED : Amazon.CloudWatchEvents.AssignPublicIp.DISABLED; } else if(networkConfiguration?.AwsvpcConfiguration?.AssignPublicIp == null) { // Enable by default if not set to make the common case easier networkConfiguration.AwsvpcConfiguration.AssignPublicIp = Amazon.CloudWatchEvents.AssignPublicIp.ENABLED; command.Logger?.WriteLine("Enabling \"Assign Public IP\" for tasks"); } } private static async Task<VpcSubnetWrapper> SetupAwsVpcNetworkConfigurationSubnets(ECSBaseDeployCommand command, string defaultVpcId, bool noExistingSubnets) { var subnets = command.GetStringValuesOrDefault(command.ClusterProperties.SubnetIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS, false); if ((subnets == null || subnets.Length == 0) && noExistingSubnets) { command.Logger?.WriteLine("No subnets specified, looking for default VPC and subnets"); var defaultSubnets = new List<string>(); try { var describeSubnetResponse = await command.EC2Client.DescribeSubnetsAsync(); foreach (var subnet in describeSubnetResponse.Subnets) { if (subnet.DefaultForAz) { if (defaultVpcId == null) { command.Logger?.WriteLine("Default VPC: " + subnet.VpcId); defaultVpcId = subnet.VpcId; } command.Logger?.WriteLine($"... Using subnet {subnet.SubnetId} ({subnet.AvailabilityZone})"); defaultSubnets.Add(subnet.SubnetId); } } } catch (Exception e) { command.Logger?.WriteLine("Warning: Unable to determine default subnets for VPC: " + e.Message); } if (defaultSubnets.Count != 0) { subnets = defaultSubnets.ToArray(); } else { subnets = command.GetStringValuesOrDefault(command.ClusterProperties.SubnetIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS, true); } } return new VpcSubnetWrapper {VpcId = defaultVpcId, Subnets = subnets}; } private static async Task<string[]> SetupAwsVpcNetworkConfigurationSecurityGroups(ECSBaseDeployCommand command, string defaultVpcId, bool noExistingSecurityGroups) { var securityGroups = command.GetStringValuesOrDefault(command.ClusterProperties.SecurityGroupIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS, false); if ((securityGroups == null || securityGroups.Length==0) && noExistingSecurityGroups) { command.Logger?.WriteLine("No security group specified, looking for default VPC and security group"); if (defaultVpcId == null) { try { var describeVpcResponse = await command.EC2Client.DescribeVpcsAsync(); var defaultVpc = describeVpcResponse.Vpcs.FirstOrDefault(x => x.IsDefault); if (defaultVpc != null) { command.Logger?.WriteLine("Default VPC: " + defaultVpc.VpcId); defaultVpcId = defaultVpc.VpcId; } else { command.Logger?.WriteLine("Unable to determine default VPC"); } } catch (Exception e) { command.Logger?.WriteLine("Warning: Unable to determine default VPC: " + e.Message); } } if (defaultVpcId != null) { try { var describeSecurityGroupResponse = await command.EC2Client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest { Filters = new List<Filter> { new Filter { Name = "vpc-id", Values = new List<string> { defaultVpcId } } } }); var defaultSecurityGroup = describeSecurityGroupResponse.SecurityGroups.FirstOrDefault(x => string.Equals(x.GroupName, "default", StringComparison.OrdinalIgnoreCase)); if (defaultSecurityGroup != null) { securityGroups = new string[] { defaultSecurityGroup.GroupId }; command.Logger?.WriteLine("Using default security group " + defaultSecurityGroup.GroupId); } else { command.Logger?.WriteLine("Unable to determine default security group for VPC"); } } catch (Exception e) { command.Logger?.WriteLine("Warning: Unable to determine default security group for VPC: " + e.Message); } } if (securityGroups == null) { securityGroups = command.GetStringValuesOrDefault(command.ClusterProperties.SecurityGroupIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS, true); } } return securityGroups; } } public class VpcSubnetWrapper { public string VpcId { get; set; } public string[] Subnets { get; set; } } }
867
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Runtime; using Amazon.Common.DotNetCli.Tools; namespace Amazon.ECS.Tools { /// <summary> /// The deploy tool exception. This is used to throw back an error to the user but is considerd a known error /// so the stack trace will not be displayed. /// </summary> public class DockerToolsException : ToolsException { public enum ECSErrorCode { EnsureClusterExistsFail, FailedToUpdateTaskDefinition, FailedToExpandImageTag, FailedToUpdateService, ClusterNotFound, PutRuleFail, PutTargetFail, RunTaskFail, LogGroupDescribeFailed, LogGroupCreateFailed } public DockerToolsException(string message, ECSErrorCode code) : base(message, code.ToString(), null) { } public DockerToolsException(string message, CommonErrorCode code) : base(message, code.ToString(), null) { } public DockerToolsException(string message, ECSErrorCode code, Exception e) : base(message, code.ToString(), e) { } } }
49
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.ECS.Tools.Commands; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Amazon.Common.DotNetCli.Tools.CLi; namespace Amazon.ECS.Tools { class Program { static void Main(string[] args) { var application = new Application("ecs", "Amazon EC2 Container Service Tools for .NET Core applications", "https://github.com/aws/aws-extensions-for-dotnet-cli", new List<ICommandInfo>() { new GroupHeaderInfo("Commands to deploy to Amazon EC2 Container Service:"), new CommandInfo<DeployServiceCommand>(DeployServiceCommand.COMMAND_NAME, DeployServiceCommand.COMMAND_DESCRIPTION, DeployServiceCommand.CommandOptions), new CommandInfo<DeployTaskCommand>(DeployTaskCommand.COMMAND_NAME, DeployTaskCommand.COMMAND_DESCRIPTION, DeployTaskCommand.CommandOptions), new CommandInfo<DeployScheduledTaskCommand>(DeployScheduledTaskCommand.COMMAND_NAME, DeployScheduledTaskCommand.COMMAND_DESCRIPTION, DeployScheduledTaskCommand.CommandOptions), new GroupHeaderInfo("Commands to manage docker images to Amazon EC2 Container Registry:"), new CommandInfo<PushDockerImageCommand>(PushDockerImageCommand.COMMAND_NAME, PushDockerImageCommand.COMMAND_DESCRIPTION, PushDockerImageCommand.CommandOptions) }); var exitCode = application.Execute(args); if (exitCode != 0) { Environment.Exit(-1); } } } }
40
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Common.DotNetCli.Tools.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ThirdParty.Json.LitJson; namespace Amazon.ECS.Tools.Commands { public class PushDockerImageProperties { public string Configuration { get; set; } public string TargetFramework { get; set; } public string PublishOptions { get; set; } public string DockerImageTag { get; set; } public string DockerBuildWorkingDirectory { get; set; } public string DockerBuildOptions { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.Switch)) != null) this.Configuration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS.Switch)) != null) this.PublishOptions = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_DOCKER_TAG.Switch)) != null) this.DockerImageTag = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY.Switch)) != null) this.DockerBuildWorkingDirectory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS.Switch)) != null) this.DockerBuildOptions = tuple.Item2.StringValue; } internal void PersistSettings(ECSBaseCommand command, JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.ConfigFileKey, command.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, command.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS.ConfigFileKey, command.GetStringValueOrDefault(this.PublishOptions, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, false)); var tag = command.GetStringValueOrDefault(this.DockerImageTag, ECSDefinedCommandOptions.ARGUMENT_DOCKER_TAG, false); if (!string.IsNullOrEmpty(tag)) { // Strip the full ECR URL name of form - protocol://aws_account_id.dkr.ecr.region.amazonaws.domain/repository:tag // irrespective of domain int dkrPos = tag.IndexOf(".dkr.ecr"); if (dkrPos != -1) { tag = tag.Substring(dkrPos + 1); int pos = tag.IndexOf('/'); if (pos != -1) { tag = tag.Substring(pos + 1); } } data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_DOCKER_TAG.ConfigFileKey, tag); } data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY.ConfigFileKey, command.GetStringValueOrDefault(this.DockerBuildWorkingDirectory, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS.ConfigFileKey, command.GetStringValueOrDefault(this.DockerBuildOptions, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, false)); } } public class ClusterProperties { public string ECSCluster { get; set; } public string LaunchType { get; set; } public string[] SubnetIds { get; set; } public string[] SecurityGroupIds { get; set; } public bool? AssignPublicIpAddress { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ECS_CLUSTER.Switch)) != null) this.ECSCluster = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE.Switch)) != null) this.LaunchType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS.Switch)) != null) this.SubnetIds = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS.Switch)) != null) this.SecurityGroupIds = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP.Switch)) != null) this.AssignPublicIpAddress = tuple.Item2.BoolValue; } internal void PersistSettings(ECSBaseCommand command, JsonData data) { data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ECS_CLUSTER.ConfigFileKey, command.GetStringValueOrDefault(this.ECSCluster, ECSDefinedCommandOptions.ARGUMENT_ECS_CLUSTER, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE.ConfigFileKey, command.GetStringValueOrDefault(this.LaunchType, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.SubnetIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.SecurityGroupIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP.ConfigFileKey, command.GetBoolValueOrDefault(this.AssignPublicIpAddress, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP, false)); } } public class TaskDefinitionProperties { public static IList<CommandOption> CommandOptions = new List<CommandOption> { ECSDefinedCommandOptions.ARGUMENT_TD_NAME, ECSDefinedCommandOptions.ARGUMENT_TD_NETWORK_MODE, ECSDefinedCommandOptions.ARGUMENT_TD_ROLE, ECSDefinedCommandOptions.ARGUMENT_TD_EXECUTION_ROLE, ECSDefinedCommandOptions.ARGUMENT_TD_CPU, ECSDefinedCommandOptions.ARGUMENT_TD_MEMORY, ECSDefinedCommandOptions.ARGUMENT_TD_VOLUMES, ECSDefinedCommandOptions.ARGUMENT_TD_PLATFORM_VERSION, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_COMMANDS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_CPU, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DISABLE_NETWORKING, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SEARCH_DOMAINS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SERVERS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_LABELS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_SECURITY_OPTIONS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENTRY_POINT, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENVIRONMENT_VARIABLES, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ESSENTIAL, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_EXTRA_HOSTS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_HOSTNAME, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINKS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINUX_PARAMETERS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LOG_CONFIGURATION, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_HARD_LIMIT, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_SOFT_LIMIT, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MOUNT_POINTS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PORT_MAPPING, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PRIVILEGED, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_READONLY_ROOT_FILESYSTEM, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ULIMITS, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_USER, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_VOLUMES_FROM, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_WORKING_DIRECTORY, }; public string ContainerName { get; set; } public int? ContainerMemoryHardLimit { get; set; } public int? ContainerMemorySoftLimit { get; set; } public string[] ContainerCommands { get; set; } public bool? ContainerDisableNetworking { get; set; } public string[] ContainerDNSSearchDomains { get; set; } public string[] ContainerDNSServers { get; set; } public Dictionary<string, string> ContainerDockerLabels { get; set; } public string[] ContainerDockerSecurityOptions { get; set; } public string[] ContainerEntryPoint { get; set; } public Dictionary<string, string> ContainerEnvironmentVariables { get; set; } public bool? ContainerEssential { get; set; } public string ContainerExtraHosts { get; set; } public string ContainerHostname { get; set; } public string[] ContainerLinks { get; set; } public string ContainerLinuxParameters { get; set; } public string ContainerLogConfiguration { get; set; } public string ContainerMountPoints { get; set; } public string[] ContainerPortMappings { get; set; } public bool? ContainerPrivileged { get; set; } public bool? ContainerReadonlyRootFilesystem { get; set; } public string ContainerUlimits { get; set; } public string ContainerUser { get; set; } public string ContainerVolumesFrom { get; set; } public string ContainerWorkingDirectory { get; set; } public string TaskDefinitionName { get; set; } public string TaskDefinitionNetworkMode { get; set; } public string TaskDefinitionRole { get; set; } public string TaskDefinitionExecutionRole { get; set; } public string TaskCPU { get; set; } public string TaskMemory { get; set; } public string TaskDefinitionVolumes { get; set; } public string TaskPlatformVersion { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_TD_NAME.Switch)) != null) this.TaskDefinitionName = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_TD_NETWORK_MODE.Switch)) != null) this.TaskDefinitionNetworkMode = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_TD_ROLE.Switch)) != null) this.TaskDefinitionRole = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_TD_EXECUTION_ROLE.Switch)) != null) this.TaskDefinitionExecutionRole = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_TD_CPU.Switch)) != null) this.TaskCPU = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_TD_MEMORY.Switch)) != null) this.TaskMemory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_TD_PLATFORM_VERSION.Switch)) != null) this.TaskPlatformVersion = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_COMMANDS.Switch)) != null) this.ContainerCommands = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DISABLE_NETWORKING.Switch)) != null) this.ContainerDisableNetworking = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SEARCH_DOMAINS.Switch)) != null) this.ContainerDNSSearchDomains = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SERVERS.Switch)) != null) this.ContainerDNSServers = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_LABELS.Switch)) != null) this.ContainerDockerLabels = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_SECURITY_OPTIONS.Switch)) != null) this.ContainerDockerSecurityOptions = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENTRY_POINT.Switch)) != null) this.ContainerEntryPoint = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENVIRONMENT_VARIABLES.Switch)) != null) this.ContainerEnvironmentVariables = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ESSENTIAL.Switch)) != null) this.ContainerEssential = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_EXTRA_HOSTS.Switch)) != null) this.ContainerExtraHosts = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_HOSTNAME.Switch)) != null) this.ContainerHostname = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINKS.Switch)) != null) this.ContainerLinks = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINUX_PARAMETERS.Switch)) != null) this.ContainerLinuxParameters = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LOG_CONFIGURATION.Switch)) != null) this.ContainerLogConfiguration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MOUNT_POINTS.Switch)) != null) this.ContainerMountPoints = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PORT_MAPPING.Switch)) != null) this.ContainerPortMappings = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PRIVILEGED.Switch)) != null) this.ContainerPrivileged = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ULIMITS.Switch)) != null) this.ContainerUlimits = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_USER.Switch)) != null) this.ContainerUser = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_VOLUMES_FROM.Switch)) != null) this.ContainerVolumesFrom = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_WORKING_DIRECTORY.Switch)) != null) this.ContainerWorkingDirectory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME.Switch)) != null) this.ContainerName = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_HARD_LIMIT.Switch)) != null) this.ContainerMemoryHardLimit = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_SOFT_LIMIT.Switch)) != null) this.ContainerMemorySoftLimit = tuple.Item2.IntValue; } internal void PersistSettings(ECSBaseCommand command, JsonData data) { data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_NAME.ConfigFileKey, command.GetStringValueOrDefault(this.TaskDefinitionName, ECSDefinedCommandOptions.ARGUMENT_TD_NAME, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_NETWORK_MODE.ConfigFileKey, command.GetStringValueOrDefault(this.TaskDefinitionNetworkMode, ECSDefinedCommandOptions.ARGUMENT_TD_NETWORK_MODE, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_CPU.ConfigFileKey, command.GetStringValueOrDefault(this.TaskCPU, ECSDefinedCommandOptions.ARGUMENT_TD_CPU, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_MEMORY.ConfigFileKey, command.GetStringValueOrDefault(this.TaskMemory, ECSDefinedCommandOptions.ARGUMENT_TD_MEMORY, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_PLATFORM_VERSION.ConfigFileKey, command.GetStringValueOrDefault(this.TaskPlatformVersion, ECSDefinedCommandOptions.ARGUMENT_TD_PLATFORM_VERSION, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_ROLE.ConfigFileKey, command.GetStringValueOrDefault(this.TaskDefinitionRole, ECSDefinedCommandOptions.ARGUMENT_TD_ROLE, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_EXECUTION_ROLE.ConfigFileKey, command.GetStringValueOrDefault(this.TaskDefinitionExecutionRole, ECSDefinedCommandOptions.ARGUMENT_TD_EXECUTION_ROLE, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_TD_VOLUMES.ConfigFileKey, command.GetStringValueOrDefault(this.TaskDefinitionVolumes, ECSDefinedCommandOptions.ARGUMENT_TD_VOLUMES, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_COMMANDS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.ContainerCommands, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_COMMANDS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DISABLE_NETWORKING.ConfigFileKey, command.GetBoolValueOrDefault(this.ContainerDisableNetworking, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DISABLE_NETWORKING, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SEARCH_DOMAINS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.ContainerDNSSearchDomains, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SEARCH_DOMAINS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SERVERS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.ContainerDNSServers, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DNS_SERVERS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_LABELS.ConfigFileKey, ECSToolsDefaults.FormatKeyValue(command.GetKeyValuePairOrDefault(this.ContainerDockerLabels, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_LABELS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_SECURITY_OPTIONS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.ContainerDockerSecurityOptions, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_DOCKER_SECURITY_OPTIONS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENTRY_POINT.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.ContainerEntryPoint, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENTRY_POINT, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ESSENTIAL.ConfigFileKey, command.GetBoolValueOrDefault(this.ContainerEssential, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ESSENTIAL, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_EXTRA_HOSTS.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerExtraHosts, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_EXTRA_HOSTS, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_HOSTNAME.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerHostname, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_HOSTNAME, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINKS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.ContainerLinks, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINKS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINUX_PARAMETERS.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerLinuxParameters, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LINUX_PARAMETERS, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LOG_CONFIGURATION.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerLogConfiguration, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_LOG_CONFIGURATION, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MOUNT_POINTS.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerMountPoints, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MOUNT_POINTS, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PRIVILEGED.ConfigFileKey, command.GetBoolValueOrDefault(this.ContainerPrivileged, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PRIVILEGED, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_READONLY_ROOT_FILESYSTEM.ConfigFileKey, command.GetBoolValueOrDefault(this.ContainerReadonlyRootFilesystem, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_READONLY_ROOT_FILESYSTEM, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ULIMITS.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerUlimits, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ULIMITS, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_USER.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerUlimits, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_USER, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_VOLUMES_FROM.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerVolumesFrom, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_VOLUMES_FROM, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_WORKING_DIRECTORY.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerWorkingDirectory, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_WORKING_DIRECTORY, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME.ConfigFileKey, command.GetStringValueOrDefault(this.ContainerName, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_HARD_LIMIT.ConfigFileKey, command.GetIntValueOrDefault(this.ContainerMemoryHardLimit, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_HARD_LIMIT, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_SOFT_LIMIT.ConfigFileKey, command.GetIntValueOrDefault(this.ContainerMemorySoftLimit, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_MEMORY_SOFT_LIMIT, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PORT_MAPPING.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.ContainerPortMappings, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_PORT_MAPPING, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENVIRONMENT_VARIABLES.ConfigFileKey, ECSToolsDefaults.FormatKeyValue(command.GetKeyValuePairOrDefault(this.ContainerEnvironmentVariables, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_ENVIRONMENT_VARIABLES, false))); } } public class DeployServiceProperties { public bool SkipImagePush { get; set; } public string ECSService { get; set; } public int? DesiredCount { get; set; } public string[] PlacementConstraints { get; set; } public string[] PlacementStrategy { get; set; } public int? DeploymentMinimumHealthyPercent { get; set; } public int? DeploymentMaximumPercent { get; set; } public string ELBServiceRole { get; set; } public string ELBTargetGroup { get; set; } public int? ELBContainerPort { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH.Switch)) != null) this.SkipImagePush = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ECS_SERVICE.Switch)) != null) this.ECSService = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT.Switch)) != null) this.DesiredCount = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MINIMUM_HEALTHY_PERCENT.Switch)) != null) this.DeploymentMinimumHealthyPercent = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MAXIMUM_PERCENT.Switch)) != null) this.DeploymentMaximumPercent = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ELB_SERVICE_ROLE.Switch)) != null) this.ELBServiceRole = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ELB_TARGET_GROUP_ARN.Switch)) != null) this.ELBTargetGroup = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ELB_CONTAINER_PORT.Switch)) != null) this.ELBContainerPort = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS.Switch)) != null) this.PlacementConstraints = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY.Switch)) != null) this.PlacementStrategy = tuple.Item2.StringValues; } internal void PersistSettings(ECSBaseCommand command, JsonData data) { data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH.ConfigFileKey, command.GetBoolValueOrDefault(this.SkipImagePush, ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ECS_SERVICE.ConfigFileKey, command.GetStringValueOrDefault(this.ECSService, ECSDefinedCommandOptions.ARGUMENT_ECS_SERVICE, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT.ConfigFileKey, command.GetIntValueOrDefault(this.DesiredCount, ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MINIMUM_HEALTHY_PERCENT.ConfigFileKey, command.GetIntValueOrDefault(this.DeploymentMinimumHealthyPercent, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MINIMUM_HEALTHY_PERCENT, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MAXIMUM_PERCENT.ConfigFileKey, command.GetIntValueOrDefault(this.DeploymentMaximumPercent, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MAXIMUM_PERCENT, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ELB_SERVICE_ROLE.ConfigFileKey, command.GetStringValueOrDefault(this.ELBServiceRole, ECSDefinedCommandOptions.ARGUMENT_ELB_SERVICE_ROLE, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ELB_TARGET_GROUP_ARN.ConfigFileKey, command.GetStringValueOrDefault(this.ELBTargetGroup, ECSDefinedCommandOptions.ARGUMENT_ELB_TARGET_GROUP_ARN, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ELB_CONTAINER_PORT.ConfigFileKey, command.GetIntValueOrDefault(this.ELBContainerPort, ECSDefinedCommandOptions.ARGUMENT_ELB_CONTAINER_PORT, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.PlacementConstraints, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.PlacementStrategy, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY, false))); } } public class DeployTaskProperties { public bool SkipImagePush { get; set; } public string TaskGroup { get; set; } public int? TaskCount { get; set; } public string[] PlacementConstraints { get; set; } public string[] PlacementStrategy { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_COUNT.Switch)) != null) this.TaskCount = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS.Switch)) != null) this.PlacementConstraints = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY.Switch)) != null) this.PlacementStrategy = tuple.Item2.StringValues; } internal void PersistSettings(ECSBaseCommand command, JsonData data) { data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_GROUP.ConfigFileKey, command.GetStringValueOrDefault(this.TaskGroup, ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_GROUP, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_COUNT.ConfigFileKey, command.GetIntValueOrDefault(this.TaskCount, ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_COUNT, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.PlacementConstraints, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS, false))); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY.ConfigFileKey, ECSToolsDefaults.FormatCommaDelimitedList(command.GetStringValuesOrDefault(this.PlacementStrategy, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY, false))); } } public class DeployScheduledTaskProperties { public bool SkipImagePush { get; set; } public string ScheduleTaskRule { get; set; } public string ScheduleTaskRuleTarget { get; set; } public string ScheduleExpression { get; set; } public string CloudWatchEventIAMRole { get; set; } public int? DesiredCount { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_NAME.Switch)) != null) this.ScheduleTaskRule = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_TARGET.Switch)) != null) this.ScheduleTaskRuleTarget = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_SCHEDULE_EXPRESSION.Switch)) != null) this.ScheduleExpression = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_CLOUDWATCHEVENT_ROLE.Switch)) != null) this.CloudWatchEventIAMRole = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT.Switch)) != null) this.DesiredCount = tuple.Item2.IntValue; } internal void PersistSettings(ECSBaseCommand command, JsonData data) { data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_NAME.ConfigFileKey, command.GetStringValueOrDefault(this.ScheduleTaskRule, ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_NAME, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_TARGET.ConfigFileKey, command.GetStringValueOrDefault(this.ScheduleTaskRuleTarget, ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_TARGET, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_SCHEDULE_EXPRESSION.ConfigFileKey, command.GetStringValueOrDefault(this.ScheduleExpression, ECSDefinedCommandOptions.ARGUMENT_SCHEDULE_EXPRESSION, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_CLOUDWATCHEVENT_ROLE.ConfigFileKey, command.GetStringValueOrDefault(this.CloudWatchEventIAMRole, ECSDefinedCommandOptions.ARGUMENT_CLOUDWATCHEVENT_ROLE, false)); data.SetIfNotNull(ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT.ConfigFileKey, command.GetIntValueOrDefault(this.DesiredCount, ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT, false)); } } }
423
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Amazon.CloudWatchEvents; using Amazon.CloudWatchEvents.Model; using Amazon.ECR; using Amazon.ECR.Model; using Amazon.ECS; using Amazon.ECS.Model; using ThirdParty.Json.LitJson; using System.IO; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Common.DotNetCli.Tools; namespace Amazon.ECS.Tools.Commands { public class DeployScheduledTaskCommand : ECSBaseDeployCommand { public const string COMMAND_NAME = "deploy-scheduled-task"; public const string COMMAND_DESCRIPTION = "Push the application to ECR and then sets up CloudWatch Event Schedule rule to run the application."; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, ECSDefinedCommandOptions.ARGUMENT_DOCKER_TAG, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH, ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_NAME, ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_TARGET, ECSDefinedCommandOptions.ARGUMENT_SCHEDULE_EXPRESSION, ECSDefinedCommandOptions.ARGUMENT_CLOUDWATCHEVENT_ROLE, ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT }, TaskDefinitionProperties.CommandOptions); DeployScheduledTaskProperties _deployScheduledTaskProperties; public DeployScheduledTaskProperties DeployScheduledTaskProperties { get { if (this._deployScheduledTaskProperties == null) { this._deployScheduledTaskProperties = new DeployScheduledTaskProperties(); } return this._deployScheduledTaskProperties; } set { this._deployScheduledTaskProperties = value; } } public DeployScheduledTaskCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); this.PushDockerImageProperties.ParseCommandArguments(values); this.TaskDefinitionProperties.ParseCommandArguments(values); this.ClusterProperties.ParseCommandArguments(values); this.DeployScheduledTaskProperties.ParseCommandArguments(values); } protected override async Task<bool> PerformActionAsync() { var skipPush = this.GetBoolValueOrDefault(this.DeployScheduledTaskProperties.SkipImagePush, ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH, false).GetValueOrDefault(); var ecsContainer = this.GetStringValueOrDefault(this.TaskDefinitionProperties.ContainerName, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME, true); var ecsTaskDefinition = this.GetStringValueOrDefault(this.TaskDefinitionProperties.TaskDefinitionName, ECSDefinedCommandOptions.ARGUMENT_TD_NAME, true); var ecsPlatformVersion = this.GetStringValueOrDefault(this.TaskDefinitionProperties.TaskPlatformVersion, ECSDefinedCommandOptions.ARGUMENT_TD_PLATFORM_VERSION, false); this.PushDockerImageProperties.DockerImageTag = GetDockerImageTag(); if (!this.PushDockerImageProperties.DockerImageTag.Contains(":")) this.PushDockerImageProperties.DockerImageTag += ":latest"; if (skipPush) { this.PushDockerImageProperties.DockerImageTag = await ECSUtilities.ExpandImageTagIfNecessary(this.Logger, this.ECRClient, this.PushDockerImageProperties.DockerImageTag); } else { var pushCommand = new PushDockerImageCommand(this.Logger, this.WorkingDirectory, this.OriginalCommandLineArguments) { ConfigFile = this.ConfigFile, DisableInteractive = this.DisableInteractive, Credentials = this.Credentials, ECRClient = this.ECRClient, Profile = this.Profile, ProfileLocation = this.ProfileLocation, ProjectLocation = this.ProjectLocation, Region = this.Region, WorkingDirectory = this.WorkingDirectory, PushDockerImageProperties = this.PushDockerImageProperties, }; var success = await pushCommand.ExecuteAsync(); if (!success) return false; this.PushDockerImageProperties.DockerImageTag = pushCommand.PushedImageUri; } var taskDefinitionArn = await ECSUtilities.CreateOrUpdateTaskDefinition(this.Logger, this.ECSClient, this, this.TaskDefinitionProperties, this.PushDockerImageProperties.DockerImageTag, IsFargateLaunch(this.ClusterProperties.LaunchType)); var ecsCluster = this.GetStringValueOrDefault(this.ClusterProperties.ECSCluster, ECSDefinedCommandOptions.ARGUMENT_ECS_CLUSTER, true); await ECSUtilities.EnsureClusterExistsAsync(this.Logger, this.ECSClient, ecsCluster); if (!ecsCluster.Contains(":")) { var arnPrefix = taskDefinitionArn.Substring(0, taskDefinitionArn.LastIndexOf(":task")); ecsCluster = arnPrefix + ":cluster/" + ecsCluster; } var ruleName = this.GetStringValueOrDefault(this.DeployScheduledTaskProperties.ScheduleTaskRule, ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_NAME, true); var targetName = this.GetStringValueOrDefault(this.DeployScheduledTaskProperties.ScheduleTaskRuleTarget, ECSDefinedCommandOptions.ARGUMENT_SCHEDULED_RULE_TARGET, false); if (string.IsNullOrEmpty(targetName)) targetName = ruleName; var scheduleExpression = this.GetStringValueOrDefault(this.DeployScheduledTaskProperties.ScheduleExpression, ECSDefinedCommandOptions.ARGUMENT_SCHEDULE_EXPRESSION, true); var cweRole = this.GetStringValueOrDefault(this.DeployScheduledTaskProperties.CloudWatchEventIAMRole, ECSDefinedCommandOptions.ARGUMENT_CLOUDWATCHEVENT_ROLE, true); var desiredCount = this.GetIntValueOrDefault(this.DeployScheduledTaskProperties.DesiredCount, ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT, false); if (!desiredCount.HasValue) desiredCount = 1; var launchType = this.GetStringValueOrDefault(this.ClusterProperties.LaunchType, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, true); var ecsParameters = new EcsParameters { TaskCount = desiredCount.Value, TaskDefinitionArn = taskDefinitionArn, LaunchType = launchType }; if (IsFargateLaunch(this.ClusterProperties.LaunchType)) { var networkConfiguration = new Amazon.CloudWatchEvents.Model.NetworkConfiguration(); await ECSUtilities.SetupAwsVpcNetworkConfigurationCloudwatchEventAsync(this, networkConfiguration); ecsParameters.NetworkConfiguration = networkConfiguration; ecsParameters.PlatformVersion = ecsPlatformVersion; await this.AttemptToCreateServiceLinkRoleAsync(); } string ruleArn = null; try { ruleArn = (await this.CWEClient.PutRuleAsync(new PutRuleRequest { Name = ruleName, ScheduleExpression = scheduleExpression, State = RuleState.ENABLED })).RuleArn; this.Logger?.WriteLine($"Put CloudWatch Event rule {ruleName} with expression {scheduleExpression}"); } catch(Exception e) { throw new DockerToolsException("Error creating CloudWatch Event rule: " + e.Message, DockerToolsException.ECSErrorCode.PutRuleFail); } try { await this.CWEClient.PutTargetsAsync(new PutTargetsRequest { Rule = ruleName, Targets = new List<Target> { new Target { Arn = ecsCluster, RoleArn = cweRole, Id = targetName, EcsParameters = ecsParameters } } }); this.Logger?.WriteLine($"Put CloudWatch Event target {targetName}"); } catch (Exception e) { throw new DockerToolsException("Error creating CloudWatch Event target: " + e.Message, DockerToolsException.ECSErrorCode.PutTargetFail); } return true; } protected override void SaveConfigFile(JsonData data) { this.PushDockerImageProperties.PersistSettings(this, data); this.TaskDefinitionProperties.PersistSettings(this, data); this.ClusterProperties.PersistSettings(this, data); this.DeployScheduledTaskProperties.PersistSettings(this, data); } } }
213
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Task = System.Threading.Tasks.Task; using Amazon.ECR.Model; using Amazon.ECS.Model; using ThirdParty.Json.LitJson; using System.IO; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Common.DotNetCli.Tools; namespace Amazon.ECS.Tools.Commands { public class DeployServiceCommand : ECSBaseDeployCommand { public const string COMMAND_NAME = "deploy-service"; public const string COMMAND_DESCRIPTION = "Push the application to ECR and runs the application as a long lived service on the ECS Cluster."; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, ECSDefinedCommandOptions.ARGUMENT_DOCKER_TAG, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP, ECSDefinedCommandOptions.ARGUMENT_ECS_CLUSTER, ECSDefinedCommandOptions.ARGUMENT_ECS_SERVICE, ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MAXIMUM_PERCENT, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MINIMUM_HEALTHY_PERCENT, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY, ECSDefinedCommandOptions.ARGUMENT_ELB_SERVICE_ROLE, ECSDefinedCommandOptions.ARGUMENT_ELB_TARGET_GROUP_ARN, ECSDefinedCommandOptions.ARGUMENT_ELB_CONTAINER_PORT }, TaskDefinitionProperties.CommandOptions); DeployServiceProperties _deployServiceProperties; public DeployServiceProperties DeployServiceProperties { get { if (this._deployServiceProperties == null) { this._deployServiceProperties = new DeployServiceProperties(); } return this._deployServiceProperties; } set { this._deployServiceProperties = value; } } public bool OverrideIgnoreTargetGroup { get; set; } public DeployServiceCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); this.PushDockerImageProperties.ParseCommandArguments(values); this.TaskDefinitionProperties.ParseCommandArguments(values); this.ClusterProperties.ParseCommandArguments(values); this.DeployServiceProperties.ParseCommandArguments(values); } protected override async Task<bool> PerformActionAsync() { var skipPush = this.GetBoolValueOrDefault(this.DeployServiceProperties.SkipImagePush, ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH, false).GetValueOrDefault(); var ecsContainer = this.GetStringValueOrDefault(this.TaskDefinitionProperties.ContainerName, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME, true); var ecsTaskDefinition = this.GetStringValueOrDefault(this.TaskDefinitionProperties.TaskDefinitionName, ECSDefinedCommandOptions.ARGUMENT_TD_NAME, true); this.PushDockerImageProperties.DockerImageTag = GetDockerImageTag(); if (!this.PushDockerImageProperties.DockerImageTag.Contains(":")) this.PushDockerImageProperties.DockerImageTag += ":latest"; if(skipPush) { this.PushDockerImageProperties.DockerImageTag = await ECSUtilities.ExpandImageTagIfNecessary(this.Logger, this.ECRClient, this.PushDockerImageProperties.DockerImageTag); } else { var pushCommand = new PushDockerImageCommand(this.Logger, this.WorkingDirectory, this.OriginalCommandLineArguments) { ConfigFile = this.ConfigFile, DisableInteractive = this.DisableInteractive, Credentials = this.Credentials, ECRClient = this.ECRClient, Profile = this.Profile, ProfileLocation = this.ProfileLocation, ProjectLocation = this.ProjectLocation, Region = this.Region, WorkingDirectory = this.WorkingDirectory, PushDockerImageProperties = this.PushDockerImageProperties, }; var success = await pushCommand.ExecuteAsync(); if (!success) return false; this.PushDockerImageProperties.DockerImageTag = pushCommand.PushedImageUri; } var taskDefinitionArn = await ECSUtilities.CreateOrUpdateTaskDefinition(this.Logger, this.ECSClient, this, this.TaskDefinitionProperties, this.PushDockerImageProperties.DockerImageTag, IsFargateLaunch(this.ClusterProperties.LaunchType)); var ecsCluster = this.GetStringValueOrDefault(this.ClusterProperties.ECSCluster, ECSDefinedCommandOptions.ARGUMENT_ECS_CLUSTER, true); await ECSUtilities.EnsureClusterExistsAsync(this.Logger, this.ECSClient, ecsCluster); var ecsService = this.GetStringValueOrDefault(this.DeployServiceProperties.ECSService, ECSDefinedCommandOptions.ARGUMENT_ECS_SERVICE, true); await CreateOrUpdateService(ecsCluster, ecsService, taskDefinitionArn, ecsContainer); this.Logger?.WriteLine($"Service {ecsService} on ECS cluster {ecsCluster} has been updated. The Cluster will now deploy the new service version."); return true; } private async Task CreateOrUpdateService(string ecsCluster, string ecsService, string taskDefinitionArn, string ecsContainer) { try { var describeServiceResponse = await this.ECSClient.DescribeServicesAsync(new DescribeServicesRequest { Cluster = ecsCluster, Services = new List<string> { ecsService } }); var desiredCount = this.GetIntValueOrDefault(this.DeployServiceProperties.DesiredCount, ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT, false); var deploymentMaximumPercent = this.GetIntValueOrDefault(this.DeployServiceProperties.DeploymentMaximumPercent, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MAXIMUM_PERCENT, false); var deploymentMinimumHealthyPercent = this.GetIntValueOrDefault(this.DeployServiceProperties.DeploymentMinimumHealthyPercent, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MINIMUM_HEALTHY_PERCENT, false); var launchType = this.GetStringValueOrDefault(this.ClusterProperties.LaunchType, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, true); NetworkConfiguration networkConfiguration = null; if (IsFargateLaunch(this.ClusterProperties.LaunchType)) { if (describeServiceResponse.Services.Count != 0) networkConfiguration = describeServiceResponse.Services[0].NetworkConfiguration; else { networkConfiguration = new NetworkConfiguration(); } await ECSUtilities.SetupAwsVpcNetworkConfigurationAsync(this, networkConfiguration); } DeploymentConfiguration deploymentConfiguration = null; if (deploymentMaximumPercent.HasValue || deploymentMinimumHealthyPercent.HasValue) { deploymentConfiguration = new DeploymentConfiguration(); if (deploymentMaximumPercent.HasValue) deploymentConfiguration.MaximumPercent = deploymentMaximumPercent.Value; if (deploymentMinimumHealthyPercent.HasValue) deploymentConfiguration.MinimumHealthyPercent = deploymentMinimumHealthyPercent.Value; } if (describeServiceResponse.Services.Count == 0 || describeServiceResponse.Services[0].Status == "INACTIVE") { this.Logger?.WriteLine($"Creating new service: {ecsService}"); var request = new CreateServiceRequest { ClientToken = Guid.NewGuid().ToString(), Cluster = ecsCluster, ServiceName = ecsService, TaskDefinition = taskDefinitionArn, DesiredCount = desiredCount.HasValue ? desiredCount.Value : 1, DeploymentConfiguration = deploymentConfiguration, LaunchType = launchType, NetworkConfiguration = networkConfiguration }; if(IsFargateLaunch(this.ClusterProperties.LaunchType)) { await this.AttemptToCreateServiceLinkRoleAsync(); } else { request.PlacementConstraints = ECSUtilities.ConvertPlacementConstraint(this.GetStringValuesOrDefault(this.DeployServiceProperties.PlacementConstraints, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS, false)); request.PlacementStrategy = ECSUtilities.ConvertPlacementStrategy(this.GetStringValuesOrDefault(this.DeployServiceProperties.PlacementStrategy, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY, false)); } var elbTargetGroup = this.GetStringValueOrDefault(this.DeployServiceProperties.ELBTargetGroup, ECSDefinedCommandOptions.ARGUMENT_ELB_TARGET_GROUP_ARN, false); if (!this.OverrideIgnoreTargetGroup && !string.IsNullOrWhiteSpace(elbTargetGroup)) { if(!IsFargateLaunch(this.ClusterProperties.LaunchType)) { request.Role = this.GetStringValueOrDefault(this.DeployServiceProperties.ELBServiceRole, ECSDefinedCommandOptions.ARGUMENT_ELB_SERVICE_ROLE, false); } var port = this.GetIntValueOrDefault(this.DeployServiceProperties.ELBContainerPort, ECSDefinedCommandOptions.ARGUMENT_ELB_CONTAINER_PORT, false); if (!port.HasValue) port = 80; request.LoadBalancers.Add(new LoadBalancer { TargetGroupArn = elbTargetGroup, ContainerName = ecsContainer, ContainerPort = port.Value }); } try { await this.ECSClient.CreateServiceAsync(request); } catch(Amazon.ECS.Model.InvalidParameterException e) { if (e.Message.StartsWith("The target group") && !string.IsNullOrEmpty(elbTargetGroup) && string.IsNullOrEmpty(this.DeployServiceProperties.ELBTargetGroup)) { request.LoadBalancers.Clear(); request.Role = null; var defaultFile = string.IsNullOrEmpty(this.ConfigFile) ? ECSToolsDefaults.DEFAULT_FILE_NAME : this.ConfigFile; this.Logger?.WriteLine($"Warning: ELB Target Group ARN specified in config file {defaultFile} does not exist."); await this.ECSClient.CreateServiceAsync(request); } else { throw; } } } else { this.Logger?.WriteLine($"Updating new service: {ecsService}"); var updateRequest = new UpdateServiceRequest { Cluster = ecsCluster, Service = ecsService, TaskDefinition = taskDefinitionArn, DeploymentConfiguration = deploymentConfiguration, NetworkConfiguration = networkConfiguration }; if(desiredCount.HasValue) { updateRequest.DesiredCount = desiredCount.Value; } await this.ECSClient.UpdateServiceAsync(updateRequest); } } catch (DockerToolsException) { throw; } catch (Exception e) { throw new DockerToolsException($"Error updating ECS service {ecsService} on cluster {ecsCluster}: {e.Message}", DockerToolsException.ECSErrorCode.FailedToUpdateService); } } protected override void SaveConfigFile(JsonData data) { PushDockerImageProperties.PersistSettings(this, data); ClusterProperties.PersistSettings(this, data); TaskDefinitionProperties.PersistSettings(this, data); DeployServiceProperties.PersistSettings(this, data); } } }
297
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ThirdParty.Json.LitJson; namespace Amazon.ECS.Tools.Commands { public class DeployTaskCommand : ECSBaseDeployCommand { public const string COMMAND_NAME = "deploy-task"; public const string COMMAND_DESCRIPTION = "Push the application to ECR and then runs it as a task on the ECS Cluster."; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, ECSDefinedCommandOptions.ARGUMENT_DOCKER_TAG, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, ECSDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_ASSIGN_PUBLIC_IP, ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_COUNT, ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_GROUP, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY }, TaskDefinitionProperties.CommandOptions); DeployTaskProperties _deployTaskProperties; public DeployTaskProperties DeployTaskProperties { get { if (this._deployTaskProperties == null) { this._deployTaskProperties = new DeployTaskProperties(); } return this._deployTaskProperties; } set { this._deployTaskProperties = value; } } public DeployTaskCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); this.PushDockerImageProperties.ParseCommandArguments(values); this.TaskDefinitionProperties.ParseCommandArguments(values); this.ClusterProperties.ParseCommandArguments(values); this.DeployTaskProperties.ParseCommandArguments(values); } protected override async Task<bool> PerformActionAsync() { var skipPush = this.GetBoolValueOrDefault(this.DeployTaskProperties.SkipImagePush, ECSDefinedCommandOptions.ARGUMENT_SKIP_IMAGE_PUSH, false).GetValueOrDefault(); var ecsContainer = this.GetStringValueOrDefault(this.TaskDefinitionProperties.ContainerName, ECSDefinedCommandOptions.ARGUMENT_CONTAINER_NAME, true); var ecsTaskDefinition = this.GetStringValueOrDefault(this.TaskDefinitionProperties.TaskDefinitionName, ECSDefinedCommandOptions.ARGUMENT_TD_NAME, true); this.PushDockerImageProperties.DockerImageTag = GetDockerImageTag(); if (!this.PushDockerImageProperties.DockerImageTag.Contains(":")) this.PushDockerImageProperties.DockerImageTag += ":latest"; if (skipPush) { this.PushDockerImageProperties.DockerImageTag = await ECSUtilities.ExpandImageTagIfNecessary(this.Logger, this.ECRClient, this.PushDockerImageProperties.DockerImageTag); } else { var pushCommand = new PushDockerImageCommand(this.Logger, this.WorkingDirectory, this.OriginalCommandLineArguments) { ConfigFile = this.ConfigFile, DisableInteractive = this.DisableInteractive, Credentials = this.Credentials, ECRClient = this.ECRClient, Profile = this.Profile, ProfileLocation = this.ProfileLocation, ProjectLocation = this.ProjectLocation, Region = this.Region, WorkingDirectory = this.WorkingDirectory, PushDockerImageProperties = this.PushDockerImageProperties, }; var success = await pushCommand.ExecuteAsync(); if (!success) return false; this.PushDockerImageProperties.DockerImageTag = pushCommand.PushedImageUri; } var taskDefinitionArn = await ECSUtilities.CreateOrUpdateTaskDefinition(this.Logger, this.ECSClient, this, this.TaskDefinitionProperties, this.PushDockerImageProperties.DockerImageTag, IsFargateLaunch(this.ClusterProperties.LaunchType)); var ecsCluster = this.GetStringValueOrDefault(this.ClusterProperties.ECSCluster, ECSDefinedCommandOptions.ARGUMENT_ECS_CLUSTER, true); await ECSUtilities.EnsureClusterExistsAsync(this.Logger, this.ECSClient, ecsCluster); var taskCount = this.GetIntValueOrDefault(this.DeployTaskProperties.TaskCount, ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_COUNT, false); if (!taskCount.HasValue) taskCount = 1; var taskGroup = this.GetStringValueOrDefault(this.DeployTaskProperties.TaskGroup, ECSDefinedCommandOptions.ARGUMENT_ECS_TASK_GROUP, false); var launchType = this.GetStringValueOrDefault(this.ClusterProperties.LaunchType, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, true); var runTaskRequest = new Amazon.ECS.Model.RunTaskRequest { Cluster = ecsCluster, TaskDefinition = taskDefinitionArn, Count = taskCount.Value, LaunchType = launchType }; if (IsFargateLaunch(this.ClusterProperties.LaunchType)) { var subnets = this.GetStringValuesOrDefault(this.ClusterProperties.SubnetIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SUBNETS, false); var securityGroups = this.GetStringValuesOrDefault(this.ClusterProperties.SecurityGroupIds, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_SECURITYGROUPS, false); var networkConfiguration = new Amazon.ECS.Model.NetworkConfiguration(); await ECSUtilities.SetupAwsVpcNetworkConfigurationAsync(this, networkConfiguration); runTaskRequest.NetworkConfiguration = networkConfiguration; await this.AttemptToCreateServiceLinkRoleAsync(); } else { runTaskRequest.PlacementConstraints = ECSUtilities.ConvertPlacementConstraint(this.GetStringValuesOrDefault(this.DeployTaskProperties.PlacementConstraints, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS, false)); runTaskRequest.PlacementStrategy = ECSUtilities.ConvertPlacementStrategy(this.GetStringValuesOrDefault(this.DeployTaskProperties.PlacementStrategy, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY, false)); } if (!string.IsNullOrEmpty(taskGroup)) runTaskRequest.Group = taskGroup; try { var response = await this.ECSClient.RunTaskAsync(runTaskRequest); this.Logger?.WriteLine($"Started {response.Tasks.Count} task:"); foreach(var task in response.Tasks) { this.Logger?.WriteLine($"\t{task.TaskArn}"); } } catch(Exception e) { throw new DockerToolsException("Error executing deploy-task: " + e.Message, DockerToolsException.ECSErrorCode.RunTaskFail); } if (this.GetBoolValueOrDefault(this.PersistConfigFile, CommonDefinedCommandOptions.ARGUMENT_PERSIST_CONFIG_FILE, false).GetValueOrDefault()) { this.SaveConfigFile(); } return true; } protected override void SaveConfigFile(JsonData data) { this.PushDockerImageProperties.PersistSettings(this, data); this.TaskDefinitionProperties.PersistSettings(this, data); this.ClusterProperties.PersistSettings(this, data); this.DeployTaskProperties.PersistSettings(this, data); } } }
191
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon; using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using Amazon.CloudWatchEvents; using Amazon.CloudWatchLogs; using Amazon.EC2; using Amazon.ECR; using Amazon.ECS; using System.Reflection; using ThirdParty.Json.LitJson; using System.Text; using System.IO; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.IdentityManagement.Model; using System.Threading; namespace Amazon.ECS.Tools.Commands { public abstract class ECSBaseCommand : BaseCommand<ECSToolsDefaults> { public ECSBaseCommand(IToolLogger logger, string workingDirectory) : base(logger, workingDirectory) { } public ECSBaseCommand(IToolLogger logger, string workingDirectory, IList<CommandOption> possibleOptions, string[] args) : base(logger, workingDirectory, possibleOptions, args) { } protected override string ToolName => Constants.TOOLNAME; IAmazonCloudWatchEvents _cweClient; public IAmazonCloudWatchEvents CWEClient { get { if (this._cweClient == null) { SetUserAgentString(); var config = new AmazonCloudWatchEventsConfig(); config.RegionEndpoint = DetermineAWSRegion(); this._cweClient = new AmazonCloudWatchEventsClient(DetermineAWSCredentials(), config); } return this._cweClient; } set { this._cweClient = value; } } IAmazonCloudWatchLogs _cwlClient; public IAmazonCloudWatchLogs CWLClient { get { if (this._cwlClient == null) { SetUserAgentString(); var config = new AmazonCloudWatchLogsConfig(); config.RegionEndpoint = DetermineAWSRegion(); this._cwlClient = new AmazonCloudWatchLogsClient(DetermineAWSCredentials(), config); } return this._cwlClient; } set { this._cwlClient = value; } } IAmazonECS _ecsClient; public IAmazonECS ECSClient { get { if (this._ecsClient == null) { SetUserAgentString(); var config = new AmazonECSConfig(); config.RegionEndpoint = DetermineAWSRegion(); this._ecsClient = new AmazonECSClient(DetermineAWSCredentials(), config); } return this._ecsClient; } set { this._ecsClient = value; } } IAmazonEC2 _ec2Client; public IAmazonEC2 EC2Client { get { if (this._ec2Client == null) { SetUserAgentString(); var config = new AmazonEC2Config(); config.RegionEndpoint = DetermineAWSRegion(); this._ec2Client = new AmazonEC2Client(DetermineAWSCredentials(), config); } return this._ec2Client; } set { this._ec2Client = value; } } public bool IsFargateLaunch(string property) { var launchType = this.GetStringValueOrDefault(property, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, true); bool isFargate = string.Equals(launchType, LaunchType.FARGATE, StringComparison.OrdinalIgnoreCase); return isFargate; } public async Task AttemptToCreateServiceLinkRoleAsync() { try { await this.IAMClient.CreateServiceLinkedRoleAsync(new CreateServiceLinkedRoleRequest { AWSServiceName = "ecs.amazonaws.com" }); this.Logger.WriteLine("Created IAM Role service role for ecs.amazonaws.com"); this.Logger.WriteLine("Waiting for new IAM Role to propagate to AWS regions"); long start = DateTime.Now.Ticks; while (TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds < RoleHelper.SLEEP_TIME_FOR_ROLE_PROPOGATION.TotalSeconds) { Thread.Sleep(TimeSpan.FromSeconds(1)); Console.Write("."); Console.Out.Flush(); } Console.WriteLine("\t Done"); } catch(Exception) { } } } }
157
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.Text; namespace Amazon.ECS.Tools.Commands { public abstract class ECSBaseDeployCommand : ECSBaseCommand { public ECSBaseDeployCommand(IToolLogger logger, string workingDirectory) : base(logger, workingDirectory) { } public ECSBaseDeployCommand(IToolLogger logger, string workingDirectory, IList<CommandOption> possibleOptions, string[] args) : base(logger, workingDirectory, possibleOptions, args) { } BasePushDockerImageCommand<ECSToolsDefaults>.PushDockerImagePropertyContainer _pushProperties; public BasePushDockerImageCommand<ECSToolsDefaults>.PushDockerImagePropertyContainer PushDockerImageProperties { get { if (this._pushProperties == null) { this._pushProperties = new BasePushDockerImageCommand<ECSToolsDefaults>.PushDockerImagePropertyContainer(); } return this._pushProperties; } set { this._pushProperties = value; } } TaskDefinitionProperties _taskDefinitionProperties; public TaskDefinitionProperties TaskDefinitionProperties { get { if (this._taskDefinitionProperties == null) { this._taskDefinitionProperties = new TaskDefinitionProperties(); } return this._taskDefinitionProperties; } set { this._taskDefinitionProperties = value; } } ClusterProperties _clusterProperties; public ClusterProperties ClusterProperties { get { if (this._clusterProperties == null) { this._clusterProperties = new ClusterProperties(); } return this._clusterProperties; } set { this._clusterProperties = value; } } protected string GetDockerImageTag() { var tag = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerImageTag, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG, false)?.ToLower(); if (string.IsNullOrEmpty(this.PushDockerImageProperties.DockerImageTag)) { tag = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerImageTag, ECSDefinedCommandOptions.ARGUMENT_DOCKER_TAG, false)?.ToLower(); if (string.IsNullOrEmpty(this.PushDockerImageProperties.DockerImageTag)) { tag = this.GetStringValueOrDefault(this.PushDockerImageProperties.DockerImageTag, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG, true).ToLower(); } } return tag; } } }
84
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Amazon.ECR.Model; using Amazon.ECR; using ThirdParty.Json.LitJson; using System.IO; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; namespace Amazon.ECS.Tools.Commands { public class PushDockerImageCommand : BasePushDockerImageCommand<ECSToolsDefaults> { public const string COMMAND_NAME = "push-image"; public const string COMMAND_DESCRIPTION = "Build Docker image and push the image to Amazon ECR."; protected override string ToolName => Constants.TOOLNAME; public PushDockerImageCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, args) { } } }
29
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.ElasticBeanstalk.Tools { public static class EBConstants { public const string DEFAULT_MANIFEST = @" { ""manifestVersion"": 1, ""deployments"": { ""aspNetCoreWeb"": [ { ""name"": ""app"", ""parameters"": { ""appBundle"": ""."", ""iisPath"": ""{iisPath}"", ""iisWebSite"": ""{iisWebSite}"" } } ] } } "; public const int DEFAULT_APPLICATION_PORT = 5000; public const string DEFAULT_WINDOWS_INSTANCE_TYPE = "t3a.medium"; public const string DEFAULT_LINUX_INSTANCE_TYPE = "t2.micro"; public const string ENVIRONMENT_TYPE_SINGLEINSTANCE = "SingleInstance"; public const string ENVIRONMENT_TYPE_LOADBALANCED = "LoadBalanced"; public const string ENHANCED_HEALTH_TYPE_ENHANCED = "enhanced"; public const string ENHANCED_HEALTH_TYPE_BASIC = "basic"; public static readonly string[] ValidEnhanceHealthType = new string[]{ ENHANCED_HEALTH_TYPE_ENHANCED, ENHANCED_HEALTH_TYPE_BASIC }; public const string LOADBALANCER_TYPE_APPLICATION = "application"; public const string LOADBALANCER_TYPE_NETWORK = "network"; public const string LOADBALANCER_TYPE_CLASSIC = "classic"; public static readonly string[] ValidLoadBalancerType = new string[] { LOADBALANCER_TYPE_APPLICATION, LOADBALANCER_TYPE_NETWORK, LOADBALANCER_TYPE_CLASSIC }; public const string PROXY_SERVER_NGINX = "nginx"; public const string PROXY_SERVER_NONE = "none"; public static readonly string[] ValidProxyServer = new string[] { PROXY_SERVER_NGINX, PROXY_SERVER_NONE }; } }
53
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.Text; namespace Amazon.ElasticBeanstalk.Tools { public class EBDefinedCommandOptions { public static readonly CommandOption ARGUMENT_INPUT_PACKAGE = new CommandOption { Name = "Package", ShortSwitch = "-pac", Switch = "--package", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Application package to use for deployment, skips building the project" }; public static readonly CommandOption ARGUMENT_EB_APPLICATION = new CommandOption { Name = "Elastic Beanstalk Application", ShortSwitch = "-app", Switch = "--application", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The name of the Elastic Beanstalk application." }; public static readonly CommandOption ARGUMENT_EB_ENVIRONMENT = new CommandOption { Name = "Elastic Beanstalk Environment", ShortSwitch = "-env", Switch = "--environment", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The name of the Elastic Beanstalk environment." }; public static readonly CommandOption ARGUMENT_CNAME_PREFIX = new CommandOption { Name = "Environment CNAME", Switch = "--cname", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "CNAME prefix for a new environment." }; public static readonly CommandOption ARGUMENT_SOLUTION_STACK = new CommandOption { Name = "Elastic Beanstalk Solution Stack", Switch = "--solution-stack", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The type of environment to create. For example \"64bit Windows Server 2016 v1.2.0 running IIS 10.0\"." }; public static readonly CommandOption ARGUMENT_ENVIRONMENT_TYPE = new CommandOption { Name = "Type of Elastic Beanstalk Environment", Switch = "--environment-type", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"Type of the environment to launch \"{EBConstants.ENVIRONMENT_TYPE_LOADBALANCED}\" or \"{EBConstants.ENVIRONMENT_TYPE_SINGLEINSTANCE}\". The default is \"{EBConstants.ENVIRONMENT_TYPE_LOADBALANCED}\"." }; public static readonly CommandOption ARGUMENT_EC2_KEYPAIR = new CommandOption { Name = "EC2 Key Pair", Switch = "--key-pair", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "EC2 Key pair assigned to the EC2 instances for the environment." }; public static readonly CommandOption ARGUMENT_INSTANCE_TYPE = new CommandOption { Name = "EC2 instance type", Switch = "--instance-type", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"Type of the EC2 instances launched for the environment. The default is \"{EBConstants.DEFAULT_LINUX_INSTANCE_TYPE}\" for Linux and \"{EBConstants.DEFAULT_WINDOWS_INSTANCE_TYPE}\" for Windows." }; public static readonly CommandOption ARGUMENT_HEALTH_CHECK_URL = new CommandOption { Name = "Health Check URL", Switch = "--health-check-url", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Health Check URL." }; public static readonly CommandOption ARGUMENT_INSTANCE_PROFILE = new CommandOption { Name = "EC2 Instance Profile", Switch = "--instance-profile", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Instance profile that provides AWS Credentials to access AWS services." }; public static readonly CommandOption ARGUMENT_SERVICE_ROLE = new CommandOption { Name = "Service Role", Switch = "--service-role", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "IAM role to allow Beanstalk to make calls to AWS services." }; public static readonly CommandOption ARGUMENT_EB_VERSION_LABEL = new CommandOption { Name = "Version Label", Switch = "--version-label", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Version label that will be assigned to the uploaded version of code. The default is current tick count." }; public static readonly CommandOption ARGUMENT_EB_TAGS = new CommandOption { Name = "Elastic Beanstalk Environment", Switch = "--tags", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "Tags to assign to the Elastic Beanstalk environment. Format is <tag1>=<value1>;<tag2>=<value2>." }; public static readonly CommandOption ARGUMENT_APP_PATH = new CommandOption { Name = "Application URL Path", Switch = "--app-path", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The application path. The default is '/'." }; public static readonly CommandOption ARGUMENT_IIS_WEBSITE = new CommandOption { Name = "IIS Web Site", Switch = "--iis-website", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The IIS WebSite for the web application. The default is 'Default Web Site'" }; public static readonly CommandOption ARGUMENT_WAIT_FOR_UPDATE = new CommandOption { Name = "Wait for Update", Switch = "--wait", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "Wait for the environment update to complete before exiting." }; public static readonly CommandOption ARGUMENT_ENABLE_XRAY = new CommandOption { Name = "Enable AWS X-Ray", Switch = "--enable-xray", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If set to true then the AWS X-Ray daemon will be enabled on EC2 instances running the application." }; public static readonly CommandOption ARGUMENT_ENHANCED_HEALTH_TYPE = new CommandOption { Name = "Enhanced Health Type", Switch = "--enhanced-health-type", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The type of enhanced health to be enabled. Valid values: {string.Join(", ", EBConstants.ValidEnhanceHealthType)}" }; public static readonly CommandOption ARGUMENT_LOADBALANCER_TYPE = new CommandOption { Name = "Loadbalancer Type", Switch = "--loadbalancer-type", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"LoadBalancer type for the environment. If no value set then a single instance environment type is created. Valid values: {EBConstants.LOADBALANCER_TYPE_APPLICATION}, {EBConstants.LOADBALANCER_TYPE_NETWORK}, {EBConstants.LOADBALANCER_TYPE_CLASSIC}" }; public static readonly CommandOption ARGUMENT_ENABLE_STICKY_SESSIONS = new CommandOption { Name = "Enable Sticky Sessions", Switch = "--enable-sticky-sessions", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If set to true sticky sessions will be enabled for the load balancer of the environment." }; public static readonly CommandOption ARGUMENT_EB_ADDITIONAL_OPTIONS = new CommandOption { Name = "Additional Options", Switch = "--additional-options", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "Additional options for the environment. Format is <option-namespace>,<option-name>=<option-value>;..." }; public static readonly CommandOption ARGUMENT_OUTPUT_PACKAGE = new CommandOption { Name = "The output zip file name", ShortSwitch = "-o", Switch = "--output-package", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The zip file containing the application will be packaged into." }; public static readonly CommandOption ARGUMENT_PROXY_SERVER = new CommandOption { Name = "Reverse Proxy Server", Switch = "--proxy-server", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The reverse proxy server used on Linux EC2 instances. Valid values: {string.Join(", ", EBConstants.ValidProxyServer)}. The default is \"{EBConstants.PROXY_SERVER_NGINX}\"." }; public static readonly CommandOption ARGUMENT_APPLICATION_PORT = new CommandOption { Name = "Application Port", Switch = "--application-port", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = $"The application port that will be redirect to port 80. The default is port {EBConstants.DEFAULT_APPLICATION_PORT}." }; } }
210
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Amazon.Common.DotNetCli.Tools; using Amazon.ElasticBeanstalk.Model; using Amazon.ElasticBeanstalk.Tools.Commands; using ThirdParty.Json.LitJson; namespace Amazon.ElasticBeanstalk.Tools { public static class EBUtilities { public static void SetupAWSDeploymentManifest(IToolLogger logger, EBBaseCommand command, DeployEnvironmentProperties options, string publishLocation) { var iisAppPath = command.GetStringValueOrDefault(options.UrlPath, EBDefinedCommandOptions.ARGUMENT_APP_PATH, false) ?? "/"; var iisWebSite = command.GetStringValueOrDefault(options.IISWebSite, EBDefinedCommandOptions.ARGUMENT_IIS_WEBSITE, false) ?? "Default Web Site"; var pathToManifest = Path.Combine(publishLocation, "aws-windows-deployment-manifest.json"); string manifest; if (File.Exists(pathToManifest)) { logger?.WriteLine("Updating existing deployment manifest"); Func<string, JsonData, JsonData> getOrCreateNode = (name, node) => { JsonData child = node[name] as JsonData; if (child == null) { child = new JsonData(); node[name] = child; } return child; }; JsonData root = JsonMapper.ToObject(File.ReadAllText(pathToManifest)); if (root["manifestVersion"] == null || !root["manifestVersion"].IsInt) { root["manifestVersion"] = 1; } JsonData deploymentNode = getOrCreateNode("deployments", root); JsonData aspNetCoreWebNode = getOrCreateNode("aspNetCoreWeb", deploymentNode); JsonData appNode; if (aspNetCoreWebNode.GetJsonType() == JsonType.None || aspNetCoreWebNode.Count == 0) { appNode = new JsonData(); aspNetCoreWebNode.Add(appNode); } else appNode = aspNetCoreWebNode[0]; if (appNode["name"] == null || !appNode["name"].IsString || string.IsNullOrEmpty((string)appNode["name"])) { appNode["name"] = "app"; } JsonData parametersNode = getOrCreateNode("parameters", appNode); parametersNode["appBundle"] = "."; parametersNode["iisPath"] = iisAppPath; parametersNode["iisWebSite"] = iisWebSite; manifest = root.ToJson(); } else { logger?.WriteLine("Creating deployment manifest"); manifest = EBConstants.DEFAULT_MANIFEST.Replace("{iisPath}", iisAppPath).Replace("{iisWebSite}", iisWebSite); if (File.Exists(pathToManifest)) File.Delete(pathToManifest); } logger?.WriteLine("\tIIS App Path: " + iisAppPath); logger?.WriteLine("\tIIS Web Site: " + iisWebSite); File.WriteAllText(pathToManifest, manifest); } public static bool IsSolutionStackWindows(string solutionStackName) { return solutionStackName.Contains("64bit Windows Server"); } public static bool IsSolutionStackLinuxNETCore(string solutionStackName) { return IsSolutionStackLinux(solutionStackName) && IsSolutionStackNETCore(solutionStackName); } public static bool IsSolutionStackLinux(string solutionStackName) { return solutionStackName.StartsWith("64bit Amazon Linux 2"); } public static bool IsSolutionStackNETCore(string solutionStackName) { return solutionStackName.Contains(".NET Core") || solutionStackName.Contains("DotNetCore"); } public static bool IsLoadBalancedEnvironmentType(string environmentType) { return string.Equals(environmentType, EBConstants.ENVIRONMENT_TYPE_LOADBALANCED, StringComparison.OrdinalIgnoreCase); } public static void SetupPackageForLinux(IToolLogger logger, EBBaseCommand command, DeployEnvironmentProperties options, string publishLocation, string reverseProxy, int? applicationPort) { // Setup Procfile var procfilePath = Path.Combine(publishLocation, "Procfile"); if(File.Exists(procfilePath)) { logger?.WriteLine("Found existing Procfile file found and using that for deployment"); return; } logger?.WriteLine("Writing Procfile for deployment bundle"); var runtimeConfigFilePath = Directory.GetFiles(publishLocation, "*.runtimeconfig.json").FirstOrDefault(); var runtimeConfigFileName = Path.GetFileName(runtimeConfigFilePath); var executingAssembly = runtimeConfigFileName.Substring(0, runtimeConfigFileName.Length - "runtimeconfig.json".Length - 1); string webCommandLine; if(IsSelfContainedPublish(runtimeConfigFilePath)) { webCommandLine = $"./{executingAssembly}"; } else { webCommandLine = $"dotnet exec ./{executingAssembly}.dll"; } if(string.Equals(reverseProxy, EBConstants.PROXY_SERVER_NONE, StringComparison.InvariantCulture)) { logger?.WriteLine("... Proxy server disabled, configuring Kestrel to listen to traffic from all hosts"); var port = applicationPort.HasValue ? applicationPort.Value : EBConstants.DEFAULT_APPLICATION_PORT; webCommandLine += $" --urls http://0.0.0.0:{port.ToString(CultureInfo.InvariantCulture)}/"; } var content = "web: " + webCommandLine; logger?.WriteLine($"... Procfile command used to start application"); logger?.WriteLine($" {content}"); File.WriteAllText(procfilePath, content); } public static bool IsSelfContainedPublish(string runtimeConfigFile) { if(File.Exists(runtimeConfigFile)) { runtimeConfigFile = File.ReadAllText(runtimeConfigFile); } JsonData root = JsonMapper.ToObject(runtimeConfigFile); var runtimeOptions = root["runtimeOptions"] as JsonData; if(runtimeOptions == null) { return false; } var includedFrameworks = runtimeOptions["includedFrameworks"] as JsonData; return includedFrameworks != null && includedFrameworks.Count > 0; } public static string FindExistingValue(this List<ConfigurationOptionSetting> settings, string ns, string name) { var setting = settings?.FirstOrDefault(x => string.Equals(x.Namespace, ns, StringComparison.InvariantCulture) && string.Equals(x.OptionName, name, StringComparison.InvariantCulture)); return setting?.Value; } } }
180
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using ThirdParty.Json.LitJson; using Amazon.Common.DotNetCli.Tools; namespace Amazon.ElasticBeanstalk.Tools { public class ElasticBeanstalkToolsDefaults : DefaultConfigFile { public const string DEFAULT_FILE_NAME = "aws-beanstalk-tools-defaults.json"; public ElasticBeanstalkToolsDefaults() { } public ElasticBeanstalkToolsDefaults(string sourceFile) : this(new JsonData(), sourceFile) { } public ElasticBeanstalkToolsDefaults(JsonData data, string sourceFile) : base(data, sourceFile) { } public override string DefaultConfigFileName => DEFAULT_FILE_NAME; } }
33
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using System; using System.Collections.Generic; using System.Text; namespace Amazon.ElasticBeanstalk.Tools { public class ElasticBeanstalkExceptions : ToolsException { public enum EBCode { EnsureBucketExistsError, FailedToUploadBundle, FailedToFindEnvironment, FailedEnvironmentUpdate, FailedCreateApplication, FailedCreateApplicationVersion, FailedToUpdateTags, FailedToDeleteEnvironment, FailedToUpdateEnvironment, FailedToDescribeEnvironmentSettings, FailedToCreateEnvironment, InvalidPackage, InvalidEnhancedHealthType, InvalidLoadBalancerType, InvalidProxyServer, } public ElasticBeanstalkExceptions(string message, EBCode code) : base(message, code.ToString(), null) { } public ElasticBeanstalkExceptions(string message, CommonErrorCode code) : base(message, code.ToString(), null) { } public ElasticBeanstalkExceptions(string message, EBCode code, Exception e) : base(message, code.ToString(), e) { } } }
43
aws-extensions-for-dotnet-cli
aws
C#
using System; using Amazon.Common.DotNetCli.Tools.CLi; using Amazon.Common.DotNetCli.Tools.Commands; using System.Collections.Generic; using Amazon.ElasticBeanstalk.Tools.Commands; namespace Amazon.ElasticBeanstalk.Tools { class Program { static void Main(string[] args) { var application = new Application("eb", "Amazon Elastic Beanstalk Tools for .NET Core applications", "https://github.com/aws/aws-extensions-for-dotnet-cli", new List<ICommandInfo>() { new GroupHeaderInfo("Commands to manage environments:"), new CommandInfo<DeployEnvironmentCommand>(DeployEnvironmentCommand.COMMAND_NAME, DeployEnvironmentCommand.COMMAND_DESCRIPTION, DeployEnvironmentCommand.CommandOptions), new CommandInfo<ListEnvironmentsCommand>(ListEnvironmentsCommand.COMMAND_NAME, ListEnvironmentsCommand.COMMAND_DESCRIPTION, ListEnvironmentsCommand.CommandOptions), new CommandInfo<DeleteEnvironmentCommand>(DeleteEnvironmentCommand.COMMAND_NAME, DeleteEnvironmentCommand.COMMAND_DESCRIPTION, DeleteEnvironmentCommand.CommandOptions), new GroupHeaderInfo("Other Commands:"), new CommandInfo<PackageCommand>(PackageCommand.COMMAND_NAME, PackageCommand.COMMAND_DESCRIPTION, PackageCommand.CommandOptions), }); var exitCode = application.Execute(args); if (exitCode != 0) { Environment.Exit(-1); } } } }
35
aws-extensions-for-dotnet-cli
aws
C#
using System.Globalization; using System.Text; namespace Amazon.ElasticBeanstalk.Tools { public class PublishOptions { private readonly string _initialOptions; private readonly bool _isWindowsEnvironment; private readonly bool _selfContained; public PublishOptions(string initialOptions, bool isWindowsEnvironment, bool selfContained) { _initialOptions = initialOptions ?? ""; _isWindowsEnvironment = isWindowsEnvironment; _selfContained = selfContained; } public string ToCliString() { var publishOptionsBuilder = new StringBuilder(_initialOptions); if (DoesNotContainRuntime()) { publishOptionsBuilder.Append($" --runtime {GetRuntimeString()}"); } if (DoesNotContainSelfContained()) { publishOptionsBuilder.Append($" --self-contained {ConvertBoolToString(_selfContained)}"); } return publishOptionsBuilder.ToString(); } private bool DoesNotContainRuntime() => !_initialOptions.Contains("-r ") && !_initialOptions.Contains("--runtime "); private string GetRuntimeString() => _isWindowsEnvironment ? "win-x64" : "linux-x64"; private bool DoesNotContainSelfContained() => !_initialOptions.Contains("--self-contained"); private string ConvertBoolToString(bool boolean) => boolean.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(); } }
45
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.Text; using ThirdParty.Json.LitJson; namespace Amazon.ElasticBeanstalk.Tools.Commands { public class DeployEnvironmentProperties { public string Configuration { get; set; } public string TargetFramework { get; set; } public bool? SelfContained { get; set; } public string PublishOptions { get; set; } public string Application { get; set; } public string Environment { get; set; } public string UrlPath { get; set; } public string IISWebSite { get; set; } public bool? WaitForUpdate { get; set; } public bool? EnableXRay { get; set; } public Dictionary<string,string> Tags { get; set; } public Dictionary<string, string> AdditionalOptions { get; set; } public string SolutionStack { get; set; } public string EnvironmentType { get; set; } public string CNamePrefix { get; set; } public string InstanceType { get; set; } public string EC2KeyPair { get; set; } public string HealthCheckUrl { get; set; } public string InstanceProfile { get; set; } public string ServiceRole { get; set; } public string VersionLabel { get; set; } public string EnhancedHealthType { get; set; } public string LoadBalancerType { get; set; } public bool? EnableStickySessions { get; set; } public string ProxyServer { get; set; } public int? ApplicationPort { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.Switch)) != null) this.Configuration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_SELF_CONTAINED.Switch)) != null) this.SelfContained = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS.Switch)) != null) this.PublishOptions = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_EB_APPLICATION.Switch)) != null) this.Application = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT.Switch)) != null) this.Environment = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_APP_PATH.Switch)) != null) this.UrlPath = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_IIS_WEBSITE.Switch)) != null) this.IISWebSite = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_WAIT_FOR_UPDATE.Switch)) != null) this.WaitForUpdate = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_EB_VERSION_LABEL.Switch)) != null) this.VersionLabel = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_EB_TAGS.Switch)) != null) this.Tags = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_EB_ADDITIONAL_OPTIONS.Switch)) != null) this.AdditionalOptions = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_SOLUTION_STACK.Switch)) != null) this.SolutionStack = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_ENVIRONMENT_TYPE.Switch)) != null) this.EnvironmentType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_CNAME_PREFIX.Switch)) != null) this.CNamePrefix = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_INSTANCE_TYPE.Switch)) != null) this.InstanceType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_EC2_KEYPAIR.Switch)) != null) this.EC2KeyPair = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_HEALTH_CHECK_URL.Switch)) != null) this.HealthCheckUrl = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_INSTANCE_PROFILE.Switch)) != null) this.InstanceProfile = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_SERVICE_ROLE.Switch)) != null) this.ServiceRole = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_ENABLE_XRAY.Switch)) != null) this.EnableXRay = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_ENHANCED_HEALTH_TYPE.Switch)) != null) this.EnhancedHealthType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_LOADBALANCER_TYPE.Switch)) != null) this.LoadBalancerType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_ENABLE_STICKY_SESSIONS.Switch)) != null) this.EnableStickySessions = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_PROXY_SERVER.Switch)) != null) this.ProxyServer = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_APPLICATION_PORT.Switch)) != null) this.ApplicationPort = tuple.Item2.IntValue; } internal void PersistSettings(EBBaseCommand command, JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.ConfigFileKey, command.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, command.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_SELF_CONTAINED.ConfigFileKey, command.GetBoolValueOrDefault(this.SelfContained, CommonDefinedCommandOptions.ARGUMENT_SELF_CONTAINED, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS.ConfigFileKey, command.GetStringValueOrDefault(this.PublishOptions, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_EB_APPLICATION.ConfigFileKey, command.GetStringValueOrDefault(this.Application, EBDefinedCommandOptions.ARGUMENT_EB_APPLICATION, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT.ConfigFileKey, command.GetStringValueOrDefault(this.Environment, EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_APP_PATH.ConfigFileKey, command.GetStringValueOrDefault(this.UrlPath, EBDefinedCommandOptions.ARGUMENT_APP_PATH, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_IIS_WEBSITE.ConfigFileKey, command.GetStringValueOrDefault(this.IISWebSite, EBDefinedCommandOptions.ARGUMENT_IIS_WEBSITE, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_EB_TAGS.ConfigFileKey, ElasticBeanstalkToolsDefaults.FormatKeyValue(command.GetKeyValuePairOrDefault(this.Tags, EBDefinedCommandOptions.ARGUMENT_EB_TAGS, false))); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_ENABLE_XRAY.ConfigFileKey, command.GetBoolValueOrDefault(this.EnableXRay, EBDefinedCommandOptions.ARGUMENT_ENABLE_XRAY, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_ENHANCED_HEALTH_TYPE.ConfigFileKey, command.GetStringValueOrDefault(this.EnhancedHealthType, EBDefinedCommandOptions.ARGUMENT_ENHANCED_HEALTH_TYPE, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_EB_ADDITIONAL_OPTIONS.ConfigFileKey, ElasticBeanstalkToolsDefaults.FormatKeyValue(command.GetKeyValuePairOrDefault(this.AdditionalOptions, EBDefinedCommandOptions.ARGUMENT_EB_ADDITIONAL_OPTIONS, false))); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_SOLUTION_STACK.ConfigFileKey, command.GetStringValueOrDefault(this.SolutionStack, EBDefinedCommandOptions.ARGUMENT_SOLUTION_STACK, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_ENVIRONMENT_TYPE.ConfigFileKey, command.GetStringValueOrDefault(this.EnvironmentType, EBDefinedCommandOptions.ARGUMENT_ENVIRONMENT_TYPE, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_LOADBALANCER_TYPE.ConfigFileKey, command.GetStringValueOrDefault(this.LoadBalancerType, EBDefinedCommandOptions.ARGUMENT_LOADBALANCER_TYPE, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_ENABLE_STICKY_SESSIONS.ConfigFileKey, command.GetBoolValueOrDefault(this.EnableStickySessions, EBDefinedCommandOptions.ARGUMENT_ENABLE_STICKY_SESSIONS, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_CNAME_PREFIX.ConfigFileKey, command.GetStringValueOrDefault(this.CNamePrefix, EBDefinedCommandOptions.ARGUMENT_CNAME_PREFIX, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_INSTANCE_TYPE.ConfigFileKey, command.GetStringValueOrDefault(this.InstanceType, EBDefinedCommandOptions.ARGUMENT_INSTANCE_TYPE, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_EC2_KEYPAIR.ConfigFileKey, command.GetStringValueOrDefault(this.EC2KeyPair, EBDefinedCommandOptions.ARGUMENT_EC2_KEYPAIR, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_HEALTH_CHECK_URL.ConfigFileKey, command.GetStringValueOrDefault(this.HealthCheckUrl, EBDefinedCommandOptions.ARGUMENT_HEALTH_CHECK_URL, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_INSTANCE_PROFILE.ConfigFileKey, command.GetStringValueOrDefault(this.InstanceProfile, EBDefinedCommandOptions.ARGUMENT_INSTANCE_PROFILE, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_SERVICE_ROLE.ConfigFileKey, command.GetStringValueOrDefault(this.ServiceRole, EBDefinedCommandOptions.ARGUMENT_SERVICE_ROLE, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_PROXY_SERVER.ConfigFileKey, command.GetStringValueOrDefault(this.ProxyServer, EBDefinedCommandOptions.ARGUMENT_PROXY_SERVER, false)); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_APPLICATION_PORT.ConfigFileKey, command.GetIntValueOrDefault(this.ApplicationPort, EBDefinedCommandOptions.ARGUMENT_APPLICATION_PORT, false)); } } public class DeleteEnvironmentProperties { public string Environment { get; set; } internal void ParseCommandArguments(CommandOptions values) { Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT.Switch)) != null) this.Environment = tuple.Item2.StringValue; } internal void PersistSettings(EBBaseCommand command, JsonData data) { data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT.ConfigFileKey, command.GetStringValueOrDefault(this.Environment, EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT, false)); } } }
152