Selling Partner API BlogVideos
SP-API DocsDeveloper ConsoleSupport
SP-API DocsDeveloper ConsoleSupport

Rotate your SP-API credentials using AWS

This blog post explains how to rotate your SP-API credentials programmatically with AWS.

by Lei W., Solutions Architect, Selling Partner Developer Services and Aonan G., Solutions Architect, Amazon Web Services, Inc. | May 17, 2023

This blog post provides an Amazon Web Services (AWS) cloud architecture for rotating your SP-API credentials. The following sections provide further details on components of this architecture. For help with getting started with AWS services, refer to Getting Started with AWS.

Introduction

To reduce the risk of exposed and compromised credentials, starting February 6th, 2023 Selling Partner Developer Services requires all developers to rotate their Login With Amazon (LWA) credentials every 180 days. If SP-API LWA credentials are not updated before the expiration target date, the API integration will lose access to SP-API. All Amazon SP-API developers are required to follow secure coding standards to follow Personal Identifiable Information (PII) requirements from the Data Protection Policy (DPP). Credentials include, but are not limited to, the encryption key, secret access key, password, and other sensitive credentials that are not supposed to be hard-coded.

Based on these requirements, Amazon is introducing a secure way to utilize an AWS technical stack, including the AWS Systems Manager Parameter Store, AWS Key Management Service (AWS KMS), Amazon EventBridge, and Amazon Simple Notification Service (Amazon SNS) to securely store credentials and get notified to rotate them in a timely manner. While this solution is tailored for AWS customers, other cloud provider customers, or developers with an on-premise environment, can also leverage equivalent services to achieve the same goal.

Architecture Overview

This architecture includes the following components and services to help developers separate their credentials and code, and provide notification services that send rotation reminders through SMS and email to the IT Admin Team:

  • AWS Lambda function along with the access token exchanger code samples representing the Developer Services calling an SP-API and LWA endpoint.
  • AWS KMS symmetric key for encrypting and decrypting the LWA credentials.
  • AWS Systems Manager Parameter Store for vaulting the LWA SecureString.
  • Amazon EventBridge for capturing scheduling and routing the LWA credential rotation notifications.
  • Amazon SNS for sending notifications to the SMS and email destination from the IT Admin Team as a rotation reminder.

Function architecture

This blog provides comprehensive guidance for the architecture workflow:

1. Use the Systems Manager Parameter Store to store your SP-API LWA credentials with AWS KMS encryption

2. Create a Lambda function using the SecureString to Call the API

3. Create an Amazon SNS Topic with an Email and SMS Subscription

4. Add EventBridge Rules to Route Message to Amazon SNS

5. Rotate LWA credentials in Systems Manager

Use the Systems Manager Parameter Store to store your SP-API LWA credentials with AWS KMS encryption

The AWS Systems Manager Parameter Store provides a secure way to store the encrypted parameters by separating the data from the code. The EC2, ECS container, and Lambda function with the Systems Manager Parameter Store specific role are able to access the secure string without exposing the credentials to any single individual.

In this LWA Client Secret example, you use the Systems Manager Parameter Store with the PutParameter to create a SecureString. The SecureString uses the AWS KMS default AES-256-GCM Symmetric algorithm to encrypt the credentials. You can create the parameter store for the client secret with the request body below. You can then use this technique to place parameters respectively with a client id and RefreshToken in the Parameter Store, though these two credentials do not need to be rotated. This will help separate the credentials from the code and meet the Secure Coding Practices requirement in the DPP.

{
  "Name": "/my-erp/lwa/clientsecret",
  "Description": "SecureString with LWA ClientSecret",
  "Value": "171yourclientsecrietf722d",
  "Type": "SecureString",
  "KeyId": "my-key-id-my-key-id",
  "Overwrite": "True",
  "Policies": [
    {
      "Type": "NoChangeNotification",
      "Version": "1.0",
      "Attributes": {
        "After": "150",
        "Unit": "Days"
      }
    }
  ]
}

Create a Lambda function using the SecureString to Call the API

Next, you will create a Lambda function to make an API call to the AWS Systems Manager services, and get the plain text of the SP-API LWA Client ID and Client Secret. To grant the required permissions for AWS KMS and Systems Manager, use the IAM Policy below for the Lambda Role.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ssm:GetParameters"
      ],
      "Resource": [
        "arn:aws:ssm:us-east-2:12DigitAWSID:parameter/my-erp*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "kms:Decrypt"
      ],
      "Resource": [
        "arn:aws:kms:us-east-2:12DigitAWSID:key/5adcc01c-762c-4906-92fa-b679b4d68890"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "logs:CreateLogGroup",
      "Resource": "arn:aws:logs:us-east-2:12DigitAWSID:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": [
        "arn:aws:logs:us-east-2:12DigitAWSID:log-group:/aws/lambda/my-lwa:*"
      ]
    }
  ]
}

In the example below, the Lambda function is used to represent the backend service component which renders the true plain text of the LWA credentials in the code and makes the API call with the LWA services and SP-API endpoint. Using this method, combining the Systems Manager and AWS KMS, you are able to separate the code and the code config in different places, and then render the real config value into the code in the runtime of the Lambda function.

def get_parameters():
    response = ssm.get_parameters(
        Names=['/my-erp/lwa/cliensecret', "/my-erp/lwa/clientidentifier", "/my-erp/refreshToken"], WithDecryption=True
    )

    payload = {'grant_type': 'refresh_token',
               'client_secret': response['Parameters'][0]["Value"],
               'client_id': response['Parameters'][1]["Value"],
               'refresh_token': response['Parameters'][2]["Value"]}
    lwa = requests.post("https://api.amazon.com/auth/o2/token", data=payload)

    return lwa.text


def lambda_handler(event, context):
    value = get_parameters()
    print("lwa value =  " + value)
    return value  # Echo back the first key value
    

The Lambda function code can also be downloaded through the Github repo. Run the following command in the project folders to create a Lambda function .zip file, and upload the zip file to the Lambda function to deploy it.

cd lambda-lwa 
pip3 install -r requirements.txt -t .
zip -r lwa-lambda-exchanger.zip .

Create an Amazon SNS Topic with an Email and SMS Subscription

You can use the Amazon SNS topic to alert an IT admin team regarding the LWA credential rotation, and use the Amazon SNS subscription destinations through Email and SMS to receive these notifications. The below CLI command can create both the Amazon SNS topic and its corresponding subscriptions.

aws sns create-topic --name lwa-credential-rotation 
aws sns subscribe --topic-arn arn:aws:sns:us-east-2:12DigitAWSID:lwa-credential-rotation --protocol email --notification-endpoint [email protected] 
aws sns subscribe --topic-arn arn:aws:sns:us-east-2:12DigitAWSID:lwa-credential-rotation --protocol sms --notification-endpoint +1XXX5550100

Add EventBridge Rules to Route Message to Amazon SNS

To route the rotation reminder to the Amazon SNS topic created in the above step, you can add an EventBridge rule that triggers the Amazon SNS notification on your specified schedule. Use the following CloudFormation YAML template to create the EventBridge rule:

AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template for EventBridge rule 'ssm-parameter-store'
Resources:
  EventRule0:
    Type: AWS::Events::Rule
    Properties:
      EventBusName: default
      EventPattern:
        source:
          - aws.ssm
        detail-type:
          - Parameter Store Policy Action
        detail:
          parameter-name:
            - "/my-erp/lwa/clientsecret"
      Name: My-ERP-Rotate
      State: ENABLED
      Targets:
        - Id: my-sns-target-to-multi-email-and-sms
          Arn: >-
            arn:aws:sns:us-east-2:12DigitAWSID:lwa-credential-rotation
           

Rotate LWA credentials in Systems Manager

After creating the above components, for each rotation due, the Systems Manager Parameter Store will send a rotation event that EventBridge will route to your Amazon SNS email and SMS subscription. To securely update the credentials, you can log into Seller Central with the developer account, navigate to the Developer Console page, and generate new SP-API LWA credentials.

Rotate LWA credentials

The existing credentials will expire after the new credentials are generated after 7 days. While the central parameter store is being used to store the LWA credentials, you can update the SecureString in the Systems Manager Parameter Store with the newly generated credentials. This will automatically be effective every time the code is triggered.

Conclusion

As time passes, the likelihood of a key being compromised increases, which can leave your systems vulnerable to cyber threats. Frequent rotation of credentials and keys limits the impact of any unauthorized access and ensures that systems are up-to-date with the latest security measures. The additional encryption process adds an extra layer of protection, ensuring that only authorized components can access the sensitive information.

This blog introduced a secure way to store SP-API LWA credentials using AWS KMS and Systems Manager Parameter Store, while also separating code and configuration, and automating the credential rotation process using EventBridge and Amazon SNS. The full solution codes can be found in this GitHub Repo. By implementing these security measures, your SP-API applications can maintain a high level of security to safeguard against potential threats.

👍

Have feedback on this post?

If you have questions or feedback on this post, we'd like to hear from you! Please vote and leave a comment using the tools at the bottom of this page.

Subscribe to updates via RSS feed.