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-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithDockerFile.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
23
aws-dotnet-deploy
aws
C#
using WorkerServiceExample; IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build(); await host.RunAsync();
11
aws-dotnet-deploy
aws
C#
namespace WorkerServiceExample { public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } } }
21
aws-dotnet-extensions-configuration
aws
C#
using Amazon; using Amazon.Extensions.NETCore.Setup; using Amazon.SimpleSystemsManagement; using Amazon.SimpleSystemsManagement.Model; using Samples; //populates some sample data to be used by this example project await PopulateSampleDataForThisProject().ConfigureAwait(false); var builder = WebApplication.CreateBuilder(args); builder.Configuration.AddSystemsManager($"/dotnet-aws-samples/systems-manager-sample/"); builder.Services.Configure<Settings>(builder.Configuration.GetSection($"common:settings")); // Add services to the container. builder.Services.AddControllers(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); static async Task PopulateSampleDataForThisProject() { var awsOptions = new AWSOptions { Region = RegionEndpoint.USEast1 }; var root = $"/dotnet-aws-samples/systems-manager-sample/common"; var parameters = new[] { new {Name = "StringValue", Value = "string-value"}, new {Name = "IntegerValue", Value = "10"}, new {Name = "DateTimeValue", Value = "2000-01-01"}, new {Name = "BooleanValue", Value = "True"}, new {Name = "TimeSpanValue", Value = "00:05:00"}, }; using (var client = awsOptions.CreateServiceClient<IAmazonSimpleSystemsManagement>()) { var result = await client.GetParametersByPathAsync(new GetParametersByPathRequest { Path = root, Recursive = true }).ConfigureAwait(false); if (result.Parameters.Count == parameters.Length) return; foreach (var parameter in parameters) { var name = $"{root}/settings/{parameter.Name}"; await client.PutParameterAsync(new PutParameterRequest { Name = name, Value = parameter.Value, Type = ParameterType.String, Overwrite = true }).ConfigureAwait(false); } } }
53
aws-dotnet-extensions-configuration
aws
C#
using System; namespace Samples { public class Settings { public string StringValue { get; set; } public int IntegerValue { get; set; } public DateTime DateTimeValue { get; set; } public bool BooleanValue { get; set; } public TimeSpan TimeSpanValue { get; set; } } }
14
aws-dotnet-extensions-configuration
aws
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace Samples.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IOptions<Settings> _settings; public ValuesController(IOptions<Settings> settings) { _settings = settings; } // GET api/values [HttpGet] public ActionResult Get() { return Ok(new { Settings = _settings.Value }); } } }
28
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager { /// <summary> /// This extension is an a different namespace to avoid misuse of this method which should only be called when being used from AWS Lambda. /// </summary> public static class ConfigurationExtensions { /// <summary> /// This method blocks while any SystemsManagerConfigurationProvider added to IConfiguration are /// currently reloading the parameters from Parameter Store. /// /// This is generally only needed when the provider is being called from a AWS Lambda function. Without this call /// in a AWS Lambda environment there is a potential of the background thread doing the refresh never running successfully. /// This can happen because the AWS Lambda compute environment is frozen after the current AWS Lambda event is complete. /// </summary> /// <param name="configuration"></param> /// <param name="timeout">Maximum time to wait for reload to be completed</param> public static void WaitForSystemsManagerReloadToComplete(this IConfiguration configuration, TimeSpan timeout) { if (configuration is ConfigurationRoot configRoot) { foreach (var provider in configRoot.Providers) { if (provider is SystemsManagerConfigurationProvider ssmProvider) { ssmProvider.WaitForReloadToComplete(timeout); } } } } } }
50
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Amazon.SimpleSystemsManagement.Model; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager { /// <inheritdoc /> /// <summary> /// Default parameter processor based on Systems Manager's suggested naming convention /// </summary> public class DefaultParameterProcessor : IParameterProcessor { /// <inheritdoc cref="ConfigurationPath.KeyDelimiter"/> public static readonly string KeyDelimiter = ConfigurationPath.KeyDelimiter; public virtual bool IncludeParameter(Parameter parameter, string path) => true; public virtual string GetKey(Parameter parameter, string path) { var name = parameter.Name.StartsWith(path, StringComparison.OrdinalIgnoreCase) ? parameter.Name.Substring(path.Length) : parameter.Name; return name.TrimStart('/').Replace("/", KeyDelimiter); } public virtual string GetValue(Parameter parameter, string path) => parameter.Value; public virtual IDictionary<string, string> ProcessParameters(IEnumerable<Parameter> parameters, string path) { return parameters .Where(parameter => IncludeParameter(parameter, path)) .Select(parameter => new { Key = GetKey(parameter, path), Value = GetValue(parameter, path) }) .ToDictionary(parameter => parameter.Key, parameter => parameter.Value, StringComparer.OrdinalIgnoreCase); } } }
57
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using Amazon.SimpleSystemsManagement.Model; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager { /// <summary> /// Processor responsible for deciding if a <see cref="Parameter"/> should be included and processing the Key /// </summary> public interface IParameterProcessor { /// <summary> /// Process parameters from AWS Parameter Store into a dictionary for <see cref="IConfiguration"/> /// </summary> /// <param name="parameters">Enumeration of <see cref="Parameter"/>s to be processed</param> /// <param name="path">Path used when retrieving the <see cref="Parameter"/></param> /// <returns>Configuration values for <see cref="IConfiguration"/></returns> IDictionary<string, string> ProcessParameters(IEnumerable<Parameter> parameters, string path); } }
37
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager { /// <inheritdoc /> /// <summary> /// Represents AWS Systems Manager variables as an <see cref="ISystemsManagerConfigurationSource" />. /// </summary> public interface ISystemsManagerConfigurationSource : IConfigurationSource { /// <summary> /// Determines if loading configuration data from AWS Systems Manager Parameter Store is optional. /// </summary> bool Optional { get; set; } /// <summary> /// Parameters will be reloaded from the AWS Systems Manager Parameter Store after the specified time frame /// </summary> TimeSpan? ReloadAfter { get; set; } /// <summary> /// Will be called if an uncaught exception occurs in <see cref="SystemsManagerConfigurationProvider"/>.Load. /// </summary> Action<SystemsManagerExceptionContext> OnLoadException { get; set; } } }
43
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Amazon.Extensions.Configuration.SystemsManager.Internal; using Amazon.SimpleSystemsManagement.Model; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager { /// <inheritdoc /> /// <summary> /// Default parameter processor based on Systems Manager's suggested naming convention /// </summary> public class JsonParameterProcessor : DefaultParameterProcessor { public override IDictionary<string, string> ProcessParameters(IEnumerable<Parameter> parameters, string path) { var outputDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (Parameter parameter in parameters.Where(parameter => IncludeParameter(parameter, path))) { // Get the extra prefix if the path is subset of paramater name. string prefix = GetKey(parameter, path); var parameterDictionary = JsonConfigurationParser.Parse(parameter.Value); foreach (var keyValue in parameterDictionary) { string key = (!string.IsNullOrEmpty(prefix) ? ConfigurationPath.Combine(prefix, keyValue.Key) : keyValue.Key); outputDictionary.Add(key, keyValue.Value); } } return outputDictionary; } } }
50
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Amazon.Extensions.Configuration.SystemsManager.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; namespace Amazon.Extensions.Configuration.SystemsManager { /// <inheritdoc /> /// <summary> /// An AWS Systems Manager based <see cref="ConfigurationProvider" />. /// </summary> public class SystemsManagerConfigurationProvider : ConfigurationProvider { private ISystemsManagerConfigurationSource Source { get; } private ISystemsManagerProcessor SystemsManagerProcessor { get; } private ManualResetEvent ReloadTaskEvent { get; } = new ManualResetEvent(true); /// <inheritdoc /> /// <summary> /// Initializes a new instance with the specified source. /// </summary> /// <param name="source">The <see cref="SystemsManagerConfigurationSource"/> used to retrieve values from AWS Systems Manager Parameter Store</param> public SystemsManagerConfigurationProvider(SystemsManagerConfigurationSource source) : this(source, new SystemsManagerProcessor(source)) { } /// <inheritdoc /> /// <summary> /// Initializes a new instance with the specified source. /// </summary> /// <param name="source">The <see cref="AppConfigConfigurationSource"/> used to retrieve values from AWS Systems Manager AppConfig</param> public SystemsManagerConfigurationProvider(AppConfigConfigurationSource source) : this(source, new AppConfigProcessor(source)) { } /// <inheritdoc /> /// <summary> /// Initializes a new instance with the specified source. /// </summary> /// <param name="source">The <see cref="ISystemsManagerConfigurationSource"/> used to retrieve values from AWS Systems Manager</param> /// <param name="systemsManagerProcessor">The <see cref="ISystemsManagerProcessor"/> used to retrieve values from AWS Systems Manager</param> public SystemsManagerConfigurationProvider(ISystemsManagerConfigurationSource source, ISystemsManagerProcessor systemsManagerProcessor) { Source = source ?? throw new ArgumentNullException(nameof(source)); SystemsManagerProcessor = systemsManagerProcessor ?? throw new ArgumentNullException(nameof(systemsManagerProcessor)); if (source.ReloadAfter != null) { ChangeToken.OnChange(() => { var cancellationTokenSource = new CancellationTokenSource(source.ReloadAfter.Value); var cancellationChangeToken = new CancellationChangeToken(cancellationTokenSource.Token); return cancellationChangeToken; }, async () => { ReloadTaskEvent.Reset(); try { await LoadAsync(true).ConfigureAwait(false); } finally { ReloadTaskEvent.Set(); } }); } } /// <summary> /// If this configuration provider is currently performing a reload of the config data this method will block until /// the reload is called. /// /// This method is not meant for general use. It is exposed so a AWS Lambda function can wait for the reload to complete /// before completing the event causing the AWS Lambda compute environment to be frozen. /// </summary> public void WaitForReloadToComplete(TimeSpan timeout) { ReloadTaskEvent.WaitOne(timeout); } /// <inheritdoc /> /// <summary> /// Loads the AWS Systems Manager Parameters. /// </summary> public override void Load() => LoadAsync(false).ConfigureAwait(false).GetAwaiter().GetResult(); // If 1) reload flag is set to true and 2) OnLoadException handler is not set, // all exceptions raised during OnReload() will be ignored. private async Task LoadAsync(bool reload) { try { var newData = await SystemsManagerProcessor.GetDataAsync().ConfigureAwait(false) ?? new Dictionary<string, string>(); if (!Data.EquivalentTo(newData)) { Data = newData; OnReload(); } } catch (Exception ex) { if (Source.Optional) return; var ignoreException = reload; if (Source.OnLoadException != null) { var exceptionContext = new SystemsManagerExceptionContext { Provider = this, Exception = ex, Reload = reload }; Source.OnLoadException(exceptionContext); ignoreException = exceptionContext.Ignore; } if (!ignoreException) throw; } } } }
145
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using Amazon.Extensions.NETCore.Setup; using Amazon.SimpleSystemsManagement.Model; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager { /// <inheritdoc /> /// <summary> /// Represents AWS Systems Manager Parameter Store variables as an <see cref="ISystemsManagerConfigurationSource" />. /// </summary> public class SystemsManagerConfigurationSource : ISystemsManagerConfigurationSource { public SystemsManagerConfigurationSource() { Filters = new List<ParameterStringFilter>(); } /// <summary> /// A Path used to filter parameters. /// </summary> public string Path { get; set; } /// <summary> /// <see cref="AWSOptions"/> used to create an AWS Systems Manager Client />. /// </summary> public AWSOptions AwsOptions { get; set; } /// <inheritdoc /> public bool Optional { get; set; } /// <inheritdoc /> public TimeSpan? ReloadAfter { get; set; } /// <summary> /// Prepends the supplied Prefix to all result keys /// </summary> public string Prefix { get; set; } /// <inheritdoc /> public Action<SystemsManagerExceptionContext> OnLoadException { get; set; } /// <summary> /// Implementation of <see cref="IParameterProcessor"/> used to process <see cref="Parameter"/> results. Defaults to <see cref="DefaultParameterProcessor"/>. /// </summary> public IParameterProcessor ParameterProcessor { get; set; } /// <summary> /// Filters to limit the request results. /// You can't filter using the parameter name. /// </summary> public List<ParameterStringFilter> Filters { get; } /// <inheritdoc /> public IConfigurationProvider Build(IConfigurationBuilder builder) { return new SystemsManagerConfigurationProvider(this); } } }
77
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager { /// <summary>Contains information about a Systems Manager load exception.</summary> public class SystemsManagerExceptionContext { /// <summary> /// The <see cref="IConfigurationProvider" /> that caused the exception. /// </summary> public IConfigurationProvider Provider { get; set; } /// <summary>The exception that occured in Load.</summary> public Exception Exception { get; set; } /// <summary>If true, the exception will not be rethrown.</summary> public bool Ignore { get; set; } /// <summary>If true, the exception was raised on a reload event</summary> public bool Reload { get; set; } } }
38
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.Extensions.Configuration.SystemsManager; using Amazon.Extensions.Configuration.SystemsManager.Internal; using Amazon.Extensions.NETCore.Setup; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.Configuration { /// <summary> /// Extension methods for registering <see cref="SystemsManagerConfigurationProvider"/> with <see cref="IConfigurationBuilder"/>. /// </summary> public static class SystemsManagerExtensions { /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager Client connection</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <param name="optional">Whether the AWS Systems Manager Parameters are optional.</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path, AWSOptions awsOptions, bool optional, TimeSpan reloadAfter) { if (path == null) throw new ArgumentNullException(nameof(path)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddSystemsManager(ConfigureSource(path, awsOptions, optional, reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager Client connection</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <param name="optional">Whether the AWS Systems Manager Parameters are optional.</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path, AWSOptions awsOptions, bool optional) { if (path == null) throw new ArgumentNullException(nameof(path)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddSystemsManager(ConfigureSource(path, awsOptions, optional)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager Client connection</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path, AWSOptions awsOptions, TimeSpan reloadAfter) { if (path == null) throw new ArgumentNullException(nameof(path)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddSystemsManager(ConfigureSource(path, awsOptions, reloadAfter: reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager Client connection</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path, AWSOptions awsOptions) { if (path == null) throw new ArgumentNullException(nameof(path)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddSystemsManager(ConfigureSource(path, awsOptions)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <param name="optional">Whether the AWS Systems Manager Parameters are optional.</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path, bool optional, TimeSpan reloadAfter) { if (path == null) throw new ArgumentNullException(nameof(path)); return builder.AddSystemsManager(ConfigureSource(path, null, optional, reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <param name="optional">Whether the AWS Systems Manager Parameters are optional.</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path, bool optional) { if (path == null) throw new ArgumentNullException(nameof(path)); return builder.AddSystemsManager(ConfigureSource(path, null, optional)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path, TimeSpan reloadAfter) { if (path == null) throw new ArgumentNullException(nameof(path)); return builder.AddSystemsManager(ConfigureSource(path, null, reloadAfter: reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter Store with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="path">The path that variable names must start with. The path will be removed from the variable names.</param> /// <exception cref="ArgumentNullException"><see cref="path"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return builder.AddSystemsManager(ConfigureSource(path, null)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager Parameter variables with a specified path. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="configureSource">Configures the source.</param> /// <exception cref="ArgumentNullException"><see cref="configureSource"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configureSource"/>.<see cref="SystemsManagerConfigurationSource.Path"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddSystemsManager(this IConfigurationBuilder builder, Action<SystemsManagerConfigurationSource> configureSource) { if (configureSource == null) throw new ArgumentNullException(nameof(configureSource)); var source = new SystemsManagerConfigurationSource(); configureSource(source); if (string.IsNullOrWhiteSpace(source.Path)) throw new ArgumentNullException(nameof(source.Path)); if (source.AwsOptions != null) return builder.Add(source); source.AwsOptions = AwsOptionsProvider.GetAwsOptions(builder); return builder.Add(source); } private static Action<SystemsManagerConfigurationSource> ConfigureSource(string path, AWSOptions awsOptions, bool optional = false, TimeSpan? reloadAfter = null) { return configurationSource => { configurationSource.Path = path; configurationSource.AwsOptions = awsOptions; configurationSource.Optional = optional; configurationSource.ReloadAfter = reloadAfter; }; } } }
193
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Net.Http; using Amazon.Extensions.NETCore.Setup; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager.AppConfig { /// <inheritdoc /> /// <summary> /// Represents AWS Systems Manager AppConfig variables as an <see cref="ISystemsManagerConfigurationSource" />. /// </summary> public class AppConfigConfigurationSource : ISystemsManagerConfigurationSource { /// <summary> /// AppConfig Application Id. /// </summary> public string ApplicationId { get; set; } /// <summary> /// AppConfig Environment Id. /// </summary> public string EnvironmentId { get; set; } /// <summary> /// AppConfig Configuration Profile Id. /// </summary> public string ConfigProfileId { get; set; } /// <summary> /// <see cref="AWSOptions"/> used to create an AWS Systems Manager Client />. /// </summary> public AWSOptions AwsOptions { get; set; } /// <inheritdoc /> public bool Optional { get; set; } /// <inheritdoc /> public TimeSpan? ReloadAfter { get; set; } /// <summary> /// Indicates to use configured lambda extension HTTP client to retrieve AppConfig data. /// </summary> internal bool UseLambdaExtension { get; set; } /// <summary> /// Used only when integrating with the AWS AppConfig Lambda extension. /// /// This property allows customizing the HttpClient connecting to the AWS AppConfig Lambda extension. This is useful /// to instrument the HttpClient for telemetry. For example adding the Amazon.XRay.Recorder.Handlers.System.Net.HttpClientXRayTracingHandler handle for AWS X-Ray tracing. /// </summary> public HttpClient CustomHttpClientForLambdaExtension { get; set; } /// <inheritdoc /> public Action<SystemsManagerExceptionContext> OnLoadException { get; set; } /// <inheritdoc /> public IConfigurationProvider Build(IConfigurationBuilder builder) { return new SystemsManagerConfigurationProvider(this); } } }
78
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.Extensions.Configuration.SystemsManager; using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Amazon.Extensions.Configuration.SystemsManager.Internal; using Amazon.Extensions.NETCore.Setup; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.Configuration { /// <summary> /// Extension methods for registering <see cref="SystemsManagerConfigurationProvider"/> with <see cref="IConfigurationBuilder"/>. /// </summary> public static class AppConfigExtensions { /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager AppConfig Client connection</param> /// <param name="optional">Whether the AWS Systems Manager AppConfig is optional.</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, AWSOptions awsOptions, bool optional, TimeSpan? reloadAfter) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId, awsOptions, optional, reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager AppConfig Client connection</param> /// <param name="optional">Whether the AWS Systems Manager AppConfig is optional.</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, AWSOptions awsOptions, bool optional) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId, awsOptions, optional)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager AppConfig Client connection</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, AWSOptions awsOptions, TimeSpan? reloadAfter) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId, awsOptions, reloadAfter: reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="awsOptions"><see cref="AWSOptions"/> used to create an AWS Systems Manager AppConfig Client connection</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="awsOptions"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, AWSOptions awsOptions) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); if (awsOptions == null) throw new ArgumentNullException(nameof(awsOptions)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId, awsOptions)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="optional">Whether the AWS Systems Manager AppConfig is optional.</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, bool optional, TimeSpan? reloadAfter) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId, optional: optional, reloadAfter: reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="reloadAfter">Initiate reload after TimeSpan</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, TimeSpan? reloadAfter) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId, reloadAfter: reloadAfter)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="optional">Whether the AWS Systems Manager AppConfig is optional.</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, bool optional) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId, optional: optional)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); return builder.AddAppConfig(ConfigureSource(applicationId, environmentId, configProfileId)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AppConfig. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="source">Configuration source.</param> /// <exception cref="ArgumentNullException"><see cref="source"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="source"/>.<see cref="AppConfigConfigurationSource.ApplicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="source"/>.<see cref="AppConfigConfigurationSource.EnvironmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="source"/>.<see cref="AppConfigConfigurationSource.ConfigProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfig(this IConfigurationBuilder builder, AppConfigConfigurationSource source) { if (source == null) throw new ArgumentNullException(nameof(source)); if (source.ApplicationId == null) throw new ArgumentNullException(nameof(source.ApplicationId)); if (source.EnvironmentId == null) throw new ArgumentNullException(nameof(source.EnvironmentId)); if (source.ConfigProfileId == null) throw new ArgumentNullException(nameof(source.ConfigProfileId)); if (source.AwsOptions == null) { source.AwsOptions = AwsOptionsProvider.GetAwsOptions(builder); } return builder.Add(source); } private static AppConfigConfigurationSource ConfigureSource( string applicationId, string environmentId, string configProfileId, AWSOptions awsOptions = null, bool optional = false, TimeSpan? reloadAfter = null ) { return new AppConfigConfigurationSource { ApplicationId = applicationId, EnvironmentId = environmentId, ConfigProfileId = configProfileId, AwsOptions = awsOptions, Optional = optional, ReloadAfter = reloadAfter }; } } }
256
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.Extensions.Configuration.SystemsManager; using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Amazon.Runtime; using Amazon.AppConfigData; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.Configuration { /// <summary> /// Extension methods for registering <see cref="SystemsManagerConfigurationProvider"/> with <see cref="IConfigurationBuilder"/>. /// </summary> public static class AppConfigForLambdaExtensions { /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AWS AppConfig using the AWS Lambda Extension. /// For more information about using the AppConfig Lambda Extension checkout the <a href="https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions.html">AppConfig user guide</a>. /// </summary> /// <remarks> /// The AppConfig Lambda extension reloads configuration data using the interval set by the AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS environment variable /// or 45 seconds if not set. The .NET configuration provider will refresh at the same interval plus a 5 second buffer for the extension to complete its update /// process. /// </remarks> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <param name="optional">Whether the AWS Systems Manager AppConfig is optional.</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfigUsingLambdaExtension(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId, bool optional) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); return builder.AddAppConfigUsingLambdaExtension(ConfigureSource(applicationId, environmentId, configProfileId, optional: optional)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AWS AppConfig using the AWS Lambda Extension. /// For more information about using the AppConfig Lambda Extension checkout the <a href="https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions.html">AppConfig user guide</a>. /// </summary> /// <remarks> /// The AppConfig Lambda extension reloads configuration data using the interval set by the AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS environment variable /// or 45 seconds if not set. The .NET configuration provider will refresh at the same interval plus a 5 second buffer for the extension to complete its update /// process. /// </remarks> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="applicationId">The AppConfig application id.</param> /// <param name="environmentId">The AppConfig environment id.</param> /// <param name="configProfileId">The AppConfig configuration profile id.</param> /// <exception cref="ArgumentNullException"><see cref="applicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="environmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="configProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfigUsingLambdaExtension(this IConfigurationBuilder builder, string applicationId, string environmentId, string configProfileId) { if (applicationId == null) throw new ArgumentNullException(nameof(applicationId)); if (environmentId == null) throw new ArgumentNullException(nameof(environmentId)); if (configProfileId == null) throw new ArgumentNullException(nameof(configProfileId)); return builder.AddAppConfigUsingLambdaExtension(ConfigureSource(applicationId, environmentId, configProfileId)); } /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from AWS Systems Manager AWS AppConfig using the AWS Lambda Extension. /// For more information about using the AppConfig Lambda Extension checkout the <a href="https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions.html">AppConfig user guide</a>. /// </summary> /// <remarks> /// The AppConfig Lambda extension reloads configuration data using the interval set by the AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS environment variable /// or 45 seconds if not set. The .NET configuration provider will refresh at the same interval plus a 5 second buffer for the extension to complete its update /// process. /// </remarks> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="source">Configuration source.</param> /// <exception cref="ArgumentNullException"><see cref="source"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="source"/>.<see cref="AppConfigConfigurationSource.ApplicationId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="source"/>.<see cref="AppConfigConfigurationSource.EnvironmentId"/> cannot be null</exception> /// <exception cref="ArgumentNullException"><see cref="source"/>.<see cref="AppConfigConfigurationSource.ConfigProfileId"/> cannot be null</exception> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAppConfigUsingLambdaExtension(this IConfigurationBuilder builder, AppConfigConfigurationSource source) { if (source == null) throw new ArgumentNullException(nameof(source)); if (source.ApplicationId == null) throw new ArgumentNullException(nameof(source.ApplicationId)); if (source.EnvironmentId == null) throw new ArgumentNullException(nameof(source.EnvironmentId)); if (source.ConfigProfileId == null) throw new ArgumentNullException(nameof(source.ConfigProfileId)); // Create a specific instance of AmazonAppConfigClient that is configured to make calls to the endpoint setup by the AppConfig Lambda layer. source.UseLambdaExtension = true; if(!source.ReloadAfter.HasValue) { // default polling duration is 45 seconds https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions.html var reloadAfter = 45; // Since the user is using Lambda extension which automatically refreshes the data default to the configuration provider defaulting // to reload at the rate the extension reloads plus 5 second buffer. var reloadAfterStr = Environment.GetEnvironmentVariable("AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS"); if (reloadAfterStr != null && !int.TryParse(reloadAfterStr, out reloadAfter)) { throw new ArgumentException("Environment variable AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS used for computing ReloadAfter is not set to a valid integer"); } reloadAfter += 5; source.ReloadAfter = TimeSpan.FromSeconds(reloadAfter); } return builder.Add(source); } private static AppConfigConfigurationSource ConfigureSource( string applicationId, string environmentId, string configProfileId, bool optional = false ) { return new AppConfigConfigurationSource { ApplicationId = applicationId, EnvironmentId = environmentId, ConfigProfileId = configProfileId, Optional = optional }; } } }
146
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Amazon.AppConfigData; using Amazon.AppConfigData.Model; using Amazon.Extensions.Configuration.SystemsManager.Internal; namespace Amazon.Extensions.Configuration.SystemsManager.AppConfig { public class AppConfigProcessor : ISystemsManagerProcessor { private AppConfigConfigurationSource Source { get; } private IDictionary<string, string> LastConfig { get; set; } private string PollConfigurationToken { get; set; } private DateTime NextAllowedPollTime { get; set; } private SemaphoreSlim _lastConfigLock = new SemaphoreSlim(1, 1); private const int _lastConfigLockTimeout = 3000; private Uri _lambdaExtensionUri; private HttpClient _lambdaExtensionClient; private IAmazonAppConfigData _appConfigDataClient; public AppConfigProcessor(AppConfigConfigurationSource source) { Source = source; if (source.ApplicationId == null) throw new ArgumentNullException(nameof(source.ApplicationId)); if (source.EnvironmentId == null) throw new ArgumentNullException(nameof(source.EnvironmentId)); if (source.ConfigProfileId == null) throw new ArgumentNullException(nameof(source.ConfigProfileId)); // Check to see if the function is being run inside Lambda. If it is not because it is running in a integ test or in the // the .NET Lambda Test Tool the Lambda extension is not available and fallback to using the AppConfig service directly. if(Source.UseLambdaExtension && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME"))) { var port = Environment.GetEnvironmentVariable("AWS_APPCONFIG_EXTENSION_HTTP_PORT") ?? "2772"; _lambdaExtensionUri = new Uri($"http://localhost:{port}/applications/{Source.ApplicationId}/environments/{Source.EnvironmentId}/configurations/{Source.ConfigProfileId}"); _lambdaExtensionClient = source.CustomHttpClientForLambdaExtension ?? new HttpClient(); } else { if(source.AwsOptions != null) { _appConfigDataClient = source.AwsOptions.CreateServiceClient<IAmazonAppConfigData>(); } else { _appConfigDataClient = new AmazonAppConfigDataClient(); } if (_appConfigDataClient is AmazonAppConfigDataClient impl) { impl.BeforeRequestEvent += ServiceClientAppender.ServiceClientBeforeRequestEvent; } } } public async Task<IDictionary<string, string>> GetDataAsync() { if(_appConfigDataClient != null) { return await GetDataFromServiceAsync().ConfigureAwait(false); } else { return await GetDataFromLambdaExtensionAsync().ConfigureAwait(false); } } private async Task<IDictionary<string,string>> GetDataFromLambdaExtensionAsync() { using (var response = await _lambdaExtensionClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, _lambdaExtensionUri)).ConfigureAwait(false)) using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { LastConfig = ParseConfig(response.Content.Headers.ContentType.ToString(), stream); } return LastConfig; } private async Task<IDictionary<string, string>> GetDataFromServiceAsync() { if(await _lastConfigLock.WaitAsync(_lastConfigLockTimeout).ConfigureAwait(false)) { try { if(DateTime.UtcNow < NextAllowedPollTime) { return LastConfig; } if (string.IsNullOrEmpty(PollConfigurationToken)) { this.PollConfigurationToken = await GetInitialConfigurationTokenAsync(_appConfigDataClient).ConfigureAwait(false); } var request = new GetLatestConfigurationRequest { ConfigurationToken = PollConfigurationToken }; var response = await _appConfigDataClient.GetLatestConfigurationAsync(request).ConfigureAwait(false); PollConfigurationToken = response.NextPollConfigurationToken; NextAllowedPollTime = DateTime.UtcNow.AddSeconds(response.NextPollIntervalInSeconds); // Configuration is empty when the last received config is the latest // so only attempt to parse the AppConfig response when it is not empty if (response.ContentLength > 0) { LastConfig = ParseConfig(response.ContentType, response.Configuration); } } finally { _lastConfigLock.Release(); } } else { return LastConfig; } return LastConfig; } private async Task<string> GetInitialConfigurationTokenAsync(IAmazonAppConfigData appConfigClient) { var request = new StartConfigurationSessionRequest { ApplicationIdentifier = Source.ApplicationId, EnvironmentIdentifier = Source.EnvironmentId, ConfigurationProfileIdentifier = Source.ConfigProfileId }; return (await appConfigClient.StartConfigurationSessionAsync(request).ConfigureAwait(false)).InitialConfigurationToken; } private static IDictionary<string, string> ParseConfig(string contentType, Stream configuration) { // Content-Type has format "media-type; charset" or "media-type; boundary" (for multipart entities). if (contentType != null) { contentType = contentType.Split(';')[0]; } switch (contentType) { case "application/json": return JsonConfigurationParser.Parse(configuration); default: throw new NotImplementedException($"Not implemented AppConfig type: {contentType}"); } } } }
177
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Extensions.NETCore.Setup; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager.Internal { public static class AwsOptionsProvider { private const string AwsOptionsConfigurationKey = "AWS_CONFIGBUILDER_AWSOPTIONS"; public static AWSOptions GetAwsOptions(IConfigurationBuilder builder) { if (builder.Properties.TryGetValue(AwsOptionsConfigurationKey, out var value) && value is AWSOptions existingOptions) { return existingOptions; } var config = builder.Build(); var newOptions = config.GetAWSOptions(); if (builder.Properties.ContainsKey(AwsOptionsConfigurationKey)) { builder.Properties[AwsOptionsConfigurationKey] = newOptions; } else { builder.Properties.Add(AwsOptionsConfigurationKey, newOptions); } return newOptions; } } }
48
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections.Generic; namespace Amazon.Extensions.Configuration.SystemsManager.Internal { public static class DictionaryExtensions { public static bool EquivalentTo<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second) => EquivalentTo(first, second, null); public static bool EquivalentTo<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second, IEqualityComparer<TValue> valueComparer) { if (first == second) return true; if (first == null || second == null) return false; if (first.Count != second.Count) return false; valueComparer = valueComparer ?? EqualityComparer<TValue>.Default; foreach (var kvp in first) { if (!second.TryGetValue(kvp.Key, out var secondValue)) return false; if (!valueComparer.Equals(kvp.Value, secondValue)) return false; } return true; } } }
40
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.Extensions.Configuration.SystemsManager.Internal { public interface ISystemsManagerProcessor { Task<IDictionary<string, string>> GetDataAsync(); } }
26
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager.Internal { public class JsonConfigurationParser { private JsonConfigurationParser() { } private readonly IDictionary<string, string> _data = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase); private readonly Stack<string> _context = new Stack<string>(); private string _currentPath; public static IDictionary<string, string> Parse(Stream input) { using (var doc = JsonDocument.Parse(input)) { var parser = new JsonConfigurationParser(); parser.VisitElement(doc.RootElement); return parser._data; } } public static IDictionary<string, string> Parse(string input) { using (var doc = JsonDocument.Parse(input)) { var parser = new JsonConfigurationParser(); parser.VisitElement(doc.RootElement); return parser._data; } } private void VisitElement(JsonElement element) { switch (element.ValueKind) { case JsonValueKind.Undefined: break; case JsonValueKind.Object: foreach (var property in element.EnumerateObject()) { EnterContext(property.Name); VisitElement(property.Value); ExitContext(); } break; case JsonValueKind.Array: VisitArray(element); break; case JsonValueKind.String: case JsonValueKind.Number: case JsonValueKind.True: case JsonValueKind.False: VisitPrimitive(element); break; case JsonValueKind.Null: VisitNull(element); break; } } private void VisitArray(JsonElement array) { int index = 0; foreach (var item in array.EnumerateArray()) { EnterContext(index.ToString(CultureInfo.InvariantCulture)); VisitElement(item); ExitContext(); index++; } } private void VisitNull(JsonElement data) { var key = _currentPath; _data[key] = null; } private void VisitPrimitive(JsonElement data) { var key = _currentPath; if (_data.ContainsKey(key)) { throw new FormatException($"A duplicate key '{key}' was found."); } _data[key] = data.ToString(); } private void EnterContext(string context) { _context.Push(context); _currentPath = ConfigurationPath.Combine(_context.Reverse()); } private void ExitContext() { _context.Pop(); _currentPath = ConfigurationPath.Combine(_context.Reverse()); } } }
129
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Reflection; using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Amazon.Runtime; namespace Amazon.Extensions.Configuration.SystemsManager.Internal { public static class ServiceClientAppender { private const string UserAgentHeader = "User-Agent"; private static readonly string AssemblyVersion = typeof(AppConfigProcessor).GetTypeInfo().Assembly.GetName().Version.ToString(); public static void ServiceClientBeforeRequestEvent(object sender, RequestEventArgs e) { if (e is WebServiceRequestEventArgs args) { if (args.Headers.ContainsKey(UserAgentHeader)) { args.Headers[UserAgentHeader] = args.Headers[UserAgentHeader] + " SSMConfigProvider/" + AssemblyVersion; } } } } }
39
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.SimpleSystemsManagement; using Amazon.SimpleSystemsManagement.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; namespace Amazon.Extensions.Configuration.SystemsManager.Internal { public class SystemsManagerProcessor : ISystemsManagerProcessor { private const string SecretsManagerPath = "/aws/reference/secretsmanager/"; private SystemsManagerConfigurationSource Source { get; } public SystemsManagerProcessor(SystemsManagerConfigurationSource source) { if (source.AwsOptions == null) throw new ArgumentNullException(nameof(source.AwsOptions)); if (source.Path == null) throw new ArgumentNullException(nameof(source.Path)); Source = source; Source.ParameterProcessor = Source.ParameterProcessor ?? (IsSecretsManagerPath(Source.Path) ? new JsonParameterProcessor() : new DefaultParameterProcessor()); } public async Task<IDictionary<string, string>> GetDataAsync() { return IsSecretsManagerPath(Source.Path) ? await GetParameterAsync().ConfigureAwait(false) : await GetParametersByPathAsync().ConfigureAwait(false); } private async Task<IDictionary<string, string>> GetParametersByPathAsync() { using (var client = Source.AwsOptions.CreateServiceClient<IAmazonSimpleSystemsManagement>()) { if (client is AmazonSimpleSystemsManagementClient impl) { impl.BeforeRequestEvent += ServiceClientAppender.ServiceClientBeforeRequestEvent; } var parameters = new List<Parameter>(); string nextToken = null; do { var response = await client.GetParametersByPathAsync(new GetParametersByPathRequest { Path = Source.Path, Recursive = true, WithDecryption = true, NextToken = nextToken, ParameterFilters = Source.Filters }).ConfigureAwait(false); nextToken = response.NextToken; parameters.AddRange(response.Parameters); } while (!string.IsNullOrEmpty(nextToken)); return AddPrefix(Source.ParameterProcessor.ProcessParameters(parameters, Source.Path), Source.Prefix); } } private async Task<IDictionary<string, string>> GetParameterAsync() { using (var client = Source.AwsOptions.CreateServiceClient<IAmazonSimpleSystemsManagement>()) { if (client is AmazonSimpleSystemsManagementClient impl) { impl.BeforeRequestEvent += ServiceClientAppender.ServiceClientBeforeRequestEvent; } var response = await client.GetParameterAsync(new GetParameterRequest { Name = Source.Path, WithDecryption = true }).ConfigureAwait(false); var prefix = Source.Prefix; return AddPrefix(Source.ParameterProcessor.ProcessParameters(new []{response.Parameter}, Source.Path), prefix); } } public static bool IsSecretsManagerPath(string path) => path.StartsWith(SecretsManagerPath, StringComparison.OrdinalIgnoreCase); public static IDictionary<string, string> AddPrefix(IDictionary<string, string> input, string prefix) { return string.IsNullOrEmpty(prefix) ? input : input.ToDictionary(pair => $"{prefix}{ConfigurationPath.KeyDelimiter}{pair.Key}", pair => pair.Value, StringComparer.OrdinalIgnoreCase); } } }
99
aws-dotnet-extensions-configuration
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Amazon; using Amazon.AppConfig; using Amazon.AppConfig.Model; using Amazon.Extensions.NETCore.Setup; using Microsoft.Extensions.Configuration; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Integ { public class AppConfigEndToEndTests { IAmazonAppConfig _appConfigClient = new AmazonAppConfigClient(RegionEndpoint.USWest2); [Fact] public async Task RefreshConfiguration() { var configSettings = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; (string applicationId, string environmentId, string configProfileId) = await CreateAppConfigResourcesAsync("RefreshWebAppTest", configSettings); try { var builder = new ConfigurationBuilder() .AddAppConfig(applicationId, environmentId, configProfileId, new AWSOptions {Region = RegionEndpoint.USWest2 }, TimeSpan.FromSeconds(5)); var configuration = builder.Build(); Assert.Equal("value1", configuration["key1"]); const string newValue = "newValue1"; configSettings["key1"] = newValue; var versionNumber = await CreateNewHostedConfig(applicationId, configProfileId, configSettings); await PerformDeploymentAsync(applicationId, environmentId, configProfileId, versionNumber); for(int i = 0; i < 10; i++) { // Wait for ConfigProvider to perform the reload await Task.Delay(TimeSpan.FromSeconds(10)); var value = configuration["key1"]; if(string.Equals(newValue, value)) { break; } } Assert.Equal(newValue, configuration["key1"]); } finally { await CleanupAppConfigResourcesAsync(applicationId, environmentId, configProfileId); } } [Fact] public async Task JsonWithCharsetConfiguration() { var configSettings = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; (string applicationId, string environmentId, string configProfileId) = await CreateAppConfigResourcesAsync("JsonWithCharsetConfiguration", configSettings, "application/json; charset=utf-8"); try { var builder = new ConfigurationBuilder() .AddAppConfig(applicationId, environmentId, configProfileId, new AWSOptions { Region = RegionEndpoint.USWest2 }, TimeSpan.FromSeconds(5)); var configuration = builder.Build(); Assert.Equal("value1", configuration["key1"]); } finally { await CleanupAppConfigResourcesAsync(applicationId, environmentId, configProfileId); } } private async Task CleanupAppConfigResourcesAsync(string applicationId, string environmentId, string configProfileId) { await _appConfigClient.DeleteEnvironmentAsync(new DeleteEnvironmentRequest {ApplicationId = applicationId, EnvironmentId = environmentId }); var listHostConfigResponse = await _appConfigClient.ListHostedConfigurationVersionsAsync(new ListHostedConfigurationVersionsRequest { ApplicationId = applicationId, ConfigurationProfileId = configProfileId }); foreach(var item in listHostConfigResponse.Items) { await _appConfigClient.DeleteHostedConfigurationVersionAsync(new DeleteHostedConfigurationVersionRequest { ApplicationId = item.ApplicationId, ConfigurationProfileId = item.ConfigurationProfileId, VersionNumber = item.VersionNumber }); } await _appConfigClient.DeleteConfigurationProfileAsync(new DeleteConfigurationProfileRequest { ApplicationId = applicationId, ConfigurationProfileId = configProfileId }); await _appConfigClient.DeleteApplicationAsync(new DeleteApplicationRequest {ApplicationId = applicationId }); } private async Task<(string applicationId, string environmentId, string configProfileId)> CreateAppConfigResourcesAsync(string seedName, IDictionary<string, string> configs, string contentType = "application/json") { var nameSuffix = DateTime.Now.Ticks; var createAppResponse = await _appConfigClient.CreateApplicationAsync(new CreateApplicationRequest { Name = seedName + "-" + nameSuffix }); var createConfigResponse = await _appConfigClient.CreateConfigurationProfileAsync(new CreateConfigurationProfileRequest { ApplicationId = createAppResponse.Id, Name = seedName + "-" + nameSuffix, LocationUri = "hosted" }); var createEnvironmentResponse = await _appConfigClient.CreateEnvironmentAsync(new CreateEnvironmentRequest { ApplicationId = createAppResponse.Id, Name = seedName + "-" + nameSuffix }); var versionNumber = await CreateNewHostedConfig(createAppResponse.Id, createConfigResponse.Id, configs, contentType); await PerformDeploymentAsync(createAppResponse.Id, createEnvironmentResponse.Id, createConfigResponse.Id, versionNumber); return (createAppResponse.Id, createEnvironmentResponse.Id, createConfigResponse.Id); } private async Task<string> CreateNewHostedConfig(string applicationId, string configProfileId, IDictionary<string, string> configs, string contentType = "application/json") { var json = JsonSerializer.Serialize(configs); var createHostedresponse = await _appConfigClient.CreateHostedConfigurationVersionAsync(new CreateHostedConfigurationVersionRequest { ApplicationId = applicationId, ConfigurationProfileId = configProfileId, ContentType = contentType, Content = new MemoryStream(UTF8Encoding.UTF8.GetBytes(json)) }); return createHostedresponse.VersionNumber.ToString(); } private async Task PerformDeploymentAsync(string applicationId, string environmentId, string configProfileId, string configVersionNumber, bool waitForDeployment = true) { var deploymentStrategyId = await GetDeploymentStrategyId(); var deploymentResponse = await _appConfigClient.StartDeploymentAsync(new StartDeploymentRequest { ApplicationId = applicationId, EnvironmentId = environmentId, ConfigurationProfileId = configProfileId, ConfigurationVersion = configVersionNumber, DeploymentStrategyId = deploymentStrategyId }); if(waitForDeployment) { await WaitForDeploymentAsync(applicationId, environmentId); } } private async Task WaitForDeploymentAsync(string applicationId, string environmentId) { var getRequest = new GetEnvironmentRequest {ApplicationId = applicationId, EnvironmentId = environmentId }; GetEnvironmentResponse getResponse; do { await Task.Delay(2000); getResponse = await _appConfigClient.GetEnvironmentAsync(getRequest); } while (getResponse.State == EnvironmentState.DEPLOYING); } private async Task<string> GetDeploymentStrategyId() { const string integTestDeploymentStrategyName = "IntegTestFast"; var paginator = _appConfigClient.Paginators.ListDeploymentStrategies(new ListDeploymentStrategiesRequest()); await foreach(var response in paginator.Responses) { var strategy = response.Items.FirstOrDefault(x => string.Equals(x.Name, integTestDeploymentStrategyName)); if (strategy != null) { return strategy.Id; } } var createResponse = await _appConfigClient.CreateDeploymentStrategyAsync(new CreateDeploymentStrategyRequest { Name = integTestDeploymentStrategyName, DeploymentDurationInMinutes = 1, FinalBakeTimeInMinutes = 0, GrowthFactor = 100, ReplicateTo = ReplicateTo.NONE }); return createResponse.Id; } } }
215
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Microsoft.Extensions.Configuration; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Integ { public class ConfigurationBuilderIntegrationTests : IClassFixture<IntegTestFixture> { private IntegTestFixture fixture; public ConfigurationBuilderIntegrationTests(IntegTestFixture fixture) { this.fixture = fixture; } [Fact] public void TestConfigurationBuilder() { var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddSystemsManager(IntegTestFixture.ParameterPrefix, fixture.AWSOptions); var configurations = configurationBuilder.Build(); Assert.All(fixture.TestData, (pair) => { Assert.Equal(pair.Value, configurations[pair.Key]); }); // Since there is no reload going on this should return back immediately. configurations.WaitForSystemsManagerReloadToComplete(TimeSpan.FromHours(1)); } } }
47
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Extensions.NETCore.Setup; using Amazon.SimpleSystemsManagement; using Amazon.SimpleSystemsManagement.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Amazon.Extensions.Configuration.SystemsManager.Integ { public class IntegTestFixture : IDisposable { public const string ParameterPrefix = @"/configuration-extension-testdata/ssm/"; public AWSOptions AWSOptions { get; private set; } private bool disposed = false; public IDictionary<string, string> TestData { get; } = new Dictionary<string, string> { {"hello", "world"}, {"hello2", "world2"}, }; public IntegTestFixture() { AWSOptions = new AWSOptions(); AWSOptions.Region = Amazon.RegionEndpoint.USWest2; seedTestData(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { cleanupTestData(); } disposed = true; } private void seedTestData() { bool success = false; using (var client = AWSOptions.CreateServiceClient<IAmazonSimpleSystemsManagement>()) { var tasks = new List<Task>(); foreach (var kv in TestData) { Console.WriteLine($"Adding parameter: ({ParameterPrefix + kv.Key}, {kv.Value})"); tasks.Add(client.PutParameterAsync(new PutParameterRequest { Name = ParameterPrefix + kv.Key, Value = kv.Value, Type = ParameterType.String })); }; Task.WaitAll(tasks.ToArray()); // due to eventual consistency, wait for 5 sec increments for 3 times to verify // test data is correctly set before executing tests. const int tries = 3; for (int i = 0; i < tries; i++) { int count = 0; GetParametersByPathResponse response; do { response = client.GetParametersByPathAsync(new GetParametersByPathRequest { Path = ParameterPrefix }).Result; count += response.Parameters.Count; } while (!string.IsNullOrEmpty(response.NextToken)); success = (count == TestData.Count); if (success) { Console.WriteLine("Verified that test data is available."); break; } else { Console.WriteLine($"Waiting on test data to be available. Waiting {count + 1}/{tries}"); Thread.Sleep(5 * 1000); } } } if (!success) throw new Exception("Failed to seed integration test data"); } private void cleanupTestData() { Console.Write($"Delete all test parameters with prefix '{ParameterPrefix}'... "); using (var client = AWSOptions.CreateServiceClient<IAmazonSimpleSystemsManagement>()) { GetParametersByPathResponse response; do { response = client.GetParametersByPathAsync(new GetParametersByPathRequest { Path = ParameterPrefix }).Result; client.DeleteParametersAsync(new DeleteParametersRequest { Names = response.Parameters.Select(p => p.Name).ToList() }).Wait(); } while (!string.IsNullOrEmpty(response.NextToken)); // no need to wait for eventual consistency here given we are not running tests back-to-back } Console.WriteLine("Done"); } } }
143
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Amazon.Extensions.NETCore.Setup; using Microsoft.Extensions.Configuration; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class AppConfigConfigurationSourceTests { [Fact] public void BuildShouldReturnSystemsManagerConfigurationProvider() { var source = new AppConfigConfigurationSource { ApplicationId = "appId", EnvironmentId = "envId", ConfigProfileId = "profileId", AwsOptions = new AWSOptions() }; var builder = new ConfigurationBuilder(); var result = source.Build(builder); Assert.IsType<SystemsManagerConfigurationProvider>(result); } } }
43
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Microsoft.Extensions.Configuration; using Moq; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class AppConfigExtensionsTests { [Fact] public void AddAppConfigWithProperInputShouldReturnProperConfigurationBuilder() { var expectedBuilder = new ConfigurationBuilder(); expectedBuilder.Sources.Add(new Mock<AppConfigConfigurationSource>().Object); const string applicationId = "appId"; const string environmentId = "envId"; const string configProfileId = "profId"; var builder = new ConfigurationBuilder(); builder.AddAppConfig(applicationId, environmentId, configProfileId); Assert.Contains( builder.Sources, source => source is AppConfigConfigurationSource configurationSource && configurationSource.ApplicationId == applicationId && configurationSource.EnvironmentId == environmentId && configurationSource.ConfigProfileId == configProfileId ); } [Fact] public void AddAppConfigWithoutAwsOptionsShouldThrowException() { var builder = new ConfigurationBuilder(); Func<IConfigurationBuilder> func = () => builder.AddAppConfig("appId", "envId", "profileId", awsOptions: null); var ex = Assert.Throws<ArgumentNullException>(func); Assert.Contains("awsOptions", ex.Message); } [Fact] public void AddAppConfigWithoutApplicationIdShouldThrowException() { var builder = new ConfigurationBuilder(); Func<IConfigurationBuilder> func = () => builder.AddAppConfig(null, "envId", "profileId"); var ex = Assert.Throws<ArgumentNullException>(func); Assert.Contains("applicationId", ex.Message); } [Fact] public void AddAppConfigWithoutEnvironmentIdShouldThrowException() { var builder = new ConfigurationBuilder(); Func<IConfigurationBuilder> func = () => builder.AddAppConfig("appId", null, "profileId"); var ex = Assert.Throws<ArgumentNullException>(func); Assert.Contains("environmentId", ex.Message); } [Fact] public void AddAppConfigWithoutProfileIdShouldThrowException() { var builder = new ConfigurationBuilder(); Func<IConfigurationBuilder> func = () => builder.AddAppConfig("appId", "envId", null); var ex = Assert.Throws<ArgumentNullException>(func); Assert.Contains("configProfileId", ex.Message); } } }
88
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Reflection; using System.Linq; using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Microsoft.Extensions.Configuration; using Moq; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class AppConfigForLambdaExtensionsTests { [Fact] public void AddAppConfigForLambdaWithProperInputShouldReturnProperConfigurationBuilder() { var expectedBuilder = new ConfigurationBuilder(); expectedBuilder.Sources.Add(new Mock<AppConfigConfigurationSource>().Object); const string applicationId = "appId"; const string environmentId = "envId"; const string configProfileId = "profId"; var builder = new ConfigurationBuilder(); builder.AddAppConfigUsingLambdaExtension(applicationId, environmentId, configProfileId); var configurationSource = builder.Sources.FirstOrDefault(source => source is AppConfigConfigurationSource) as AppConfigConfigurationSource; Assert.NotNull(configurationSource); Assert.Equal(applicationId, configurationSource.ApplicationId); Assert.Equal(environmentId, configurationSource.EnvironmentId); Assert.Equal(configProfileId, configurationSource.ConfigProfileId); var property = typeof(AppConfigConfigurationSource).GetProperty("UseLambdaExtension", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(property); Assert.True((bool)property.GetValue(configurationSource)); } [Fact] public void AddAppConfigForLambdaWithoutApplicationIdShouldThrowException() { var builder = new ConfigurationBuilder(); Func<IConfigurationBuilder> func = () => builder.AddAppConfigUsingLambdaExtension(null, "envId", "profileId"); var ex = Assert.Throws<ArgumentNullException>(func); Assert.Contains("applicationId", ex.Message); } [Fact] public void AddAppConfigForLambdaWithoutEnvironmentIdShouldThrowException() { var builder = new ConfigurationBuilder(); Func<IConfigurationBuilder> func = () => builder.AddAppConfigUsingLambdaExtension("appId", null, "profileId"); var ex = Assert.Throws<ArgumentNullException>(func); Assert.Contains("environmentId", ex.Message); } [Fact] public void AddAppConfigForLambdaWithoutProfileIdShouldThrowException() { var builder = new ConfigurationBuilder(); Func<IConfigurationBuilder> func = () => builder.AddAppConfigUsingLambdaExtension("appId", "envId", null); var ex = Assert.Throws<ArgumentNullException>(func); Assert.Contains("configProfileId", ex.Message); } } }
82
aws-dotnet-extensions-configuration
aws
C#
using System.Collections.Generic; using Amazon.SimpleSystemsManagement.Model; using Moq; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class DefaultParameterProcessorTests { private readonly IParameterProcessor _parameterProcessor; public DefaultParameterProcessorTests() { _parameterProcessor = new DefaultParameterProcessor(); } [Fact] public void ProcessParametersTest() { var parameters = new List<Parameter> { new Parameter {Name = "/start/path/p1/p2-1", Value = "p1:p2-1"}, new Parameter {Name = "/start/path/p1/p2-2", Value = "p1:p2-2"}, new Parameter {Name = "/start/path/p1/p2/p3-1", Value = "p1:p2:p3-1"}, new Parameter {Name = "/start/path/p1/p2/p3-2", Value = "p1:p2:p3-2"}, }; const string path = "/start/path"; var data = _parameterProcessor.ProcessParameters(parameters, path); Assert.All(data, item => Assert.Equal(item.Value, item.Key)); } [Fact] public void ProcessParametersRootTest() { var parameters = new List<Parameter> { new Parameter {Name = "/p1", Value = "p1"}, new Parameter {Name = "p2", Value = "p2"}, }; const string path = "/"; var data = _parameterProcessor.ProcessParameters(parameters, path); Assert.All(data, item => Assert.Equal(item.Value, item.Key)); } } }
51
aws-dotnet-extensions-configuration
aws
C#
using System.Collections.Generic; using Amazon.Extensions.Configuration.SystemsManager.Internal; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class DictionaryExtensionsTests { [Theory] [MemberData(nameof(EquivalentToData))] public void TestEquivalentTo(IDictionary<string, string> first, IDictionary<string, string> second, bool equals) { Assert.Equal(equals, first.EquivalentTo(second)); } public static TheoryData<IDictionary<string, string>, IDictionary<string, string>, bool> EquivalentToData => new TheoryData<IDictionary<string, string>, IDictionary<string, string>, bool> { {new Dictionary<string, string>(), new Dictionary<string, string>(), true}, {new Dictionary<string, string>(), null, false}, {new Dictionary<string, string>(), new Dictionary<string, string> {{"a", "a"}}, false}, {new Dictionary<string, string> {{"a", "a"}}, new Dictionary<string, string> {{"a", "a"}}, true}, {new Dictionary<string, string> {{"a", "a"}}, new Dictionary<string, string> {{"a", "a"}, {"b", "b"}}, false}, {new Dictionary<string, string> {{"a", "a"}}, new Dictionary<string, string> {{"b", "b"}}, false}, {new Dictionary<string, string> {{"a", "a"}}, new Dictionary<string, string> {{"a", "b"}}, false}, {new Dictionary<string, string> {{"a", "a"}}, new Dictionary<string, string> {{"b", "a"}}, false}, {new Dictionary<string, string> {{"a", "a"},{"b", "b"}}, new Dictionary<string, string> {{"b", "b"},{"a", "a"}}, true} }; } }
30
aws-dotnet-extensions-configuration
aws
C#
using System.Collections.Generic; using Amazon.SimpleSystemsManagement.Model; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class JsonParameterProcessorTests { private readonly IParameterProcessor _parameterProcessor; public JsonParameterProcessorTests() { _parameterProcessor = new JsonParameterProcessor(); } [Fact] public void ProcessParametersTest() { var parameters = new List<Parameter> { new Parameter {Name = "/p1", Value = "{\"p1\": \"p1\"}"}, new Parameter {Name = "p2", Value = "{\"p2\": \"p2\"}"}, new Parameter {Name = "/p1/p3", Value = "{\"p3key\": \"p3value\"}"}, new Parameter {Name = "/p4", Value = "{\"p4key\": { \"p5key\": \"p5value\" } }"}, new Parameter {Name = "/p6", Value = "{\"p6key\": { \"p7key\": { \"p8key\": \"p8value\" } } }"}, new Parameter {Name = "/ObjectA", Value = "{\"Bucket\": \"arnA\"}"}, new Parameter {Name = "/ObjectB", Value = "{\"Bucket\": \"arnB\"}"}, new Parameter {Name = "/", Value = "{\"testParam\": \"testValue\"}"} }; var expected = new Dictionary<string, string>() { { "p1:p1", "p1" }, { "p2:p2", "p2" }, { "p1:p3:p3key", "p3value" }, { "p4:p4key:p5key", "p5value" }, { "p6:p6key:p7key:p8key", "p8value" }, { "ObjectA:Bucket", "arnA" }, { "ObjectB:Bucket", "arnB" }, { "testParam", "testValue" } }; const string path = "/"; var data = _parameterProcessor.ProcessParameters(parameters, path); Assert.All(expected, item => Assert.Equal(item.Value, data[item.Key])); } } }
48
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections.Generic; using Amazon.Extensions.Configuration.SystemsManager.AppConfig; using Amazon.Extensions.Configuration.SystemsManager.Internal; using Amazon.Extensions.NETCore.Setup; using Amazon.SimpleSystemsManagement.Model; using Moq; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class SystemsManagerConfigurationProviderTests { private readonly Mock<ISystemsManagerProcessor> _systemsManagerProcessorMock = new Mock<ISystemsManagerProcessor>(); [Fact] public void LoadForParameterStoreShouldReturnProperParameters() { var parameters = new List<Parameter> { new Parameter {Name = "/start/path/p1/p2-1", Value = "p1:p2-1"}, new Parameter {Name = "/start/path/p1/p2-2", Value = "p1:p2-2"}, new Parameter {Name = "/start/path/p1/p2/p3-1", Value = "p1:p2:p3-1"}, new Parameter {Name = "/start/path/p1/p2/p3-2", Value = "p1:p2:p3-2"} }; var parameterProcessorMock = new Mock<IParameterProcessor>(); var provider = ConfigureParameterStoreConfigurationProvider(parameterProcessorMock, parameters); provider.Load(); foreach (var parameter in parameters) { Assert.True(provider.TryGet(parameter.Value, out _)); } parameterProcessorMock.VerifyAll(); } [Fact] public void LoadForAppConfigShouldReturnProperValues() { var values = new Dictionary<string, string> { { "testKey", "testValue" }, { "testKey2", "testValue2" }, { "testKey3", "testValue3" }, { "testKey4", "testValue4" }, { "testKey5", "testValue5" } }; var provider = ConfigureAppConfigConfigurationProvider(values); provider.Load(); foreach (var parameter in values) { Assert.True(provider.TryGet(parameter.Key, out _)); } } private SystemsManagerConfigurationProvider ConfigureParameterStoreConfigurationProvider(Mock<IParameterProcessor> parameterProcessorMock, IReadOnlyCollection<Parameter> parameters) { const string path = "/start/path"; var source = new SystemsManagerConfigurationSource { ParameterProcessor = parameterProcessorMock.Object, AwsOptions = new AWSOptions(), Path = path }; var provider = new SystemsManagerConfigurationProvider(source, _systemsManagerProcessorMock.Object); var getData = new DefaultParameterProcessor().ProcessParameters(parameters, path); _systemsManagerProcessorMock.Setup(p => p.GetDataAsync()).ReturnsAsync(() => getData); return provider; } private SystemsManagerConfigurationProvider ConfigureAppConfigConfigurationProvider(IDictionary<string, string> values) { var source = new AppConfigConfigurationSource { ApplicationId = "appId", EnvironmentId = "envId", ConfigProfileId = "profileId", AwsOptions = new AWSOptions() }; _systemsManagerProcessorMock.Setup(p => p.GetDataAsync()).ReturnsAsync(() => values); var provider = new SystemsManagerConfigurationProvider(source, _systemsManagerProcessorMock.Object); return provider; } } }
110
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Extensions.NETCore.Setup; using Microsoft.Extensions.Configuration; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class SystemsManagerConfigurationSourceTests { [Fact] public void BuildSuccessTest() { var source = new SystemsManagerConfigurationSource { AwsOptions = new AWSOptions(), Path = "/temp/" }; var builder = new ConfigurationBuilder(); var result = source.Build(builder); Assert.IsType<SystemsManagerConfigurationProvider>(result); } [Fact] public void FiltersInitializedTest() { var source = new SystemsManagerConfigurationSource(); Assert.NotNull(source.Filters); } } }
48
aws-dotnet-extensions-configuration
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.Extensions.NETCore.Setup; using Microsoft.Extensions.Configuration; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class SystemsManagerExtensionsTests { [Theory] [MemberData(nameof(SourceExtensionData))] [MemberData(nameof(WithAWSOptionsExtensionData))] [MemberData(nameof(NoAWSOptionsExtensionData))] public void AddSystemsManagerInlineTest(Func<IConfigurationBuilder, IConfigurationBuilder> configurationBuilder, Type exceptionType, string exceptionMessage) { var builder = new ConfigurationBuilder(); IConfigurationBuilder ExecuteBuilder() => configurationBuilder(builder); if (exceptionType != null) { var ex = Assert.Throws(exceptionType, ExecuteBuilder); Assert.Contains(exceptionMessage, ex.Message, StringComparison.Ordinal); } else { var result = ExecuteBuilder(); Assert.Equal(builder, result); } } public static TheoryData<Func<IConfigurationBuilder, IConfigurationBuilder>, Type, string> SourceExtensionData => new TheoryData<Func<IConfigurationBuilder, IConfigurationBuilder>, Type, string> { {builder => builder.AddSystemsManager(CreateSource(null, null, false, null, null)), typeof(ArgumentNullException), "Path"}, {builder => builder.AddSystemsManager(CreateSource(null, null, true, null, null)), typeof(ArgumentNullException), "Path"}, {builder => builder.AddSystemsManager(CreateSource("/path", null, false, null, null)), null, null}, {builder => builder.AddSystemsManager(CreateSource("/aws/reference/secretsmanager/somevalue", null, false, null, null)), null, null} }; public static TheoryData<Func<IConfigurationBuilder, IConfigurationBuilder>, Type, string> WithAWSOptionsExtensionData => new TheoryData<Func<IConfigurationBuilder, IConfigurationBuilder>, Type, string> { {builder => builder.AddSystemsManager(null, null), typeof(ArgumentNullException), "path"}, {builder => builder.AddSystemsManager("/path", null), typeof(ArgumentNullException), "awsOptions"}, {builder => builder.AddSystemsManager(null, new AWSOptions()), typeof(ArgumentNullException), "path"}, {builder => builder.AddSystemsManager("/aws/reference/secretsmanager/somevalue", new AWSOptions()), null, null}, {builder => builder.AddSystemsManager("/path", new AWSOptions(), true), null, null}, {builder => builder.AddSystemsManager("/path", new AWSOptions(), false), null, null}, {builder => builder.AddSystemsManager("/path", new AWSOptions(), TimeSpan.Zero), null, null}, {builder => builder.AddSystemsManager("/path", new AWSOptions(), TimeSpan.Zero), null, null}, {builder => builder.AddSystemsManager("/path", new AWSOptions(), true, TimeSpan.Zero), null, null}, {builder => builder.AddSystemsManager("/path", new AWSOptions(), false, TimeSpan.Zero), null, null} }; public static TheoryData<Func<IConfigurationBuilder, IConfigurationBuilder>, Type, string> NoAWSOptionsExtensionData => new TheoryData<Func<IConfigurationBuilder, IConfigurationBuilder>, Type, string> { {builder => builder.AddSystemsManager(null as string), typeof(ArgumentNullException), "path"}, {builder => builder.AddSystemsManager("/path"), null, null}, {builder => builder.AddSystemsManager("/aws/reference/secretsmanager/somevalue"), null, null}, {builder => builder.AddSystemsManager("/path", true), null, null}, {builder => builder.AddSystemsManager("/path", false), null, null}, {builder => builder.AddSystemsManager("/path", TimeSpan.Zero), null, null}, {builder => builder.AddSystemsManager("/path", TimeSpan.Zero), null, null}, {builder => builder.AddSystemsManager("/path", true, TimeSpan.Zero), null, null}, {builder => builder.AddSystemsManager("/path", false, TimeSpan.Zero), null, null} }; private static Action<SystemsManagerConfigurationSource> CreateSource(string path, AWSOptions awsOptions, bool optional, TimeSpan? reloadAfter, Action<SystemsManagerExceptionContext> onLoadException) { return source => { source.Path = path; source.AwsOptions = awsOptions; source.Optional = optional; source.ReloadAfter = reloadAfter; source.OnLoadException = onLoadException; }; } } }
94
aws-dotnet-extensions-configuration
aws
C#
using System.Collections.Generic; using System.Linq; using Amazon.Extensions.Configuration.SystemsManager.Internal; using Amazon.SimpleSystemsManagement.Model; using Moq; using Xunit; namespace Amazon.Extensions.Configuration.SystemsManager.Tests { public class SystemsManagerProcessorTests { [Theory] [InlineData("/aws/reference/secretsmanager/", true)] [InlineData("/not-sm-path/", false)] public void IsSecretsManagerPathTest(string path, bool expected) { Assert.Equal(expected, SystemsManagerProcessor.IsSecretsManagerPath(path)); } [Theory] [InlineData(null)] [InlineData("prefix")] public void AddPrefixTest(string prefix) { var data = new Dictionary<string, string> { { "Key", "Value" } }; var output = SystemsManagerProcessor.AddPrefix(data, prefix); if (prefix == null) { Assert.Equal(data, output); } else { foreach (var item in output) { Assert.StartsWith($"{prefix}:", item.Key); } } } } }
41
aws-dotnet-session-provider
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SampleWebApp { public partial class Default : System.Web.UI.Page { const string PageCountKey = "PageCount"; protected void Page_Load(object sender, EventArgs e) { } public int PageCount { get { if (this.Session[PageCountKey] == null) { this.Session[PageCountKey] = 0; } int value = Convert.ToInt32(this.Session[PageCountKey]); value++; this.Session[PageCountKey] = value; return value; } } } }
35
aws-dotnet-session-provider
aws
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SampleWebApp { public partial class Default { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; } }
27
aws-dotnet-session-provider
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SampleWebApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SampleWebApp")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f1dbf565-0dbc-4399-a5d3-af8ab24bb50e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
36
aws-dotnet-session-provider
aws
C#
/* * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.IO; using System.Web; using System.Web.Configuration; using System.Configuration; using System.Configuration.Provider; using System.Collections.Generic; using System.Collections.Specialized; using System.Web.SessionState; using System.Text; using System.Threading; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.DynamoDBv2.DocumentModel; using Amazon.Runtime; using Amazon.Runtime.Internal.Util; using Amazon.Util; namespace Amazon.SessionProvider { /// <summary> /// DynamoDBSessionStateStore is a custom session state provider that can be used inside of an ASP.NET application. Session state is saved /// inside a DynamoDB table that can be configured in the web.config. If the table does not exist the provider will create /// it during initialization with default read and write units set to 10 and 5 unless configured otherwise. If the table is created /// the application startup will block for about a minute while the table is being created. /// /// Example web.config entry setting up the session state provider. /// <code> /// &lt;sessionState /// mode="Custom" /// customProvider="DynamoDBSessionStoreProvider"&gt; /// &lt;providers&gt; /// &lt;add name="DynamoDBSessionStoreProvider" /// type="Amazon.SessionProvider.DynamoDBSessionStateStore, AWS.SessionProvider" /// AWSProfileName="default" /// AWSProfilesLocation=".aws/credentials" /// Region="us-east-1" /// Table="ASP.NET_SessionState" /// TTLAttributeName="ExpirationTime" /// TTLExpiredSessionsSeconds="86400" /// /&gt; /// &lt;/providers&gt; /// &lt;/sessionState&gt; /// </code> /// /// <para> /// The schema for the table used to store session requires a string hash key with no range key. The provider will look up the name of the hash key during /// initialization so any name can be given for the hash key. /// </para> /// /// <para> /// Below is a list of configuration attributes that can specified in the provider element in the web.config. /// <list type="table"> /// <listheader> /// <term>Config Constant</term> /// <term>Use</term> /// </listheader> /// <item> /// <term>AWSProfileName</term> /// <description>Profile used. This can be set at either the provider or in the appSettings.</description> /// </item> /// <item> /// <term>AWSProfilesLocation</term> /// <description>Location of the credentials file. This can be set at either the provider or in the appSettings.</description> /// </item> /// <item> /// <term>Region</term> /// <description>Required string attribute. The region to use DynamoDB in. Possible values are us-east-1, us-west-1, us-west-2, eu-west-1, ap-northeast-1, ap-southeast-1.</description> /// </item> /// <item> /// <term>Service URL</term> /// <description>The URL of the DynamoDB endpoint. This can be used instead of region. This property is commonly used for connecting to DynamoDB Local (e.g. http://localhost:8000/)</description> /// </item> /// <item> /// <term>Application</term> /// <description>Optional string attribute. Application is used to partition the session data in the table so it can be used for more than one application.</description> /// </item> /// <item> /// <term>Table</term> /// <description>Optional string attribute. The table used to store session data. The default is ASP.NET_SessionState.</description> /// </item> /// <item> /// <term>ReadCapacityUnits</term> /// <description>Optional int attribute. The read capacity units if the table is created. The default is 10.</description> /// </item> /// <item> /// <term>WriteCapacityUnits</term> /// <description>Optional int attribute. The write capacity units if the table is created. The default is 5.</description> /// </item> /// <item> /// <term>UseOnDemandReadWriteCapacity</term> /// <description>Optional boolean attribute. UseOnDemandReadWriteCapacity controls whether the table will be created with its read/write capacity set to On-Demand. Default is false.</description> /// </item> /// <item> /// <term>CreateIfNotExist</term> /// <description>Optional boolean attribute. CreateIfNotExist controls whether the table will be auto created if it doesn't exist. Default is true.</description> /// </item> /// <item> /// <term>StrictDisableSession</term> /// <description>Optional boolean attribute. If EnabledSessionState is False globally or on an individual page/view/controller, ASP.NET will still send a keepalive request to dynamo. Setting this to true disables keepalive requests when EnableSessionState is False. Default is false.</description> /// </item> /// <item> /// <term>TTLAttributeName</term> /// <description>Optional string attribute. The name of the TTL attribute for the table. This must be specified for session items to contain TTL-compatible data.</description> /// </item> /// <item> /// <term>TTLExpiredSessionsSeconds</term> /// <description>Optional int attribute. The minimum number of seconds after session expiration before sessions are eligible for TTL. By default this is 0. This value must be non-negative.</description> /// </item> /// </list> /// </para> /// </summary> public class DynamoDBSessionStateStore : SessionStateStoreProviderBase { private const string CURRENT_RECORD_FORMAT_VERSION = "1"; private const int DESCRIBE_INTERVAL = 5000; private const string ACTIVE_STATUS = "Active"; private static readonly GetItemOperationConfig CONSISTENT_READ_GET = new GetItemOperationConfig(); private static readonly UpdateItemOperationConfig LOCK_UPDATE_CONFIG = new UpdateItemOperationConfig(); private static readonly ILogger _logger = Logger.GetLogger(typeof(DynamoDBSessionStateStore)); static DynamoDBSessionStateStore() { CONSISTENT_READ_GET.ConsistentRead = true; LOCK_UPDATE_CONFIG.Expected = new Document(); LOCK_UPDATE_CONFIG.Expected[ATTRIBUTE_LOCKED] = false; LOCK_UPDATE_CONFIG.ReturnValues = ReturnValues.AllNewAttributes; } // Possible config names set in the web.config. public const string CONFIG_ACCESSKEY = "AWSAccessKey"; public const string CONFIG_SECRETKEY = "AWSSecretKey"; public const string CONFIG_PROFILENAME = "AWSProfileName"; public const string CONFIG_PROFILESLOCATION = "AWSProfilesLocation"; public const string CONFIG_APPLICATION = "Application"; public const string CONFIG_TABLE = "Table"; public const string CONFIG_REGION = "Region"; public const string CONFIG_SERVICE_URL = "ServiceURL"; public const string CONFIG_INITIAL_READ_UNITS = "ReadCapacityUnits"; public const string CONFIG_INITIAL_WRITE_UNITS = "WriteCapacityUnits"; public const string CONFIG_ON_DEMAND_READ_WRITE_CAPACITY = "UseOnDemandReadWriteCapacity"; public const string CONFIG_CREATE_TABLE_IF_NOT_EXIST = "CreateIfNotExist"; public const string CONFIG_STRICT_DISABLE_SESSION = "StrictDisableSession"; public const string CONFIG_TTL_ATTRIBUTE = "TTLAttributeName"; public const string CONFIG_TTL_EXPIRED_SESSIONS_SECONDS = "TTLExpiredSessionsSeconds"; // This is not const because we will use whatever is the hash key defined for // the table as long as it is a string. private static string ATTRIBUTE_SESSION_ID = "SessionId"; // The attribute names stored for the session record. public const string ATTRIBUTE_CREATE_DATE = "CreateDate"; public const string ATTRIBUTE_LOCKED = "Locked"; public const string ATTRIBUTE_LOCK_DATE = "LockDate"; public const string ATTRIBUTE_LOCK_ID = "LockId"; public const string ATTRIBUTE_EXPIRES = "Expires"; public const string ATTRIBUTE_SESSION_ITEMS = "SessionItems"; public const string ATTRIBUTE_FLAGS = "Flags"; public const string ATTRIBUTE_RECORD_FORMAT_VERSION = "Ver"; const string DEFAULT_TABLENAME = "ASP.NET_SessionState"; // Fields that come from the web.config string _accessKey; string _secretKey; string _profileName; string _profilesLocation; string _tableName = DEFAULT_TABLENAME; string _regionName; string _serviceURL; string _application = ""; int _initialReadUnits = 10; int _initialWriteUnits = 5; bool _useOnDemandReadWriteCapacity = false; bool _createIfNotExist = true; bool _strictDisableSession = false; uint _ttlExtraSeconds = 0; string _ttlAttributeName = null; IAmazonDynamoDB _ddbClient; Table _table; TimeSpan _timeout = new TimeSpan(0, 20, 0); /// <summary> /// Default Constructor /// </summary> public DynamoDBSessionStateStore() { } /// <summary> /// Constructor for testing. /// </summary> /// <param name="ddbClient"></param> public DynamoDBSessionStateStore(IAmazonDynamoDB ddbClient) { this._ddbClient = ddbClient; SetupTable(); } /// <summary> /// Constructor for testing. /// </summary> /// <param name="name"></param> /// <param name="config"></param> public DynamoDBSessionStateStore(string name, NameValueCollection config) { Initialize(name, config); } /// <summary> /// Gets the name of the table used to store session data. /// </summary> public string TableName { get { return this._tableName; } } /// <summary> /// Initializes the provider by pulling the config info from the web.config and validate/create the DynamoDB table. /// If the table is being created this method will block until the table is active. /// </summary> /// <param name="name"></param> /// <param name="config"></param> public override void Initialize(string name, NameValueCollection config) { _logger.InfoFormat("Initialize : Initializing Session provider {0}", name); if (config == null) throw new ArgumentNullException("config"); base.Initialize(name, config); GetConfigSettings(config); RegionEndpoint region = null; if(!string.IsNullOrEmpty(this._regionName)) region = RegionEndpoint.GetBySystemName(this._regionName); AWSCredentials credentials = null; if (!string.IsNullOrEmpty(this._accessKey)) { credentials = new BasicAWSCredentials(this._accessKey, this._secretKey); } else if (!string.IsNullOrEmpty(this._profileName)) { if (string.IsNullOrEmpty(this._profilesLocation)) credentials = new StoredProfileAWSCredentials(this._profileName); else credentials = new StoredProfileAWSCredentials(this._profileName, this._profilesLocation); } AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig(); if (region != null) ddbConfig.RegionEndpoint = region; if (!string.IsNullOrEmpty(this._serviceURL)) ddbConfig.ServiceURL = this._serviceURL; if (credentials != null) { this._ddbClient = new AmazonDynamoDBClient(credentials, ddbConfig); } else { this._ddbClient = new AmazonDynamoDBClient(ddbConfig); } ((AmazonDynamoDBClient)this._ddbClient).BeforeRequestEvent += DynamoDBSessionStateStore_BeforeRequestEvent; SetupTable(); } const string UserAgentHeader = "User-Agent"; void DynamoDBSessionStateStore_BeforeRequestEvent(object sender, RequestEventArgs e) { Amazon.Runtime.WebServiceRequestEventArgs args = e as Amazon.Runtime.WebServiceRequestEventArgs; if (args == null || !args.Headers.ContainsKey(UserAgentHeader)) return; args.Headers[UserAgentHeader] = args.Headers[UserAgentHeader] + " SessionStateProvider"; } private void SetupTable() { try { var tableConfig = CreateTableConfig(); this._table = Table.LoadTable(this._ddbClient, tableConfig); } catch (ResourceNotFoundException) { } if (this._table == null) { if (this._createIfNotExist) this._table = CreateTable(); else throw new AmazonDynamoDBException(string.Format("Table {0} was not found to be used to store session state and autocreate is turned off.", this._tableName)); } else { ValidateTable(); } } private void GetConfigSettings(NameValueCollection config) { this._accessKey = config[CONFIG_ACCESSKEY]; this._secretKey = config[CONFIG_SECRETKEY]; this._profileName= config[CONFIG_PROFILENAME]; this._profilesLocation = config[CONFIG_PROFILESLOCATION]; this._regionName = config[CONFIG_REGION]; this._serviceURL = config[CONFIG_SERVICE_URL]; if (!string.IsNullOrEmpty(config[CONFIG_TABLE])) { this._tableName = config[CONFIG_TABLE]; } if (!string.IsNullOrEmpty(config[CONFIG_APPLICATION])) { this._application = config[CONFIG_APPLICATION]; } if (!string.IsNullOrEmpty(config[CONFIG_CREATE_TABLE_IF_NOT_EXIST])) { this._createIfNotExist = bool.Parse(config[CONFIG_CREATE_TABLE_IF_NOT_EXIST]); } if (!string.IsNullOrEmpty(config[CONFIG_INITIAL_READ_UNITS])) { this._initialReadUnits = int.Parse(config[CONFIG_INITIAL_READ_UNITS]); } if (!string.IsNullOrEmpty(config[CONFIG_INITIAL_WRITE_UNITS])) { this._initialWriteUnits = int.Parse(config[CONFIG_INITIAL_WRITE_UNITS]); } if (!string.IsNullOrEmpty(config[CONFIG_ON_DEMAND_READ_WRITE_CAPACITY])) { this._useOnDemandReadWriteCapacity = bool.Parse(config[CONFIG_ON_DEMAND_READ_WRITE_CAPACITY]); } if (!string.IsNullOrEmpty(config[CONFIG_STRICT_DISABLE_SESSION])) { this._strictDisableSession = bool.Parse(config[CONFIG_STRICT_DISABLE_SESSION]); } if (!string.IsNullOrEmpty(config[CONFIG_TTL_ATTRIBUTE])) { this._ttlAttributeName = config[CONFIG_TTL_ATTRIBUTE]; } if (!string.IsNullOrEmpty(config[CONFIG_TTL_EXPIRED_SESSIONS_SECONDS])) { this._ttlExtraSeconds = uint.Parse(config[CONFIG_TTL_EXPIRED_SESSIONS_SECONDS]); } string applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; if (applicationName != null) { Configuration cfg = WebConfigurationManager.OpenWebConfiguration(applicationName); if (cfg != null) { SessionStateSection sessionConfig = cfg.GetSection("system.web/sessionState") as SessionStateSection; if (sessionConfig != null) { this._timeout = sessionConfig.Timeout; } } } } /// <summary> /// Provider returns false for this method. /// </summary> /// <param name="expireCallback"></param> /// <returns></returns> public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) { return false; } /// <summary> /// Returns read-only session-state data from the DynamoDB table. /// </summary> /// <param name="context"></param> /// <param name="sessionId"></param> /// <param name="locked"></param> /// <param name="lockAge"></param> /// <param name="lockId"></param> /// <param name="actionFlags"></param> /// <returns></returns> public override SessionStateStoreData GetItem(HttpContext context, string sessionId, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags) { LogInfo("GetItem", sessionId, context); return GetSessionStoreItem(false, context, sessionId, out locked, out lockAge, out lockId, out actionFlags); } /// <summary> /// Returns session-state data from the DynamoDB table. /// </summary> /// <param name="context"></param> /// <param name="sessionId"></param> /// <param name="locked"></param> /// <param name="lockAge"></param> /// <param name="lockId"></param> /// <param name="actionFlags"></param> /// <returns></returns> public override SessionStateStoreData GetItemExclusive(HttpContext context, string sessionId, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags) { LogInfo("GetItemExclusive", sessionId, context); return GetSessionStoreItem(true, context, sessionId, out locked, out lockAge, out lockId, out actionFlags); } /// <summary> /// Get the session for DynamoDB and optionally lock the record. /// </summary> /// <param name="lockRecord"></param> /// <param name="context"></param> /// <param name="sessionId"></param> /// <param name="locked"></param> /// <param name="lockAge"></param> /// <param name="lockId"></param> /// <param name="actionFlags"></param> /// <returns></returns> private SessionStateStoreData GetSessionStoreItem(bool lockRecord, HttpContext context, string sessionId, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags) { LogInfo("GetSessionStoreItem", sessionId, lockRecord, context); // Initial values for return value and out parameters. SessionStateStoreData item = null; lockAge = TimeSpan.Zero; lockId = Guid.NewGuid().ToString(); locked = false; actionFlags = SessionStateActions.None; bool foundRecord = false; bool deleteData = false; DateTime newLockedDate = DateTime.Now; Document session = null; if (lockRecord) { Document lockDoc = new Document(); lockDoc[ATTRIBUTE_SESSION_ID] = GetHashKey(sessionId); lockDoc[ATTRIBUTE_LOCK_ID] = lockId.ToString(); lockDoc[ATTRIBUTE_LOCKED] = true; lockDoc[ATTRIBUTE_LOCK_DATE] = DateTime.Now; try { session = this._table.UpdateItem(lockDoc, LOCK_UPDATE_CONFIG); locked = false; } catch (ConditionalCheckFailedException) { // This means the record is already locked by another request. locked = true; } } if (session == null) { session = this._table.GetItem(GetHashKey(sessionId), CONSISTENT_READ_GET); if (session == null && lockRecord) { locked = true; } } string serializedItems = null; if (session != null) { DateTime expire = (DateTime)session[ATTRIBUTE_EXPIRES]; if (expire < DateTime.Now) { deleteData = true; locked = false; } else { foundRecord = true; DynamoDBEntry entry; if (session.TryGetValue(ATTRIBUTE_SESSION_ITEMS, out entry)) { serializedItems = (string)entry; } if (session.Contains(ATTRIBUTE_LOCK_ID)) lockId = (string)session[ATTRIBUTE_LOCK_ID]; if (session.Contains(ATTRIBUTE_FLAGS)) actionFlags = (SessionStateActions)((int)session[ATTRIBUTE_FLAGS]); if (session.Contains(ATTRIBUTE_LOCK_DATE) && session[ATTRIBUTE_LOCK_DATE] != null) { DateTime lockDate = (DateTime)session[ATTRIBUTE_LOCK_DATE]; lockAge = DateTime.Now.Subtract(lockDate); } } } if (deleteData) { this.deleteItem(sessionId); } // The record was not found. Ensure that locked is false. if (!foundRecord) { locked = false; lockId = null; } // If the record was found and you obtained a lock, then clear the actionFlags, // and create the SessionStateStoreItem to return. if (foundRecord && !locked) { if (actionFlags == SessionStateActions.InitializeItem) { Document updateDoc = new Document(); updateDoc[ATTRIBUTE_SESSION_ID] = GetHashKey(sessionId); updateDoc[ATTRIBUTE_FLAGS] = 0; this._table.UpdateItem(updateDoc); item = CreateNewStoreData(context, (int)this._timeout.TotalMinutes); } else { item = deserialize(context, serializedItems, (int)this._timeout.TotalMinutes); } } return item; } /// <summary> /// Updates the session-item information in the session-state data store with values from the current request, and clears the lock on the data. /// </summary> /// <param name="context">The HttpContext for the current request.</param> /// <param name="sessionId">The session identifier for the current request.</param> /// <param name="item">The SessionStateStoreData object that contains the current session values to be stored.</param> /// <param name="lockId">The lock identifier for the current request.</param> /// <param name="newItem">true to identify the session item as a new item; false to identify the session item as an existing item.</param> public override void SetAndReleaseItemExclusive(HttpContext context, string sessionId, SessionStateStoreData item, object lockId, bool newItem) { LogInfo("SetAndReleaseItemExclusive", sessionId, lockId, newItem, context); string serialized = serialize(item.Items as SessionStateItemCollection); var expiration = DateTime.Now.Add(this._timeout); Document newValues = new Document(); newValues[ATTRIBUTE_SESSION_ID] = GetHashKey(sessionId); newValues[ATTRIBUTE_LOCKED] = false; newValues[ATTRIBUTE_LOCK_ID] = null; newValues[ATTRIBUTE_LOCK_DATE] = DateTime.Now; newValues[ATTRIBUTE_EXPIRES] = expiration; newValues[ATTRIBUTE_FLAGS] = 0; newValues[ATTRIBUTE_SESSION_ITEMS] = serialized; newValues[ATTRIBUTE_RECORD_FORMAT_VERSION] = CURRENT_RECORD_FORMAT_VERSION; SetTTLAttribute(newValues, expiration); if (newItem) { newValues[ATTRIBUTE_CREATE_DATE] = DateTime.Now; this._table.PutItem(newValues); } else { Document expected = new Document(); expected[ATTRIBUTE_LOCK_ID] = lockId.ToString(); // Not really any reason the condition should fail unless we get in some sort of weird // app pool reset mode. try { this._table.UpdateItem(newValues, new UpdateItemOperationConfig() { Expected = expected }); } catch (ConditionalCheckFailedException) { LogInfo("(SetAndReleaseItemExclusive) Conditional check failed for update.", sessionId, context); } } } /// <summary> /// Releases a lock on an item in the session data store. /// </summary> /// <param name="context">The HttpContext for the current request.</param> /// <param name="sessionId">The session identifier for the current request.</param> /// <param name="lockId">The lock identifier for the current request.</param> public override void ReleaseItemExclusive(HttpContext context, string sessionId, object lockId) { LogInfo("ReleaseItemExclusive", sessionId, lockId, context); Document doc = this._table.GetItem(GetHashKey(sessionId), CONSISTENT_READ_GET); if (doc == null) { LogError("ReleaseItemExclusive Failed to retrieve state for session id: " + sessionId, sessionId, lockId, context); return; } var expiration = DateTime.Now.Add(this._timeout); doc[ATTRIBUTE_LOCKED] = false; doc[ATTRIBUTE_EXPIRES] = expiration; SetTTLAttribute(doc, expiration); Document expected = new Document(); expected[ATTRIBUTE_LOCK_ID] = lockId.ToString(); try { this._table.UpdateItem(doc, new UpdateItemOperationConfig() { Expected = expected }); } catch (ConditionalCheckFailedException) { LogInfo("(ReleaseItemExclusive) Conditional check failed for update.", sessionId, context); } } /// <summary> /// Removes the session record for DynamoDB. /// </summary> /// <param name="context"></param> /// <param name="sessionId"></param> /// <param name="lockId"></param> /// <param name="item"></param> public override void RemoveItem(HttpContext context, string sessionId, object lockId, SessionStateStoreData item) { LogInfo("RemoveItem", sessionId, lockId, context); if (lockId == null) { deleteItem(sessionId); } else { Document doc = this._table.GetItem(GetHashKey(sessionId), CONSISTENT_READ_GET); if (doc.Contains(ATTRIBUTE_LOCK_ID)) { string currentLockId = (string)doc[ATTRIBUTE_LOCK_ID]; if (string.Equals(currentLockId, lockId)) { deleteItem(sessionId); } } } } /// <summary> /// Creates an initial session record in the DynamoDB table. /// </summary> /// <param name="context"></param> /// <param name="sessionId"></param> /// <param name="timeout"></param> public override void CreateUninitializedItem(HttpContext context, string sessionId, int timeout) { LogInfo("CreateUninitializedItem", sessionId, timeout, context); var expiration = DateTime.Now.Add(this._timeout); Document session = new Document(); session[ATTRIBUTE_SESSION_ID] = GetHashKey(sessionId); session[ATTRIBUTE_LOCKED] = false; session[ATTRIBUTE_CREATE_DATE] = DateTime.Now; session[ATTRIBUTE_EXPIRES] = expiration; session[ATTRIBUTE_FLAGS] = 1; session[ATTRIBUTE_RECORD_FORMAT_VERSION] = CURRENT_RECORD_FORMAT_VERSION; SetTTLAttribute(session, expiration); this._table.PutItem(session); } /// <summary> /// Creates a new SessionStateStoreData object to be used for the current request. /// </summary> /// <param name="context"></param> /// <param name="timeout"></param> /// <returns></returns> public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout) { LogInfo("CreateNewStoreData", timeout, context); HttpStaticObjectsCollection sessionStatics = null; if (context != null) sessionStatics = SessionStateUtility.GetSessionStaticObjects(context); return new SessionStateStoreData(new SessionStateItemCollection(), sessionStatics, timeout); } /// <summary> /// Updates the expiration date and time of an item in the DynamoDB table. /// </summary> /// <param name="context"></param> /// <param name="sessionId"></param> public override void ResetItemTimeout(HttpContext context, string sessionId) { LogInfo("ResetItemTimeout", sessionId, context); var suppressKeepalive = _strictDisableSession && context.Session == null; if (suppressKeepalive) return; var expiration = DateTime.Now.Add(this._timeout); Document doc = new Document(); doc[ATTRIBUTE_SESSION_ID] = GetHashKey(sessionId); doc[ATTRIBUTE_LOCKED] = false; doc[ATTRIBUTE_EXPIRES] = expiration; SetTTLAttribute(doc, expiration); this._table.UpdateItem(doc); } /// <summary> /// A utility method for cleaning up expired sessions that IIS failed to delete. The method performs a scan on the ASP.NET_SessionState table /// with a condition that the expiration date is in the past and calls delete on all the keys returned. Scans can be costly on performance /// so use this method sparingly like a nightly or weekly clean job. /// </summary> /// <param name="dbClient">The AmazonDynamoDB client used to find a delete expired sessions.</param> public static void DeleteExpiredSessions(IAmazonDynamoDB dbClient) { LogInfo("DeleteExpiredSessions"); DeleteExpiredSessions(dbClient, DEFAULT_TABLENAME); } /// <summary> /// A utility method for cleaning up expired sessions that IIS failed to delete. The method performs a scan on the table /// with a condition that the expiration date is in the past and calls delete on all the keys returned. Scans can be costly on performance /// so use this method sparingly like a nightly or weekly clean job. /// </summary> /// <param name="dbClient">The AmazonDynamoDB client used to find a delete expired sessions.</param> /// <param name="tableName">The table to search.</param> public static void DeleteExpiredSessions(IAmazonDynamoDB dbClient, string tableName) { LogInfo("DeleteExpiredSessions"); var tableConfig = CreateTableConfig(tableName); Table table = Table.LoadTable(dbClient, tableConfig); ScanFilter filter = new ScanFilter(); filter.AddCondition(ATTRIBUTE_EXPIRES, ScanOperator.LessThan, DateTime.Now); ScanOperationConfig config = new ScanOperationConfig(); config.AttributesToGet = new List<string> { ATTRIBUTE_SESSION_ID }; config.Select = SelectValues.SpecificAttributes; config.Filter = filter; Search search = table.Scan(config); do { DocumentBatchWrite batchWrite = table.CreateBatchWrite(); List<Document> page = search.GetNextSet(); foreach (var document in page) { batchWrite.AddItemToDelete(document); } batchWrite.Execute(); } while (!search.IsDone); } /// <summary> /// Empty implementation of the override. /// </summary> public override void Dispose() { } /// <summary> /// Empty implementation of the override. /// </summary> /// <param name="context"></param> public override void InitializeRequest(HttpContext context) { } /// <summary> /// Empty implementation of the override. /// </summary> /// <param name="context"></param> public override void EndRequest(HttpContext context) { } private Table CreateTable() { CreateTableRequest createRequest = new CreateTableRequest { TableName = this._tableName, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = ATTRIBUTE_SESSION_ID, KeyType = "HASH" } }, AttributeDefinitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = ATTRIBUTE_SESSION_ID, AttributeType = "S" } } }; if (this._useOnDemandReadWriteCapacity) { createRequest.BillingMode = BillingMode.PAY_PER_REQUEST; } else { createRequest.ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = this._initialReadUnits, WriteCapacityUnits = this._initialWriteUnits }; } CreateTableResponse response = this._ddbClient.CreateTable(createRequest); DescribeTableRequest descRequest = new DescribeTableRequest { TableName = this._tableName }; // Wait till table is active bool isActive = false; while (!isActive) { Thread.Sleep(DESCRIBE_INTERVAL); DescribeTableResponse descResponse = this._ddbClient.DescribeTable(descRequest); string tableStatus = descResponse.Table.TableStatus; if (string.Equals(tableStatus, ACTIVE_STATUS, StringComparison.InvariantCultureIgnoreCase)) isActive = true; } if (!string.IsNullOrEmpty(this._ttlAttributeName)) { this._ddbClient.UpdateTimeToLive(new UpdateTimeToLiveRequest { TableName = this._tableName, TimeToLiveSpecification = new TimeToLiveSpecification { AttributeName = this._ttlAttributeName, Enabled = true } }); } var tableConfig = CreateTableConfig(); Table table = Table.LoadTable(this._ddbClient, tableConfig); return table; } private TableConfig CreateTableConfig() { var tableConfig = CreateTableConfig(this._tableName); if (!string.IsNullOrEmpty(this._ttlAttributeName)) { tableConfig.AttributesToStoreAsEpoch.Add(this._ttlAttributeName); } return tableConfig; } private static TableConfig CreateTableConfig(string tableName) { var tableConfig = new TableConfig(tableName) { Conversion = DynamoDBEntryConversion.V1 }; return tableConfig; } /// <summary> /// Make sure existing table is valid to be used as a session store. /// </summary> private void ValidateTable() { if (this._table.HashKeys.Count != 1) throw new AmazonDynamoDBException(string.Format("Table {0} cannot be used to store session data because it does not define a single hash key", this._tableName)); string hashKey = this._table.HashKeys[0]; KeyDescription hashKeyDescription = this._table.Keys[hashKey]; if (hashKeyDescription.Type != DynamoDBEntryType.String) throw new AmazonDynamoDBException(string.Format("Table {0} cannot be used to store session data because hash key is not a string.", this._tableName)); if (this._table.RangeKeys.Count > 0) throw new AmazonDynamoDBException(string.Format("Table {0} cannot be used to store session data because it contains a range key in its schema.", this._tableName)); ATTRIBUTE_SESSION_ID = hashKey; } private void SetTTLAttribute(Document doc, DateTime expiration) { if (!string.IsNullOrEmpty(this._ttlAttributeName)) doc[this._ttlAttributeName] = expiration.AddSeconds(_ttlExtraSeconds); } private void deleteItem(string sessionId) { Document doc = new Document(); doc[ATTRIBUTE_SESSION_ID] = GetHashKey(sessionId); this._table.DeleteItem(doc); } private string serialize(SessionStateItemCollection items) { MemoryStream ms = new MemoryStream(); BinaryWriter writer = new BinaryWriter(ms); if (items != null) items.Serialize(writer); writer.Close(); return Convert.ToBase64String(ms.ToArray()); } private SessionStateStoreData deserialize(HttpContext context, string serializedItems, int timeout) { SessionStateItemCollection sessionItems = new SessionStateItemCollection(); if (serializedItems != null) { MemoryStream ms = new MemoryStream(Convert.FromBase64String(serializedItems)); if (ms.Length > 0) { BinaryReader reader = new BinaryReader(ms); sessionItems = SessionStateItemCollection.Deserialize(reader); } } HttpStaticObjectsCollection statics = null; if (context != null) statics = SessionStateUtility.GetSessionStaticObjects(context); return new SessionStateStoreData(sessionItems, statics, timeout); } /// <summary> /// Combine application and session id for hash key. /// </summary> /// <param name="sessionId"></param> /// <returns></returns> private string GetHashKey(string sessionId) { if (string.IsNullOrEmpty(this._application)) return sessionId; return string.Format("{0}-{1}", this._application, sessionId); } private static void LogInfo(string methodName) { _logger.InfoFormat("{0}", methodName); } private static void LogInfo(string methodName, string sessionId, HttpContext context) { _logger.InfoFormat("{0} : SessionId {1}, Context {2}", methodName, sessionId ?? "NULL", context == null ? "NULL" : "HttpContext"); } private static void LogInfo(string methodName, string sessionId, bool lockRecord, HttpContext context) { _logger.InfoFormat("{0} : SessionId {1}, LockRecord {2}, Context {3} ", methodName, sessionId ?? "NULL", lockRecord, context == null ? "NULL" : "HttpContext"); } private static void LogInfo(string methodName, string sessionId, object lockId, bool newItem, HttpContext context) { _logger.InfoFormat("{0} : SessionId {1}, LockId {2}, NewItem {3}, Context {4} ", methodName, sessionId ?? "NULL", lockId == null ? "NULL" : lockId.ToString(), newItem, context == null ? "NULL" : "HttpContext"); } private static void LogInfo(string methodName, string sessionId, object lockId, HttpContext context) { _logger.InfoFormat("{0} : SessionId {1}, LockId {2}, Context {3} ", methodName, sessionId ?? "NULL", lockId == null ? "NULL" : lockId.ToString(), context == null ? "NULL" : "HttpContext"); } private static void LogInfo(string methodName, string sessionId, int timeout, HttpContext context) { _logger.InfoFormat("{0} : SessionId {1}, Timeout {2}, Context {3} ", methodName, sessionId ?? "NULL", timeout, context == null ? "NULL" : "HttpContext"); } private static void LogInfo(string methodName, int timeout, HttpContext context) { _logger.InfoFormat("{0} : Timeout {1}, Context {2} ", methodName, timeout, context == null ? "NULL" : "HttpContext"); } private static void LogError(string methodName, string sessionId, object lockId, HttpContext context) { string message = string.Format("{0} : SessionId {1}, LockId {2}, Context {3} ", methodName, sessionId ?? "NULL", lockId == null ? "NULL" : lockId.ToString(), context == null ? "NULL" : "HttpContext"); _logger.Error(new Exception(message), message); } private static void LogError(string methodName, Exception exception) { _logger.Error(exception, "{0} : {1}", methodName, exception.Message); } } }
1,051
aws-dotnet-session-provider
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. #if (NET35 ||NET40) [assembly: AssemblyTitle("AWS.SessionProvider (.NET 3.5)")] #else [assembly: AssemblyTitle("AWS.SessionProvider (.NET 4.5)")] #endif [assembly: AssemblyDescription("Amazon Web Services Session Provider Extensions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("Amazon Web Services Session Provider Extensions")] [assembly: AssemblyCopyright("Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("972e230e-a3b8-4854-9b6e-805a4e73398d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("4.0")] [assembly: AssemblyFileVersion("4.0.0")]
42
aws-dotnet-session-provider
aws
C#
using Amazon; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; using Amazon.DynamoDBv2.Model; using Amazon.SessionProvider; using Amazon.Util; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Reflection; using System.Threading; using System.Web.SessionState; using Xunit; namespace AWS.SessionProvider.Test { public class SessionStoreTest : IDisposable { private static DynamoDBSessionStateStore store; private string tableName; private const string ttlAttributeName = "TTL"; private readonly int ttlExpiredSessionsSeconds = (int)TimeSpan.FromDays(7).TotalSeconds; private static string sessionId = DateTime.Now.ToFileTime().ToString(); private static TimeSpan newTimeout = TimeSpan.FromSeconds(5); private static FieldInfo timeoutField; private static TimeSpan waitPeriod = TimeSpan.FromSeconds(10); private static TimeSpan tableActiveMaxTime = TimeSpan.FromMinutes(5); private static RegionEndpoint region = RegionEndpoint.USEast1; private static AmazonDynamoDBClient CreateClient() { var client = new AmazonDynamoDBClient(region); return client; } public SessionStoreTest() { timeoutField = typeof(DynamoDBSessionStateStore).GetField("_timeout", BindingFlags.NonPublic | BindingFlags.Instance); Assert.NotNull(timeoutField); } public void Dispose() { using (var client = CreateClient()) { client.DeleteTable(new DeleteTableRequest { TableName = this.tableName }); WaitUntilTableReady(client, null); } } [Fact] public void DynamoDBSessionStateStoreTest() { var config = new NameValueCollection(); config.Add(DynamoDBSessionStateStore.CONFIG_REGION, region.SystemName); config.Add(DynamoDBSessionStateStore.CONFIG_TABLE, "SessionStoreWithUserSpecifiedCapacity"); config.Add(DynamoDBSessionStateStore.CONFIG_APPLICATION, "IntegTest"); config.Add(DynamoDBSessionStateStore.CONFIG_INITIAL_READ_UNITS, "10"); config.Add(DynamoDBSessionStateStore.CONFIG_INITIAL_WRITE_UNITS, "10"); config.Add(DynamoDBSessionStateStore.CONFIG_CREATE_TABLE_IF_NOT_EXIST, "true"); Test(config); config.Add(DynamoDBSessionStateStore.CONFIG_TTL_ATTRIBUTE, ttlAttributeName); config.Add(DynamoDBSessionStateStore.CONFIG_TTL_EXPIRED_SESSIONS_SECONDS, ttlExpiredSessionsSeconds.ToString()); Test(config); } [TestMethod] public void DynamoDBOnDemandCapacityTest() { var config = new NameValueCollection(); config.Add(DynamoDBSessionStateStore.CONFIG_REGION, region.SystemName); config.Add(DynamoDBSessionStateStore.CONFIG_TABLE, "SessionStoreWithOnDemandCapacity"); config.Add(DynamoDBSessionStateStore.CONFIG_APPLICATION, "IntegTest2"); config.Add(DynamoDBSessionStateStore.CONFIG_ON_DEMAND_READ_WRITE_CAPACITY, "true"); config.Add(DynamoDBSessionStateStore.CONFIG_CREATE_TABLE_IF_NOT_EXIST, "true"); Test(config); } private void Test(NameValueCollection config) { using (var client = CreateClient()) { store = new DynamoDBSessionStateStore("TestSessionProvider", config); timeoutField.SetValue(store, newTimeout); this.tableName = config[DynamoDBSessionStateStore.CONFIG_TABLE]; WaitUntilTableReady(client, TableStatus.ACTIVE); var table = Table.LoadTable(client, this.tableName); var creationTime = DateTime.Now; store.CreateUninitializedItem(null, sessionId, 10); var items = GetAllItems(table); Assert.Single(items); var testTtl = config.AllKeys.Contains(DynamoDBSessionStateStore.CONFIG_TTL_ATTRIBUTE); var firstItem =items[0]; Assert.Equal(testTtl, firstItem.ContainsKey(ttlAttributeName)); if (testTtl) { var epochSeconds = firstItem[ttlAttributeName].AsInt(); Assert.NotEqual(0, epochSeconds); var expiresDateTime = AWSSDKUtils.ConvertFromUnixEpochSeconds(epochSeconds); var expectedExpiresDateTime = (creationTime + newTimeout).AddSeconds(ttlExpiredSessionsSeconds); Assert.True((expiresDateTime - expectedExpiresDateTime) < TimeSpan.FromMinutes(1)); } var hasOnDemandReadWriteCapacity = config.AllKeys.Contains(DynamoDBSessionStateStore.CONFIG_ON_DEMAND_READ_WRITE_CAPACITY); if (hasOnDemandReadWriteCapacity) { var mode = client.DescribeTable(tableName).Table.BillingModeSummary.BillingMode; Assert.AreEqual(mode, BillingMode.PAY_PER_REQUEST); } bool locked; TimeSpan lockAge; object lockId; SessionStateActions actionFlags; store.GetItem(null, sessionId, out locked, out lockAge, out lockId, out actionFlags); Thread.Sleep(newTimeout); DynamoDBSessionStateStore.DeleteExpiredSessions(client, tableName); items = GetAllItems(table); Assert.Empty(items); } } private static List<Document> GetAllItems(Table table) { Assert.NotNull(table); var allItems = table.Scan(new ScanFilter()).GetRemaining().ToList(); return allItems; } private void WaitUntilTableReady(AmazonDynamoDBClient client, TableStatus targetStatus) { var startTime = DateTime.Now; TableStatus status; while ((DateTime.Now - startTime) < tableActiveMaxTime) { try { status = client.DescribeTable(tableName).Table.TableStatus; } catch(ResourceNotFoundException) { status = null; } if (status == targetStatus) return; Thread.Sleep(waitPeriod); } } } }
162
aws-dotnet-session-provider
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWS.SessionProvider.Test")] [assembly: AssemblyDescription("Amazon Web Services Session Provider Extensions Tests")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("Amazon Web Services Session Provider Extensions Tests")] [assembly: AssemblyCopyright("Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d1476e36-5859-4ad5-8785-0b67fff938eb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-dotnet-trace-listener
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Diagnostics; namespace SampleTraceListenerUsage { /// <summary> /// <para> /// This simple console application is configured in the app.config to use the AWS Trace Listener. This will cause Trace.Write calls /// to be written to a Logs table in DynamoDB. To confirm this view the Logs table in the DynamoDB table browser. /// </para> /// <para> /// The application will use the default profile for credentials and the us-west-2 region. When first launched it will /// create the Logs table if it doesn't exist. Be sure to delete this table when done testing to avoid charges. /// </para> /// </summary> class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++ ) { Trace.WriteLine(string.Format("Test logging message {0}", i)); Thread.Sleep(500); } Trace.Flush(); } } }
34
aws-dotnet-trace-listener
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SampleTraceListenerUsage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SampleTraceListenerUsage")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6ea2563a-dc7c-42b4-a7df-2563f40dd0fe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-dotnet-trace-listener
aws
C#
/* * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; using Timer = System.Timers.Timer; namespace Amazon.TraceListener { /// <summary> /// <para> /// DynamoDBTraceListener is a custom TraceListener that logs events to a DynamoDB table. /// The listener can be configured through the application's .config file or by instantiating /// an instance of DynamoDBTraceListener and setting the Configuration property on the instance. /// </para> /// /// <para> /// The target table must have a string hash key and a string range key. /// If the table does not exist the listener will create it during initialization with /// default read and write units set to 1 and 10, respectively, unless configured otherwise. /// </para> /// /// <para> /// While DynamoDBTraceListener is running, it will write temporary log files into current /// directory. These log files will be deleted once the data is pushed to DynamoDB. /// The logs are pushed to DynamoDB under the following conditions: /// 1. Flush is called on the DynamoDBTraceListener /// 2. Close is called on the DynamoDBTraceListener /// 3. WritePeriod has elapsed since last write /// /// (If the listener is used with the SDK clients, Flush is invoked when the client is disposed.) /// /// If the application exits and there are still log files (in the event Flush is not invoked or /// the application terminates unexpectedly), these log files will be pushed to DynamoDB on the /// next execution of the application. /// /// Log files can also be flushed manually by creating an instance of DynamoDBTraceListener and /// using the FlushLog method on a particular log file. /// </para> /// /// <para> /// Example of an app.config entry setting up the listener with all possible configurations specified: /// <code> /// &lt;system.diagnostics&gt; /// &lt;trace&gt; /// &lt;listeners&gt; /// &lt;add name=&quot;dynamo&quot; type=&quot;Amazon.TraceListener.DynamoDBTraceListener, AWS.TraceListener&quot; /// AWSProfileName="default" /// AWSProfilesLocation=".aws/credentials" /// Region=&quot;us-west-2&quot; /// Table=&quot;Logs&quot; /// CreateIfNotExist=&quot;true&quot; /// ReadCapacityUnits=&quot;1&quot; /// WriteCapacityUnits=&quot;10&quot; /// HashKey=&quot;Origin&quot; /// RangeKey=&quot;Timestamp&quot; /// MaxLength=&quot;10000&quot; /// ExcludeAttributes=&quot;Callstack, Host&quot; /// HashKeyFormat=&quot;{Host}-{EventType}-{ProcessId}&quot; /// RangeKeyFormat=&quot;{Time}&quot; /// WritePeriodMs=&quot;60000&quot; /// LogFilesDir=&quot;C:\Logs&quot; /// /&gt; /// &lt;/listeners&gt; /// &lt;/trace&gt; /// &lt;/system.diagnostics&gt; /// </code> /// </para> /// </summary> public class DynamoDBTraceListener : System.Diagnostics.TraceListener { #region Private fields private object generalLock = new object(); private Timer writeTimer = null; private TextWriter writer = null; private DateTime lastTimestamp = DateTime.MinValue; private static string logFileNameFormat = string.Format("{0}.{1}.log", typeof(DynamoDBTraceListener).FullName, "{0}"); private static string eventLogsFileName = "events.log"; private static string eventLogsFormat = "{0}.{1} {2} > {3}"; private static string logFileSearchPattern = string.Format(logFileNameFormat, "*"); private static string tempLogFileName = string.Concat(Guid.NewGuid().ToString(), ".", string.Format(logFileNameFormat, "temp")); private const int bufferSize = 0x1000; // 4 KB private static bool canWriteToEventLog; private static string eventLogSource = typeof(DynamoDBTraceListener).Name; private static DynamoDBEntryConversion conversionSchema = DynamoDBEntryConversion.V1; private string _currentLogFile = null; private string CurrentLogFile { get { if (_currentLogFile == null) { _currentLogFile = GetNewLogFilePath(); } return _currentLogFile; } } private string _eventLogsFile = null; private string GetEventLogsFileLocation() { if (_eventLogsFile == null) { if (!string.IsNullOrEmpty(_logFileDirectory)) _eventLogsFile = Path.Combine(_logFileDirectory, eventLogsFileName); } return _eventLogsFile; } private string _logFileDirectory = null; private string LogFileDirectory { get { if (_logFileDirectory == null) { // Try the log directories in order string[] directoriesToTest = { Configuration.LogFilesDirectory, // user-specified Directory.GetCurrentDirectory(), // current Path.Combine(Path.GetTempPath(), "DDBTLLogs") // Windows Temp }; foreach (var path in directoriesToTest) { if (string.IsNullOrEmpty(path)) continue; string directory = Path.GetFullPath(path); try { if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); string testPath = Path.Combine(directory, tempLogFileName); // Test write File.WriteAllText(testPath, testPath); // If write succeeds, delete file and use path if (File.Exists(testPath)) { File.Delete(testPath); _logFileDirectory = directory; break; } } catch { } } if (_logFileDirectory == null) { // If no directory has been set, disable the listener. DisableListener("Could not determine log file directory"); } else WriteLogMessage("DynamoDBTraceListener will store temporary log files under " + _logFileDirectory, EventLogEntryType.Information); } return _logFileDirectory; } } private AmazonDynamoDBClient _client = null; private AmazonDynamoDBClient Client { get { if (_client == null) { try { AmazonDynamoDBConfig config = new AmazonDynamoDBConfig { DisableLogging = true }; if (Configuration.Region != null) config.RegionEndpoint = Configuration.Region; else if (!string.IsNullOrEmpty(Configuration.ServiceURL)) config.ServiceURL = Configuration.ServiceURL; AWSCredentials credentials = null; if (!string.IsNullOrEmpty(Configuration.AWSAccessKey) && !string.IsNullOrEmpty(Configuration.AWSSecretKey)) credentials = new BasicAWSCredentials(Configuration.AWSAccessKey, Configuration.AWSSecretKey); else if (!string.IsNullOrEmpty(Configuration.AWSProfileName)) { if (string.IsNullOrEmpty(Configuration.AWSProfilesLocation)) credentials = new StoredProfileAWSCredentials(Configuration.AWSProfileName); else credentials = new StoredProfileAWSCredentials(Configuration.AWSProfileName, Configuration.AWSProfilesLocation); } else if (Configuration.AWSCredentials != null) credentials = Configuration.AWSCredentials; if (credentials != null) _client = new AmazonDynamoDBClient(credentials, config); else _client = new AmazonDynamoDBClient(config); } catch (Exception e) { DisableListener("Could not construct AmazonDynamoDBClient: " + e); } } return _client; } } private bool _isTableActive = false; private bool IsTableActive { get { if (!_isTableActive) { lock (generalLock) { if (!_isTableActive) { try { DescribeTableRequest describeRequest = new DescribeTableRequest { TableName = Configuration.TableName }; DescribeTableResponse descResponse = Client.DescribeTable(describeRequest); string tableStatus = descResponse.Table.TableStatus; if (string.Equals(tableStatus, activeStatus, StringComparison.OrdinalIgnoreCase)) _isTableActive = true; } catch (Exception e) { DisableListener(string.Format("Table {0} could not be described: {1}", Configuration.TableName, e)); } } } } return _isTableActive; } } private Table _table = null; private Table Table { get { if (_table == null) { lock (generalLock) { if (_table == null) { // Get/create table if (!Table.TryLoadTable(Client, Configuration.TableName, out _table)) { if (Configuration.CreateTableIfNotExist) _table = CreateTable(); else { DisableListener(string.Format("Table {0} was not found to be used to log, and autocreate is turned off.", Configuration.TableName)); return null; } } // Validate table if (_table == null) DisableListener(string.Format("Table {0} could not be found or created", Configuration.TableName)); else if (_table.HashKeys == null || _table.HashKeys.Count != 1) DisableListener(string.Format("Table {0} was found, but does not contain a single hash key", Configuration.TableName)); else if (_table.RangeKeys == null || _table.RangeKeys.Count != 1) DisableListener(string.Format("Table {0} was found, but does not contain a single range key", Configuration.TableName)); } } } return _table; } } private TraceEventCache TraceEventCache { get { return new TraceEventCache(); } } #endregion #region Properties/configuration private static Regex variableRegex = new Regex(@"\{(\w*?)\}", RegexOptions.Compiled); private static TimeSpan oneMillisecond = TimeSpan.FromMilliseconds(1); private static int minWritePeriodMs = (int)TimeSpan.FromSeconds(10).TotalMilliseconds; private static Configs defaultConfigs = new Configs(); private static string host = System.Environment.MachineName; private const string activeStatus = "Active"; private const string ellipsis = "..."; private string ATTRIBUTE_ORIGIN { get { return Table.HashKeys[0]; } } private string ATTRIBUTE_TIMESTAMP { get { return Table.RangeKeys[0]; } } private const string ATTRIBUTE_MESSAGE = "Message"; private const string ATTRIBUTE_HOST = "Host"; private const string ATTRIBUTE_TIME = "Time"; private const string ATTRIBUTE_SOURCE = "Source"; private const string ATTRIBUTE_CALLSTACK = "Callstack"; private const string ATTRIBUTE_PROCESSID = "ProcessId"; private const string ATTRIBUTE_THREADID = "ThreadId"; private const string ATTRIBUTE_EVENTID = "EventId"; private const string ATTRIBUTE_EVENTTYPE = "EventType"; private const string CONFIG_ACCESSKEY = "AWSAccessKey"; private const string CONFIG_SECRETKEY = "AWSSecretKey"; private const string CONFIG_PROFILENAME = "AWSProfileName"; private const string CONFIG_PROFILESLOCATION = "AWSProfilesLocation"; private const string CONFIG_REGION = "Region"; private const string CONFIG_SERVICE_URL = "ServiceURL"; private const string CONFIG_TABLE = "Table"; private const string CONFIG_CREATE_TABLE_IF_NOT_EXIST = "CreateIfNotExist"; private const string CONFIG_READ_UNITS = "ReadCapacityUnits"; private const string CONFIG_WRITE_UNITS = "WriteCapacityUnits"; private const string CONFIG_HASHKEY = "HashKey"; private const string CONFIG_RANGEKEY = "RangeKey"; private const string CONFIG_MAXLENGTH = "MaxLength"; private const string CONFIG_EXCLUDEATTRIBUTES = "ExcludeAttributes"; private const string CONFIG_HASHKEYFORMAT = "HashKeyFormat"; private const string CONFIG_RANGEKEYFORMAT = "RangeKeyFormat"; private const string CONFIG_WRITEPERIODMS = "WritePeriodMs"; private const string CONFIG_LOGFILESDIR = "LogFilesDir"; private Configs _configuration = null; /// <summary> /// Current configuration. /// </summary> public Configs Configuration { get { if (_configuration == null) { lock (generalLock) { if (_configuration == null) { _configuration = GetConfigFromAttributes(); } } } return _configuration; } set { lock (generalLock) { _configuration = value; } } } /// <summary> /// Whether the DynamoDBTraceListener is enabled. /// Read-only field that is set to false if the listener is disabled. /// The listener can be disabled if initialization has failed (in which case an error will be /// logged to the event log) or the listener was closed. /// </summary> public bool IsEnabled { get; private set; } #endregion #region Private methods // Get a new time-stamped log file path. private string GetNewLogFilePath() { string logFileName = string.Format(logFileNameFormat, DateTime.Now.ToFileTime()); string logFilePath = Path.Combine(LogFileDirectory, logFileName); return logFilePath; } // Disposes of and nulls out the writer private void DisposeWriter() { if (writer != null) { try { writer.Flush(); writer.Close(); } catch { } writer = null; } } // Create logs table and return Table object. Table won't be active yet. private Table CreateTable() { try { Client.CreateTable(new CreateTableRequest { TableName = Configuration.TableName, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = defaultConfigs.HashKey, KeyType = "HASH" }, new KeySchemaElement { AttributeName = defaultConfigs.RangeKey, KeyType = "RANGE" } }, AttributeDefinitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = defaultConfigs.HashKey, AttributeType = "S" }, new AttributeDefinition { AttributeName = defaultConfigs.RangeKey, AttributeType = "S" } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = Configuration.ReadUnits, WriteCapacityUnits = Configuration.WriteUnits } }); } catch (Exception e) { WriteLogMessage(string.Format("Error while creating table {0}: {1}", Configuration.TableName, e.ToString()), EventLogEntryType.Error); return null; } Table table = Table.LoadTable(Client, Configuration.TableName, conversionSchema); return table; } // Expands environment and attribute variables in string private string ExpandVariables(string value, Document doc) { string result = value; result = Environment.ExpandEnvironmentVariables(result); result = variableRegex.Replace(result, match => { string key = match.Groups[1].Captures[0].Value; if (doc.Contains(key)) return doc[key].AsString(); else return match.Captures[0].Value; }); return result; } // Composes a Document and pushes to background thread to log whenever private void Log(TraceEventCache eventCache, string source, TraceEventType eventType, int eventId, params object[] data) { if (!IsEnabled) return; Document doc = new Document(); // Populate event data doc[ATTRIBUTE_CALLSTACK] = LimitLength(eventCache.Callstack); doc[ATTRIBUTE_PROCESSID] = eventCache.ProcessId; doc[ATTRIBUTE_THREADID] = eventCache.ThreadId; doc[ATTRIBUTE_HOST] = LimitLength(host); doc[ATTRIBUTE_SOURCE] = LimitLength(source); doc[ATTRIBUTE_EVENTTYPE] = eventType.ToString(); doc[ATTRIBUTE_EVENTID] = eventId; doc[ATTRIBUTE_TIME] = GetCurrentTimestamp(); // Set the message if (data != null && data.Length > 0) { string message = ComposeMessage(data); doc[ATTRIBUTE_MESSAGE] = LimitLength(message); } doc = doc.ForceConversion(conversionSchema); // Set hash/range keys, possibly from event data doc[ATTRIBUTE_ORIGIN] = ExpandVariables(Configuration.HashKeyFormat, doc); doc[ATTRIBUTE_TIMESTAMP] = ExpandVariables(Configuration.RangeKeyFormat, doc); // Remove attributes that should be excluded if (Configuration.ExcludeAttributes != null) { foreach (string exclude in Configuration.ExcludeAttributes) { doc[exclude] = null; } } // Add message to documents list AppendDocument(doc); } // Limits the length of a string to Configuration.MaxLength private string LimitLength(string value) { if (value != null && value.Length > Configuration.MaxLength) value = value.Substring(0, Configuration.MaxLength - ellipsis.Length) + ellipsis; return value; } // Creates a message string from data objects private string ComposeMessage(object[] data) { string message; if (data == null || data.Length == 0) message = string.Empty; if (data.Length == 1) message = data[0].ToString(); else { StringBuilder builder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { if (i != 0) { builder.Append(", "); } if (data[i] != null) { builder.Append(data[i].ToString()); } } message = builder.ToString(); } return message; } // Retrieves a non-colliding timestamp private DateTime GetCurrentTimestamp() { DateTime now = DateTime.Now; // DateTime is converted to an ISO 8601 string with millisecond precision, // so we may need to avoid range key collisions by incrementing the date by a millisecond lock (generalLock) { var diff = (now - lastTimestamp); if (diff.TotalMilliseconds < 1) now = lastTimestamp + oneMillisecond; lastTimestamp = now; } return now; } // Ensures that the writer object is created and ready for writing. // Otherwise, disables the listener. private bool EnsureWriter() { if (writer == null) { try { writer = new StreamWriter(CurrentLogFile, true, Encoding.UTF8, bufferSize); } catch (Exception e) { DisableListener("Error writing log file: " + e.ToString()); } } return IsEnabled; } // Appends a Document to the log file. private void AppendDocument(Document doc) { if (!IsEnabled) return; string json = null; try { // JsonMapper doesn't properly serialize Documents, so we store the attribute map Dictionary<string, AttributeValue> attributeMap = doc.ToAttributeMap(); json = JsonMapper.ToJson(attributeMap); } catch { json = null; } if (string.IsNullOrEmpty(json)) return; // Perform write lock (generalLock) { if (EnsureWriter()) { writer.WriteLine(json); } } } // Timer action for handling timed writes private void TimedWriter(object sender, System.Timers.ElapsedEventArgs e) { if (!IsEnabled) { writeTimer.Enabled = false; return; } // Update interval, as it may have been changed after the start writeTimer.Interval = Configuration.WritePeriod.TotalMilliseconds; if (IsLogFileEmpty(CurrentLogFile)) return; Flush(); } // Reads documents from the old log files. private IEnumerable<Document> GetDocuments(string path) { if (!IsEnabled || IsLogFileEmpty(path)) yield break; using (Stream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { Dictionary<string, AttributeValue> map; try { map = JsonMapper.ToObject<Dictionary<string, AttributeValue>>(line); } catch { map = null; } if (map != null && map.Count > 0) { Document doc = Document.FromAttributeMap(map); yield return doc; } } } } // Returns true if the log file doesn't exist or has length = 0. private bool IsLogFileEmpty(string path) { var fileInfo = new FileInfo(path); return (!fileInfo.Exists || fileInfo.Length == 0); } // If file is no longer active, attempts to delete it. If that fails, empties the file out. private void DeleteLogFile(string path) { try { File.Delete(path); } catch { } if (!IsLogFileEmpty(path)) { try { File.Open(path, FileMode.Truncate, FileAccess.Write, FileShare.Read).Close(); } catch { } } } // Writes an event log message private void WriteLogMessage(string message, EventLogEntryType logEntryType) { // try the event log if (canWriteToEventLog) { WriteToEventLog(message, logEntryType); } // if event log is not available, write to a file if (!canWriteToEventLog) { WriteToEventFile(message, logEntryType); } } // Writes event to EventLog private void WriteToEventLog(string message, EventLogEntryType logEntryType) { try { EventLog.WriteEntry(eventLogSource, message, logEntryType); } catch { canWriteToEventLog = false; } } // Writes event to file, if one can be written private void WriteToEventFile(string message, EventLogEntryType logEntryType) { string logsFilePath = GetEventLogsFileLocation(); if (!string.IsNullOrEmpty(logsFilePath)) { using (var stream = File.Open(logsFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) using (var writer = new StreamWriter(stream)) { writer.WriteLine(eventLogsFormat, eventLogSource, logEntryType.ToString(), DateTime.Now.ToString(), message); } } } // Disables the DynamoDBTraceListener and writes an error event log message private void DisableListener(string message) { IsEnabled = false; WriteLogMessage("DynamoDBTraceListener disabled: " + message, EventLogEntryType.Error); } // Initializes DynamoDBTraceListener private void Init() { ConfigureEventLog(); ConfigureWriteTimer(); IsEnabled = true; } // Sets up the write timer private void ConfigureWriteTimer() { // Property Attributes isn't set yet, so set first timer to go off at minimum period writeTimer = new Timer(minWritePeriodMs); writeTimer.AutoReset = true; writeTimer.Elapsed += TimedWriter; writeTimer.Enabled = true; } // Creates source if one does not exist private void ConfigureEventLog() { try { if (!EventLog.SourceExists(eventLogSource)) EventLog.CreateEventSource(eventLogSource, "Application"); canWriteToEventLog = true; } catch { canWriteToEventLog = false; } } #endregion #region TraceListener Overrides protected override string[] GetSupportedAttributes() { return new string[] { CONFIG_ACCESSKEY, CONFIG_SECRETKEY, CONFIG_PROFILENAME, CONFIG_PROFILESLOCATION, CONFIG_REGION, CONFIG_SERVICE_URL, CONFIG_TABLE, CONFIG_CREATE_TABLE_IF_NOT_EXIST, CONFIG_READ_UNITS, CONFIG_WRITE_UNITS, CONFIG_HASHKEY, CONFIG_RANGEKEY, CONFIG_MAXLENGTH, CONFIG_EXCLUDEATTRIBUTES, CONFIG_HASHKEYFORMAT, CONFIG_RANGEKEYFORMAT, CONFIG_WRITEPERIODMS, CONFIG_LOGFILESDIR }; } public override bool IsThreadSafe { get { return false; } } public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { Log(eventCache, source, eventType, id, data); } public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { Log(eventCache, source, eventType, id, data); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { Log(eventCache, source, eventType, id); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { Log(eventCache, source, eventType, id, string.Format(format, args)); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { Log(eventCache, source, eventType, id, message); } public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId) { Log(eventCache, source, TraceEventType.Transfer, id, relatedActivityId); } public override void Write(string message) { TraceData(TraceEventCache, this.Name, TraceEventType.Information, 0, message); } public override void WriteLine(string message) { TraceData(TraceEventCache, this.Name, TraceEventType.Information, 0, message); } protected override void WriteIndent() { } public override void Flush() { if (!IsEnabled) return; // Flush to disk if (writer != null) { writer.Flush(); } // Only flush log files to DynamoDB when the table is active if (!IsTableActive) return; // Get existing log files var logFiles = Directory .GetFiles(LogFileDirectory, logFileSearchPattern) .Where(p => !IsLogFileEmpty(p)); // Use new log file for subsequent logs lock (generalLock) { _currentLogFile = GetNewLogFilePath(); DisposeWriter(); } // Push log files to DynamoDB, then empty/delete them. // Each log file is sent to DynamoDB in its own batch. foreach (var oldLog in logFiles) { try { FlushLog(oldLog); } catch (Exception e) { DisableListener("Unable to write logs to DynamoDB: " + e); return; } } } public override void Close() { Flush(); base.Close(); } #endregion #region Dispose Pattern Implementation bool disposed = false; /// <summary> /// Implements the Dispose pattern /// </summary> /// <param name="disposing">Whether this object is being disposed via a call to Dispose /// or garbage collected.</param> protected override void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { Flush(); DisposeWriter(); } IsEnabled = false; disposed = true; } } /// <summary> /// The destructor for the client class. /// </summary> ~DynamoDBTraceListener() { this.Dispose(false); } #endregion #region Attribute methods private char[] valueSeparators = { ',' }; // Retrieves a configuration from Attributes or the default configuration private Configs GetConfigFromAttributes() { // parse attributes to exclude var excludeAttributes = GetAttribute(CONFIG_EXCLUDEATTRIBUTES) .Split(valueSeparators, StringSplitOptions.RemoveEmptyEntries) // split list by valueSeparators .Select(s => (s ?? string.Empty).Trim()) // convert null to "" and trim .Where(s => s.Length > 0) // keep only non-empty strings .ToArray(); // parse write period int writePeriodMs = GetAttributeAsInt(CONFIG_WRITEPERIODMS, (int)defaultConfigs.WritePeriod.TotalMilliseconds); writePeriodMs = Math.Max(writePeriodMs, minWritePeriodMs); // construct configs from attributes var configs = new Configs { AWSAccessKey = GetAttribute(CONFIG_ACCESSKEY), AWSSecretKey = GetAttribute(CONFIG_SECRETKEY), AWSProfileName = GetAttribute(CONFIG_PROFILENAME), AWSProfilesLocation = GetAttribute(CONFIG_PROFILESLOCATION), Region = RegionEndpoint.GetBySystemName(GetAttribute(CONFIG_REGION, defaultConfigs.Region.SystemName)), ServiceURL = GetAttribute(CONFIG_SERVICE_URL), TableName = GetAttribute(CONFIG_TABLE, defaultConfigs.TableName), ReadUnits = GetAttributeAsInt(CONFIG_READ_UNITS, defaultConfigs.ReadUnits), WriteUnits = GetAttributeAsInt(CONFIG_WRITE_UNITS, defaultConfigs.WriteUnits), CreateTableIfNotExist = GetAttributeAsBool(CONFIG_CREATE_TABLE_IF_NOT_EXIST, defaultConfigs.CreateTableIfNotExist), MaxLength = GetAttributeAsInt(CONFIG_MAXLENGTH, defaultConfigs.MaxLength), HashKeyFormat = GetAttribute(CONFIG_HASHKEYFORMAT, defaultConfigs.HashKeyFormat), RangeKeyFormat = GetAttribute(CONFIG_RANGEKEYFORMAT, defaultConfigs.RangeKeyFormat), HashKey = GetAttribute(CONFIG_HASHKEY, defaultConfigs.HashKey), RangeKey = GetAttribute(CONFIG_RANGEKEY, defaultConfigs.RangeKey), WritePeriod = TimeSpan.FromMilliseconds(writePeriodMs), ExcludeAttributes = excludeAttributes, LogFilesDirectory = GetAttribute(CONFIG_LOGFILESDIR, defaultConfigs.LogFilesDirectory) }; return configs; } private bool GetAttributeAsBool(string name, bool defaultValue = false) { string value = GetAttribute(name); bool b; if (string.IsNullOrEmpty(value) || !bool.TryParse(value, out b)) b = defaultValue; return b; } private int GetAttributeAsInt(string name, int defaultValue = -1) { string value = GetAttribute(name); int i; if (string.IsNullOrEmpty(value) || !int.TryParse(value, out i)) i = defaultValue; return i; } private string GetAttribute(string name, string defaultValue = "") { if (Attributes.ContainsKey(name)) return Attributes[name]; else return defaultValue; } #endregion #region Constructor /// <summary> /// Constructs an instance of the DynamoDBTraceListener. /// </summary> public DynamoDBTraceListener() : base() { Init(); } /// <summary> /// Constructs a named instance of the DynamoDBTraceListener. /// </summary> public DynamoDBTraceListener(string name) : base(name) { Init(); } #endregion #region Public methods /// <summary> /// Flushes an existing log to DynamoDB, then deletes/empties the log file. /// This method can be invoked manually to flush left-over log files. /// </summary> /// <param name="log"></param> public void FlushLog(string log) { // Get Documents stored in log file var documents = GetDocuments(log); // Create, populate and execute BatchWrite var batchWrite = Table.CreateBatchWrite(); foreach (var doc in documents) { batchWrite.AddDocumentToPut(doc); } // Attempt to write (may throw exception) batchWrite.Execute(); // If BatchWrite succeeded, empty old log file DeleteLogFile(log); } #endregion #region Public classes /// <summary> /// DynamoDBTraceListener configurations. /// </summary> public class Configs { #region Login/table properties /// <summary> /// Access key to use. /// Config key: AWSAccessKey /// </summary> public string AWSAccessKey { get; set; } /// <summary> /// Secret key to use. /// Config key: AWSSecretKey /// </summary> public string AWSSecretKey { get; set; } /// <summary> /// Profile to use. /// Config key: AWSProfileName /// </summary> public string AWSProfileName { get; set; } /// <summary> /// Location of credentials file. /// Config key: AWSProfilesLocation /// </summary> public string AWSProfilesLocation { get; set; } /// <summary> /// Credentials to use. /// This property can only be set programmatically. /// </summary> public AWSCredentials AWSCredentials { get; set; } /// <summary> /// Region for the table. Default is US West 2 (Oregon). /// Config key: Region /// </summary> public RegionEndpoint Region { get; set; } /// <summary> /// The URL of the DynamoDB endpoint. This can be used instead of region. This property is commonly used for connecting to DynamoDB Local (e.g. http://localhost:8000/) /// Config key: ServiceURL /// </summary> public string ServiceURL { get; set; } /// <summary> /// Table used to store logs. Default is "Logs". /// Config key: Table /// </summary> public string TableName { get; set; } #endregion #region Table-creation properties /// <summary> /// Controls whether the table will be auto created if it doesn't exist. The default is true. /// Config key: CreateIfNotExist /// </summary> public bool CreateTableIfNotExist { get; set; } /// <summary> /// The read capacity units if the table is created. The default is 1. /// Config key: ReadCapacityUnits /// </summary> public int ReadUnits { get; set; } /// <summary> /// The write capacity units if the table is created. The default is 10. /// Config key: WriteCapacityUnits /// </summary> public int WriteUnits { get; set; } /// <summary> /// The hash-key name if the table is created. The default is "Origin". /// Config key: HashKey /// </summary> public string HashKey { get; set; } /// <summary> /// The range-key name if the table is created. The default is "Timestamp". /// Config key: RangeKey /// </summary> public string RangeKey { get; set; } #endregion #region Message/logging properties /// <summary> /// The maximum length of any one attribute. The default is 10,000 characters. /// Config key: MaxLength /// </summary> public int MaxLength { get; set; } /// <summary> /// Format of the hash key. The default is "{Host}". /// The format can include environment variables, attributes from the logged message, or can /// be a constant value. /// /// Environment variables are specified like so: %ComputerName% /// Attributes are specified like so: {Host} /// For example: {Host}-{EventType}-{ProcessId} or %ComputerName%-{EventType}-{ProcessId} /// /// Config key: HashKeyFormat /// </summary> public string HashKeyFormat { get; set; } /// <summary> /// Format of the range key. The default is "{Time}". /// The format can include environment variables, attributes from the logged message, or can /// be a constant value. /// /// Environment variables are specified like so: %Time% /// Attributes are specified like so: {Time} /// /// Config key: RangeKeyFormat /// </summary> public string RangeKeyFormat { get; set; } /// <summary> /// Array of attributes to exclude from the logged item. Default is null. /// Config key: ExcludeAttributes (comma-separated list of attribute names) /// </summary> public string[] ExcludeAttributes { get; set; } /// <summary> /// Largest time between writes to DynamoDB. /// If this period has passed since the last log write, all accumulated messages /// are written to DynamoDB immediately. /// /// The listener only pushes messages to DynamoDB when the target table is active /// AND one of the following happens: /// 1. The time equal to WritePeriod since last write has elapsed /// 2. Flush is called /// 3. Close is called /// /// Default value is 1 minute. Smallest allowed value is 0 seconds. /// /// Config key: WritePeriodMs (number of milliseconds) /// </summary> public TimeSpan WritePeriod { get; set; } /// <summary> /// The directory that temporary log files should be written to. /// If the value is not specified, listener attempts to use the application's current /// directory, then the Windows temporary directory. If none of these are accessible, /// the listener will be disabled and an error message will be written to the error log. /// /// Default value is null. /// /// Config key: LogFilesDir /// </summary> public string LogFilesDirectory { get; set; } #endregion #region Constructor /// <summary> /// Constructs a default Configs instance. /// </summary> public Configs() { HashKey = "Origin"; RangeKey = "Timestamp"; TableName = "Logs"; ReadUnits = 1; WriteUnits = 10; CreateTableIfNotExist = true; MaxLength = 10 * 1000; Region = RegionEndpoint.USWest2; HashKeyFormat = "{Host}"; RangeKeyFormat = "{Time}"; WritePeriod = TimeSpan.FromMinutes(1); LogFilesDirectory = null; } #endregion } #endregion } }
1,211
aws-dotnet-trace-listener
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. #if (NET35 ||NET40) [assembly: AssemblyTitle("AWS.TraceListener (.NET 3.5)")] #else [assembly: AssemblyTitle("AWS.TraceListener (.NET 4.5)")] #endif [assembly: AssemblyDescription("Amazon Web Services Trace Listener Extensions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("Amazon Web Services Session Provider Extensions")] [assembly: AssemblyCopyright("Copyright 2012-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("787dc3e7-52d9-45b6-abd6-c6e705147cc5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.1")] [assembly: AssemblyFileVersion("3.1.0.1")]
41
aws-encryption-sdk-dafny
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using Org.BouncyCastle.Utilities.Encoders; using RSA = RSAEncryption.RSA; namespace Benchmarks { public abstract class BaseEncryptDecryptBenchmark { [ParamsSource(nameof(ValuesForPlaintextLengthBytes))] public int PlaintextLengthBytes { get; set; } [ParamsSource(nameof(ValuesForFrameLengthBytes))] public int FrameLengthBytes { get; set; } private IAwsEncryptionSdk _encryptionSdk; private IKeyring _keyring; private MemoryStream _plaintext; private MemoryStream _ciphertext; private Dictionary<string, string> _encryptionContext; /** * Concrete benchmark classes should implement this method. */ protected abstract IKeyring CreateKeyring(); // Runs once for each combination of params [GlobalSetup] public void GlobalSetup() { _encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); _keyring = CreateKeyring(); _plaintext = new MemoryStream(PlaintextLengthBytes); _plaintext.SetLength(PlaintextLengthBytes); // need to set this because buffer is 0-length by default RandomNumberGenerator.Create().GetBytes(_plaintext.GetBuffer()); _encryptionContext = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } }; _ciphertext = Encrypt().Ciphertext; } [Benchmark] public EncryptOutput Encrypt() => _encryptionSdk.Encrypt(new EncryptInput { Keyring = _keyring, Plaintext = _plaintext, EncryptionContext = _encryptionContext, AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, FrameLength = FrameLengthBytes }); [Benchmark] public DecryptOutput Decrypt() => _encryptionSdk.Decrypt(new DecryptInput { Keyring = _keyring, Ciphertext = _ciphertext }); private static readonly int[] DefaultValuesForPlaintextLengthBytes = { 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000 }; public static IEnumerable<int> ValuesForPlaintextLengthBytes() => ParseIntsFromEnvVar("BENCHMARK_PLAINTEXT_LENGTH_BYTES", DefaultValuesForPlaintextLengthBytes); private static readonly int[] DefaultValuesForFrameLengthBytes = { 1024, 4096, 65536 }; public static IEnumerable<int> ValuesForFrameLengthBytes() => ParseIntsFromEnvVar("BENCHMARK_FRAME_LENGTH_BYTES", DefaultValuesForFrameLengthBytes); /// <summary> /// Parses the named environment variable as comma-separated integers and returns them, /// or returns the given default values if the environment variable is empty. /// </summary> /// <exception cref="ApplicationException">if the environment variable is incorrectly formatted</exception> private static IEnumerable<int> ParseIntsFromEnvVar(string name, IEnumerable<int> defaults) { var envValue = Environment.GetEnvironmentVariable(name); if (string.IsNullOrWhiteSpace(envValue)) { return defaults; } try { return envValue .Split(',') .Select(part => int.Parse(part.Trim())) // Evaluate this query immediately so that we catch parse exceptions right away, // and not when the caller tries to use the results .ToList(); } catch (FormatException exception) { throw new ApplicationException( $"Environment variable {name} could not be parsed as comma-separated ints", exception); } } } public class RawAesKeyringBenchmark : BaseEncryptDecryptBenchmark { private static readonly string AES_256_KEY_MATERIAL_B64 = "AAECAwQFBgcICRAREhMUFRYXGBkgISIjJCUmJygpMDE="; protected override IKeyring CreateKeyring() { var providers = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); return providers.CreateRawAesKeyring(new CreateRawAesKeyringInput { KeyNamespace = "aes_namespace", KeyName = "aes_name", WrappingAlg = AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16, WrappingKey = new MemoryStream(Base64.Decode(AES_256_KEY_MATERIAL_B64)) }); } } public class RawRsaKeyringBenchmark : BaseEncryptDecryptBenchmark { protected override IKeyring CreateKeyring() { RSA.GenerateKeyPairBytes(2048, out var publicKeyBytes, out var privateKeyBytes); var providers = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); return providers.CreateRawRsaKeyring(new CreateRawRsaKeyringInput { KeyNamespace = "rsa_namespace", KeyName = "rsa_name", PaddingScheme = PaddingScheme.OAEP_SHA512_MGF1, PublicKey = new MemoryStream(publicKeyBytes), PrivateKey = new MemoryStream(privateKeyBytes) }); } } public class Program { public static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); } }
159
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 AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrates setting the commitment policy. /// The commitment policy is a security feature that, if set to its strictest /// setting, ensures that messages are decrypted with the same data key /// used to encrypt them. /// Read more about Key Commitment and the commitment policy Here: /// https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#key-commitment public class CommitmentPolicyExample { private static void Run(MemoryStream plaintext) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); // Set the EncryptionSDK's commitment policy parameter var esdkConfig = new AwsEncryptionSdkConfig { CommitmentPolicy = CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT }; // Instantiate the EncryptionSDK with the configuration var encryptionSdk = AwsEncryptionSdkFactory.CreateAwsEncryptionSdk(esdkConfig); // For illustrative purposes we create a Raw AES Keyring. You can use any keyring in its place. var keyring = GetRawAESKeyring(materialProviders); // Encrypt your plaintext data. // Since the CommitmentPolicy is set to Forbid Encrypt, // the Encryption SDK will encrypt the plaintext without key commitment. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = keyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the same keyring you used on encrypt. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = keyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); // Demonstrate that an EncryptionSDK that enforces Key Commitment on Decryption // will fail to decrypt the encrypted message (as it was encrypted without Key Commitment). var failedDecryption = false; esdkConfig = new AwsEncryptionSdkConfig { CommitmentPolicy = CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT }; // Instantiate the EncryptionSDK with the configuration encryptionSdk = AwsEncryptionSdkFactory.CreateAwsEncryptionSdk(esdkConfig); // Repeat the earlier decryption steps, proving that they fail try { encryptionSdk.Decrypt(decryptInput); } #pragma warning disable 168 catch (AwsEncryptionSdkException ignore) #pragma warning restore 168 { failedDecryption = true; } Assert.True(failedDecryption); // Demonstrate that the EncryptionSDK will not allow the commitment policy // and the Algorithm Suite to be in conflict. var failedEncrypt = false; // Now, the `encryptionSDK` is configured to Require Key Commitment // on both Encrypt and Decrypt (this was set on lines 100 - 105). // If we try and Encrypt data with an Algorithm that does not support Commitment: encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = keyring, EncryptionContext = encryptionContext, AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 }; // The encryption will fail. try { encryptionSdk.Encrypt(encryptInput); } #pragma warning disable 168 catch (AwsEncryptionSdkException ignore) #pragma warning restore 168 { failedEncrypt = true; } Assert.True(failedEncrypt); } // We test examples to ensure they remain up-to-date. [Fact] public void TestCommitmentPolicyExample() { Run(GetPlaintextStream()); } }
149
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 Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; using static ExampleUtils.WriteExampleResources; /// Demonstrate using Discovery Filters. /// /// Discovery Filters are used to restrict Discovery Keyrings /// to trusted AWS Accounts. /// The Accounts are specified by their Account Ids /// and the partition they are in. /// /// It's always a best practice to specify your wrapping keys explicitly. /// This practice assures that you only use the keys that you intend. /// It also improves performance by preventing you from /// inadvertently using keys in a different AWS account or Region, /// or attempting to decrypt with keys that you don't have permission to use. /// /// However, when decrypting with AWS KMS keyrings, /// you are not required to specify wrapping keys. /// The AWS Encryption SDK can get the key identifier /// from the metadata of the encrypted data key. /// /// When specifying AWS KMS wrapping keys for decrypting is impractical /// (such as when encrypting using AWS KMS Aliases), /// you can use discovery keyrings. /// /// When you can not specify your wrapping keys explicitly, /// using a Discovery Filter is a best practice. /// /// Particularly if an application is decrypting messages from multiple sources, /// adding trusted AWS accounts to the discovery filter allows it to /// protect itself from decrypting messages from untrusted sources. public class DiscoveryFilterExample { const string fileName = "defaultRegionKmsKey.bin"; /// <param name="plaintext">unencrypted data</param> /// <param name="trustedAccountIds">List of AWS Account Ids that are trusted.</param> /// <param name="awsPartition">AWS Partition that contains all the members of "trustedAccountIds".</param> /// <exception cref="Exception"></exception> private static void Run( MemoryStream plaintext, List<string> trustedAccountIds, string awsPartition ) { /* 1. Instantiate the Material Providers and Encryption SDK */ var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); // Instantiate the Encryption SDK such that it limits the number of // Encrypted Data Keys a ciphertext may contain. // Discovery Keyrings are an excellent tool // for handling encrypted messages from multiple sources. // Limiting the number of encrypted data keys is a best practice, // particularly when decrypting messages from multiple sources. // See the LimitEncryptedDataKeysExample for details. var esdkConfig = new AwsEncryptionSdkConfig { MaxEncryptedDataKeys = 1 }; var encryptionSdk = AwsEncryptionSdkFactory.CreateAwsEncryptionSdk(esdkConfig); /* 2. Create a Discovery Keyring with a Discovery Filter */ // We create a Discovery keyring to use for decryption. // We'll add a discovery filter so that we limit the set of Encrypted Data Keys // we are willing to decrypt to only ones created by KMS keys from // trusted accounts. var decryptKeyringInput = new CreateAwsKmsDiscoveryKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(), DiscoveryFilter = new DiscoveryFilter { AccountIds = trustedAccountIds, Partition = awsPartition } }; var decryptKeyring = materialProviders.CreateAwsKmsDiscoveryKeyring(decryptKeyringInput); /* 3. Retrieve or create an encrypted message to decrypt. */ // To focus on Discovery Filters, // we rely on a helper method to load the encrypted message. var ciphertext = ReadMessage(fileName); Dictionary<string, string> encryptionContext = GetEncryptionContext(); /* 4. Decrypt the encrypted data. */ var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = decryptKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); /* 5. Verify the encryption context */ VerifyEncryptionContext(decryptOutput, encryptionContext); /* 6. Verify the decrypted plaintext is the original plaintext */ VerifyDecryptedIsPlaintext(decryptOutput, plaintext); /* 7. Create a discovery filter that excludes the encrypted data key */ // If we create a Discovery Filter that excludes // all the accounts the ciphertext was encrypted with, // the decryption will fail. decryptKeyringInput.DiscoveryFilter = new DiscoveryFilter { AccountIds = new List<string> {"123456789012"}, Partition = awsPartition }; /* 8. Validate the excluding discovery filter fails to decrypt the ciphertext */ var decryptFailed = false; var failingKeyring = materialProviders.CreateAwsKmsDiscoveryKeyring(decryptKeyringInput); decryptInput.Keyring = failingKeyring; try { encryptionSdk.Decrypt(decryptInput); } catch (AwsEncryptionSdkException) { decryptFailed = true; } Assert.True(decryptFailed); } /// <summary> /// For this example, we break out encryption context verification /// into a helper method. /// While encryption context verification is a best practice, it is not /// the topic of this example. /// </summary> private static void VerifyEncryptionContext( DecryptOutput decryptOutput, Dictionary<string, string> encryptionContext ) { // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) throw new Exception("Encryption context does not match expected values"); } /// <summary> /// This helper method ensures the decrypted message is the same as the /// encrypted message. /// </summary> private static void VerifyDecryptedIsPlaintext(DecryptOutput decryptOutput, MemoryStream plaintext) { // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestDiscoveryFilterExample() { if (!File.Exists(GetResourcePath(fileName))) { EncryptAndWrite(GetPlaintextStream(), GetDefaultRegionKmsKeyArn(), fileName); } Run(GetPlaintextStream(), GetAccountIds(), "aws"); } }
178
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.Linq; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate limiting the number of Encrypted Data Keys [EDKs] allowed /// when encrypting or decrypting a message. /// Limiting encrypted data keys is most valuable when you are decrypting /// messages from an untrusted source. /// By default, the ESDK will allow up to 65,535 encrypted data keys. /// A malicious actor might construct an encrypted message with thousands of /// encrypted data keys, none of which can be decrypted. /// As a result, the AWS Encryption SDK would attempt to decrypt each /// encrypted data key until it exhausted the encrypted data keys in the message. public class LimitEncryptedDataKeysExample { private static void Run(MemoryStream plaintext, int maxEncryptedDataKeys) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); // Set the EncryptionSDK's MaxEncryptedDataKeys parameter var esdkConfig = new AwsEncryptionSdkConfig { MaxEncryptedDataKeys = maxEncryptedDataKeys }; // Instantiate the EncryptionSDK with the configuration var encryptionSdk = AwsEncryptionSdkFactory.CreateAwsEncryptionSdk(esdkConfig); // We will use a helper method to create a Multi Keyring with `maxEncryptedDataKeys` AES Keyrings var keyrings = new Queue<IKeyring>(); for (long i = 1; i <= maxEncryptedDataKeys; i++) { keyrings.Enqueue(GetRawAESKeyring(materialProviders)); } var createMultiKeyringInput = new CreateMultiKeyringInput { Generator = keyrings.Dequeue(), ChildKeyrings = keyrings.ToList() }; var multiKeyring = materialProviders.CreateMultiKeyring(createMultiKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = multiKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the same keyring you used on encrypt. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = multiKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); // Demonstrate that an EncryptionSDK with a lower MaxEncryptedDataKeys // will fail to decrypt the encrypted message. var failedDecryption = false; esdkConfig = new AwsEncryptionSdkConfig { MaxEncryptedDataKeys = maxEncryptedDataKeys - 1 }; // Instantiate the EncryptionSDK with the configuration encryptionSdk = AwsEncryptionSdkFactory.CreateAwsEncryptionSdk(esdkConfig); // Repeat the earlier decryption steps, proving that they fail try { encryptionSdk.Decrypt(decryptInput); } #pragma warning disable 168 catch (AwsEncryptionSdkException ignore) #pragma warning restore 168 { failedDecryption = true; } Assert.True(failedDecryption); } // We test examples to ensure they remain up-to-date. [Fact] public void TestLimitEncryptedDataKeysExample() { Run(GetPlaintextStream(), 3); } }
135
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 AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Org.BouncyCastle.Security; // In this example, we use BouncyCastle to generate a wrapping key. using Xunit; /// Demonstrate an encrypt/decrypt cycle using a raw AES keyring and a non-signing Algorithm Suite. /// This also demonstrates how to customize the Algorithm Suite used to encrypt the plaintext. /// For a full list of the Algorithm Suites the Encryption SDK supports, /// see https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/algorithms-reference.html public class NonSigningAlgorithmSuiteExample { private static void Run(MemoryStream plaintext) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Generate a 256-bit AES key to use with your keyring. // Here we use BouncyCastle, but you don't have to. // // In practice, you should get this key from a secure key management system such as an HSM. var key = new MemoryStream(GeneratorUtilities.GetKeyGenerator("AES256").GenerateKey()); // The key namespace and key name are defined by you // and are used by the raw AES keyring to determine // whether it should attempt to decrypt an encrypted data key. // // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/choose-keyring.html#use-raw-aes-keyring var keyNamespace = "Some managed raw keys"; var keyName = "My 256-bit AES wrapping key"; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create the keyring that determines how your data keys are protected. var createKeyringInput = new CreateRawAesKeyringInput { KeyNamespace = keyNamespace, KeyName = keyName, WrappingKey = key, // This is the algorithm that will encrypt the Data Key. // It is different from the Algorithm Suite. WrappingAlg = AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16 }; var keyring = materialProviders.CreateRawAesKeyring(createKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = keyring, EncryptionContext = encryptionContext, // Here, we customize the Algorithm Suite that is used to Encrypt the plaintext. // In particular, we use an Algorithm Suite without Signing. // Signature verification adds a significant performance cost on decryption. // If the users encrypting data and the users decrypting data are equally trusted, // consider using an algorithm suite that does not include signing. // See more about Digital Signatures: // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#digital-sigs AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the same keyring you used on encrypt. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = keyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestNonSigningAlgorithmSuiteExample() { Run(ExampleUtils.ExampleUtils.GetPlaintextStream()); } }
121
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.Linq; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; using static ExampleUtils.WriteExampleResources; /// Demonstrates using a Custom Client Supplier. /// See <c>RegionalRoleClientSupplier.cs</c> for the details of implementing a /// custom client supplier. /// This example uses an <c>AwsKmsMrkDiscoveryMultiKeyring</c>, but all /// the AWS Multi Keyrings take Client Suppliers. public class ClientSupplierExample { private const string FILE_NAME = "defaultRegionMrkKey.bin"; private static void Run(MemoryStream plaintext, List<string> accountIds, List<string> regions) { // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); /* 1. Generate or load a ciphertext encrypted by the KMS Key. */ // To focus on Client Suppliers, we will rely on a helper method // to provide the encrypted message (ciphertext). var ciphertext = ReadMessage(FILE_NAME); var encryptionContext = GetEncryptionContext(); /* 2. Create a KMS Multi Keyring with the `RegionalRoleClientSupplier` */ // Now create a Discovery keyring to use for decryption. // We are passing in our Custom Client Supplier. var createDecryptKeyringInput = new CreateAwsKmsMrkDiscoveryMultiKeyringInput { ClientSupplier = new RegionalRoleClientSupplier(), Regions = regions, DiscoveryFilter = new DiscoveryFilter() { AccountIds = accountIds, Partition = "aws" } }; // This is a Multi Keyring composed of MRK Discovery Keyrings. // All the keyrings have the same Discovery Filter. // Each keyring has its own KMS Client, which is provisioned by the Custom Client Supplier. var multiKeyring = materialProviders.CreateAwsKmsMrkDiscoveryMultiKeyring(createDecryptKeyringInput); /* 3. Decrypt the ciphertext with created KMS Multi Keyring */ // On Decrypt, the header of the encrypted message (ciphertext) will be parsed. // The header contains the Encrypted Data Keys (EDKs), which, if the EDK // was encrypted by a KMS Keyring, includes the KMS Key arn. // For each member of the Multi Keyring, every EDK will try to be decrypted until a decryption is successful. // Since every member of the Multi Keyring is a MRK Discovery Keyring: // Each Keyring will filter the EDKs by the Discovery Filter and the keyring's region. // For each filtered EDK, the keyring will attempt decryption with the keyring's client. // All of this is done serially, until a success occurs or all keyrings have failed all (filtered) EDKs. // KMS MRK Discovery Keyrings will attempt to decrypt Multi Region Keys (MRKs) and regular KMS Keys. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = multiKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); /* 4. Verify the encryption context */ VerifyEncryptionContext(decryptOutput, encryptionContext); /* 5. Verify the decrypted plaintext is the same as the original */ VerifyDecryptedIsPlaintext(decryptOutput, plaintext); /* 6. Test the Missing Region Exception */ // Demonstrate catching a custom exception. var createMultiFailed = false; createDecryptKeyringInput.Regions = new List<string>() {"fake-region"}; try { materialProviders.CreateAwsKmsMrkDiscoveryMultiKeyring(createDecryptKeyringInput); } // Note that the exception returned is NOT a `MissingRegionException` catch (MissingRegionException) { throw; } // But is cast down to an `AwsCryptographicMaterialProvidersBaseException`. catch (AwsCryptographicMaterialProvidersBaseException exception) { // However, the message is as expected. Assert.Equal( "Region fake-region is not supported by this client supplier", exception.Message); createMultiFailed = true; } finally { Assert.True(createMultiFailed); } } /// <summary> /// For this example, we break out the Encryption Context Verification /// into a helper method. /// While Encryption Context Verification is a best practice, it is not /// the topic of this example. /// </summary> private static void VerifyEncryptionContext( DecryptOutput decryptOutput, Dictionary<string, string> encryptionContext ) { // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) throw new Exception("Encryption context does not match expected values"); } /// <summary> /// This is helper method that ensures the decrypted message is the /// same as the encrypted message. /// </summary> private static void VerifyDecryptedIsPlaintext(DecryptOutput decryptOutput, MemoryStream plaintext) { var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestClientSupplierExample() { if (!File.Exists(GetResourcePath(FILE_NAME))) { EncryptAndWrite(GetPlaintextStream(), GetDefaultRegionMrkKeyArn(), FILE_NAME); } Run( GetPlaintextStream(), GetAccountIds(), GetRegionIAMRoleMap().Keys.ToList() ); } }
154
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 Amazon; using Amazon.KeyManagementService; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using AWS.EncryptionSDK.Core; using static ExampleUtils.ExampleUtils; /// <summary> /// Demonstrates implementing a Custom Client Supplier. /// This Client Supplier will create KMS Clients with different IAM roles, /// depending on the Region passed. /// </summary> // When implementing a Custom Client Supplier ALWAYS extend the Base class, // not the interface. public class RegionalRoleClientSupplier : ClientSupplierBase { /// <summary> /// Maps a Region to the Arn of the IAM Role the client supplier will /// use when supplying a client. /// </summary> private static Dictionary<string, string> _regionIAMRoleMap; /// <summary> /// Amazon Security Token Service, or STS, allows customers to fetch /// temporary credentials. /// </summary> private static IAmazonSecurityTokenService _stsClient; public RegionalRoleClientSupplier() { _regionIAMRoleMap = GetRegionIAMRoleMap(); _stsClient = new AmazonSecurityTokenServiceClient(); } /// <summary> /// This is the meat of a Client Supplier. /// Whenever the AWS Encryption SDK needs to create a KMS client, /// it will call <c>GetClient</c> for the regions in which it needs to call /// KMS. /// In this example, we utilize a Dictionary /// to map regions to particular IAM Roles. /// We use Amazon Security Token Service to fetch temporary credentials, /// and then provision a Key Management Service (KMS) Client /// with those credentials and the input region. /// </summary> /// <param name="input"><c>GetClientInput</c> is just the region</param> /// <returns>A KMS Client</returns> /// <exception cref="MissingRegionException">If the Region requested is missing from the RegionIAMRole Map</exception> /// <exception cref="AssumeRoleException">If the Assume Role call fails</exception> protected override IAmazonKeyManagementService _GetClient(GetClientInput input) { // Check our RegionIAMRole map for the provided region. // If it is missing, throw a Missing Region Exception. if (!_regionIAMRoleMap.ContainsKey(input.Region)) throw new MissingRegionException(input.Region); // Otherwise, call Amazon STS to assume the role. var iamArn = _regionIAMRoleMap[input.Region]; var task = _stsClient.AssumeRoleAsync(new AssumeRoleRequest { RoleArn = iamArn, DurationSeconds = 900, // 15 minutes is the minimum value RoleSessionName = "ESDK-NET-Custom-Client-Example" }); AssumeRoleResponse response; // Await the async response try { response = task.Result; } catch (Exception e) { throw new AssumeRoleException(input.Region, iamArn, e); } // Return a KMS Client with the credentials from STS and the Region. return new AmazonKeyManagementServiceClient( response.Credentials, RegionEndpoint.GetBySystemName(input.Region)); } } // Custom Exceptions SHOULD extend from the Library's Base Exception. // This is a quirk of using Dafny to generate the Encryption SDK. // The Encryption SDK will handle dotnet's System.Exception, // but the exception message will be altered. // By extending from the Library's Base Exception, // you can ensure the exception's message will be as intended. public class MissingRegionException : AwsCryptographicMaterialProvidersBaseException { public MissingRegionException(string region) : base( $"Region {region} is not supported by this client supplier") { } } public class AssumeRoleException : AwsCryptographicMaterialProvidersBaseException { public AssumeRoleException(string region, string roleArn, Exception e) : base( $"Attempt to assume Role Arn {roleArn} for Region {region}" + $" encountered unexpected: {e.GetType()}: \"{e.Message}\"") { // At this time, the Encryption SDK only retains exception messages, // and not the entire stack trace. // As such, it is helpful to manually log the exceptions // (ideally, a logging framework would be used, instead of console). Console.Out.Write(e); } }
114
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 AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate an encrypt/decrypt cycle using a Custom Cryptographic Materials Manager (CMM). /// `SigningSuiteOnlyCMM.cs` demonstrates creating a custom CMM to reject Non-Signing Algorithms. public class SigningOnlyExample { private static void Run(MemoryStream plaintext) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create a keyring via a helper method. var keyring = GetRawAESKeyring(materialProviders); // Create an instance of the custom CMM var cmm = new SigningSuiteOnlyCMM(keyring, materialProviders); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, MaterialsManager = cmm, EncryptionContext = encryptionContext, AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the same cryptographic material manager // you used on encrypt. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, MaterialsManager = cmm }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); VerifyEncryptionContext(decryptOutput, encryptionContext); VerifyDecryptedIsPlaintext(decryptOutput, plaintext); // Demonstrate that a Non Signing Algorithm Suite will be rejected // by the CMM. var encryptFailed = false; encryptInput = new EncryptInput { Plaintext = plaintext, MaterialsManager = cmm, EncryptionContext = encryptionContext, AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY }; try { encryptionSdk.Encrypt(encryptInput); } // The Encryption SDK converts the custom exception // to an AwsEncryptionSdkBaseException, while retaining // the exception message. catch (AwsEncryptionSdkBaseException baseException) { Assert.Equal("Algorithm Suite must use Signing", baseException.Message); encryptFailed = true; } Assert.True(encryptFailed); // Demonstrate that a message encrypted with a Non-Signing Algorithm // will also be rejected. // Create an encrypted message with a Non-Signing Algorithm. // Here, we do not use the Signing Only CMM, but just pass a Keyring. // The Encryption SDK will then create a Default CMM to facilitate the // assembling and checking the cryptographic materials. var keyringEncryptInput = new EncryptInput { Plaintext = plaintext, EncryptionContext = encryptionContext, AlgorithmSuiteId = AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, Keyring = keyring }; encryptOutput = encryptionSdk.Encrypt(keyringEncryptInput); ciphertext = encryptOutput.Ciphertext; decryptInput.Ciphertext = ciphertext; // Verify that the Signing Only CMM will fail decryption var decryptFailed = false; try { encryptionSdk.Decrypt(decryptInput); } catch (AwsEncryptionSdkBaseException) { decryptFailed = true; } Assert.True(decryptFailed); } private static void VerifyEncryptionContext( DecryptOutput decryptOutput, Dictionary<string, string> encryptionContext ) { // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } } private static void VerifyDecryptedIsPlaintext(DecryptOutput decryptOutput, MemoryStream plaintext) { // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestSigningOnlyExample() { Run(GetPlaintextStream()); } }
162
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.Collections.Immutable; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; /// <summary> /// Demonstrates creating a custom Cryptographic Materials Manager (CMM). /// The SigningSuiteOnlyCMM ensures that callers use an Algorithm Suite with /// signing. This is a best practice. Read more about Digital Signing: /// https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#digital-sigs /// Read more about Cryptographic Materials Managers (CMMs): /// https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#crypt-materials-manager /// </summary> public class SigningSuiteOnlyCMM : CryptographicMaterialsManagerBase { private readonly ICryptographicMaterialsManager _cmm; private readonly ImmutableHashSet<AlgorithmSuiteId> _approvedAlgos = new HashSet<AlgorithmSuiteId>() { AlgorithmSuiteId.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, AlgorithmSuiteId.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, AlgorithmSuiteId.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, AlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 }.ToImmutableHashSet(); public SigningSuiteOnlyCMM(IKeyring keyring, IAwsCryptographicMaterialProviders materialProviders) { // Create a DefaultCryptographicMaterialsManager to facilitate // GetEncryptionMaterials and DecryptionMaterials // after this CMM approves the Algorithm Suite. var cmmInput = new CreateDefaultCryptographicMaterialsManagerInput { Keyring = keyring }; _cmm = materialProviders.CreateDefaultCryptographicMaterialsManager(cmmInput); } protected override GetEncryptionMaterialsOutput _GetEncryptionMaterials(GetEncryptionMaterialsInput input) { if (!_approvedAlgos.Contains(input.AlgorithmSuiteId)) { throw new NonSigningSuiteException(); } return _cmm.GetEncryptionMaterials(input); } protected override DecryptMaterialsOutput _DecryptMaterials(DecryptMaterialsInput input) { if (!_approvedAlgos.Contains(input.AlgorithmSuiteId)) { throw new NonSigningSuiteException(); } return _cmm.DecryptMaterials(input); } } // Custom Exceptions SHOULD extend from the Library's Base Exception. // The Encryption SDK will handle dotnet's System.Exception, // but the exception message will be altered. // By extending from the Library's Base Exception, // you can ensure the exception's message will be as intended. public class NonSigningSuiteException : AwsCryptographicMaterialProvidersBaseException { public NonSigningSuiteException() : base("Algorithm Suite must use Signing") { } }
71
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.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using Amazon; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Org.BouncyCastle.Security; namespace ExampleUtils { class ExampleUtils { // The name of the environment variable storing the key to use in examples private static string TEST_AWS_KMS_KEY_ID_ENV_VAR = "AWS_ENCRYPTION_SDK_EXAMPLE_KMS_KEY_ID"; private static string TEST_AWS_KMS_KEY_ID_2_ENV_VAR = "AWS_ENCRYPTION_SDK_EXAMPLE_KMS_KEY_ID_2"; private static string TEST_AWS_KMS_MRK_KEY_ID_ENV_VAR = "AWS_ENCRYPTION_SDK_EXAMPLE_KMS_MRK_KEY_ID"; private static string TEST_AWS_KMS_MRK_KEY_ID_ENV_VAR_2 = "AWS_ENCRYPTION_SDK_EXAMPLE_KMS_MRK_KEY_ID_2"; // The name of the environment variable storing the IAM Role Arn to use in examples private static string TEST_AWS_LIMITED_ROLE_ENV_VAR = "AWS_ENCRYPTION_SDK_EXAMPLE_LIMITED_ROLE_ARN_US_EAST_1"; private static string TEST_AWS_LIMITED_ROLE_ENV_VAR_2 = "AWS_ENCRYPTION_SDK_EXAMPLE_LIMITED_ROLE_ARN_EU_WEST_1"; private const string ENCRYPTED_MESSAGE_PATH = "../../../resources/"; private static readonly ImmutableDictionary<string, string> ENCRYPTION_CONTEXT = new Dictionary<string, string> { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }.ToImmutableDictionary(); static public MemoryStream GetPlaintextStream() { return new MemoryStream(Encoding.UTF8.GetBytes( "Lorem ipsum dolor sit amet, consectetur adipiscing elit." )); } static public string GetEnvVariable(string keyName) { string value = Environment.GetEnvironmentVariable(keyName); if (value == null) { throw new ArgumentException( String.Format("Please set environment variable {0} to a valid KMS key ARN", keyName) ); } return value; } static public RegionEndpoint GetRegionEndpointFromArn(string arn_string) { Arn arn = Arn.Parse(arn_string); return RegionEndpoint.GetBySystemName(arn.Region); } static public string GetDefaultRegionKmsKeyArn() { return GetEnvVariable(TEST_AWS_KMS_KEY_ID_ENV_VAR); } static public string GetAlternateRegionKmsKeyArn() { return GetEnvVariable(TEST_AWS_KMS_KEY_ID_2_ENV_VAR); } static public string GetDefaultRegionMrkKeyArn() { return GetEnvVariable(TEST_AWS_KMS_MRK_KEY_ID_ENV_VAR); } static public string GetAlternateRegionMrkKeyArn() { return GetEnvVariable(TEST_AWS_KMS_MRK_KEY_ID_ENV_VAR_2); } static public List<string> GetAccountIds() { return new List<string>() {"658956600833"}; } static public List<string> GetRegions() { return new List<string>() {"us-west-2", "us-east-1"}; } static public Dictionary<string, string> GetRegionIAMRoleMap() { return new Dictionary<string, string>() { {RegionEndpoint.USEast1.SystemName, GetEnvVariable(TEST_AWS_LIMITED_ROLE_ENV_VAR)}, {RegionEndpoint.EUWest1.SystemName, GetEnvVariable(TEST_AWS_LIMITED_ROLE_ENV_VAR_2)} }; } // Helper method to create RawAESKeyring for examples. public static IKeyring GetRawAESKeyring(IAwsCryptographicMaterialProviders materialProviders) { // Generate a 256-bit AES key to use with your keyring. // Here we use BouncyCastle, but you don't have to. // // In practice, you should get this key from a secure key management system such as an HSM. var key = new MemoryStream(GeneratorUtilities.GetKeyGenerator("AES256").GenerateKey()); // The key namespace and key name are defined by you // and are used by the raw AES keyring to determine // whether it should attempt to decrypt an encrypted data key. // // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/choose-keyring.html#use-raw-aes-keyring var keyNamespace = "Some managed raw keys"; var keyName = "My 256-bit AES wrapping key"; // Create the keyring that determines how your data keys are protected. var createAesKeyringInput = new CreateRawAesKeyringInput { KeyNamespace = keyNamespace, KeyName = keyName, WrappingKey = key, WrappingAlg = AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16 }; var aesKeyring = materialProviders.CreateRawAesKeyring(createAesKeyringInput); return aesKeyring; } public static Dictionary<string, string> GetEncryptionContext() { return ENCRYPTION_CONTEXT.ToDictionary(p => p.Key, p => p.Value); } public static MemoryStream EncryptMessageWithKMSKey(MemoryStream plaintext, string kmsKeyArn) { var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); var createKeyringInput = new CreateAwsKmsMrkMultiKeyringInput() { Generator = kmsKeyArn }; var encryptKeyring = materialProviders.CreateAwsKmsMrkMultiKeyring(createKeyringInput); var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = encryptKeyring, EncryptionContext = GetEncryptionContext() }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; return ciphertext; } public static string GetResourcePath(string name) { return ENCRYPTED_MESSAGE_PATH + name; } public static void WriteMessage(MemoryStream message, string path) { using (var file = new FileStream(GetResourcePath(path), FileMode.OpenOrCreate, FileAccess.Write)) message.CopyTo(file); } public static MemoryStream ReadMessage(string path) { var rtn = new MemoryStream(); using (var file = new FileStream(GetResourcePath(path), FileMode.Open, FileAccess.Read)) file.CopyTo(rtn); return rtn; } } }
177
aws-encryption-sdk-dafny
aws
C#
using System.IO; using static ExampleUtils.ExampleUtils; namespace ExampleUtils { public static class WriteExampleResources { public static void EncryptAndWrite(MemoryStream plaintext, string kmsKeyArn, string fileName) { var ciphertext = EncryptMessageWithKMSKey(plaintext, kmsKeyArn); WriteMessage(ciphertext, fileName); } } }
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.Collections.Generic; using System.IO; using Amazon; using Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate decryption using an AWS KMS discovery keyring. public class AwsKmsDiscoveryKeyringExample { private static void Run(MemoryStream plaintext, string keyArn) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create the keyring that determines how your data keys are protected. Though this example highlights // Discovery keyrings, Discovery keyrings cannot be used to encrypt, so for encryption we create // a KMS keyring without discovery mode. var createKeyringInput = new CreateAwsKmsKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(), KmsKeyId = keyArn }; var encryptKeyring = materialProviders.CreateAwsKmsKeyring(createKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = encryptKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Now create a Discovery keyring to use for decryption. We'll add a discovery filter so that we limit // the set of ciphertexts we are willing to decrypt to only ones created by KMS keys in our account and // partition. var createDecryptKeyringInput = new CreateAwsKmsDiscoveryKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(), DiscoveryFilter = new DiscoveryFilter() { AccountIds = GetAccountIds(), Partition = "aws" } }; var decryptKeyring = materialProviders.CreateAwsKmsDiscoveryKeyring(createDecryptKeyringInput); // On Decrypt, the header of the encrypted message (ciphertext) will be parsed. // The header contains the Encrypted Data Keys (EDKs), which, if the EDK // was encrypted by a KMS Keyring, includes the KMS Key ARN. // The Discovery Keyring filters these EDKs for // EDKs encrypted by Single Region OR Multi Region KMS Keys. // If a Discovery Filter is present, these KMS Keys must belong // to an AWS Account ID in the discovery filter's AccountIds and // must be from the discovery filter's partition. // Finally, KMS is called to decrypt each filtered EDK until an EDK is // successfully decrypted. The resulting data key is used to decrypt the // ciphertext's message. // If all calls to KMS fail, the decryption fails. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = decryptKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsDiscoveryKeyringExample() { Run(GetPlaintextStream(), GetDefaultRegionKmsKeyArn()); } }
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.Generic; using System.IO; using Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate decryption using a Multi-Keyring containing multiple AWS KMS /// Discovery Keyrings. public class AwsKmsDiscoveryMultiKeyringExample { private static void Run(MemoryStream plaintext, string keyArn, List<string> accountIds, List<string> regions) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create the keyring that determines how your data keys are protected. Though this example highlights // Discovery keyrings, Discovery keyrings cannot be used to encrypt, so for encryption we create // a KMS keyring without discovery mode. var createKeyringInput = new CreateAwsKmsKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(), KmsKeyId = keyArn }; var encryptKeyring = materialProviders.CreateAwsKmsKeyring(createKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = encryptKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Now create a Discovery keyring to use for decryption. We'll add a discovery filter so that we limit // the set of ciphertexts we are willing to decrypt to only ones created by KMS keys in our accounts and // partition. var createDecryptKeyringInput = new CreateAwsKmsDiscoveryMultiKeyringInput { Regions = regions, DiscoveryFilter = new DiscoveryFilter() { AccountIds = accountIds, Partition = "aws" } }; // This is a Multi Keyring composed of Discovery Keyrings. // There is a keyring for every region in `regions`. // All the keyrings have the same Discovery Filter. // Each keyring has its own KMS Client, which is created for the keyring's region. var multiKeyring = materialProviders.CreateAwsKmsDiscoveryMultiKeyring(createDecryptKeyringInput); // On Decrypt, the header of the encrypted message (ciphertext) will be parsed. // The header contains the Encrypted Data Keys (EDKs), which, if the EDK // was encrypted by a KMS Keyring, includes the KMS Key ARN. // For each member of the Multi Keyring, every EDK will try to be decrypted until a decryption is successful. // Since every member of the Multi Keyring is a Discovery Keyring: // Each Keyring will filter the EDKs by the Discovery Filter // For the filtered EDKs, the keyring will try to decrypt it with the keyring's client. // All of this is done serially, until a success occurs or all keyrings have failed all (filtered) EDKs. // KMS Discovery Keyrings will attempt to decrypt Multi Region Keys (MRKs) and regular KMS Keys. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = multiKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsDiscoveryMultiKeyringExample() { Run( GetPlaintextStream(), GetDefaultRegionKmsKeyArn(), GetAccountIds(), GetRegions() ); } }
126
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 Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; /// Demonstrate an encrypt/decrypt cycle using an AWS KMS keyring. public class AwsKmsKeyringExample { private static void Run(MemoryStream plaintext, string keyArn) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create the keyring that determines how your data keys are protected. var createKeyringInput = new CreateAwsKmsKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(), KmsKeyId = keyArn }; var keyring = materialProviders.CreateAwsKmsKeyring(createKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = keyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the same keyring you used on encrypt. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = keyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsKeyringExample() { Run(ExampleUtils.ExampleUtils.GetPlaintextStream(), ExampleUtils.ExampleUtils.GetDefaultRegionKmsKeyArn()); } }
93
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.IO; using Amazon; using Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; using static ExampleUtils.WriteExampleResources; /// Demonstrate decryption using an AWS KMS Multi-Region Key (MRK) discovery keyring. public class AwsKmsMrkDiscoveryKeyringExample { private const string FILE_NAME = "defaultRegionMrkKey.bin"; private static void Run(MemoryStream plaintext, RegionEndpoint decryptRegion) { // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // To focus on the AWS KMS MRK Discovery Keyring, // we will rely on a helper method // to provide the encrypted message (ciphertext). var ciphertext = ReadMessage(FILE_NAME); var encryptionContext = GetEncryptionContext(); // Now create a Discovery keyring to use for decryption. // In order to illustrate the MRK behavior of this keyring, we configure // the keyring to use the second KMS region where the MRK is replicated to. var createDecryptKeyringInput = new CreateAwsKmsMrkDiscoveryKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(decryptRegion), Region = decryptRegion.SystemName, DiscoveryFilter = new DiscoveryFilter() { AccountIds = GetAccountIds(), Partition = "aws" } }; var decryptKeyring = materialProviders.CreateAwsKmsMrkDiscoveryKeyring(createDecryptKeyringInput); // On Decrypt, the header of the encrypted message (ciphertext) will be parsed. // The header contains the Encrypted Data Keys (EDKs), which, if the EDK // was encrypted by a KMS Keyring, includes the KMS Key ARN. // The MRK Discovery Keyring filters these EDKs for: // - EDKs encrypted by Single Region KMS Keys in the keyring's region // OR // - EDKs encrypted by Multi Region KMS Keys // Additionally, the keyring filters these KMS encrypted data keys // by the keyring's Discovery Filter, if a Discovery Filter is // present on the keyring. // Finally, KMS is called to decrypt each filtered EDK until an EDK is // successfully decrypted. The resulting data key is used to decrypt the // ciphertext's message. // If all calls to KMS fail, the decryption fails. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = decryptKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsMrkDiscoveryKeyringExample() { if (!File.Exists(GetResourcePath(FILE_NAME))) { EncryptAndWrite(GetPlaintextStream(), GetDefaultRegionMrkKeyArn(), FILE_NAME); } Run( GetPlaintextStream(), GetRegionEndpointFromArn(GetAlternateRegionMrkKeyArn()) ); } }
101
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 Amazon; using Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate decryption using a Multi-Keyring containing multiple AWS KMS /// MRK Discovery Keyrings. public class AwsKmsMrkDiscoveryMultiKeyringExample { private static void Run(MemoryStream plaintext, string keyArn, List<string> accountIds, List<string> regions) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create the keyring that determines how your data keys are protected. // Though this example highlights Discovery keyrings, Discovery keyrings // cannot be used to encrypt, so for encryption we create a KMS MRK keyring. var createKeyringInput = new CreateAwsKmsMrkKeyringInput { // Create a KMS Client for the region of the Encrypt MRK Key KmsClient = new AmazonKeyManagementServiceClient(GetRegionEndpointFromArn(keyArn)), KmsKeyId = keyArn }; var encryptKeyring = materialProviders.CreateAwsKmsMrkKeyring(createKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = encryptKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Now create a MRK Discovery Multi Keyring to use for decryption. // We'll add a discovery filter to limit the set of encrypted data keys // we are willing to decrypt to only ones created by KMS keys in select // accounts and the partition `aws`. // MRK Discovery keyrings also filter encrypted data keys by the region // the keyring is created with. var mkrDiscoveryMultiKeyring = new CreateAwsKmsMrkDiscoveryMultiKeyringInput { Regions = regions, DiscoveryFilter = new DiscoveryFilter() { AccountIds = accountIds, Partition = "aws" } }; // This is a Multi Keyring composed of Discovery Keyrings. // There is a keyring for every region in `regions`. // All the keyrings have the same Discovery Filter. // Each keyring has its own KMS Client, which is created for the keyring's region. var multiKeyring = materialProviders.CreateAwsKmsMrkDiscoveryMultiKeyring(mkrDiscoveryMultiKeyring); // On Decrypt, the header of the encrypted message (ciphertext) will be parsed. // The header contains the Encrypted Data Keys (EDKs), which, if the EDK // was encrypted by a KMS Keyring, includes the KMS Key ARN. // For each member of the Multi Keyring, every EDK will try to be decrypted until a decryption is successful. // Since every member of the Multi Keyring is a Discovery Keyring: // Each Keyring will filter the EDKs by the Discovery Filter and the Keyring's region. // For each filtered EDK, the keyring will attempt decryption with the keyring's client. // All of this is done serially, until a success occurs or all keyrings have failed all (filtered) EDKs. // KMS MRK Discovery Keyrings will attempt to decrypt Multi Region Keys (MRKs) and regular KMS Keys. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = multiKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsMrkDiscoveryMultiKeyringExample() { Run( GetPlaintextStream(), GetDefaultRegionMrkKeyArn(), GetAccountIds(), GetRegions() ); } }
131
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 Amazon; using Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate an encrypt/decrypt cycle using an AWS MRK keyring. public class AwsKmsMrkKeyringExample { private static void Run(MemoryStream plaintext, string encryptKeyArn, string decryptKeyArn) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create a keyring that will encrypt your data, using a KMS MRK key in the first region. var createEncryptKeyringInput = new CreateAwsKmsMrkKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(GetRegionEndpointFromArn(encryptKeyArn)), KmsKeyId = encryptKeyArn }; var encryptKeyring = materialProviders.CreateAwsKmsMrkKeyring(createEncryptKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = encryptKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Create a keyring that will decrypt your data, using the same KMS MRK key replicated to the second region. // This example assumes you have already replicated your key; for more info on this, see the KMS documentation: // https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html var createDecryptKeyringInput = new CreateAwsKmsMrkKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(GetRegionEndpointFromArn(decryptKeyArn)), KmsKeyId = decryptKeyArn }; var decryptKeyring = materialProviders.CreateAwsKmsMrkKeyring(createDecryptKeyringInput); // Decrypt your encrypted data using the decrypt keyring. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = decryptKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsMrkKeyringExample() { Run( GetPlaintextStream(), GetDefaultRegionMrkKeyArn(), GetAlternateRegionMrkKeyArn() ); } }
108
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 Amazon; using Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate an encrypt/decrypt cycle using a Multi-Keyring made up of multiple AWS KMS /// MRK Keyrings. public class AwsKmsMrkMultiKeyringExample { // For this example, `mrkKeyArn` is the ARN for an AWS KMS multi-Region key (MRK) // located in your default region, and `kmsKeyArn` is the ARN for a KMS key, // possibly located in a different Region than the MRK. // Finally, `mrkReplicaKeyArn` is the ARN for a MRK that // is a replica of the `mrkKeyArn` in a second region. private static void Run(MemoryStream plaintext, string mrkKeyArn, string kmsKeyArn, string mrkReplicaKeyArn) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create an AwsKmsMrkMultiKeyring that protects your data under two different KMS Keys. // The Keys can either be regular KMS keys or MRKs. // Either KMS Key individually is capable of decrypting data encrypted under this keyring. var createAwsKmsMultiKeyringInput = new CreateAwsKmsMrkMultiKeyringInput { Generator = mrkKeyArn, KmsKeyIds = new List<string>() {kmsKeyArn} }; var kmsMultiKeyring = materialProviders.CreateAwsKmsMrkMultiKeyring(createAwsKmsMultiKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = kmsMultiKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the AwsKmsMrkMultiKeyring. // It will decrypt the data using the generator KMS key since // it is the first available KMS key on the keyring that // is capable of decrypting the data. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = kmsMultiKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); // Demonstrate that a single AwsKmsMrkKeyring configured with a replica of a MRK from the // multi-keyring used to encrypt the data is also capable of decrypting the data. // // Not shown is that a KMS Keyring created with `kmsKeyArn` could also decrypt this message. // Create a single AwsKmsMrkKeyring with the replica KMS MRK from the second region. var createKeyringInput = new CreateAwsKmsMrkKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(GetRegionEndpointFromArn(mrkReplicaKeyArn)), KmsKeyId = mrkReplicaKeyArn }; var mrkReplicaKeyring = materialProviders.CreateAwsKmsMrkKeyring(createKeyringInput); // Decrypt your encrypted data using the keyring configured with the KMS MRK from the second region. decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = mrkReplicaKeyring }; var mrkReplicaOutput = encryptionSdk.Decrypt(decryptInput); // Verify the Encryption Context on the output foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var mrkReplicaDecrypted = mrkReplicaOutput.Plaintext; Assert.Equal(mrkReplicaDecrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsMrkMultiKeyringExample() { Run( GetPlaintextStream(), GetDefaultRegionMrkKeyArn(), GetDefaultRegionKmsKeyArn(), GetAlternateRegionMrkKeyArn() ); } }
146
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 Amazon; using Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate an encrypt/decrypt cycle using a Multi-Keyring made up of multiple AWS KMS /// Keyrings. public class AwsKmsMultiKeyring { // For this example, `defaultRegionKeyArn` is the ARN for a KMS Key located in your default region, // and `secondRegionKeyArn` is the ARN for a KMS Key located in some second Region. private static void Run(MemoryStream plaintext, string defaultRegionKeyArn, string secondRegionKeyArn) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create a AwsKmsMultiKeyring that protects your data under two different KMS Keys. // Either KMS Key individually is capable of decrypting data encrypted under this AwsKmsMultiKeyring. var createAwsKmsMultiKeyringInput = new CreateAwsKmsMultiKeyringInput { Generator = defaultRegionKeyArn, KmsKeyIds = new List<string>() {secondRegionKeyArn} }; var kmsMultiKeyring = materialProviders.CreateAwsKmsMultiKeyring(createAwsKmsMultiKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = kmsMultiKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the AwsKmsMultiKeyring. // It will decrypt the data using the generator KMS key since // it is the first available KMS key on the AwsKmsMultiKeyring that // is capable of decrypting the data. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = kmsMultiKeyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); // Demonstrate that a single AwsKmsKeyring configured with either KMS key // is also capable of decrypting the data. // // Create a single AwsKmsKeyring with the KMS key from our second region. var createKeyringInput = new CreateAwsKmsKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(GetRegionEndpointFromArn(secondRegionKeyArn)), KmsKeyId = secondRegionKeyArn }; var kmsKeyring = materialProviders.CreateAwsKmsKeyring(createKeyringInput); // Decrypt your encrypted data using the AwsKmsKeyring configured with the KMS Key from the second region. var kmsKeyringDecryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = kmsKeyring }; var kmsKeyringDecryptOutput = encryptionSdk.Decrypt(kmsKeyringDecryptInput); // Verify the Encryption Context on the output foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var kmsKeyringDecrypted = kmsKeyringDecryptOutput.Plaintext; Assert.Equal(kmsKeyringDecrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestAwsKmsMultiKeyringExample() { Run( GetPlaintextStream(), GetDefaultRegionKmsKeyArn(), GetAlternateRegionKmsKeyArn() ); } }
139
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 Amazon.KeyManagementService; using AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; using static ExampleUtils.ExampleUtils; /// Demonstrate an encrypt/decrypt cycle using a Multi keyring consisting of an /// AWS KMS Keyring and a raw AES keyring. public class MultiKeyringExample { private static void Run(MemoryStream plaintext, string keyArn) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create a KMS keyring to use as the generator. var createKeyringInput = new CreateAwsKmsKeyringInput { KmsClient = new AmazonKeyManagementServiceClient(), KmsKeyId = keyArn }; var kmsKeyring = materialProviders.CreateAwsKmsKeyring(createKeyringInput); // Create a raw AES keyring to additionally encrypt under var rawAESKeyring = GetRawAESKeyring(materialProviders); // Create a MultiKeyring that consists of the previously created Keyrings. // When using this MultiKeyring to encrypt data, either `kmsKeyring` or // `rawAESKeyring` (or a MultiKeyring containing either) may be used to decrypt the data. var createMultiKeyringInput = new CreateMultiKeyringInput { Generator = kmsKeyring, ChildKeyrings = new List<IKeyring>() {rawAESKeyring} }; var multiKeyring = materialProviders.CreateMultiKeyring(createMultiKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = multiKeyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the MultiKeyring used on encrypt. // The MultiKeyring will use `kmsKeyring` to decrypt the ciphertext // since it is the first available internal keyring which is capable // of decrypting the ciphertext. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var multiKeyringDecryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = multiKeyring }; var multiKeyringDecryptOutput = encryptionSdk.Decrypt(multiKeyringDecryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!multiKeyringDecryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var multiKeyringDecrypted = multiKeyringDecryptOutput.Plaintext; Assert.Equal(multiKeyringDecrypted.ToArray(), plaintext.ToArray()); // Demonstrate that you can also successfully decrypt data using the `rawAESKeyring` directly. // Because you used a MultiKeyring on Encrypt, you can use either the `kmsKeyring` or // `rawAESKeyring` individually to decrypt the data. var rawAESKeyringDecryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = rawAESKeyring }; var rawAESKeyringDecryptOutput = encryptionSdk.Decrypt(rawAESKeyringDecryptInput); // Verify your Encryption Context foreach (var expectedPair in encryptionContext) { if (!rawAESKeyringDecryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var rawAESKeyringDecrypted = rawAESKeyringDecryptOutput.Plaintext; Assert.Equal(rawAESKeyringDecrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestMultiKeyringExample() { Run( GetPlaintextStream(), GetDefaultRegionKmsKeyArn() ); } }
137
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 AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Org.BouncyCastle.Security; // In this example, we use BouncyCastle to generate a wrapping key. using Xunit; /// Demonstrate an encrypt/decrypt cycle using a raw AES keyring. public class RawAESKeyringExample { private static void Run(MemoryStream plaintext) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"encryption", "context"}, {"is not", "secret"}, {"but adds", "useful metadata"}, {"that can help you", "be confident that"}, {"the data you are handling", "is what you think it is"} }; // Generate a 256-bit AES key to use with your keyring. // Here we use BouncyCastle, but you don't have to. // // In practice, you should get this key from a secure key management system such as an HSM. var key = new MemoryStream(GeneratorUtilities.GetKeyGenerator("AES256").GenerateKey()); // The key namespace and key name are defined by you // and are used by the raw AES keyring to determine // whether it should attempt to decrypt an encrypted data key. // // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/choose-keyring.html#use-raw-aes-keyring var keyNamespace = "Some managed raw keys"; var keyName = "My 256-bit AES wrapping key"; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create the keyring that determines how your data keys are protected. var createKeyringInput = new CreateRawAesKeyringInput { KeyNamespace = keyNamespace, KeyName = keyName, WrappingKey = key, WrappingAlg = AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16 }; var keyring = materialProviders.CreateRawAesKeyring(createKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = keyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the same keyring you used on encrypt. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = keyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestRawAESKeyringExample() { Run(ExampleUtils.ExampleUtils.GetPlaintextStream()); } }
108
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 AWS.EncryptionSDK; using AWS.EncryptionSDK.Core; using Xunit; /// Demonstrate an encrypt/decrypt cycle using a raw RSA keyring. public class RawRSAKeyringExample { // Used to test our example below. static string PRIVATE_KEY_PEM_FILENAME = "RSAKeyringExamplePrivateKey.pem"; static string PUBLIC_KEY_PEM_FILENAME = "RSAKeyringExamplePublicKey.pem"; private static void Run(MemoryStream plaintext, string publicKeyFileName, string privateKeyFileName) { // Create your encryption context. // Remember that your encryption context is NOT SECRET. // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context var encryptionContext = new Dictionary<string, string>() { {"name", "encryption context"}, {"is_secret", "false"}, {"is_public", "true"}, {"purpose", "useful metadata"} }; // Get our PEM encoded RSA private and public keys var publicKey = new MemoryStream(System.IO.File.ReadAllBytes(publicKeyFileName)); var privateKey = new MemoryStream(System.IO.File.ReadAllBytes(privateKeyFileName)); // The key namespace and key name are defined by you // and are used by the raw RSA keyring to determine // whether it should attempt to decrypt an encrypted data key. // // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/choose-keyring.html#use-raw-rsa-keyring var keyNamespace = "Some managed raw keys"; var keyName = "My 2048-bit RSA wrapping key"; // Instantiate the Material Providers and the AWS Encryption SDK var materialProviders = AwsCryptographicMaterialProvidersFactory.CreateDefaultAwsCryptographicMaterialProviders(); var encryptionSdk = AwsEncryptionSdkFactory.CreateDefaultAwsEncryptionSdk(); // Create the keyring that determines how your data keys are protected. var createRawRsaKeyringInput = new CreateRawRsaKeyringInput { KeyNamespace = keyNamespace, KeyName = keyName, PaddingScheme = PaddingScheme.OAEP_SHA512_MGF1, PublicKey = publicKey, PrivateKey = privateKey }; var keyring = materialProviders.CreateRawRsaKeyring(createRawRsaKeyringInput); // Encrypt your plaintext data. var encryptInput = new EncryptInput { Plaintext = plaintext, Keyring = keyring, EncryptionContext = encryptionContext }; var encryptOutput = encryptionSdk.Encrypt(encryptInput); var ciphertext = encryptOutput.Ciphertext; // Demonstrate that the ciphertext and plaintext are different. Assert.NotEqual(ciphertext.ToArray(), plaintext.ToArray()); // Decrypt your encrypted data using the same keyring you used on encrypt. // // You do not need to specify the encryption context on decrypt // because the header of the encrypted message includes the encryption context. var decryptInput = new DecryptInput { Ciphertext = ciphertext, Keyring = keyring }; var decryptOutput = encryptionSdk.Decrypt(decryptInput); // Before your application uses plaintext data, verify that the encryption context that // you used to encrypt the message is included in the encryption context that was used to // decrypt the message. The AWS Encryption SDK can add pairs, so don't require an exact match. // // In production, always use a meaningful encryption context. foreach (var expectedPair in encryptionContext) { if (!decryptOutput.EncryptionContext.TryGetValue(expectedPair.Key, out var decryptedValue) || !decryptedValue.Equals(expectedPair.Value)) { throw new Exception("Encryption context does not match expected values"); } } // Demonstrate that the decrypted plaintext is identical to the original plaintext. var decrypted = decryptOutput.Plaintext; Assert.Equal(decrypted.ToArray(), plaintext.ToArray()); } // We test examples to ensure they remain up-to-date. [Fact] public void TestRawRSAKeyringExample() { RSAEncryption.RSA.GenerateKeyPairBytes(2048, out var publicKeyBytes, out var privateKeyBytes); File.WriteAllBytes(PRIVATE_KEY_PEM_FILENAME, privateKeyBytes); File.WriteAllBytes(PUBLIC_KEY_PEM_FILENAME, publicKeyBytes); Run(ExampleUtils.ExampleUtils.GetPlaintextStream(), PUBLIC_KEY_PEM_FILENAME, PRIVATE_KEY_PEM_FILENAME); } }
115
aws-encryption-sdk-dafny
aws
C#
using System.Reflection; [assembly: AssemblyTitle("AWS.EncryptionSDK")] // This should be kept in sync with the version number in AWSEncryptionSDK.csproj [assembly: AssemblyVersion("3.1.0")]
7
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.IO; 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>; // General-purpose utilities for invoking Dafny from C#, // including converting between common Dafny and C# datatypes. // Note this class is NOT intended to be part of the .NET ESDK API, but only // for internal use in adapting between that API and the Dafny equivalent. public class DafnyFFI { public static byte[] ByteArrayFromSequence(ibyteseq seq) { // TODO: Find a way to safely avoid copying byte[] copy = new byte[seq.Elements.Length]; Array.Copy(seq.Elements, 0, copy, 0, seq.Elements.Length); return copy; } public static MemoryStream MemoryStreamFromSequence(ibyteseq seq) { return new MemoryStream(ByteArrayFromSequence(seq)); } public static ibyteseq SequenceFromMemoryStream(MemoryStream bytes) { // TODO: Find a way to safely avoid copying return SequenceFromByteArray(bytes.ToArray()); } public static ibyteseq SequenceFromByteArray(byte[] bytearray) { return byteseq.FromArray(bytearray); } public static string StringFromDafnyString(icharseq dafnyString) { // TODO: Find a way to safely avoid copying. // The contents of a Dafny.Sequence should never change, but since a Dafny.ArraySequence // currently allows direct access to its array we can't assume that's true. return new string(dafnyString.Elements); } public static icharseq DafnyStringFromString(string s) { // This is safe since string#ToCharArray() creates a fresh array return charseq.FromArray(s.ToCharArray()); } public static ibyteseq DafnyUTF8BytesFromString(string s) { return byteseq.FromArray(Encoding.UTF8.GetBytes(s)); } public static T ExtractResult<T>(_IResult<T, icharseq> iResult) { Result<T, icharseq> result = (Result<T, icharseq>) iResult; if (result is Result_Success<T, icharseq> s) { return s.value; } else if (result is Result_Failure<T, icharseq> f) { // TODO-RS: Need to refine the wrapped value in a Failure so we // can throw specific exception types. throw new DafnyException(StringFromDafnyString(f.error)); } else { throw new ArgumentException(message: "Unrecognized STL.Result constructor"); } } public static _IOption<T> NullableToOption<T>(T t) { return t == null ? Option<T>.create_None() : Option<T>.create_Some(t); } public static _IResult<T, icharseq> CreateFailure<T>(string msg) where T : class { return Result<T, icharseq>.create_Failure(DafnyStringFromString(msg)); } public static _IOutcome<icharseq> CreateFail(string msg) { return Outcome<icharseq>.create_Fail(DafnyStringFromString(msg)); } } public class DafnyException : Exception { public DafnyException(string message) : base(message) { } }
90
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 AesWrappingAlg : ConstantClass { public static readonly AesWrappingAlg ALG_AES128_GCM_IV12_TAG16 = new AesWrappingAlg("ALG_AES128_GCM_IV12_TAG16"); public static readonly AesWrappingAlg ALG_AES192_GCM_IV12_TAG16 = new AesWrappingAlg("ALG_AES192_GCM_IV12_TAG16"); public static readonly AesWrappingAlg ALG_AES256_GCM_IV12_TAG16 = new AesWrappingAlg("ALG_AES256_GCM_IV12_TAG16"); public static readonly AesWrappingAlg[] Values = { ALG_AES128_GCM_IV12_TAG16, ALG_AES192_GCM_IV12_TAG16, ALG_AES256_GCM_IV12_TAG16 }; public AesWrappingAlg(string value) : base(value) { } } }
33
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 AlgorithmSuiteId : ConstantClass { public static readonly AlgorithmSuiteId ALG_AES_128_GCM_IV12_TAG16_NO_KDF = new AlgorithmSuiteId("0x0014"); public static readonly AlgorithmSuiteId ALG_AES_192_GCM_IV12_TAG16_NO_KDF = new AlgorithmSuiteId("0x0046"); public static readonly AlgorithmSuiteId ALG_AES_256_GCM_IV12_TAG16_NO_KDF = new AlgorithmSuiteId("0x0078"); public static readonly AlgorithmSuiteId ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256 = new AlgorithmSuiteId("0x0114"); public static readonly AlgorithmSuiteId ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256 = new AlgorithmSuiteId("0x0146"); public static readonly AlgorithmSuiteId ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256 = new AlgorithmSuiteId("0x0178"); public static readonly AlgorithmSuiteId ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 = new AlgorithmSuiteId("0x0214"); public static readonly AlgorithmSuiteId ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 = new AlgorithmSuiteId("0x0346"); public static readonly AlgorithmSuiteId ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 = new AlgorithmSuiteId("0x0378"); public static readonly AlgorithmSuiteId ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY = new AlgorithmSuiteId("0x0478"); public static readonly AlgorithmSuiteId ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 = new AlgorithmSuiteId("0x0578"); public static readonly AlgorithmSuiteId[] Values = { ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256, ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, ALG_AES_128_GCM_IV12_TAG16_NO_KDF, ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256, ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, ALG_AES_192_GCM_IV12_TAG16_NO_KDF, ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, ALG_AES_256_GCM_IV12_TAG16_NO_KDF }; public AlgorithmSuiteId(string value) : base(value) { } } }
55
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 AwsCryptographicMaterialProviders : AwsCryptographicMaterialProvidersBase { internal readonly Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProviders _impl; internal AwsCryptographicMaterialProviders(Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProviders impl) { this._impl = impl; } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkMultiKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateAwsKmsMrkMultiKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsMrkMultiKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateRawRsaKeyring( AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateRawRsaKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawRsaKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateRawRsaKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateRawAesKeyring( AWS.EncryptionSDK.Core.CreateRawAesKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateRawAesKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateRawAesKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateRawAesKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_CreateAwsKmsMrkKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsMrkKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkDiscoveryKeyringInput internalInput = TypeConversion .ToDafny_N3_aws__N13_encryptionSdk__N4_core__S36_CreateAwsKmsMrkDiscoveryKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsMrkDiscoveryKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IClientSupplier _CreateDefaultClientSupplier( AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateDefaultClientSupplierInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S32_CreateDefaultClientSupplierInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IClientSupplier, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateDefaultClientSupplier(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S23_ClientSupplierReference( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsDiscoveryKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S33_CreateAwsKmsDiscoveryKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsDiscoveryKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsDiscoveryMultiKeyringInput internalInput = TypeConversion .ToDafny_N3_aws__N13_encryptionSdk__N4_core__S38_CreateAwsKmsDiscoveryMultiKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsDiscoveryMultiKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.ICryptographicMaterialsManager _CreateDefaultCryptographicMaterialsManager( AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateDefaultCryptographicMaterialsManagerInput internalInput = TypeConversion .ToDafny_N3_aws__N13_encryptionSdk__N4_core__S47_CreateDefaultCryptographicMaterialsManagerInput( input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateDefaultCryptographicMaterialsManager(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion .FromDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateCryptographicMaterialsManagerOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S24_CreateAwsKmsKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateMultiKeyring( AWS.EncryptionSDK.Core.CreateMultiKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateMultiKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S23_CreateMultiKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateMultiKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMultiKeyringInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S29_CreateAwsKmsMultiKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsMultiKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput input) { Dafny.Aws.EncryptionSdk.Core._ICreateAwsKmsMrkDiscoveryMultiKeyringInput internalInput = TypeConversion .ToDafny_N3_aws__N13_encryptionSdk__N4_core__S41_CreateAwsKmsMrkDiscoveryMultiKeyringInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IKeyring, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.CreateAwsKmsMrkDiscoveryMultiKeyring(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S19_CreateKeyringOutput( result.dtor_value); } } }
224
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 AwsCryptographicMaterialProvidersBase : IAwsCryptographicMaterialProviders { public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput input) { input.Validate(); return _CreateAwsKmsKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput input) { input.Validate(); return _CreateAwsKmsDiscoveryKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput input) { input.Validate(); return _CreateAwsKmsMultiKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMultiKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput input) { input.Validate(); return _CreateAwsKmsDiscoveryMultiKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsDiscoveryMultiKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput input) { input.Validate(); return _CreateAwsKmsMrkKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput input) { input.Validate(); return _CreateAwsKmsMrkMultiKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkMultiKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput input) { input.Validate(); return _CreateAwsKmsMrkDiscoveryKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkDiscoveryKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateAwsKmsMrkDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput input) { input.Validate(); return _CreateAwsKmsMrkDiscoveryMultiKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateAwsKmsMrkDiscoveryMultiKeyring( AWS.EncryptionSDK.Core.CreateAwsKmsMrkDiscoveryMultiKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateMultiKeyring(AWS.EncryptionSDK.Core.CreateMultiKeyringInput input) { input.Validate(); return _CreateMultiKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateMultiKeyring( AWS.EncryptionSDK.Core.CreateMultiKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateRawAesKeyring( AWS.EncryptionSDK.Core.CreateRawAesKeyringInput input) { input.Validate(); return _CreateRawAesKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateRawAesKeyring( AWS.EncryptionSDK.Core.CreateRawAesKeyringInput input); public AWS.EncryptionSDK.Core.IKeyring CreateRawRsaKeyring( AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput input) { input.Validate(); return _CreateRawRsaKeyring(input); } protected abstract AWS.EncryptionSDK.Core.IKeyring _CreateRawRsaKeyring( AWS.EncryptionSDK.Core.CreateRawRsaKeyringInput input); public AWS.EncryptionSDK.Core.ICryptographicMaterialsManager CreateDefaultCryptographicMaterialsManager( AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput input) { input.Validate(); return _CreateDefaultCryptographicMaterialsManager(input); } protected abstract AWS.EncryptionSDK.Core.ICryptographicMaterialsManager _CreateDefaultCryptographicMaterialsManager( AWS.EncryptionSDK.Core.CreateDefaultCryptographicMaterialsManagerInput input); public AWS.EncryptionSDK.Core.IClientSupplier CreateDefaultClientSupplier( AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput input) { input.Validate(); return _CreateDefaultClientSupplier(input); } protected abstract AWS.EncryptionSDK.Core.IClientSupplier _CreateDefaultClientSupplier( AWS.EncryptionSDK.Core.CreateDefaultClientSupplierInput input); } }
143
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 AwsCryptographicMaterialProvidersBaseException : Exception { public AwsCryptographicMaterialProvidersBaseException() : base() { } public AwsCryptographicMaterialProvidersBaseException(string message) : base(message) { } } }
21
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 AwsCryptographicMaterialProvidersException : AwsCryptographicMaterialProvidersBaseException { public AwsCryptographicMaterialProvidersException(string message) : base(message) { } } }
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; using System.IO; using System.Collections.Generic; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public static class AwsCryptographicMaterialProvidersFactory { static readonly Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersFactory. AwsCryptographicMaterialProvidersFactory _impl = new Dafny.Aws.EncryptionSdk.Core.AwsCryptographicMaterialProvidersFactory. AwsCryptographicMaterialProvidersFactory(); public static AWS.EncryptionSDK.Core.IAwsCryptographicMaterialProviders CreateDefaultAwsCryptographicMaterialProviders() { Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProviders, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = _impl.CreateDefaultAwsCryptographicMaterialProviders(); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion .FromDafny_N3_aws__N13_encryptionSdk__N4_core__S42_AwsCryptographicMaterialProvidersReference( result.dtor_value); } } }
35
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 ClientSupplier : ClientSupplierBase { internal readonly Dafny.Aws.EncryptionSdk.Core.IClientSupplier _impl; internal ClientSupplier(Dafny.Aws.EncryptionSdk.Core.IClientSupplier impl) { this._impl = impl; } protected override Amazon.KeyManagementService.IAmazonKeyManagementService _GetClient( AWS.EncryptionSDK.Core.GetClientInput input) { Dafny.Aws.EncryptionSdk.Core._IGetClientInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S14_GetClientInput(input); Wrappers_Compile._IResult<Dafny.Com.Amazonaws.Kms.IKeyManagementServiceClient, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.GetClient(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S15_GetClientOutput(result.dtor_value); } } }
36
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 ClientSupplierBase : IClientSupplier { public Amazon.KeyManagementService.IAmazonKeyManagementService GetClient( AWS.EncryptionSDK.Core.GetClientInput input) { input.Validate(); return _GetClient(input); } protected abstract Amazon.KeyManagementService.IAmazonKeyManagementService _GetClient( AWS.EncryptionSDK.Core.GetClientInput input); } }
23
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 CommitmentPolicy : ConstantClass { public static readonly CommitmentPolicy FORBID_ENCRYPT_ALLOW_DECRYPT = new CommitmentPolicy("FORBID_ENCRYPT_ALLOW_DECRYPT"); public static readonly CommitmentPolicy REQUIRE_ENCRYPT_ALLOW_DECRYPT = new CommitmentPolicy("REQUIRE_ENCRYPT_ALLOW_DECRYPT"); public static readonly CommitmentPolicy REQUIRE_ENCRYPT_REQUIRE_DECRYPT = new CommitmentPolicy("REQUIRE_ENCRYPT_REQUIRE_DECRYPT"); public static readonly CommitmentPolicy[] Values = { FORBID_ENCRYPT_ALLOW_DECRYPT, REQUIRE_ENCRYPT_ALLOW_DECRYPT, REQUIRE_ENCRYPT_REQUIRE_DECRYPT }; public CommitmentPolicy(string value) : base(value) { } } }
33
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 CreateAwsKmsDiscoveryKeyringInput { private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient; private AWS.EncryptionSDK.Core.DiscoveryFilter _discoveryFilter; private System.Collections.Generic.List<string> _grantTokens; public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } internal bool IsSetKmsClient() { return this._kmsClient != null; } public AWS.EncryptionSDK.Core.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } internal bool IsSetDiscoveryFilter() { return this._discoveryFilter != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public void Validate() { if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); } } }
56
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 CreateAwsKmsDiscoveryMultiKeyringInput { private System.Collections.Generic.List<string> _regions; private AWS.EncryptionSDK.Core.DiscoveryFilter _discoveryFilter; private AWS.EncryptionSDK.Core.IClientSupplier _clientSupplier; private System.Collections.Generic.List<string> _grantTokens; public System.Collections.Generic.List<string> Regions { get { return this._regions; } set { this._regions = value; } } internal bool IsSetRegions() { return this._regions != null; } public AWS.EncryptionSDK.Core.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } internal bool IsSetDiscoveryFilter() { return this._discoveryFilter != null; } public AWS.EncryptionSDK.Core.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } internal bool IsSetClientSupplier() { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public void Validate() { if (!IsSetRegions()) throw new System.ArgumentException("Missing value for required property 'Regions'"); } } }
67
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 CreateAwsKmsKeyringInput { private string _kmsKeyId; private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient; private System.Collections.Generic.List<string> _grantTokens; public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } internal bool IsSetKmsClient() { return this._kmsClient != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public void Validate() { if (!IsSetKmsKeyId()) throw new System.ArgumentException("Missing value for required property 'KmsKeyId'"); if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); } } }
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; namespace AWS.EncryptionSDK.Core { public class CreateAwsKmsMrkDiscoveryKeyringInput { private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient; private AWS.EncryptionSDK.Core.DiscoveryFilter _discoveryFilter; private System.Collections.Generic.List<string> _grantTokens; private string _region; public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } internal bool IsSetKmsClient() { return this._kmsClient != null; } public AWS.EncryptionSDK.Core.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } internal bool IsSetDiscoveryFilter() { return this._discoveryFilter != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public string Region { get { return this._region; } set { this._region = value; } } internal bool IsSetRegion() { return this._region != null; } public void Validate() { if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); if (!IsSetRegion()) throw new System.ArgumentException("Missing value for required property 'Region'"); } } }
69
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 CreateAwsKmsMrkDiscoveryMultiKeyringInput { private System.Collections.Generic.List<string> _regions; private AWS.EncryptionSDK.Core.DiscoveryFilter _discoveryFilter; private AWS.EncryptionSDK.Core.IClientSupplier _clientSupplier; private System.Collections.Generic.List<string> _grantTokens; public System.Collections.Generic.List<string> Regions { get { return this._regions; } set { this._regions = value; } } internal bool IsSetRegions() { return this._regions != null; } public AWS.EncryptionSDK.Core.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } internal bool IsSetDiscoveryFilter() { return this._discoveryFilter != null; } public AWS.EncryptionSDK.Core.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } internal bool IsSetClientSupplier() { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public void Validate() { if (!IsSetRegions()) throw new System.ArgumentException("Missing value for required property 'Regions'"); } } }
67
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 CreateAwsKmsMrkKeyringInput { private string _kmsKeyId; private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient; private System.Collections.Generic.List<string> _grantTokens; public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } internal bool IsSetKmsClient() { return this._kmsClient != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public void Validate() { if (!IsSetKmsKeyId()) throw new System.ArgumentException("Missing value for required property 'KmsKeyId'"); if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); } } }
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; namespace AWS.EncryptionSDK.Core { public class CreateAwsKmsMrkMultiKeyringInput { private string _generator; private System.Collections.Generic.List<string> _kmsKeyIds; private AWS.EncryptionSDK.Core.IClientSupplier _clientSupplier; private System.Collections.Generic.List<string> _grantTokens; public string Generator { get { return this._generator; } set { this._generator = value; } } internal bool IsSetGenerator() { return this._generator != null; } public System.Collections.Generic.List<string> KmsKeyIds { get { return this._kmsKeyIds; } set { this._kmsKeyIds = value; } } internal bool IsSetKmsKeyIds() { return this._kmsKeyIds != null; } public AWS.EncryptionSDK.Core.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } internal bool IsSetClientSupplier() { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public void Validate() { } } }
66
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 CreateAwsKmsMultiKeyringInput { private string _generator; private System.Collections.Generic.List<string> _kmsKeyIds; private AWS.EncryptionSDK.Core.IClientSupplier _clientSupplier; private System.Collections.Generic.List<string> _grantTokens; public string Generator { get { return this._generator; } set { this._generator = value; } } internal bool IsSetGenerator() { return this._generator != null; } public System.Collections.Generic.List<string> KmsKeyIds { get { return this._kmsKeyIds; } set { this._kmsKeyIds = value; } } internal bool IsSetKmsKeyIds() { return this._kmsKeyIds != null; } public AWS.EncryptionSDK.Core.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } internal bool IsSetClientSupplier() { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } internal bool IsSetGrantTokens() { return this._grantTokens != null; } public void Validate() { } } }
66
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 CreateDefaultClientSupplierInput { public void Validate() { } } }
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; using AWS.EncryptionSDK.Core; namespace AWS.EncryptionSDK.Core { public class CreateDefaultCryptographicMaterialsManagerInput { private AWS.EncryptionSDK.Core.IKeyring _keyring; 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 (!IsSetKeyring()) throw new System.ArgumentException("Missing value for required property 'Keyring'"); } } }
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 CreateMultiKeyringInput { private AWS.EncryptionSDK.Core.IKeyring _generator; private System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring> _childKeyrings; public AWS.EncryptionSDK.Core.IKeyring Generator { get { return this._generator; } set { this._generator = value; } } internal bool IsSetGenerator() { return this._generator != null; } public System.Collections.Generic.List<AWS.EncryptionSDK.Core.IKeyring> ChildKeyrings { get { return this._childKeyrings; } set { this._childKeyrings = value; } } internal bool IsSetChildKeyrings() { return this._childKeyrings != null; } public void Validate() { if (!IsSetChildKeyrings()) throw new System.ArgumentException("Missing value for required property 'ChildKeyrings'"); } } }
44
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 CreateRawAesKeyringInput { private string _keyNamespace; private string _keyName; private System.IO.MemoryStream _wrappingKey; private AWS.EncryptionSDK.Core.AesWrappingAlg _wrappingAlg; public string KeyNamespace { get { return this._keyNamespace; } set { this._keyNamespace = value; } } internal bool IsSetKeyNamespace() { return this._keyNamespace != null; } public string KeyName { get { return this._keyName; } set { this._keyName = value; } } internal bool IsSetKeyName() { return this._keyName != null; } public System.IO.MemoryStream WrappingKey { get { return this._wrappingKey; } set { this._wrappingKey = value; } } internal bool IsSetWrappingKey() { return this._wrappingKey != null; } public AWS.EncryptionSDK.Core.AesWrappingAlg WrappingAlg { get { return this._wrappingAlg; } set { this._wrappingAlg = value; } } internal bool IsSetWrappingAlg() { return this._wrappingAlg != null; } public void Validate() { if (!IsSetKeyNamespace()) throw new System.ArgumentException("Missing value for required property 'KeyNamespace'"); if (!IsSetKeyName()) throw new System.ArgumentException("Missing value for required property 'KeyName'"); if (!IsSetWrappingKey()) throw new System.ArgumentException("Missing value for required property 'WrappingKey'"); if (!IsSetWrappingAlg()) throw new System.ArgumentException("Missing value for required property 'WrappingAlg'"); } } }
73
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 CreateRawRsaKeyringInput { private string _keyNamespace; private string _keyName; private AWS.EncryptionSDK.Core.PaddingScheme _paddingScheme; private System.IO.MemoryStream _publicKey; private System.IO.MemoryStream _privateKey; public string KeyNamespace { get { return this._keyNamespace; } set { this._keyNamespace = value; } } internal bool IsSetKeyNamespace() { return this._keyNamespace != null; } public string KeyName { get { return this._keyName; } set { this._keyName = value; } } internal bool IsSetKeyName() { return this._keyName != null; } public AWS.EncryptionSDK.Core.PaddingScheme PaddingScheme { get { return this._paddingScheme; } set { this._paddingScheme = value; } } internal bool IsSetPaddingScheme() { return this._paddingScheme != null; } public System.IO.MemoryStream PublicKey { get { return this._publicKey; } set { this._publicKey = value; } } internal bool IsSetPublicKey() { return this._publicKey != null; } public System.IO.MemoryStream PrivateKey { get { return this._privateKey; } set { this._privateKey = value; } } internal bool IsSetPrivateKey() { return this._privateKey != null; } public void Validate() { if (!IsSetKeyNamespace()) throw new System.ArgumentException("Missing value for required property 'KeyNamespace'"); if (!IsSetKeyName()) throw new System.ArgumentException("Missing value for required property 'KeyName'"); if (!IsSetPaddingScheme()) throw new System.ArgumentException("Missing value for required property 'PaddingScheme'"); } } }
83
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 CryptographicMaterialsManager : CryptographicMaterialsManagerBase { internal readonly Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager _impl; internal CryptographicMaterialsManager(Dafny.Aws.EncryptionSdk.Core.ICryptographicMaterialsManager impl) { this._impl = impl; } protected override AWS.EncryptionSDK.Core.DecryptMaterialsOutput _DecryptMaterials( AWS.EncryptionSDK.Core.DecryptMaterialsInput input) { Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S21_DecryptMaterialsInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IDecryptMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.DecryptMaterials(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S22_DecryptMaterialsOutput( result.dtor_value); } protected override AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput _GetEncryptionMaterials( AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput input) { Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsInput internalInput = TypeConversion.ToDafny_N3_aws__N13_encryptionSdk__N4_core__S27_GetEncryptionMaterialsInput(input); Wrappers_Compile._IResult<Dafny.Aws.EncryptionSdk.Core._IGetEncryptionMaterialsOutput, Dafny.Aws.EncryptionSdk.Core.IAwsCryptographicMaterialProvidersException> result = this._impl.GetEncryptionMaterials(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError_AwsCryptographicMaterialProvidersBaseException( result.dtor_error); return TypeConversion.FromDafny_N3_aws__N13_encryptionSdk__N4_core__S28_GetEncryptionMaterialsOutput( result.dtor_value); } } }
52
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 CryptographicMaterialsManagerBase : ICryptographicMaterialsManager { public AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput GetEncryptionMaterials( AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput input) { input.Validate(); return _GetEncryptionMaterials(input); } protected abstract AWS.EncryptionSDK.Core.GetEncryptionMaterialsOutput _GetEncryptionMaterials( AWS.EncryptionSDK.Core.GetEncryptionMaterialsInput input); public AWS.EncryptionSDK.Core.DecryptMaterialsOutput DecryptMaterials( AWS.EncryptionSDK.Core.DecryptMaterialsInput input) { input.Validate(); return _DecryptMaterials(input); } protected abstract AWS.EncryptionSDK.Core.DecryptMaterialsOutput _DecryptMaterials( AWS.EncryptionSDK.Core.DecryptMaterialsInput input); } }
33
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 DecryptionMaterials { private AWS.EncryptionSDK.Core.AlgorithmSuiteId _algorithmSuiteId; private System.Collections.Generic.Dictionary<string, string> _encryptionContext; private System.IO.MemoryStream _plaintextDataKey; private System.IO.MemoryStream _verificationKey; 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.IO.MemoryStream PlaintextDataKey { get { return this._plaintextDataKey; } set { this._plaintextDataKey = value; } } internal bool IsSetPlaintextDataKey() { return this._plaintextDataKey != null; } public System.IO.MemoryStream VerificationKey { get { return this._verificationKey; } set { this._verificationKey = value; } } internal bool IsSetVerificationKey() { return this._verificationKey != 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'"); } } }
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 DecryptMaterialsInput { private AWS.EncryptionSDK.Core.AlgorithmSuiteId _algorithmSuiteId; private AWS.EncryptionSDK.Core.CommitmentPolicy _commitmentPolicy; private System.Collections.Generic.List<AWS.EncryptionSDK.Core.EncryptedDataKey> _encryptedDataKeys; private System.Collections.Generic.Dictionary<string, string> _encryptionContext; public AWS.EncryptionSDK.Core.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } internal bool IsSetAlgorithmSuiteId() { return this._algorithmSuiteId != null; } public AWS.EncryptionSDK.Core.CommitmentPolicy CommitmentPolicy { get { return this._commitmentPolicy; } set { this._commitmentPolicy = value; } } internal bool IsSetCommitmentPolicy() { return this._commitmentPolicy != 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.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } internal bool IsSetEncryptionContext() { return this._encryptionContext != null; } public void Validate() { if (!IsSetAlgorithmSuiteId()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuiteId'"); if (!IsSetCommitmentPolicy()) throw new System.ArgumentException("Missing value for required property 'CommitmentPolicy'"); if (!IsSetEncryptedDataKeys()) throw new System.ArgumentException("Missing value for required property 'EncryptedDataKeys'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); } } }
74