/******************************************************************************* * Copyright 2012-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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.SecretsManager; using Amazon.SecretsManager.Model; namespace Amazon.PowerShell.Cmdlets.SEC { /// /// Creates a new version with a new encrypted secret value and attaches it to the secret. /// The version can contain a new SecretString value or a new SecretBinary /// value. /// /// /// /// We recommend you avoid calling PutSecretValue at a sustained rate of /// more than once every 10 minutes. When you update the secret value, Secrets Manager /// creates a new version of the secret. Secrets Manager removes outdated versions when /// there are more than 100, but it does not remove versions created less than 24 hours /// ago. If you call PutSecretValue more than once every 10 minutes, you /// create more versions than Secrets Manager removes, and you will reach the quota for /// secret versions. /// /// You can specify the staging labels to attach to the new version in VersionStages. /// If you don't include VersionStages, then Secrets Manager automatically /// moves the staging label AWSCURRENT to this version. If this operation /// creates the first version for the secret, then Secrets Manager automatically attaches /// the staging label AWSCURRENT to it. If this operation moves the staging /// label AWSCURRENT from another version to this version, then Secrets Manager /// also automatically moves the staging label AWSPREVIOUS to the version /// that AWSCURRENT was removed from. /// /// This operation is idempotent. If you call this operation with a ClientRequestToken /// that matches an existing version's VersionId, and you specify the same secret data, /// the operation succeeds but does nothing. However, if the secret data is different, /// then the operation fails because you can't modify an existing version; you can only /// create new ones. /// /// Secrets Manager generates a CloudTrail log entry when you call this action. Do not /// include sensitive information in request parameters except SecretBinary /// or SecretString because it might be logged. For more information, see /// Logging /// Secrets Manager events with CloudTrail. /// Required permissions: secretsmanager:PutSecretValue. For more /// information, see /// IAM policy actions for Secrets Manager and Authentication /// and access control in Secrets Manager. /// /// [Cmdlet("Write", "SECSecretValue", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("Amazon.SecretsManager.Model.PutSecretValueResponse")] [AWSCmdlet("Calls the AWS Secrets Manager PutSecretValue API operation.", Operation = new[] {"PutSecretValue"}, SelectReturnType = typeof(Amazon.SecretsManager.Model.PutSecretValueResponse))] [AWSCmdletOutput("Amazon.SecretsManager.Model.PutSecretValueResponse", "This cmdlet returns an Amazon.SecretsManager.Model.PutSecretValueResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class WriteSECSecretValueCmdlet : AmazonSecretsManagerClientCmdlet, IExecutor { protected override bool IsSensitiveRequest { get; set; } = true; #region Parameter ClientRequestToken /// /// /// A unique identifier for the new version of the secret. If you use the Amazon Web Services CLI or one of the Amazon Web Services SDKs to call /// this operation, then you can leave this parameter empty because they generate a random /// UUID for you. If you don't use the SDK and instead generate a raw HTTP request to /// the Secrets Manager service endpoint, then you must generate a ClientRequestToken /// yourself for new versions and include that value in the request. This value helps ensure idempotency. Secrets Manager uses this value to prevent the /// accidental creation of duplicate versions if there are failures and retries during /// the Lambda rotation function processing. We recommend that you generate a UUID-type /// value to ensure uniqueness within the specified secret. This value becomes the VersionId of the new version. /// /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ClientRequestToken { get; set; } #endregion #region Parameter SecretBinary /// /// /// The binary data to encrypt and store in the new version of the secret. To use this /// parameter in the command-line tools, we recommend that you store your binary data /// in a file and then pass the contents of the file as a parameter. You must include SecretBinary or SecretString, but not both.You can't access this value from the Secrets Manager console. /// /// The cmdlet will automatically convert the supplied parameter of type string, string[], System.IO.FileInfo or System.IO.Stream to byte[] before supplying it to the service. /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Amazon.PowerShell.Common.MemoryStreamParameterConverter] public byte[] SecretBinary { get; set; } #endregion #region Parameter SecretId /// /// /// The ARN or name of the secret to add a new version to.For an ARN, we recommend that you specify a complete ARN rather than a partial ARN. /// See Finding /// a secret from a partial ARN.If the secret doesn't already exist, use CreateSecret instead. /// /// #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String SecretId { get; set; } #endregion #region Parameter SecretString /// /// /// The text to encrypt and store in the new version of the secret. You must include SecretBinary or SecretString, but not both.We recommend you create the secret string as JSON key/value pairs, as shown in the /// example. /// /// [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] public System.String SecretString { get; set; } #endregion #region Parameter VersionStage /// /// /// A list of staging labels to attach to this version of the secret. Secrets Manager /// uses staging labels to track versions of a secret through the rotation process.If you specify a staging label that's already associated with a different version /// of the same secret, then Secrets Manager removes the label from the other version /// and attaches it to this version. If you specify AWSCURRENT, and it is /// already attached to another version, then Secrets Manager also moves the staging label /// AWSPREVIOUS to the version that AWSCURRENT was removed from.If you don't include VersionStages, then Secrets Manager automatically /// moves the staging label AWSCURRENT to this version. /// /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("VersionStages")] public System.String[] VersionStage { get; set; } #endregion #region Parameter Select /// /// Use the -Select parameter to control the cmdlet output. The default value is '*'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.SecretsManager.Model.PutSecretValueResponse). /// Specifying the name of a property of type Amazon.SecretsManager.Model.PutSecretValueResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// /// Changes the cmdlet behavior to return the value passed to the SecretString parameter. /// The -PassThru parameter is deprecated, use -Select '^SecretString' instead. This parameter will be removed in a future version. /// [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^SecretString' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { this._AWSSignerType = "v4"; base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.SecretId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Write-SECSecretValue (PutSecretValue)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.SecretString; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ClientRequestToken = this.ClientRequestToken; context.SecretBinary = this.SecretBinary; context.SecretId = this.SecretId; #if MODULAR if (this.SecretId == null && ParameterWasBound(nameof(this.SecretId))) { WriteWarning("You are passing $null as a value for parameter SecretId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.SecretString = this.SecretString; if (this.VersionStage != null) { context.VersionStage = new List(this.VersionStage); } // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { System.IO.MemoryStream _SecretBinaryStream = null; try { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.SecretsManager.Model.PutSecretValueRequest(); if (cmdletContext.ClientRequestToken != null) { request.ClientRequestToken = cmdletContext.ClientRequestToken; } if (cmdletContext.SecretBinary != null) { _SecretBinaryStream = new System.IO.MemoryStream(cmdletContext.SecretBinary); request.SecretBinary = _SecretBinaryStream; } if (cmdletContext.SecretId != null) { request.SecretId = cmdletContext.SecretId; } if (cmdletContext.SecretString != null) { request.SecretString = cmdletContext.SecretString; } if (cmdletContext.VersionStage != null) { request.VersionStages = cmdletContext.VersionStage; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } finally { if( _SecretBinaryStream != null) { _SecretBinaryStream.Dispose(); } } } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.SecretsManager.Model.PutSecretValueResponse CallAWSServiceOperation(IAmazonSecretsManager client, Amazon.SecretsManager.Model.PutSecretValueRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Secrets Manager", "PutSecretValue"); try { #if DESKTOP return client.PutSecretValue(request); #elif CORECLR return client.PutSecretValueAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String ClientRequestToken { get; set; } public byte[] SecretBinary { get; set; } public System.String SecretId { get; set; } public System.String SecretString { get; set; } public List VersionStage { get; set; } public System.Func Select { get; set; } = (response, cmdlet) => response; } } }