<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[NordHero - Medium]]></title>
        <description><![CDATA[Making customers superheroes on AWS, Azure &amp; Google Cloud - Medium]]></description>
        <link>https://medium.com/nordhero?source=rss----7e48f9ef5db8---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>NordHero - Medium</title>
            <link>https://medium.com/nordhero?source=rss----7e48f9ef5db8---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:20:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/nordhero" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Speeding Up Data on AWS: From Ingestion to Insights]]></title>
            <link>https://medium.com/nordhero/speeding-up-data-on-aws-from-ingestion-to-insights-bd949875a074?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/bd949875a074</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws-quicksight]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Pekka Malmirae]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 04:22:21 GMT</pubDate>
            <atom:updated>2024-08-06T04:22:20.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ec3Lph1ZaVwdH6AFKYcq5w.jpeg" /><figcaption>Speeding Up Data on AWS: From Ingestion to Insights</figcaption></figure><p><em>In a production-scale cloud environment, data is scattered across various storage formats and locations, such as RDS databases, DynamoDB tables, time series databases, S3 files, and external systems. While Amazon QuickSight can directly connect to many data sources, it is often not preferred due to design principles, costs, performance, and user experience. Instead, the best practice is to build a centralized data lake with tools to consolidate and transform data for business intelligence tools. But how can you optimize the data pipeline from ingestion to insights to ensure processed data is ready for analysis as quickly as possible?</em></p><p>In this article, we use real-world open data sets on Helsinki region public traffic, imported as DynamoDB tables. We showcase, how we can transform data from the source to a Data Lake in S3, combine the Data Sets in QuickSight to create interesting and actionable insights, and eventually, how we can speed up the Data Pipeline to ensure the insights are always as up-to-date as possible.</p><h3>Anatomy of a typical Serverless Data Pipeline on AWS</h3><p>NordHero has implemented data pipelines for various customers on AWS utilizing our <a href="https://www.nordhero.com/offerings/data-to-insights">Data to Insights Jump Start offering</a>. The solution uses</p><ul><li><strong>AWS Glue Jobs</strong> to extract data from their sources, transform the data to be efficiently utilized with BI tools, and load the data in Parquet or ORC format to a data lake based on <strong>Amazon S3</strong></li><li><strong>AWS Glue Crawlers</strong> to determine the data lake schemas and to store the schemas in <strong>AWS Glue Data Catalog</strong></li><li><strong>Amazon Athena</strong> to provide a scalable and super-fast SQL interface to the data stored in the S3 data lake</li><li><strong>AWS QuickSight</strong> to analyze the data, build actionable insights on the data, and deliver the insights to business users</li></ul><figure><img alt="An example of Serverless Data Pipeline on AWS" src="https://cdn-images-1.medium.com/max/1024/0*LyC3GPgVWaLxHL_Z.jpg" /><figcaption>An example of Serverless Data Pipeline on AWS</figcaption></figure><p>AWS Glue is an AWS-managed service, meaning that AWS manages the needed compute instances, their software, and the scaling of the resources. You only pay for your data’s processing time. You can create and run several AWS Glue jobs to extract, transform, and load (ETL) data from various data sources into the data lake and build different curated datasets in the data lake for various data consumption needs.</p><p>Amazon S3 is an ideal service to be used as the storage foundation for a data lake, providing several benefits:</p><ul><li><strong>Scalability and Elasticity:</strong> Amazon S3 can scale massively to store virtually unlimited amounts of data, without the need for provisioning or managing storage infrastructure.</li><li><strong>Data Lake Architecture:</strong> S3 enables a decoupled storage and compute architecture, allowing you to store data in its raw form and use various analytics services and tools to process and analyze the data without being tied to a specific compute engine. S3 integrates seamlessly with various AWS analytics services like Amazon Athena, AWS Glue, Amazon EMR, Amazon QuickSight, and AWS Lake Formation, enabling you to build end-to-end data processing and analytics pipelines.</li><li><strong>Cost-Effective:</strong> Amazon S3 offers a cost-effective storage solution, with pricing based on the amount of data stored and accessed. You can also leverage different storage classes (e.g., S3 Glacier) for cost optimization based on data access patterns.</li><li><strong>Data Durability and Availability:</strong> Amazon S3 is designed for 99.999999999% durability and 99.99% availability, ensuring your data is safe and accessible when needed.</li><li><strong>Data Lake Security and Compliance:</strong> Amazon S3 provides robust security features, including access control, encryption at rest and in transit, and integration with AWS Identity and Access Management (IAM) for granular permissions management.</li><li><strong>Data Sharing and Collaboration:</strong> With Amazon S3, you can easily share data across teams, projects, or even with external parties, enabling collaboration and data monetization opportunities.</li><li><strong>Centralized Data Repository:</strong> A data lake on Amazon S3 serves as a centralized repository for all your structured, semi-structured, and unstructured data, breaking down data silos and enabling data democratization within your organization.</li></ul><p>Here’s an example AWS Glue Job script, written in Python, that extracts passenger data from a DynamoDB table named <em>hsl-passengers</em>, transforms the column names from uppercase to lowercase, casts <em>passenger_count</em> field from <em>String</em> to <em>Integer</em> type, and lastly writes the transformed data in an S3 bucket in <em>Parquet</em> format.</p><pre>import sys<br>from datetime import datetime, date, timedelta<br><br>from awsglue.transforms import *<br>from awsglue.utils import getResolvedOptions<br>from pyspark.context import SparkContext<br>from awsglue.context import GlueContext<br>from awsglue.job import Job<br>from pyspark.sql.dataframe import DataFrame<br>from pyspark.sql.types import IntegerType<br>from pyspark.sql.functions import col<br><br><br>SPARK_CONTEXT = SparkContext.getOrCreate()<br>GLUE_CONTEXT = GlueContext(SPARK_CONTEXT)<br>spark = GLUE_CONTEXT.spark_session<br>logger = GLUE_CONTEXT.get_logger()<br><br><br>def read_dynamo_db(tablename: str):<br>    &quot;&quot;&quot;Reads DynamoDB table into a DynamicFrame&quot;&quot;&quot;<br><br>    dyf = GLUE_CONTEXT.create_dynamic_frame.from_options(<br>        connection_type=&quot;dynamodb&quot;,<br>        connection_options={<br>            &quot;dynamodb.input.tableName&quot;: f&quot;{tablename}&quot;,<br>            &quot;dynamodb.throughput.read.percent&quot;: &quot;0.5&quot;,<br>            &quot;dynamodb.splits&quot;: &quot;1&quot;,<br>        },<br>    )<br>    return dyf<br><br><br>def write_log(message: str):<br>    &quot;&quot;&quot;Writes log to multiple outputs&quot;&quot;&quot;<br>    logger.warn(message)<br>    print(message)<br><br><br>def write_to_s3(s3_output_base_path: str, name: str, df: DataFrame):<br>    &quot;&quot;&quot;Writes data to specific folder in S3&quot;&quot;&quot;<br><br>    path = f&quot;{s3_output_base_path}/{name}&quot;<br>    if not (&quot;processed&quot; in path):<br>        raise Exception(<br>            &quot;Output folder must contain path element &#39;processed&#39; to be valid&quot;<br>        )<br>    write_log(f&quot;Writing output to {path}&quot;)<br>    df.write.mode(&quot;overwrite&quot;).format(&quot;parquet&quot;).partitionBy(&quot;object_id&quot;).save(path)<br><br><br>def main():<br><br>    # @params: [JOB_NAME]<br>    args = getResolvedOptions(<br>        sys.argv,<br>        [&quot;JOB_NAME&quot;, &quot;s3_output_path&quot;],<br>    )<br><br>    job = Job(GLUE_CONTEXT)<br>    job.init(args[&quot;JOB_NAME&quot;], args)<br><br>    # Let&#39;s only overwrite partitions that have changed, even though we store all data<br>    spark.conf.set(&quot;spark.sql.sources.partitionOverwriteMode&quot;, &quot;dynamic&quot;)<br><br>    s3_output_path = args[&quot;s3_output_path&quot;]<br><br>    write_log(f&quot;Parameter &#39;s3_output_path&#39;: {s3_output_path}&quot;)<br><br>    # Reading data from DynamoDb<br>    passengers_raw = read_dynamo_db(&quot;hsl-passengers&quot;).toDF()<br><br>    passengers = (<br>        passengers_raw.withColumnRenamed(&quot;OBJECTID&quot;, &quot;object_id&quot;)<br>        .withColumnRenamed(&quot;SHORTID&quot;, &quot;short_id&quot;)<br>        .withColumnRenamed(&quot;STOPNAME&quot;, &quot;stop_name&quot;)<br>        .withColumn(&quot;passenger_count&quot;, col(&quot;PASSENGERCOUNT&quot;).cast(IntegerType()))<br>        .drop(&quot;PASSENGERCOUNT&quot;)<br>    )<br><br>    write_to_s3(s3_output_path, &quot;passengers-data&quot;, passengers)<br><br>    job.commit()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>When you trigger the AWS Glue Job, AWS Glue fires up the needed Apache Spark compute instances, manages the parallel job execution between cluster nodes, and ramps down the compute services after the job execution has finished.</p><h3>Optimizing the data delivery to the data lake with AWS Glue</h3><p>You need to consider several things when optimizing the ETL process with AWS Glue, but eventually, it comes down to two criteria. The primary criterion is <strong>Time</strong>. The data lake is never 100% up-to-date with the source data. So the key question is, how often should the data be updated? The secondary criterion is always <strong>Money</strong>. After setting the Time criterion, how can the costs of the ETL process be optimized?</p><p>To beat the criteria, you need to plan your data pipeline well. Here are a few spices to compete against the clock:</p><ol><li><strong>Scale cluster capacity:</strong> Adjust the number of Data Processing Units (DPUs) and worker types based on your workload requirements. AWS Glue allows you to scale resources up or down to match the demands of your ETL jobs.</li><li><strong>Use the latest AWS Glue version:</strong> AWS regularly releases new versions of AWS Glue with performance improvements and new features. Upgrade to the latest version to take advantage of these enhancements.</li><li><strong>Reduce data scan:</strong> Minimize the amount of data your jobs scan by using techniques like partitioning, caching, and filtering data early in the ETL process.</li><li><strong>Parallelize tasks:</strong> Divide your ETL tasks into smaller parts and process them concurrently to improve throughput. AWS Glue supports parallelization through features like repartitioning and coalesce operations.</li><li><strong>Minimize planning overhead:</strong> Reduce the time spent on planning by optimizing your AWS Glue Data Catalog, using the correct data types, and avoiding unnecessary schema changes.</li><li><strong>Optimize shuffles:</strong> Minimize the amount of data shuffled between tasks, as shuffles can be resource-intensive. Use techniques like repartitioning and coalescing to reduce shuffles.</li><li><strong>Optimize user-defined functions (UDFs):</strong> If you’re using UDFs, ensure they are efficient and optimize their execution using vectorization and caching.</li><li><strong>Use AWS Glue Auto Scaling:</strong> Enable AWS Glue Auto Scaling to adjust the number of workers based on your workload automatically, ensuring efficient resource utilization.</li><li><strong>Monitor and tune:</strong> Use AWS Glue’s monitoring capabilities, such as the Spark UI and CloudWatch metrics, to identify bottlenecks and tune your jobs accordingly.</li><li><strong>Leverage AWS Glue Workflow:</strong> Use AWS Glue Workflow to orchestrate and manage your ETL pipelines, ensuring efficient execution and resource utilization.</li><li><strong>Optimize data formats:</strong> Use columnar data formats like Parquet or ORC, which are optimized for analytical workloads and can improve query performance.</li><li><strong>Leverage AWS Glue Data Catalog:</strong> Use the AWS Glue Data Catalog to store and manage your data schemas, which can improve planning and reduce overhead.</li><li><strong>Optimize data compression:</strong> Use appropriate compression techniques to reduce the amount of data transferred and stored, improving performance and reducing costs.</li><li><strong>Avoid processing the same data multiple times:</strong> Use AWS Glue Job bookmarks to track the data already processed by the ETL job, and update only the changed partitions when loading data to the data lake.</li></ol><p>Here’s an example of AWS Glue Workflow. The workflow processes Helsinki Region Transport (HSL) open data on passenger amounts and public transport stops and shifts. The workflow has a trigger named <em>hsl-data-glue-workflow-trigger</em> that is configured to start once per hour. The trigger will fire up five parallel AWS Glue Jobs to process data related to <em>shifts</em>, <em>passengers</em>, <em>stoptypes</em>, <em>network</em> and <em>stops</em>. When all these Jobs end up in the SUCCESS state, the <em>hsl-data-glue-crawler-trigger</em> is triggered to start an AWS Glue Crawler to update the data schemas in the AWS Glue Data Catalog.</p><figure><img alt="An example of AWS Glue Workflow that processes open HSL transport data" src="https://cdn-images-1.medium.com/max/727/0*2azethx_Yxh7qWrH.jpg" /><figcaption>An example of AWS Glue Workflow that processes open HSL transport data</figcaption></figure><p>AWS Glue Workflows support three types of start triggers:</p><ul><li><strong>Schedule:</strong> The workflow is started according to a defined schedule (e.g., daily, weekly, monthly, or a custom cron expression).</li><li><strong>On-demand:</strong> The workflow is started manually from the AWS Glue console, API, or AWS CLI.</li><li><strong>EventBridge event:</strong> The workflow starts with a single Amazon EventBridge event or a batch of Amazon EventBridge events.</li></ul><h3>Optimizing the data insights experience with Amazon QuickSight</h3><p>From a data consumption perspective, the key criterion is that the data be up-to-date and instantly available. If there’s lots of data in the data lake, updating an analysis or dashboard view in Amazon QuickSight might take even tens of seconds. That will make the business analytics experience very poor and generate lots of costs.</p><p>Amazon QuickSight has solved this issue with a lightning-fast in-memory caching solution called <em>SPICE</em> (Super-fast, Parallel, In-memory Calculation Engine). When configuring QuickSight DataSets, you have the option to either query the underlying data directly or utilize SPICE. QuickSight comes with a 10 GB SPICE allocation per QuickSight Author license, and additional SPICE capacity can be purchased with GB/month pricing.</p><p>When using SPICE, the underlying data from the data sources, such as a data lake, is loaded into SPICE. QuickSight Analyses and Dashboards utilize only the version of data available in SPICE. SPICE can be refreshed</p><ul><li>manually</li><li>by a preconfigured schedule</li><li>through QuickSight API</li></ul><p>The SPICE refresh timing becomes an issue when targeting to have as recent data available in QuickSight as possible. Consider a situation where the Glue Workflow, containing multiple ETL jobs, runs once per hour and updates several datasets in the S3 data lake. In our imaginary example, the workflow process typically lasts 20 minutes. Still, depending on the amount of changed data in the data sources since the last run and the current utilization level of the AWS-managed Glue hardware, the Workflow run can take between 14 and 40 minutes.</p><p>In addition, the QuickSight SPICE refresh process runs on AWS-managed computing resources, and in our case, refreshing one QuickSight DataSet might take 2–8 minutes.</p><p>And in a typical production-scale QuickSight environment, the order of DataSet refreshes matter. There are “simple” DataSets that are not dependent on any other DataSet and then there combined DataSets that utilize simple DataSets. Before starting to refresh one DataSet in QuickSight, we need to be sure that all underlying DataSets our DataSet is dependent on have first been refreshed.</p><p>Here’s an example of a combined DataSet in QuickSight. All datasets available in data lake have first been brought to QuickSight, and now the <em>passengers</em> data is first joined with <em>stops</em> data while passenger amounts are counted per stop. Then <em>stops</em> data is joined with <em>stoptypes</em> data (whether the stop is a glass shelter, steel shelter, post,…), <em>network</em> data (is it a bus stop, subway stop, tram stop,…) and <em>shifts</em> data (number of public transport shifts between different stops).</p><figure><img alt="An example of a combined DataSet in QuickSight" src="https://cdn-images-1.medium.com/max/1024/0*yCTckq1AV-ifCQLk.jpg" /><figcaption>An example of a combined DataSet in QuickSight</figcaption></figure><h3>Optimizing the whole data pipeline from ingestion to insights with event triggering and AWS Step Functions</h3><p>So how can we manage this all automatically and with optimal timing? To solve the issues, we need to</p><ul><li>use AWS Glue Workflow to automate and order the Jobs and Crawlers within the Glue ETL process</li><li>Refresh the QuickSight DataSets into SPICE immediately after Glue Workflow has finished its execution</li><li>Refresh the QuickSight DataSets in the correct order so that the “simple” DataSets get updated first and combined DataSets right after the simple ones</li></ul><p>Luckily we can achieve the latter two by utilizing AWS StepFunctions and CloudWatch Event Triggering!</p><h4>Triggering a Step Function when Glue Workflow has finished</h4><p>AWS Glue Crawlers create CloudWatch Events on their lifecycle changes, and we can trigger an AWS Step Function State Machine execution when the last Crawler in our Glue Workflow sends a <em>Succeeded</em> event. Here’s a CDK/TypeScript snippet on creating the event rule to watch for Glue Crawler state change events and to start the Step Function execution:</p><pre>    // Event rule to trigger the Step Function<br>    new events.CfnRule(this, &quot;CrawlerSucceededRule&quot;, {<br>      description: &quot;Glue crawler succeeded&quot;,<br>      roleArn: smTriggerRole.roleArn,<br>      name: `statemachine-trigger-rule`,<br>      eventPattern: {<br>        source: [&quot;aws.glue&quot;],<br>        &quot;detail-type&quot;: [&quot;Glue Crawler State Change&quot;],<br>        detail: {<br>          state: [&quot;Succeeded&quot;],<br>          crawlerName: [{ &quot;equals-ignore-case&quot;: `hsl-data-glue-crawler` }],<br>        },<br>      },<br>      targets: [<br>        {<br>          arn: cfnStateMachine.attrArn,<br>          id: cfnStateMachine.attrName,<br>          roleArn: smTriggerRole.roleArn,<br>        },<br>      ],<br>    });</pre><h4>Refreshing QuickSight DataSets with AWS Step Functions State Machine</h4><p>The AWS Step Functions have inbuilt integrations with loads of different AWS services, including AWS QuickSight. Therefore, it is straightforward to build a State Machine that starts refreshing the QuickSight DataSet SPICE — the process is called DataSet Ingestion. The following image shows an AWS Step Functions State Machine that processes QuickSight DataSet Ingestions in two phases — in the first phase, it parallelly ingests data on five QuickSight DataSets: <em>network</em>, <em>stops</em>, <em>passengers</em>, <em>shifts</em> and <em>stoptypes</em>. When all those ingestions have been successfully finished, the State Machine continues to ingest the second set of QuickSight DataSets, which in this example contains only one DataSet: <em>passengers-and-stops</em>.</p><figure><img alt="An example of a Step Function that ingests QuickSight DataSet refreshes in two phases" src="https://cdn-images-1.medium.com/max/1024/0*EAol6Fq6vvw38Tjp.jpg" /><figcaption>An example of a Step Function that ingests QuickSight DataSet refreshes in two phases</figcaption></figure><p>For each QuickSight DataSet, the State Machine</p><ol><li>Starts the Ingestion process with <strong>CreateIngestion</strong> call and saves the IngestionId value of the started Ingestion process</li><li>Checks the Ingestion status with <strong>DescribeIngestion</strong> call</li><li>If IngestionStatus is <em>COMPLETED</em>, <em>CANCELLED</em> or <em>FAILED</em>, it will pass the phase</li><li>Otherwise, it will wait for 20 seconds and check the Ingestion status again</li></ol><h3>Summing it up</h3><p>As an end result, we now have a data pipeline that is triggered automatically by a predefined schedule, or with EventBridge event, and that starts ingesting QuickSight DataSets in correct order and as quickly as underlying data is updated. And now we can enjoy the actionable, up-to-date insights:</p><figure><img alt="An example of AWS QuickSight Analysis that utilizes combined QuickSight DataSets" src="https://cdn-images-1.medium.com/max/1024/0*nOkPu0wY_1RoA7xx.jpg" /><figcaption>An example of AWS QuickSight Analysis that utilizes combined QuickSight DataSets</figcaption></figure><p>In this article, we reviewed the components of AWS’s serverless data lake solution and explored ways to optimize its performance and user experience. Lastly, we learned how to automate the whole process from data ingestion to data insights with AWS Step Functions and AWS Glue Crawler Event Triggering.</p><p>We hope you enjoyed the journey. If you would like to set up a Serverless Data Pipeline and Data Lake on AWS, we are here to help. Just <a href="https://www.nordhero.com/company/">contact us</a> or <a href="https://calendly.com/pekka-malmirae-nordhero/30min">book a meeting with us</a>!</p><p>The examples in this article were build using data adapted from Helsinki Region Transport’s (HSL) public data on transport stations, shifts and passengers. The original data is available on <a href="https://hri.fi/">Helsinki Region Infoshare</a> site.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd949875a074" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/speeding-up-data-on-aws-from-ingestion-to-insights-bd949875a074">Speeding Up Data on AWS: From Ingestion to Insights</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Verified Permissions — Part V — Integration with AWS CloudTrail]]></title>
            <link>https://medium.com/nordhero/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/6b19c6c359c9</guid>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Teemu Niiranen]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 13:46:31 GMT</pubDate>
            <atom:updated>2024-03-26T13:46:31.913Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon Verified Permissions — Part V — Integration with AWS CloudTrail</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOTg4nFQt2mL2AXNo-Yx4w.png" /></figure><p>This article is part of a series about Verified Permissions:</p><ul><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-i-essentials-774a148d6c2d">Part 1 — Essentials</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08">Part 2 — Integration with your app</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a">Part 3 — Integration with Amazon Cognito</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317">Part 4 — Complete Example</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9">Part 5 — Integration with AWS CloudTrail</a></li></ul><p>Welcome back! In this article, we will delve into the auditing capabilities of Amazon Verified Permissions. This audit trail, in computing, serves as a record of the changes made to a database or file — ensuring the security and integrity of your system. Visibility into the system’s activity is vital to security and operational best practices. The audit trail enables operational and risk auditing, governance, and compliance.</p><h3>What is AWS CloudTrail?</h3><p>AWS CloudTrail is an AWS service that records actions taken by a user, role, or an AWS service and records these as events. CloudTrail is active in your AWS account when you create it, and its flexibility and numerous options allow you to tailor it to your specific needs. You have a 90-day <em>event history</em> for free, and you can create <em>trails</em> to store these events in an Amazon S3 bucket, with optional delivery to Amazon CloudWatch Logs and Amazon EventBridge. The latest addition to the toolbox is <em>AWS CloudTrail Lake</em>, a managed data lake approach, <a href="https://aws.amazon.com/blogs/mt/announcing-aws-cloudtrail-lake-a-managed-audit-and-security-lake/">announced on January 5th, 2022</a>. So, you have a wealth of options to build a robust foundation for auditing, putting you firmly in control of your AWS services.</p><p>Every event contains identity information about who generated the request:</p><ul><li>Root or AWS Identity and Access Management (IAM) user credentials.</li><li>Temporary security credentials for a role or federated user.</li><li>Another AWS service.</li></ul><h3>Verified Permissions API Events</h3><p>CloudTrail logs all Verified Permissions API actions, also called management events. For example, calls to the CreatePolicy, DeletePolicy, or CreateIdentitySource (Cognito User Pool) actions generate entries in the CloudTrail log files. If you deployed the sample application from the previous article, head to the CloudTrail service in AWS Console and select the Event History from the left-hand side. Now filter the events based on the event source and input “verifiedpermissions.amazonaws.com”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pj6cA5SWNofjp7Rs" /></figure><p>To access detailed information about a specific event record, click on the name in the CloudTrail service in the AWS Console. Here is an example of a PutSchema event above where I have masked some identifiable information:</p><pre>{<br>    &quot;eventVersion&quot;: &quot;1.08&quot;,<br>    &quot;userIdentity&quot;: {<br>        &quot;type&quot;: &quot;AssumedRole&quot;,<br>        &quot;principalId&quot;: &quot;AROARCVGIMMWM22HD45FP:xxxxxxxxxxxxxxxxxx&quot;,<br>        &quot;arn&quot;: &quot;arn:aws:iam::xxxxxxxxxxxx:role/aws-reserved/sso.amazonaws.com/eu-west-1/AWSReservedSSO_AWSAdministratorxxxxxxxxxxxxxx&quot;,<br>        &quot;accountId&quot;: &quot;xxxxxxxxxxxx&quot;,<br>        &quot;accessKeyId&quot;: &quot;AKIAIOSFODNN7EXAMPLE&quot;<br>    },<br>    &quot;eventTime&quot;: &quot;2024-03-20T11:07:02Z&quot;,<br>    &quot;eventSource&quot;: &quot;verifiedpermissions.amazonaws.com&quot;,<br>    &quot;eventName&quot;: &quot;PutSchema&quot;,<br>    &quot;awsRegion&quot;: &quot;eu-north-1&quot;,<br>    &quot;sourceIPAddress&quot;: &quot;xx.xx.xx.xx&quot;,<br>    &quot;userAgent&quot;: &quot;APN/1.0 HashiCorp/1.0 Terraform/1.6.2 (+https://www.terraform.io) terraform-provider-aws/dev (+https://registry.terraform.io/providers/hashicorp/aws) aws-sdk-go-v2/1.25.0 os/macos lang/go#1.21.7 md/GOOS#darwin md/GOARCH#arm64 api/verifiedpermissions#1.9.0&quot;,<br>    &quot;requestParameters&quot;: {<br>        &quot;policyStoreId&quot;: &quot;LYHyHqQYkP8AwggRu97Vjg&quot;<br>    },<br>    &quot;responseElements&quot;: {<br>        &quot;policyStoreId&quot;: &quot;LYHyHqQYkP8AwggRu97Vjg&quot;,<br>        &quot;namespaces&quot;: [<br>            &quot;HeroApp&quot;<br>        ],<br>        &quot;createdDate&quot;: &quot;2024-03-20T11:07:02.37082Z&quot;,<br>        &quot;lastUpdatedDate&quot;: &quot;2024-03-20T11:07:02.37082Z&quot;<br>    },<br>    &quot;requestID&quot;: &quot;e46be152-937f-47eb-94c4-11646fd4d7d9&quot;,<br>    &quot;eventID&quot;: &quot;ea910dbc-c624-4d6f-8110-754f253475d6&quot;,<br>    &quot;readOnly&quot;: false,<br>    &quot;resources&quot;: [<br>        {<br>            &quot;accountId&quot;: &quot;xxxxxxxxxxxx&quot;,<br>            &quot;type&quot;: &quot;AWS::VerifiedPermissions::PolicyStore&quot;,<br>            &quot;ARN&quot;: &quot;arn:aws:verifiedpermissions::xxxxxxxxxxxx:policy-store/LYHyHqQYkP8AwggRu97Vjg&quot;<br>        }<br>    ],<br>    &quot;eventType&quot;: &quot;AwsApiCall&quot;,<br>    &quot;managementEvent&quot;: true,<br>    &quot;recipientAccountId&quot;: &quot;xxxxxxxxxxxx&quot;,<br>    &quot;eventCategory&quot;: &quot;Management&quot;<br>}</pre><p>For example, you can continue experimenting with changing the policies and redeploying with Terraform or changing the policies in the AWS console to check how things get logged. More information about the CloudTrail record contents can be found <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-record-contents.html?icmpid=docs_console_unmapped">in the AWS documentation</a>. And more Verified Permissions examples <a href="https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/cloudtrail.html">here</a>.</p><p>Now, we have an audit trail for the control plane, but if we also want to audit the policy engine, we need to add support for the data events.</p><h3>Verified Permissions Data Events</h3><p>Data events like IsAuthorized, BatchIsAuthorized, and IsAuthorizedWithToken are not logged by default. These events are interesting because you can also log the authorization decisions inside your application. To record CloudTrail data events, you must explicitly add the supported resources or resource types you want to collect activity. Data event capture requires the creation of a trail, which has additional charges.</p><p>For demonstration purposes, let’s create a new trail in the AWS Console and include only the Amazon Verified Permissions data events.</p><h3>CloudTrail Setup for Data Event Logging</h3><p>First, head to CloudTrail service and select the Trails menu from the left-hand side. Then push the “Create trail” button from the upper right corner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X3PPivgeVM3OPHjA" /></figure><p>A trail needs to have a name; let’s call it <em>avp-data-events</em>. By default, CloudTrail wants to create a new S3 bucket and encrypt it using a customer-managed KMS key. We are OK with the S3-managed encryption so we can check that off. From optional settings, enable the CloudWatch integration. Finally, input a name for the IAM role. Otherwise, the defaults are fine for our purposes, press the “Next” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FRky0FZRz_cI_Zsg" /></figure><p>Next, choose the events to be logged. We are only interested in data events, so check only that one. Select Amazon Verified Permissions as the data event type and log all events. Press the “Next” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tsccly8VhKUgochr" /></figure><p>Review the selection and press the “Create trail” button.</p><h3>Testing the Data Events</h3><p>Next is time to play around with the Hero API. I selected the user persona and made some requests via the AppSync Queries console.</p><p>Next, go to CloudWatch service, click Log groups under the Logs menu, and open the log group you specified in the previous section. Typically, CloudTrail delivers an event within 5 minutes of the API call, so be patient if you can’t see log streams with the last event timestamp straightaway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LgcRF0ujckArOfCK" /></figure><p>Here is an example where I again masked some information like the AWS account identifiers and IP addresses:</p><pre>{<br>    &quot;eventVersion&quot;: &quot;1.08&quot;,<br>    &quot;userIdentity&quot;: {<br>        &quot;type&quot;: &quot;AssumedRole&quot;,<br>        &quot;principalId&quot;: &quot;AROARCVGIMMWM57KVRUAX:hero-appsync-auth-dev&quot;,<br>        &quot;arn&quot;: &quot;arn:aws:iam::xxxxxxxxxxxx:role/hero-appsync-auth-dev&quot;,<br>        &quot;accountId&quot;: &quot;xxxxxxxxxxxx&quot;,<br>        &quot;accessKeyId&quot;: &quot;ASIARCVGIMMWD6AJ54LQ&quot;<br>    },<br>    &quot;eventTime&quot;: &quot;2024-03-22T10:54:07Z&quot;,<br>    &quot;eventSource&quot;: &quot;verifiedpermissions.amazonaws.com&quot;,<br>    &quot;eventName&quot;: &quot;BatchIsAuthorized&quot;,<br>    &quot;awsRegion&quot;: &quot;eu-north-1&quot;,<br>    &quot;sourceIPAddress&quot;: &quot;xx.xx.xx.xx&quot;,<br>    &quot;userAgent&quot;: &quot;aws-sdk-js/3.525.0 ua/2.0 os/linux#5.10.210-220.852.amzn2.x86_64 lang/js md/nodejs#20.11.1 api/verifiedpermissions#3.525.0 exec-env/AWS_Lambda_nodejs20.x&quot;,<br>    &quot;requestParameters&quot;: {<br>        &quot;requests&quot;: [<br>            {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;AddHero&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                }<br>            },<br>            {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;GetHero&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                }<br>            },<br>            {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;ListHeroes&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                }<br>            },<br>            {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;GetHeroName&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                }<br>            }<br>        ],<br>        &quot;policyStoreId&quot;: &quot;LYHyHqQYkP8AwggRu97Vjg&quot;<br>    },<br>    &quot;responseElements&quot;: null,<br>    &quot;additionalEventData&quot;: {<br>        &quot;results&quot;: [<br>            {<br>                &quot;request&quot;: {<br>                    &quot;principal&quot;: {<br>                        &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                        &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                    },<br>                    &quot;action&quot;: {<br>                        &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                        &quot;actionId&quot;: &quot;AddHero&quot;<br>                    }<br>                },<br>                &quot;decision&quot;: &quot;DENY&quot;<br>            },<br>            {<br>                &quot;request&quot;: {<br>                    &quot;principal&quot;: {<br>                        &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                        &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                    },<br>                    &quot;action&quot;: {<br>                        &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                        &quot;actionId&quot;: &quot;GetHero&quot;<br>                    }<br>                },<br>                &quot;decision&quot;: &quot;ALLOW&quot;<br>            },<br>            {<br>                &quot;request&quot;: {<br>                    &quot;principal&quot;: {<br>                        &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                        &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                    },<br>                    &quot;action&quot;: {<br>                        &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                        &quot;actionId&quot;: &quot;ListHeroes&quot;<br>                    }<br>                },<br>                &quot;decision&quot;: &quot;ALLOW&quot;<br>            },<br>            {<br>                &quot;request&quot;: {<br>                    &quot;principal&quot;: {<br>                        &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                        &quot;entityId&quot;: &quot;eu-north-1_cFkdRqDX0|e8bd9731-972f-43d5-af9a-8847094a2b19&quot;<br>                    },<br>                    &quot;action&quot;: {<br>                        &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                        &quot;actionId&quot;: &quot;GetHeroName&quot;<br>                    }<br>                },<br>                &quot;decision&quot;: &quot;DENY&quot;<br>            }<br>        ]<br>    },<br>    &quot;requestID&quot;: &quot;a0ad7ed6-d68b-4c42-8a94-37c68f5f98b9&quot;,<br>    &quot;eventID&quot;: &quot;9ea01479-fc61-46bb-b1e5-71dfc97c6ad0&quot;,<br>    &quot;readOnly&quot;: true,<br>    &quot;resources&quot;: [<br>        {<br>            &quot;accountId&quot;: &quot;xxxxxxxxxxxx&quot;,<br>            &quot;type&quot;: &quot;AWS::VerifiedPermissions::PolicyStore&quot;,<br>            &quot;ARN&quot;: &quot;arn:aws:verifiedpermissions::xxxxxxxxxxxx:policy-store/LYHyHqQYkP8AwggRu97Vjg&quot;<br>        }<br>    ],<br>    &quot;eventType&quot;: &quot;AwsApiCall&quot;,<br>    &quot;managementEvent&quot;: false,<br>    &quot;recipientAccountId&quot;: &quot;xxxxxxxxxxxx&quot;,<br>    &quot;eventCategory&quot;: &quot;Data&quot;<br>}</pre><p>Note the difference: the managementEvent is false this time, and the eventCategory is data.</p><h3>Conclusion</h3><p>Integration of Amazon Verified Permissions and AWS CloudTrail increases the observability and auditability of your application. You can track which users accessed specific resources by correlating CloudTrail event records with Amazon Verified Permissions policies. This aids with security and compliance auditing. This was the first part of this series, at least for now. Thank you for following along!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b19c6c359c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9">Amazon Verified Permissions — Part V — Integration with AWS CloudTrail</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Verified Permissions — Part IV — Complete Example]]></title>
            <link>https://medium.com/nordhero/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/1a9d33aeb317</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Teemu Niiranen]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 13:45:51 GMT</pubDate>
            <atom:updated>2024-03-26T13:45:50.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon Verified Permissions — Part IV — Complete Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOTg4nFQt2mL2AXNo-Yx4w.png" /></figure><p>This article is part of a series about Verified Permissions:</p><ul><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-i-essentials-774a148d6c2d">Part 1 — Essentials</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08">Part 2 — Integration with your app</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a">Part 3 — Integration with Amazon Cognito</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317">Part 4 — Complete Example</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9">Part 5 — Integration with AWS CloudTrail</a></li></ul><p>Hello, and welcome aboard again! This article will dive into a complete working architecture utilizing multiple AWS services: Amazon Verified Permissions, Amazon Cognito, Amazon AppSync (with JavaScript resolvers), and Amazon DynamoDB — a complete example of a GraphQL API that uses Amazon Verified Permissions for authorization requests.</p><p>We are utilizing the BatchIsAuthorized API to simultaneously get authorization decisions for all supported API queries and mutations, including the denied fields. We are doing some mapping and the token signature validation because of the lack of support for batch authorization and Cognito groups with ready IsAuthorizedWithToken API. We use OpenTofu/Terraform for the infrastructure, TypeScript for JavaScript resolvers, and the Lambda Authorizer.</p><p>The idea is to implement all our learned tricks and build an API for the hero management system. The architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S4AhMv9BbibJopRR" /></figure><p>The solution is written with an infrastructure-as-code approach, but we are going through the necessary parts and manual steps.</p><h3>Pre-requisites</h3><p>You need to have AWS CLI, OpenTofu (or Terraform), and Node installed on your machine, as well as Git, <a href="https://github.com/teemuniiranen/hero-api">to clone the repository from GitHub</a>.</p><p>I have used the following:</p><ul><li>AWS CLI v2.15.30</li><li>OpenTofu v1.6.2</li><li>Node v21.6.0</li><li>Terragrunt v0.55.3 (Optional, supports OpenTofu from v0.52.0)</li></ul><h3>Terraform Providers and Modules Used</h3><p>The solutions use the following Terraform dependencies.</p><p>Terraform providers:</p><ul><li>hashicorp/aws</li><li>hashicorp/awscc</li></ul><p>Some modules from the excellent <a href="https://github.com/terraform-aws-modules">terraform-aws-modules</a> repository:</p><ul><li>terraform-aws-modules/appsync/aws</li><li>terraform-aws-modules/dynamodb-table/aws</li><li>terraform-aws-modules/lambda/aws</li></ul><h3>Cognito</h3><p>We must prepare a Cognito User Pool and create User and Admin groups and a User Pool Client. All these steps are outlined in the <em>infra/cognito.tf </em>file. We have encountered this in the previous articles, but now we are also creating the groups with aws_cognito_user_group resource from the hashicorp/aws provider:</p><pre>resource &quot;aws_cognito_user_group&quot; &quot;user&quot; {<br>  name         = &quot;User&quot;<br>  user_pool_id = aws_cognito_user_pool.this.id<br>}</pre><h3>Database</h3><p>The solution uses a DynamoDB table as a database, and we are using a single table design defined in the <em>infra/dynamodb.tf</em> file. That’s why our schema is generic; the partition key is named PK, and the sort key SK. There is also a global secondary index named GSI1 with a similar generic approach, GSI1PK as the primary key, and the GSI1SK as the sort key. I recommend Alex DeBries’s great articles and re:Invent sessions to get familiar with the ideology. Start <a href="https://www.alexdebrie.com/posts/dynamodb-single-table/">here</a>. Also, Rick Houlihan’s re:Invent sessions, like <a href="https://aws.amazon.com/dynamodb/resources/reinvent-2019-advanced-design-patterns/">DynamoDB Deep Dive: Advanced Design Patterns (DAT403)</a>.</p><p>We could have used any other approach as well. Our example is simple, but it also acts as a playground if you want to develop your DynamoDB skills further. The most important attributes in our table for our hero profiles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6X2TkithViX7KPA7D3hSQ.png" /></figure><p>In the global secondary index, we use the table sort key as the primary key and the region attribute as the sort key for our hero profile data. Now we can query the profiles from the specific region:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyt14eCFetqfT-FPlOckOg.png" /></figure><p>PS. I generated superhero names and their true identities with Amazon Bedrock and the Anthropic Claude v2.1 model.</p><h3>AppSync GraphQL Schema</h3><p>GraphQL schema defines what data can be queried or mutated. To support the database schema above, we can use the following (located in <em>schema.graphql</em>):</p><pre>enum REGION {<br>  EMEA<br>  NA<br>  LATAM<br>  APAC<br>}<br><br>type Hero {<br>  heroId: ID<br>  region: REGION<br>  name: String<br>  alias: String<br>}<br><br>type HeroIterator {<br>  heroes: [Hero]<br>  nextToken: String<br>}<br><br>input HeroInput {<br>  name: String!<br>  region: REGION!<br>  alias: String!<br>}<br><br>type Mutation {<br>  addHero(name: String!, region: REGION!, alias: String!): Hero!<br>}<br><br>type Query {<br>  getHero(heroId: ID!): Hero<br>  listHeroes(region: REGION, limit: Int, nextToken: String): HeroIterator!<br>}<br><br>schema {<br>  query: Query<br>  mutation: Mutation<br>}</pre><p>List heroes query also has pagination available, controlled by the limit and nextToken attributes. You can control the page size with the limit attribute, but the response is also automatically paginated if the DynamoDB response is larger than 1 MB. I have used the CLI tool <em>codegen</em> from AWS Amplify to generate the TypeScript types based on the schema file (API.ts, mutations.ts, and queries.ts files).</p><h3>Verified Permissions</h3><p>The infrastructure code is located in the <em>infra/verified-permissions.tf</em> file and the schema can be found in the <em>policies/schema.json</em>.</p><p>Policies:</p><ul><li>For the admin persona: <em>policies/admin_policy.cedar</em>.</li><li>For the user persona: <em>policies/user_policy.cedar</em>.</li></ul><p>The difference is that the admin can do all actions: AddHero, ListHeros, GetHero, and GetHeroName. Our user persona is permitted only to query GetHero and ListHeroes. So, there is no access to add a hero or reveal the real identity of the hero with the GetHeroName action.</p><h3>AppSync Infrastructure as Code</h3><p>AppSync is the service that glues our architecture together. File appsync.tf contains all the necessary infrastructure definitions to create an AppSync API with Lambda Authorizer. It also defines our DynamoDB data source:</p><pre>datasources = {<br>    dynamodb_table = {<br>      type       = &quot;AMAZON_DYNAMODB&quot;<br>      table_name = join(&quot;-&quot;, [var.nameprefix, &quot;table&quot;, var.env])<br>      region     = var.aws_region<br>    }<br>}</pre><p>The resolvers: queries to get an individual hero profile and list of heroes, and the mutation to add a hero:</p><pre>resolvers = {<br>  &quot;Query.getHero&quot; = {<br>    kind  = &quot;UNIT&quot;<br>    type  = &quot;Query&quot;<br>    field = &quot;getHero&quot;<br>    code  = file(&quot;../out/appsync/getHero.js&quot;)<br>    runtime = {<br>      name            = &quot;APPSYNC_JS&quot;<br>      runtime_version = &quot;1.0.0&quot;<br>    }<br>    data_source = &quot;dynamodb_table&quot;<br>  }<br><br>  &quot;Query.listHeroes&quot; = {<br>    kind  = &quot;UNIT&quot;<br>    type  = &quot;Query&quot;<br>    field = &quot;listHeroes&quot;<br>    code  = file(&quot;../out/appsync/listHeroes.js&quot;)<br>    runtime = {<br>      name            = &quot;APPSYNC_JS&quot;<br>      runtime_version = &quot;1.0.0&quot;<br>    }<br>    data_source = &quot;dynamodb_table&quot;<br>  }<br><br>  &quot;Mutation.addHero&quot; = {<br>    kind  = &quot;UNIT&quot;<br>    type  = &quot;Mutation&quot;<br>    field = &quot;addHero&quot;<br>    code  = file(&quot;../out/appsync/addHero.js&quot;)<br>    runtime = {<br>      name            = &quot;APPSYNC_JS&quot;<br>      runtime_version = &quot;1.0.0&quot;<br>    }<br>    data_source = &quot;dynamodb_table&quot;<br>  }<br>}</pre><p>We are using the APPSYNC_JS runtime, which is equal to JavasScript Resolver, announced in <a href="https://aws.amazon.com/blogs/aws/aws-appsync-graphql-apis-supports-javascript-resolvers/">November 2022</a>. The old-school option would be to use Apache Velocity Templates (VTL), but with JavaScript, we can write unit tests more easily and possibly reuse the code. I have provided an example of the unit test in the addHero.test.ts file. Don’t get confused, so mix JS resolvers with Lambda resolvers! JS resolvers don’t have lambda cold start and come with no extra cost, but they have many limitations, like no network or file system access. You can also use many other programming languages with Lambda functions. Check the AWS documentation for more information about the <a href="https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-overview-js.html">APPSYNC_JS runtime</a>.</p><p>Only pipeline resolvers were supported at the announcement, but on <a href="https://aws.amazon.com/about-aws/whats-new/2023/08/aws-appsync-javascript-all-resolvers-graphql-apis/">August 16th, 2023</a>, AWS extended the support to unit resolvers. This is an excellent place to test those out, and the <em>kind = “UNIT”</em> attribute controls that part. JS resolver implementations are located under the <em>src/appsync/resolvers</em> directory.</p><h3>AppSync Lambda Authorizer</h3><p>Lambda Authorizer is the core of this article, and the implementation can be found in the src/appsync/authorizer/authorizer.ts file. The first step is to verify that the access token has not expired and that it has a valid signature signed by the Cognito User Pool. I’m using the <a href="https://github.com/awslabs/aws-jwt-verify">aws-jwt-verify</a> library for this, which makes it a straightforward operation:</p><pre>import { CognitoJwtVerifier } from &quot;aws-jwt-verify&quot;;<br><br>const verifier = CognitoJwtVerifier.create({<br>  userPoolId: &quot;&lt;cognito user pool identifier&gt;&quot;,<br>  tokenUse: &quot;access&quot;,<br>  clientId: &quot;&lt;cognito client identifier&gt;&quot;,<br>});<br><br>const token = await verifier.verify(authorizationToken);</pre><p>The verify function returns the decoded token payload, which we can use to check the user identifier (sub) and the Cognito groups (cognito:groups):</p><pre>{<br>  &quot;sub&quot;: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>  &quot;cognito:groups&quot;: [<br>    &quot;User&quot;<br>  ],<br>  &quot;iss&quot;: &quot;https://cognito-idp.eu-north-1.amazonaws.com/eu-north-1_5hlzvmgIe&quot;,<br>  ...  <br>}</pre><p>We are mapping the combination of the user pool ID and the sub claim to the user entity identifier. Cognito groups claim, which consists of group names, we need to map to Verified Permissions entity item parents in the BatchIsAuthorized requests:</p><pre>{<br>  identifier: {<br>    entityType: &quot;HeroApp::User&quot;,<br>    entityId: &quot;eu-north-1_5hlzvmgIe|b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>  },<br>  parents: [<br>    {<br>      entityType: &quot;HeroApp::Group&quot;,<br>      entityId: &quot;User&quot;,<br>    }<br>  ],<br>}</pre><p>We also have a JavaScript map, which is used to construct the BatchIsAuthorized requests using the keys and for mapping the actions back to GraphQL fields for AppSync Lambda Authorizer output:</p><pre>[<br>    [&quot;AddHero&quot;, &quot;Mutation.addHero&quot;],<br>    [&quot;GetHero&quot;, &quot;Query.getTask&quot;],<br>    [&quot;ListHeroes&quot;, &quot;Query.listHeroes&quot;],<br>    [<br>      &quot;GetHeroName&quot;,<br>      `arn:aws:appsync:${region}:${accountId}:apis/${apiId}/types/Hero/fields/name`,<br>    ],<br>]</pre><p>All the mapping functions can be found in the <em>src/appsync/authorizer/permissions.ts</em> files.</p><h3>Deployment</h3><p>There are local Terragrunt configurations you can use to deploy the solution. The default uses AWS Stockholm region (eu-north-1), but you can change that from the <em>deployment/dev/env.hcl</em> file. Requires active AWS CLI session or access keys profile:</p><pre>$ git clone https://github.com/teemuniiranen/hero-api<br>$ cd hero-api/deployment/dev/hero-api<br>$ terragrunt init<br>$ terragrunt apply</pre><pre>npm install</pre><p>Bundle the TypeScript code into JavaScript:</p><pre>npm run bundle</pre><p>Run the tests:</p><pre>npm run test</pre><p>The Terraform code is located under the <em>infra</em> directory. Check the <em>variables.tf</em>; aws_region controls the region.</p><p>From the output, note down the user identifier (cognito_user_pool_id) and the Cognito client identifier (cognito_client_id).</p><h3>Testing</h3><p>Next, we create some test users for Cognito and assign them to groups. Finally, we use the access tokens to call the AppSync API in the AWS Console.</p><h3>Create a Cognito user</h3><p>You can create new users via AWS Console, but the user is required to change the temporary password after creation. Also, we need to authenticate the user to get the tokens. It’s easy with an AWS CLI command:</p><pre>aws cognito-idp admin-create-user \<br>  --user-pool-id &lt;your cognito user pool id&gt; \<br>  --username test-user</pre><p>Change the generated password and make it permanent:</p><pre>aws cognito-idp admin-set-user-password \<br>  --user-pool-id &lt;your cognito user pool id&gt; \<br>  --username test-user \<br>  --password &lt;your password&gt; \<br>  --permanent</pre><p>And assign the user to the User group:</p><pre>aws cognito-idp admin-add-user-to-group \<br>  --user-pool-id  &lt;your cognito user pool id&gt; \<br>  --username test-user \<br>  --group-name User</pre><p>Finally, sign in to get the tokens for the API:</p><pre>aws cognito-idp admin-initiate-auth \<br>  --auth-flow ADMIN_NO_SRP_AUTH \<br>  --user-pool-id  &lt;your cognito user pool id&gt; \<br>  --client-id  &lt;your cognito client id&gt; \<br>  --auth-parameters USERNAME=test-user,PASSWORD=&lt;your password&gt;</pre><p>Copy the value of the AccessToken property in the response:</p><pre>{<br>    &quot;ChallengeParameters&quot;: {},<br>    &quot;AuthenticationResult&quot;: {<br>        &quot;AccessToken&quot;: &quot;eyJra...</pre><p>Repeat the process to create an admin user by changing at least the username and the group name to Admin.</p><h3>Test with AppSync Queries Tool</h3><p>AppSync has a built-in test tool for queries. Open the AWS Console, go to AppSync service, and select the hero API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7tdDRd-oYzQxKpIF" /></figure><p>From the left-hand side menu, select the Queries. AWS Lambda has been pre-selected for the authorization provider. Now input our admin user’s access token into the “Authorization Token” field. From the Explorer window, select Mutation and press the “+” button to generate a template. Fill in the template and run the mutation from the Run button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sTygPcNgLPzwyemL" /></figure><p>The result window on the right-hand side should now show some data related to the newly added hero. The great thing about GraphQL is that you can control what data should be returned. In the example above, only heroId is selected, but you can also add other hero entity fields. Add a couple of heroes more. If you change the token to the test user’s access token, you get a not authorized response:</p><pre>{<br>  &quot;data&quot;: null,<br>  &quot;errors&quot;: [<br>    {<br>      &quot;path&quot;: [<br>        &quot;addHero&quot;<br>      ],<br>      &quot;data&quot;: null,<br>      &quot;errorType&quot;: &quot;Unauthorized&quot;,<br>      &quot;errorInfo&quot;: null,<br>      &quot;locations&quot;: [<br>        {<br>          &quot;line&quot;: 2,<br>          &quot;column&quot;: 3,<br>          &quot;sourceName&quot;: null<br>        }<br>      ],<br>      &quot;message&quot;: &quot;Not Authorized to access addHero on type Mutation&quot;<br>    }<br>  ]<br>}</pre><p>Now change to list heroes query and try to list all fields:</p><pre>query MyQuery {<br>  listHeroes {<br>    heroes {<br>      alias<br>      heroId<br>      name<br>      region<br>    }<br>  }<br>}</pre><p>You should get the list of heroes but with null name fields and errors stating that you are not authorized to access the name on type Hero:</p><pre>...  <br>&quot;errors&quot;: [<br>    {<br>      &quot;path&quot;: [<br>        &quot;listHeroes&quot;,<br>        &quot;heroes&quot;,<br>        0,<br>        &quot;name&quot;<br>      ],<br>      &quot;data&quot;: null,<br>      &quot;errorType&quot;: &quot;Unauthorized&quot;,<br>      &quot;errorInfo&quot;: null,<br>      &quot;locations&quot;: [<br>        {<br>          &quot;line&quot;: 6,<br>          &quot;column&quot;: 7,<br>          &quot;sourceName&quot;: null<br>        }<br>      ],<br>      &quot;message&quot;: &quot;Not Authorized to access name on type Hero&quot;<br>    },<br> ...</pre><p>You can continue experimenting with AppSync by changing the Verified Permissions policies. The caching is turned off for the authorizer response, so you can experiment with the policy changes without delay. You can turn the caching on by changing the <em>authorizer_result_ttl_in_seconds</em> value to higher than zero seconds in <em>infra/appsync.tf</em> file.</p><h3>Conclusion</h3><p>This architecture provides a robust foundation for implementing role-based access control for the GrapghQL API. The caching can be turned on to offer faster authorization decisions and reduce Verified Permissions costs. The trade-off is that you must be careful when extending the API because this method allows access by default if the new action is not mapped to the static configuration array! Another option is not to use the batch authorization method and always map the query or mutation and the requested fields to the authorization call. You could use a naming convention to make it more generic. I hope you found this example helpful in applying Verified Permissions in your applications.</p><p><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9">Part 5 — Integration with AWS CloudTrail</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a9d33aeb317" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317">Amazon Verified Permissions — Part IV — Complete Example</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Verified Permissions — Part III — Integration with Amazon Cognito]]></title>
            <link>https://medium.com/nordhero/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/48dff62c2a8a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Teemu Niiranen]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 13:45:21 GMT</pubDate>
            <atom:updated>2024-03-26T13:45:21.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon Verified Permissions — Part III — Integration with Amazon Cognito</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOTg4nFQt2mL2AXNo-Yx4w.png" /></figure><p>This article is part of a series about Verified Permissions:</p><ul><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-i-essentials-774a148d6c2d">Part 1 — Essentials</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08">Part 2 — Integration with your app</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a">Part 3 — Integration with Amazon Cognito</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317">Part 4 — Complete Example</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9">Part 5 — Integration with AWS CloudTrail</a></li></ul><p>Welcome back to this article series about Amazon Verified Permissions. The last article covered different integration points when making authorization decisions inside your application. This article continues the journey with Authorization APIs. The next, and currently the last, API to cover is the <a href="https://docs.aws.amazon.com/verifiedpermissions/latest/apireference/API_IsAuthorizedWithToken.html">IsAuthorizedWithToken</a>, which presently supports only identity and access tokens issued by Amazon Cognito in JSON Web Token (JWT) format.</p><h3>What is Amazon Cognito?</h3><p>Amazon Cognito is an identity platform for web and mobile apps. It’s a user directory, an authentication server, and an authorization service for OAuth 2.0 access tokens and AWS credentials. You can authenticate and authorize users from the built-in user directory that supports users, groups, and customer attributes. Or integrate Cognito with enterprise directory or consumer identity providers like Google and Facebook. It’s a fully managed, serverless service that scales to handle millions of users and provide low-latency responses.</p><h3>Amazon Cognito User Pool</h3><p>A user pool is a user directory and OpenID Connect (OIDC) identity provider built-in Amazon Cognito service. It’s for authentication; users can sign in through the user pool or federate through a third-party identity provider (IdP). The other half of the Cognito is identity pools for authorization user access to AWS APIs, but that’s out of the scope of this article. After successful authentication, Amazon Cognito creates a session and returns an identity token, an access token, and a refresh token for the authenticated user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6gwPiT1kQTqN4nZQ" /></figure><p>Both identity and access tokens are supported for authorization with IsAuthorizedWithToken API in Amazon Verified Permissions for tokens provided by Amazon Cognito User Pools. You can use a refresh token to get new tokens or revoke existing tokens.</p><h3>Identity Token</h3><p>An identity token contains claims about the authenticated user’s identity, such as name, email, and phone number.</p><p>Example content of the Cognito identity token:</p><pre>{<br>  &quot;sub&quot;: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>  &quot;cognito:groups&quot;: [<br>    &quot;User&quot;<br>  ],<br>  &quot;email_verified&quot;: true,<br>  &quot;iss&quot;: &quot;https://cognito-idp.eu-north-1.amazonaws.com/eu-north-1_her0vmgIe&quot;,<br>  &quot;phone_number_verified&quot;: true,<br>  &quot;cognito:username&quot;: &quot;hero-user&quot;,<br>  &quot;origin_jti&quot;: &quot;cf0ec9f6-e990-4dce-a864-29131082d927&quot;,<br>  &quot;aud&quot;: &quot;5dlnem8jsrdivs7e2724usinkm&quot;,<br>  &quot;event_id&quot;: &quot;7b8c5882-e6fd-4706-8fbc-334b6b1581ab&quot;,<br>  &quot;token_use&quot;: &quot;id&quot;,<br>  &quot;auth_time&quot;: 1710426106,<br>  &quot;name&quot;: &quot;John Smith&quot;,<br>  &quot;phone_number&quot;: &quot;+12065551212&quot;,<br>  &quot;exp&quot;: 1710429706,<br>  &quot;iat&quot;: 1710426106,<br>  &quot;jti&quot;: &quot;98f25027-0a5e-408e-b27b-b6ed876edc21&quot;,<br>  &quot;email&quot;: &quot;hero.user@example.com&quot;,<br>  &quot;custom:user_tier&quot;: &quot;partner&quot;<br>}</pre><p>The ID token can contain OIDC standard claims defined in <a href="https://openid.net/specs/openid-connect-core-1_0.html#Claims">OIDC standard claims</a>. The ID token can also include custom attributes you define in your user pool. Amazon Cognito prepends “custom:” to custom attribute names and writes attribute values to the ID token as strings regardless of attribute type.</p><p>More detailed information is in the <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html">Cognito documentation</a>.</p><h3>Access Token</h3><p>The idea of an access token is defined in OAuth specification, while identity tokens are defined in OpenID Connect. By Oauth 2.0 specification, the purpose of the access token is to authorize API operations by using it in the requests to the resource server. Identity tokens should not be used to make requests to the resource server; this is sometimes referred to as an anti-pattern. These principles have been misused; for example, API Gateway and AppSync authorizer for Cognito also support identity tokens. I’m getting sidetracked here, but you can use both also with Amazon Verified Permissions.</p><p>In the Cognito access token, the <em>scope</em> claim is a special one. The scope is a logical grouping of claims the access token can access. The format differs depending on the identity server product. Still, it can often consist of two parts, with the Cedar terminology, action, and the resource, delimited with a special character like order_read or read:orders. Check out this great article, “<a href="https://auth0.com/blog/on-the-nature-of-oauth2-scopes/">On The Nature of OAuth2’s Scopes</a>”, on the Okta website to learn more about the concept.</p><p>Example content of the Cognito access token:</p><pre>{<br>  &quot;sub&quot;: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>  &quot;cognito:groups&quot;: [<br>    &quot;User&quot;<br>  ],<br>  &quot;iss&quot;: &quot;https://cognito-idp.eu-north-1.amazonaws.com/eu-north-1_5hlzvmgIe&quot;,<br>  &quot;client_id&quot;: &quot;5dlnem8jsrdivs7e2724usinkm&quot;,<br>  &quot;origin_jti&quot;: &quot;cf0ec9f6-e990-4dce-a864-29131082d927&quot;,<br>  &quot;event_id&quot;: &quot;7b8c5882-e6fd-4706-8fbc-334b6b1581ab&quot;,<br>  &quot;token_use&quot;: &quot;access&quot;,<br>  &quot;scope&quot;: &quot;aws.cognito.signin.user.admin&quot;,<br>  &quot;auth_time&quot;: 1710426106,<br>  &quot;exp&quot;: 1710429706,<br>  &quot;iat&quot;: 1710426106,<br>  &quot;jti&quot;: &quot;744da750-af1f-4b62-b360-41abaf5936d3&quot;,<br>  &quot;username&quot;: &quot;hero-user&quot;<br>}</pre><p>The aws.cognito.signin.user.admin scope authorizes the Amazon Cognito user pools API and is the only scope provided for user pool users by default. It permits the query and update of all information about a user pool user with, for example, the GetUser and UpdateUserAttributes API operations. We can also notice that Cognito uses a dotted approach for claims.</p><p>You can create your resource servers to define custom scopes, but that is out of the scope of this article. For more information, check the <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html">Cognito documentation</a>. Remember that there are limitations when using Secure Remote Password (USER_SRP_AUTH authentication flow in Cognito), and custom scopes work only with the hosted UI. You can get around this with the pre-token generation Lambda trigger, which will be explained more in the next section. I think this is not that clearly stated in the documentation, but the following note tries to warn about this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7qCrQR9T4WOthJgc" /></figure><h3>Customizing the Tokens with Lambda Functions</h3><p>Amazon Cognito also provides a programmatical way of customizing the token contents. You can execute your custom code and programmatically return additional custom claims using the <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html">pre-token generation Lambda trigger</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tPf0zz635e5MoqUO" /></figure><p>Enriching the token with identity-related data from the database is a good practice. I don’t recommend using Amazon Cognito as a user database for often queried or mutated attributes because it has a relatively low request rate quota limit. GetUser API has a limit of 120 requests per second by default, but it is adjustable. You can purchase an increase to adjustable Amazon Cognito quotas. Check out tips for optimizing request rates <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/limits.html#managing-request-rate-quotas">here</a>.</p><p>The pre-token Lambda trigger was previously limited to identity tokens, but on December 18th, 2023, <a href="https://aws.amazon.com/about-aws/whats-new/2023/12/amazon-cognito-user-pools-customize-access-tokens/">Amazon announced the support for access tokens</a>. Note that this requires enabling the Cognito advanced security features, which impacts the price.</p><h3>Policies and Cognito Tokens</h3><p>Amazon Verified Permissions automatically validates the token signature and expiration date and extracts the token claims. However, you still need to model those as attributes, in the case of identity token, or as a context, in the case of access token, in your schema.</p><p>Note: If you delete an Amazon Cognito user pool or user, tokens from that deleted pool or that deleted user continue to be usable until they expire.</p><h3>Identity Token</h3><p>From the identity token example above, we can map custom:user_tier claims in the following way to make it optional:</p><pre>{<br>  &quot;HeroApp&quot;: {<br>    &quot;entityTypes&quot;: {<br>      &quot;User&quot;: {<br>        &quot;memberOfTypes&quot;: [<br>          &quot;Group&quot;<br>        ],<br>        &quot;shape&quot;: {<br>          &quot;type&quot;: &quot;Record&quot;,<br>          &quot;attributes&quot;: {<br>            &quot;custom&quot;: {<br>              &quot;type&quot;: &quot;Record&quot;,<br>              &quot;attributes&quot;: {<br>                &quot;user_tier&quot;: {<br>                  &quot;type&quot;: &quot;String&quot;<br>                }<br>              }<br>            }<br>          }<br>        }<br>      },<br>     ...</pre><p>When writing Cedar policies using Amazon Cognito user pool claims that contain a colon character, you must reference them with a period (.) instead. For example, you must change cognito:username to cognito.username. Unfortunately, cognito:groups claim is not currently supported. We can now implement an attribute-based partner policy by using the custom:user_tier claim:</p><pre>permit(<br>  principal,<br>  action in [HeroApp::Action::&quot;AddHero&quot;],<br>  resource<br>) when {<br>  principal.custom.user_tier == &quot;partner&quot;<br>};</pre><p>Note that this would require all our supported principals to have a custom.user_tier attribute, so also HeroApp::Group entity or the policy creation will fail. Amazon Verified Permissions currently supports Cedar v2.4. In Cedar v3, you can use the <a href="https://docs.cedarpolicy.com/policies/syntax-operators.html#operator-is">“is” (entity type test)</a> keyword, so maybe something like this works in the future:</p><pre>permit(<br>  principal is HeroApp::User,<br>  action in [HeroApp::Action::&quot;AddHero&quot;],<br>  resource<br>) when {<br>  principal.custom.user_tier == &quot;partner&quot;<br>};</pre><h3>Access Token</h3><p>An access token is mapped to a context object when passed to Verified Permissions, which must also be mapped to the schema:</p><pre>{<br>  &quot;HeroApp&quot;: {<br>    &quot;actions&quot;: {<br>      &quot;AddHero&quot;: {<br>        &quot;appliesTo&quot;: {<br>          &quot;context&quot;: {<br>            &quot;type&quot;: &quot;ReusedContext&quot;<br>          },<br>          &quot;resourceTypes&quot;: [<br>            &quot;Hero&quot;<br>          ]<br>        }<br>      }<br>    },<br>    ...<br>    &quot;commonTypes&quot;: {<br>      &quot;ReusedContext&quot;: {<br>        &quot;attributes&quot;: {<br>          &quot;token&quot;: {<br>            &quot;type&quot;: &quot;Record&quot;,<br>            &quot;attributes&quot;: {<br>              &quot;scope&quot;: {<br>                &quot;type&quot;: &quot;String&quot;<br>              },<br>              &quot;client_id&quot;: {<br>                &quot;type&quot;: &quot;String&quot;<br>              }<br>            }<br>          }<br>        },<br>        &quot;type&quot;: &quot;Record&quot;<br>      }<br>    }<br>  }<br>}</pre><p>So we could allow the same AddHero action when the client_id matches and aws.cognito.signin.user.admin is included in the scope claim:</p><pre>permit(<br>  principal,<br>  action in [HeroApp::Action::&quot;AddHero&quot;],<br>  resource<br>) when { <br>  context.token.client_id == &quot;5dlnem8jsrdivs7e2724usinkm&quot; &amp;&amp;<br>  context.token.scope like &quot;*aws.cognito.signin.user.admin*&quot;<br>};</pre><h3>Integration</h3><p>The service integration is straightforward. All you need to do is to add a new identity source to your policy store. You can do it with a simple form in the AWS Console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xD32LURRGeKwhKSq" /></figure><p>I recommend the Infrastructure as Code approach, where we can again utilize the hashicorp/awscc provider and the <a href="https://registry.terraform.io/providers/hashicorp/awscc/latest/docs/resources/verifiedpermissions_identity_source#principal_entity_type">awscc_verifiedpermissions_identity_source</a> resource.</p><pre>resource &quot;awscc_verifiedpermissions_identity_source&quot; &quot;identity_source&quot; {<br>  policy_store_id = aws_verifiedpermissions_policy_store.store.id<br>  configuration = {<br>    cognito_user_pool_configuration = {<br>      user_pool_arn = aws_cognito_user_pool.this.arn<br>      client_ids = [aws_cognito_user_pool_client.this.id]<br>    }<br>  }<br>  principal_entity_type = &quot;HeroApp::User&quot;<br>}</pre><p>No matter the approach, you must define the Cognito User Pool ID and map the principal. It is not that the identifier will be a combination of the user pool ID and the user sub. Additionally, you can restrict the validation to specific client application identifiers only.</p><h3>Testing the Policy</h3><p>You can’t test the authorization with the Test Bench feature of Amazon Verified Permissions. Note that IsAuthorizedWithToken API derives the principal from the identity token. You must not include that principal in the entity parameter, or the operation fails and reports a conflict between the two entity sources. If you provide an access token, you can include the entity as part of the entity parameter to provide additional attributes.</p><p>An example with AWS CLI and the first identity token above:</p><pre>aws verifiedpermissions is-authorized-with-token \<br>    --policy-store-id &lt;policy_store_id&gt; \<br>    --identity-token &lt;id_token&gt; \<br>    --action actionType=&quot;HeroApp::Action&quot;,actionId=&quot;AddHero&quot;</pre><p>Response:</p><pre>{<br>    &quot;decision&quot;: &quot;ALLOW&quot;,<br>    &quot;determiningPolicies&quot;: [<br>        {<br>            &quot;policyId&quot;: &quot;KRRbJQyUebgvjjEAAHXkFB&quot;<br>        }<br>    ],<br>    &quot;errors&quot;: []<br>}</pre><p>Where policyId is the policy identifier of our newly made partner policy.</p><h3>Conclusion</h3><p>Unfortunately, some critical parts are still missing, including the Cognito user pool group claim, the batch authorization support, and the testing support with the Test Bench. It would be very nice if the group claim could be mapped to a HeroApp::Group parent principal. I’m waiting for these to eliminate some of the unnecessary heavy lifting. In the following article, we are putting the theory into action. We will create an example API utilizing the new skills we have learned!</p><p><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317">Part 4 — Complete Example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48dff62c2a8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a">Amazon Verified Permissions — Part III — Integration with Amazon Cognito</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Verified Permissions — Part II — Integration with your app]]></title>
            <link>https://medium.com/nordhero/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/9bc4cd2aba08</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Teemu Niiranen]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 13:44:33 GMT</pubDate>
            <atom:updated>2024-03-26T13:44:33.050Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon Verified Permissions — Part II — Integration with your app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOTg4nFQt2mL2AXNo-Yx4w.png" /></figure><p>This article is part of a series about Verified Permissions:</p><ul><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-i-essentials-774a148d6c2d">Part 1 — Essentials</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08">Part 2 — Integration with your app</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a">Part 3 — Integration with Amazon Cognito</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317">Part 4 — Complete Example</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9">Part 5 — Integration with AWS CloudTrail</a></li></ul><p>The previous article covered essential topics such as schema design and policies. This article will delve into various strategies for integrating Amazon Verified Permissions into your application, focusing on serverless building blocks like applications behind Amazon API Gateway or Amazon AppSync.</p><h3>Lambda Authorizers</h3><p>Lambda Authorizers enables you to implement custom authorization logic by running your code. Amazon API Gateway and Amazon AppSync support Lambda Authorizers, albeit with functional differences.</p><h3>Lambda Authorizer with Amazon API Gateway</h3><p>AWS has a <a href="https://aws.amazon.com/blogs/security/building-fine-grained-authorization-using-amazon-cognito-api-gateway-and-iam/">great blog post</a> about implementing custom authorization logic with API Gateway. I recommend checking it out before going any further. DynamoDB is a policy store in that solution, but you can also apply the approach with Amazon Verified Permissions. The architecture could be similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zE7wpitKg8DkAcmD" /></figure><p>The policy format used by API Gateway is similar to Amazon IAM policies. For our hero application and admin role, we could return a policy similar to this:</p><pre>{<br>   &quot;Version&quot;:&quot;2012-10-17&quot;,<br>   &quot;Statement&quot;:[<br>      {<br>         &quot;Sid&quot;:&quot;Hero-API&quot;,<br>         &quot;Effect&quot;:&quot;Allow&quot;,<br>         &quot;Action&quot;:&quot;execute-api:Invoke&quot;,<br>         &quot;Resource&quot;:[<br>            &quot;arn:aws:execute-api:eu-north-1:123456789012:her0dhp7b5/v1/GET/heroes&quot;,<br>            &quot;arn:aws:execute-api:eu-north-1:123456789012:her0dhp7b5/v1/POST/heroes&quot;,<br>            &quot;arn:aws:execute-api:eu-north-1:123456789012:her0dhp7b5/v1/GET/heroes/*&quot;<br>         ]<br>      }<br>   ]<br>}</pre><p>One of the advantages of this approach is that it can cache the response for a maximum of 3600 seconds or 1 hour. This caching helps to reduce the number of function executions and latency. The HTTP header containing the authentication token serves as a cache key, and you can perform initial validation with regex to prevent calls with incorrect token headers.</p><p>A good option for integration! To integrate with the Amazon Verified Permissions, we would need to verify the token and map the token content and the request data to the Amazon Verified Permissions authorization requests, but more on that later. Remember to return a constant response for a token when using caching because API Gateway will also use the same response for other API endpoints.</p><h3>Lambda Authorizer with Amazon AppSync</h3><p>The architecture with Lambda Authorizer is similar; just change the API Gateway icon to the AppSync icon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IWWH71ABLV73dpQ1" /></figure><p>AppSync takes a different approach with the Lambda Authorizer output. It allows or denies access based on the isAuthorized field value together with the fine-grained information in the deniedFields attribute. You can also pass context data to resolvers in the resolverContext field and override the default caching time-to-live with the ttlOverride field. A JavaScript example for our user without adding permissions (as a little bonus, also a feature that denies access to the name field to reveal the true identity of our hero):</p><pre>{<br>      isAuthorized: true,<br>      resolverContext: {<br>        userId: &quot;a2701ad0-5ed1-468d-b779-6eb8e594b6fd&quot;,<br>      },<br>      deniedFields: [<br>         &quot;Mutation.addHero&quot;,<br>         &quot;arn:aws:appsync:eu-north-1:123456789012:apis/her0d5cbi5gsbhsm2hpnskwpim/types/Hero/fields/name&quot;,<br>      ],<br>}</pre><p>Note <em>isAuthorized: true</em> here! Because our deniedFields lists Mutation.addHero as denied, the result is still denied if the current request was actually for the addHero mutation. So, the isAuthorized field is not acting as a master switch, which helps us build constant, cached responses and prevents us from accidentally allowing all further requests if we want to use the deny strategy.</p><p>The same maximum time-to-live value, 3600 seconds, also applies to AppSync, and you can do the initial token validation with regex. You can then do further logic in the resolver and return an unauthorized response. In practice, you must move some of the authorization logic to the resolver by returning true in the isAuthorized field and passing the context data in the resolverContext field if you consider caching and the authorizing data resides outside the token, in the request context (query string, variables, etc.).</p><h3>Other Integration Points</h3><p>Another option is the AVP authorization request in our application code, which could be a Lambda function behind the API Gateway or a Lambda resolver or resolver pipeline in the case of AppSync. For example, your microservice may run inside the Docker container. The downside is that we are adding some authorization logic together near the business logic. On the other hand, we can implement finer-grained caching, for example, not just token-based caching.</p><h3>Pricing Considerations</h3><p>Without caching, the authorizer Lambda runs for every API Gateway or AppSync request that hits the API and generates many Lambda invocations and Amazon Verified Permissions calls. Amazon Verified Permission uses a tiered pricing model. The first 40 million requests per month cost $150/million authorization requests, but there is no minimum number of requests.</p><p>Example: If your application makes 10,000 authorization requests, then you are charged for 10,000 requests ($150 / 1,000,000 * 10,000 = $1.50). To compare it with the Lambda pricing, and if you could utilize ARM architecture, the price would be $0.20 / million requests in the Stockholm region. For the exact 10,000 requests and if the average execution time would be 100 ms with 512 MB of memory — this makes $0.20 / 1,000.000 * 10,000 + 100ms * $0.0000000083/ms * 10,000 = $0.002 + $0.0083 = $0.01. So, compared to Lambda pricing, it’s high, but with a smart caching strategy, you can save money and keep your applications fast.</p><p>The trade-off with caching is that changes to your policies won’t take place immediately.</p><h3>Authorization Requests</h3><p>At the time of writing, you can use three different authorization APIs: <a href="https://docs.aws.amazon.com/verifiedpermissions/latest/apireference/API_IsAuthorized.html">IsAuthorized</a>, <a href="https://docs.aws.amazon.com/verifiedpermissions/latest/apireference/API_IsAuthorizedWithToken.html">IsAuthorizedWithToken</a>, and <a href="https://docs.aws.amazon.com/verifiedpermissions/latest/apireference/API_BatchIsAuthorized.html">BatchIsAuthorized</a>. We will handle the IsAuthorizedWithToken API in the following article because it relates to Amazon Cognito Integration. Amazon also <a href="https://aws.amazon.com/about-aws/whats-new/2024/03/amazon-verified-permissions-default-quota-authorization-apis/">recently increased the default quota</a> for authorization APIs from 30 to 200 transactions per second (TPS), and customers requiring more than 200 TPS can request a quota increase, so this is a so-called soft limit.</p><h3>IsAuthorized</h3><p>IsAuthorized is for making a single authorization decision described in the request parameters. Here is an example request from the previous article but now just executed with AWS SDK for JavaScript/TypeScript:</p><pre>import {<br>  VerifiedPermissionsClient,<br>  IsAuthorizedCommand,<br>  IsAuthorizedCommandInput,<br>} from &quot;@aws-sdk/client-verifiedpermissions&quot;;<br><br>const client = new VerifiedPermissionsClient();<br><br>const input: IsAuthorizedCommandInput = {<br>  policyStoreId: &quot;my-policy-store-id&quot;,<br>  principal: {<br>    entityType: &quot;HeroApp::User&quot;,<br>    entityId: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>  },<br>  action: {<br>    actionType: &quot;HeroApp::Action&quot;,<br>    actionId: &quot;GetHero&quot;,<br>  },<br>  resource: {<br>    entityType: &quot;HeroApp::Hero&quot;,<br>    entityId: &quot;825837ac-2023-4aff-afc8-a39787b70e5c&quot;,<br>  },<br>  entities: {<br>    entityList: [<br>      {<br>        identifier: {<br>          entityType: &quot;HeroApp::User&quot;,<br>          entityId: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>        },<br>        parents: [<br>          {<br>            entityType: &quot;HeroApp::Group&quot;,<br>            entityId: &quot;User&quot;,<br>          },<br>        ],<br>      },<br>    ],<br>  },<br>};<br><br>const command = new IsAuthorizedCommand(input);<br>const isAuthorizedResponse = await client.send(command);<br>// {<br>//   &quot;decision&quot;: &quot;ALLOW&quot;, // or &quot;DENY&quot;<br>//   &quot;determiningPolicies&quot;: [<br>//       {<br>//           &quot;policyId&quot;: &quot;Gnv793ZtShkv2j7wxvqBai&quot; // User Policy<br>//       }<br>//   ],<br>//   &quot;errors&quot;: [], // possible list of object with errorDescription field<br>// }</pre><h3>BatchIsAuthorized</h3><p>With BatchIsAuthorized, you can make a series of decisions about multiple authorization requests for one principal or resource. The principal or the resource parameter must be identical across all requests, or you will get an error response. The BatchIsAuthrorized method is relatively new, and it was <a href="https://aws.amazon.com/about-aws/whats-new/2023/11/amazon-verified-permissions-supports-batch-authorization/">announced</a> just before the last re:Invent on November 20th, 2023. With BatchIsAuthorized, you can process up to 30 authorization decisions, simplifying building applications where a single user action requires multiple actions to be authorized. I like this addition! With authorizing in batches, you can significantly reduce costs by paying just for one request. The batching also affects the solution’s performance because you do not suffer from the networking latency between the individual IsAuthorized calls.</p><p>What I like even more is that this also simplifies user interface usage. We can batch call authorization from a user experience perspective to show or hide the UI section based on the same permissions! So we can keep the UI in sync with our API permissions and dynamically change the experience by changing the policies with no code changes needed if you have mapped all the necessary data. More about the mapping will be in the next section.</p><p>Note that the Test Bench feature in the AWS Console doesn’t currently support BatchIsAuthorized, but you can use <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/batch-is-authorized.html">AWS CLI for these calls</a>.</p><p>Let’s also have an AWS SDK example for the BatchIsAuthorized, but let’s apply it to our hero scenario and the AppSync Lambda authorizer above. Let’s request the authorization decision for our non-admin user and get all our supported actions: GetHero, AddHero, ListHeroes, plus the new GetHeroName that controls the access to the name attribute, the real identity of the hero. GetHeroName should be automatically denied because we haven’t introduced a policy allowing that action.</p><pre>import {<br>  VerifiedPermissionsClient,<br>  BatchIsAuthorizedCommand,<br>  BatchIsAuthorizedCommandInput,<br>} from &quot;@aws-sdk/client-verifiedpermissions&quot;;<br><br>const client = new VerifiedPermissionsClient();<br><br>const input: BatchIsAuthorizedCommandInput = {<br>  policyStoreId: &quot;my-policy-store-id&quot;,<br>  requests: [<br>      {<br>        principal: {<br>          entityType: &quot;HeroApp::User&quot;,<br>          entityId: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>        },<br>        action: {<br>          actionType: &quot;HeroApp::Action&quot;,<br>          actionId: &quot;GetHero&quot;,<br>        },<br>      },<br>      {<br>        principal: {<br>          entityType: &quot;HeroApp::User&quot;,<br>          entityId: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>        },<br>        action: {<br>          actionType: &quot;HeroApp::Action&quot;,<br>          actionId: &quot;AddHero&quot;,<br>        },<br>      },<br>      {<br>        principal: {<br>          entityType: &quot;HeroApp::User&quot;,<br>          entityId: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>        },<br>        action: {<br>          actionType: &quot;HeroApp::Action&quot;,<br>          actionId: &quot;ListHeroes&quot;,<br>        },<br>      },<br>      {<br>        principal: {<br>          entityType: &quot;HeroApp::User&quot;,<br>          entityId: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>        },<br>        action: {<br>          actionType: &quot;HeroApp::Action&quot;,<br>          actionId: &quot;GetHeroName&quot;,<br>        },<br>      },<br>  ],<br>  entities: {<br>    entityList: [<br>      {<br>        identifier: {<br>          entityType: &quot;HeroApp::User&quot;,<br>          entityId: &quot;b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;,<br>        },<br>        parents: [<br>          {<br>            entityType: &quot;HeroApp::Group&quot;,<br>            entityId: &quot;User&quot;,<br>          },<br>        ],<br>      },<br>    ],<br>  },<br>};<br><br>const command = new BatchIsAuthorizedCommand(input);<br>const isAuthorizedResponse = await client.send(command);</pre><p>So, in total, 4 out of a maximum 30 requests. Note that we are not interested in a detailed level of the Hero resource, so we have left it out. The response would include a results array that we then would need to map to AppSync response format:</p><pre>{<br>    &quot;results&quot;: [<br>        {<br>            &quot;decision&quot;: &quot;ALLOW&quot;,<br>            &quot;determiningPolicies&quot;: [<br>                {<br>                    &quot;policyId&quot;: &quot;Gnv793ZtShkv2j7wxvqBai&quot;<br>                }<br>            ],<br>            &quot;errors&quot;: [],<br>            &quot;request&quot;: {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;GetHero&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_5hlzvmgIe|b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;decision&quot;: &quot;DENY&quot;,<br>            &quot;determiningPolicies&quot;: [],<br>            &quot;errors&quot;: [],<br>            &quot;request&quot;: {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;AddHero&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_5hlzvmgIe|b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;decision&quot;: &quot;ALLOW&quot;,<br>            &quot;determiningPolicies&quot;: [<br>                {<br>                    &quot;policyId&quot;: &quot;Gnv793ZtShkv2j7wxvqBai&quot;<br>                }<br>            ],<br>            &quot;errors&quot;: [],<br>            &quot;request&quot;: {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;ListHeroes&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_5hlzvmgIe|b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;decision&quot;: &quot;DENY&quot;,<br>            &quot;determiningPolicies&quot;: [],<br>            &quot;errors&quot;: [],<br>            &quot;request&quot;: {<br>                &quot;action&quot;: {<br>                    &quot;actionType&quot;: &quot;HeroApp::Action&quot;,<br>                    &quot;actionId&quot;: &quot;GetHeroName&quot;<br>                },<br>                &quot;principal&quot;: {<br>                    &quot;entityType&quot;: &quot;HeroApp::User&quot;,<br>                    &quot;entityId&quot;: &quot;eu-north-1_5hlzvmgIe|b89463bf-c061-4945-a17b-4a3d9bea33fa&quot;<br>                }<br>            }<br>        }<br>    ],<br>}</pre><h3>Mapping</h3><p>No matter the integration point, some mapping is needed to pass the data required to authorization requests. Mapping is the key to success, and with more comprehensive mapping, you most likely don’t need the code change, only the change to the policy. In practice, the balance naturally depends on how fine-grained needs you have for authorization. With Lambda Authorizers introduced above, mapping to the supported output format is also needed, such as mapping the Amazon Verified Permissions response to the Lambda function output.</p><p>As you can see from these static API call examples above, all data related to the authorization rule must be present. You need to include the possible hierarchies, like a user belonging to a group (principal), which could be available in the request encoded to a JWT token. Or provide the attribute data to make attribute-based access control (attributes of the target resource). Conversely, this might force you to fetch that data from the database before the authorization call if it is not included in the request. Also, resources could be hierarchical. You might easily map the action part based on the request, but an excellent example of an exception is our GetHeroName action, which is not an AppSync query but a single GrapghQL field.</p><h3>Conclusion</h3><p>We covered quite a lot, which also took more time and thought than I had initially planned. Mapping the Amazon Verified Permissions request for role-based access control could be straightforward based on the original query. Still, attribute-based access control might require more data fetching before authorization. All this depends on the schema and how fine-grained the access control needs to be. In the following article, we continue in the world of mapping permissions and cover the Amazon Cognito integration and what Amazon has done to help you on that journey.</p><p>In the last re:invent 23, Amazon demonstrated Amazon Verified Permissions with a sample toy store application built with AWS Amplify. It uses the API Gateway Lambda Authorizer approach for the backend, and both IsAuthorized and BatchIsAuthroized were used in the demo. The session recording can be found on YouTube titled “<a href="https://www.youtube.com/watch?v=ptzb-oBwjxM">AWS re:Invent 2023 — How to use Amazon Verified Permissions for authorization inside apps (SEC241)</a>”. If you are eager to check the mapping implementation immediately, check <a href="https://github.com/aws-samples/avp-toy-store-sample/blob/main/src/main/java/org/example/api/LambdaAuthorizer.java">the Java implementation for the Lambda Authorizer</a>. I recommend watching this session! Another great session is <a href="https://www.youtube.com/watch?v=1AdkZJSmTQI">AWS re:Inforce 2023 — Fine-grained authorization for apps with Amazon Verified Permissions (IAM308)</a>.</p><p><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a">Part 3 — Integration with Amazon Cognito</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bc4cd2aba08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08">Amazon Verified Permissions — Part II — Integration with your app</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Verified Permissions — Part I — Essentials]]></title>
            <link>https://medium.com/nordhero/amazon-verified-permissions-part-i-essentials-774a148d6c2d?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/774a148d6c2d</guid>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Teemu Niiranen]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 13:43:35 GMT</pubDate>
            <atom:updated>2024-03-28T06:20:35.076Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon Verified Permissions — Part I — Essentials</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOTg4nFQt2mL2AXNo-Yx4w.png" /></figure><p>This article is part of a series about Verified Permissions:</p><ul><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-i-essentials-774a148d6c2d">Part 1 — Essentials</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08">Part 2 — Integration with your app</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iii-integration-with-amazon-cognito-48dff62c2a8a">Part 3 — Integration with Amazon Cognito</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-iv-complete-example-1a9d33aeb317">Part 4 — Complete Example</a></li><li><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-v-integration-with-aws-cloudtrail-6b19c6c359c9">Part 5 — Integration with AWS CloudTrail</a></li></ul><p>Building authentication for an application is a straightforward process. However, the complexity arises when you need to incorporate fine-grained authorization, such as different user roles or attribute-based access control. The business logic can already be intricate, and when combined with authorization logic, it can quickly become overwhelming. But what if you could separate your authorization logic from your application logic? Or use the same audit trail for both your app and infrastructure? Amazon Verified Permissions is an answer to all these needs!</p><p>This newcomer, <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-verified-permissions-generally-available/">generally available</a> since June 13, 2023, is an exciting option. It is also evolving fast, with the latest additions like enhanced visual mode and batch authorization. In this series of articles, I’ll guide you through this service. In this first part, we’ll cover the essentials, schema design, and policy language. The following articles will explore how to call the service from your application to make authorization decisions. We are also applying the knowledge gathered to build a fully working GraphQL API with Amazon AppSync service and integrate it with Amazon Cognito and Amazon Verified Permissions to support role-based access control. Finally, we look at the CloudTrail integration, which offers audit trail capabilities.</p><p>I will reference an imaginary custom application throughout the article series. This application is a hero management system that is used to manage superheroes. The two most essential personas are the admin persona, which can add heroes to the system, and the user persona, which can list the heroes without revealing their true identity, the name attribute.</p><h3>What is Amazon Verified Permissions?</h3><p>Amazon Verified Permissions is a fully managed and scalable authorization service that contains the control plane; you can define fine-grained authorization policies with open-source language <a href="https://www.cedarpolicy.com/en">Cedar</a> and the data plane or “the engine” to query for authorization decisions. With AVP, you can standardize and centralize policy management, administration, and audit. Essential concepts are policy store, schema, and policies. Cedar itself was first introduced with AWS Verified Access service, <a href="https://aws.amazon.com/blogs/networking-and-content-delivery/introducing-aws-verified-access-general-availability/">generally available</a> since April 28, 2023, in preview during AWS re:Invent 2022. AWS Verified Access is out of the scope of this article series, but you can look at <a href="https://aws.amazon.com/blogs/security/a-walk-through-aws-verified-access-policies/">a blog post</a> about it on the AWS Security Blog.</p><h3>AWS Identity and Access Management (IAM) vs. Amazon Verified Permissions</h3><p>Verified Permissions should not be mixed with AWS Identity and Access Management (IAM). AWS IAM manages identities and access to <em>AWS services and resources</em>. This could be access to AWS accounts and inside accounts to different services and their resources. Amazon Verified Permissions is a permissions management and authorization service for <em>custom applications you built</em>.</p><h3>Policy Store</h3><p>The policy store is a container for your policies. It also includes a schema that validates the policies you add to the store. The policy validation mode controls this behavior. Amazon recommends creating one policy store per application or one per tenant for multi-tenant applications. This approach ensures that your policies are organized and easily manageable, enhancing the efficiency of your authorization process.</p><h3>Deploy with Terraform</h3><p>Terraform example of policy store creation with <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">hashicorp/aws</a> provider:</p><pre>resource &quot;aws_verifiedpermissions_policy_store&quot; &quot;store&quot; {<br>  validation_settings {<br>    mode = &quot;STRICT&quot; // validate against the schema<br>  }<br>  description = &quot;Hero App Policy Store&quot;<br>}</pre><h3>Schema</h3><p>The <em>schema</em> is a declaration of the structure of the <em>entity types</em> and <em>actions</em> your application supports for authorization decisions. Entity types can be further divided into <em>principals</em> and <em>resources</em> — <em>principals</em> can take one or more <em>actions</em> on a <em>resource. </em>Entity types can also have attributes to support attribute-based access control (ABAC), and entity types can be members of other types to support grouping or, for example, role-based access control (RBAC) — more detailed information in <a href="https://docs.cedarpolicy.com/overview/terminology.html#schema">Cedar documentation</a>.</p><p>The schema is defined in a JSON format, but AWS Console also provides a graphical tool for building and visualizing the schema.</p><p>Example for our Hero application:</p><pre>{<br>    &quot;HeroApp&quot;: {<br>        &quot;entityTypes&quot;: {<br>            &quot;User&quot;: {<br>                &quot;memberOfTypes&quot;: [<br>                    &quot;Group&quot;<br>                ],<br>                &quot;shape&quot;: {<br>                    &quot;type&quot;: &quot;Record&quot;,<br>                    &quot;attributes&quot;: {}<br>                }<br>            },<br>            &quot;Group&quot;: {<br>                &quot;shape&quot;: {<br>                    &quot;type&quot;: &quot;Record&quot;,<br>                    &quot;attributes&quot;: {}<br>                }<br>            },<br>            &quot;Hero&quot;: {<br>                &quot;shape&quot;: {<br>                    &quot;type&quot;: &quot;Record&quot;,<br>                    &quot;attributes&quot;: {<br>                        &quot;rating&quot;: {<br>                            &quot;type&quot;: &quot;Long&quot;<br>                        },<br>                        &quot;region&quot;: {<br>                            &quot;name&quot;: &quot;Region&quot;,<br>                            &quot;type&quot;: &quot;Entity&quot;<br>                        }<br>                    }<br>                }<br>            },<br>            &quot;Region&quot;: {<br>                &quot;shape&quot;: {<br>                    &quot;type&quot;: &quot;Record&quot;,<br>                    &quot;attributes&quot;: {}<br>                }<br>            }<br>        },<br>        &quot;actions&quot;: {<br>            &quot;AddHero&quot;: {<br>                &quot;appliesTo&quot;: {<br>                    &quot;principalTypes&quot;: [<br>                        &quot;User&quot;,<br>                        &quot;Group&quot;<br>                    ],<br>                    &quot;resourceTypes&quot;: [&quot;Hero&quot;]<br>                }<br>            },<br>            &quot;GetHero&quot;: {<br>                &quot;appliesTo&quot;: {<br>                    &quot;principalTypes&quot;: [<br>                        &quot;User&quot;,<br>                        &quot;Group&quot;<br>                    ],<br>                    &quot;resourceTypes&quot;: [&quot;Hero&quot;]<br>                }<br>            },<br>            &quot;ListHeroes&quot;: {<br>                &quot;appliesTo&quot;: {<br>                    &quot;principalTypes&quot;: [<br>                        &quot;User&quot;,<br>                        &quot;Group&quot;<br>                    ],<br>                    &quot;resourceTypes&quot;: [&quot;Hero&quot;]<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>The example shows that our application supports three different actions: AddHero, GetHero, and ListHeroes. A single user or a user group member can take these actions on Hero entities. HeroApp, at the root level, is a namespace definition. A namespace is a string prefix for a type, separated by a pair of colons (::) as a delimiter in the policies. Verified Permissions supports one namespace per policy store to prevent ambiguity.</p><p>The visual mode in the AWS console would be similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xzBhsDRaQMRPJ_bs" /></figure><h3>Deploy with Terraform</h3><p>Terraform example of schema creation with the same hashicorp/aws provider:</p><pre>resource &quot;aws_verifiedpermissions_schema&quot; &quot;schema&quot; {<br>  policy_store_id = aws_verifiedpermissions_policy_store.store.id<br><br>  definition {<br>    value = file(&quot;../policies/schema.json&quot;)<br>  }<br>}</pre><p>The schema.json file contains our example schema, which is shown above.</p><h3>Policy</h3><p>A <em>policy</em> is a statement that either permits or forbids a <em>principal</em> to take one or more <em>actions</em> on a <em>resource</em>. We could have a policy, for example, an admin group, to allow all actions, including AddHero:</p><pre>permit (<br>    principal in HeroApp::Group::&quot;Admin&quot;,<br>    action in [<br>        HeroApp::Action::&quot;AddHero&quot;,<br>        HeroApp::Action::&quot;ListHeroes&quot;,<br>        HeroApp::Action::&quot;GetHero&quot;],<br>    resource<br>);</pre><p>And a policy for user groups to allow only get actions:</p><pre>permit (<br>    principal in HeroApp::Group::&quot;User&quot;,<br>    action in [HeroApp::Action::&quot;ListHeroes&quot;, HeroApp::Action::&quot;GetHero&quot;],<br>    resource<br>);</pre><p>Note that in these examples, we don’t have any restrictions on the resource, in this case, the Hero entity, which has some attributes defined in our schema: rating and region. With these, we could define even fine-grained permissions to limit actions for heroes in a specific region. Resources could also be restricted to a single resource (by an identifier, for example) or a group of resources. Still, the schema does not support any hero groups at the moment.</p><p>Let’s create an EMEA admin policy with a when-condition:</p><pre>permit (<br>    principal in HeroApp::Group::&quot;EmeaAdmin&quot;,<br>    action in [<br>        HeroApp::Action::&quot;AddHero&quot;,<br>        HeroApp::Action::&quot;ListHeroes&quot;,<br>        HeroApp::Action::&quot;GetHero&quot;],<br>    resource<br>)<br>when {<br>    resource.region == HeroApp::Region::&quot;EMEA&quot;<br>};</pre><p>Attribute could be something the principal has, but in our case, no attributes are defined for User or Group entities.</p><p>You can also explicitly deny access (in this example for user identifier “a2701ad0–5ed1–468d-b779–6eb8e594b6fd”) with the forbid keyword:</p><pre>forbid (<br>    principal == HeroApp::User::&quot;a2701ad0-5ed1-468d-b779-6eb8e594b6fd&quot;,<br>    action in [HeroApp::Action::&quot;AddHero&quot;],<br>    resource<br>);</pre><p>More policy examples can also be found in <a href="https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policies_examples.html">AWS documentation</a>.</p><h3>Context</h3><p><em>Context</em> is the information relevant to policy decisions but not part of the identity of your principal, action, or resource. Context attributes could be connection-related data like IP source address or whether the user has used multi-factor authentication (MFA) during the authentication process. You can add this to your authorization requests, but let’s go back to this in later articles. Context attributes also need to be modeled to actions in the schema.</p><p>Example of policy using the context attribute:</p><pre>permit (<br>    principal in HeroApp::Group::&quot;User&quot;,<br>    action in [HeroApp::Action::&quot;ListHeroes&quot;, HeroApp::Action::&quot;GetHero&quot;],<br>    resource<br>)<br>when {<br>    context.MultiFactorAuthPresent == true &amp;&amp;<br>    context.NetworkInfo.IPAddress like &quot;192.0.2.*&quot;<br>};</pre><h3>Deploy with Terraform</h3><p>Unfortunately, the hashicorp/aws provider doesn’t support policies at the time of writing (besides the policy templates), so we need to use another approach. You can use the aws_cloudformation_stack resource or a different provider like AWS Cloud Control API based on <a href="https://registry.terraform.io/providers/hashicorp/awscc/latest">hashicorp/awscc</a>.</p><p>With awscc, we can quite handy define the policies as code:</p><pre>resource &quot;awscc_verifiedpermissions_policy&quot; &quot;admin_policy&quot; {<br>  policy_store_id = aws_verifiedpermissions_policy_store.store.id<br>  definition = {<br>    static = {<br>      statement   = file(&quot;../policies/admin_policy.cedar&quot;)<br>      description = &quot;Admin Policy&quot;<br>    }<br>  }<br>}</pre><p>Where our first admin policy example would be located in the admin_policy.cedar file.</p><h3>Policy Templates</h3><p><em>Policy templates</em> are reusable policy blueprints with placeholders for the principal, resource, or both. This allows the policy to be defined once and then attached to multiple principals and resources. Updates to the template are reflected across all principals and resources that use the template. Policies linked to a policy template are called <em>template-linked policies</em>, while examples in the policy section are called <em>static policies</em>.</p><p>Example:</p><pre>permit(<br>    principal == ?principal,<br>    action in [<br>        HeroApp::Action::&quot;Add&quot;,<br>        HeroApp::Action::&quot;Get&quot;,<br>        HeroApp::Action::&quot;List&quot;<br>    ],<br>    resource == ?resource<br>);</pre><h3>Testing the policies with the Test bench console</h3><p>The Test Bench is a feature of AVP that allows you to test and troubleshoot the policies by making authorization requests. You can use the visual mode or a JSON document mode in the AWS Console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*siTMchailyWD60XE" /></figure><p>Let’s have a quick test and try to add a hero with our user role, with visual mode and filing in the following:</p><p>Principal:</p><ul><li>HeroApp::Group = User</li></ul><p>Resource:</p><ul><li>HeroApp::Hero = 825837ac-2023–4aff-afc8-a39787b70e5c (user identifier)</li></ul><p>Attributes:</p><ul><li>region: Entity HeroApp::Region = NA (region identifier, North America)</li><li>rating: Long = 5</li></ul><p>Action:</p><ul><li>HeroApp::Action = AddHero</li></ul><p>Additional entities:</p><ul><li>HeroApp::Region = NA (North America)</li></ul><p>Note that because our Hero references another entity region, we must also define that one in the additional entities section. After pressing the “Run authorization request” button, we see the deny response as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hnKpTPFU4Fi9YO7x" /></figure><p>If we change only the group to Admin, we get the allowed response as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hHHvTj5kG3t9kOOC" /></figure><p>Note that the test bench reports also the policy that satisfied the allowed decision. In this case, the Admin Policy.</p><h3>Conclusion</h3><p>In this article, we covered the essential building blocks of Amazon Verified Permissions to get started with schema and policy design and how to test policies with the test bench feature. We also covered code snippets for Terraform to deploy all the needed pieces with infrastructure as a code approach. In the next article, we will integrate the Amazon Verified Permissions service with different strategies, so stay tuned!</p><p><a href="https://medium.com/@teemu.niiranen/amazon-verified-permissions-part-ii-integration-with-your-app-9bc4cd2aba08">Part 2 — Integration with your app</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=774a148d6c2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/amazon-verified-permissions-part-i-essentials-774a148d6c2d">Amazon Verified Permissions — Part I — Essentials</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s new and noteworthy on AWS — Summer 2023 edition]]></title>
            <link>https://medium.com/nordhero/whats-new-and-noteworthy-on-aws-summer-2023-edition-cd96c9b8234a?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/cd96c9b8234a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Pekka Malmirae]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 06:58:30 GMT</pubDate>
            <atom:updated>2023-08-23T06:58:30.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>What’s new and noteworthy on AWS — Summer 2023 edition</h3><p><em>During my summer vacation, I occasionally glimpsed the AWS announcements feed but didn’t have time to dig into the list. I still got the feeling that there were some major releases, so I decided to go through all those hundreds of announcements and put together a comprehensive list of the most remarkable and noteworthy releases and new features around my favorite topics: Data &amp; Analytics, Serverless Architecture &amp; App Development, AWS Management &amp; DevOps &amp; IaC, and Security. I hope that also you find some gems from the list!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Clz8cFh2rac4eDAT1T4JXw.jpeg" /></figure><p>The summer of 2023 was indeed scorching hot for what comes to AWS and releasing new services and features. From the start of June until late August 2023, the list of recent announcements is impressive. There are over 600 announcements that I read through, and I hand-picked 45 top news on Data, Serverless, DevOps, and Security spaces. Several features have now been released as GA or in Preview that had already been announced at AWS re:Invent in November 2022 with flashing lights. But talk is cheap, so here are my top picks from the summer releases, ordered by solution area and release date.</p><h3>Data &amp; Analytics</h3><h4>Amazon QuickSight launches geospatial heatmap for points on maps</h4><p><em>Released: Jun 5, 2023</em></p><p>It has been possible to create analyses and dashboards with geospatial map visuals also earlier, but now it is possible to have a geospatial heat map with your own data. Please see following example image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sSIGp8nfSguIO3wy.png" /></figure><p>Amazon QuickSight geospatial heat map, image from AWS QuickSight Documentation</p><p>Geospatial heat map style uses color gradations to indicate areas of high and low data point concentration, allowing readers to zoom in and out, pan across the map, and explore the data in detail. When the map is zoomed in to a certain level, the heat layer automatically reverts back to the basic points, allowing readers to interact with the underlying points.</p><p>See here for more details: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-quicksight-geospatial-heatmap-points-maps/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-quicksight-geospatial-heatmap-points-maps/</a></p><h4>AWS Glue for Ray is now generally available</h4><p><em>Released: Jun 5, 2023</em></p><p>AWS Glue for Ray is now generally available. AWS Glue for Ray is based on open-source compute framework <a href="https://ray.io/"><strong>ray.io</strong></a>. AWS Glue for Ray combines Glue’s serverless capability for data integration with possibility to develop ETL jobs with Python programming language.</p><p>AWS Glue for Ray facilitates the distributed processing of your Python code over multi-node clusters. You can create and run Ray jobs anywhere that you can run AWS Glue ETL jobs. This includes existing AWS Glue jobs, command line interfaces (CLIs), and APIs.</p><p>AWS Glue for Ray is generally available currently in the following AWS Regions: US East (Ohio), US East (N. Virginia), US West (Oregon), Asia Pacific (Tokyo), and Europe (Ireland).</p><p>More info: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-glue-ray-generally-available/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-glue-ray-generally-available/</a></p><h4>AWS Glue Data Quality is now generally available</h4><p><em>Released: Jun 6, 2023</em></p><p>AWS announces general availability of AWS Glue Data Quality, a capability that automatically measures and monitors data lake and data pipeline quality. AWS Glue Data Quality helps reduce the need for manual data quality work by using open-source <a href="https://github.com/awslabs/deequ"><strong>Deequ</strong></a> to evaluate rules and measure and monitor the data quality of petabyte-scale data lakes. It then recommends data quality rules to get started. You can update recommended rules or add new rules. If facing any issues with data quality, you can configure actions to alert users.</p><p>You can validate the data quality of Amazon Redshift, Apache Iceberg, Apache HUDI, and Delta Lake datasets that are cataloged in the AWS Glue Data Catalog. The quality results are published to Amazon EventBridge, simplifying how users are alerted and integrating data quality results with other applications.</p><p>AWS Glue Data Quality is generally available in all AWS Regions where AWS Glue is available. To learn more: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-glue-data-quality-generally-available/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-glue-data-quality-generally-available/</a></p><h4>Amazon Redshift Serverless now supports query scheduling and Single sign-on support</h4><p><em>Released: Jun 7, 2023</em></p><p>Amazon Redshift Serverless now allows scheduling of SQL queries. With scheduling, you can automate time sensitive or long running queries. You can utilize the scheduled queries with Amazon Redshift Query Editor V2 or Amazon Redshift Data API.</p><p>Amazon Redshift Serverless supports now also Single sign-on with Identity Providers (IdP). How it works is that you can pass a list of database roles granted to a user based on his/her IdP group membership. Redshift administrator then configures the Identity Provider(IdP) to pass in database roles by adding specific principal tags as SAML attributes. The sign-on support can be used with Amazon Redshift Query Editor V2, JDBC/ODBC clients, and Data API.</p><p>The features are available in all regions that support Amazon Redshift Serverless. Read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-redshift-query-scheduling-single-sign-on/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-redshift-query-scheduling-single-sign-on/</a></p><h4>Amazon QuickSight now supports APIs to automate and accelerate assets deployment</h4><p><em>Released: Jun 7, 2023</em></p><p>This is a long-awaited feature! QuickSight has earlier been it’s own island inside an AWS Account, and it has been extremely difficult to automate QuickSight assets’ deployment from one environment to another. It has been possible through API or CLI, but requiring heavy-duty coding in managing all dependencies between assets and the environments.</p><p>So now it is possible to export and import a QuickSight asset with all required dependencies. The feature supports all essential QuickSight assets such as dashboards, analysis, datasets including ingestion schedules, datasources, themes, and VPC configurations. You can even select whether to export the assets as plain JSON or as CloudFormation templates.</p><p>The new APIs are available with the Amazon QuickSight Enterprise edition in following AWS Regions where QuickSight is available: US East (N. Virginia and Ohio), US West (Oregon), Canada, Sao Paulo, Europe (Frankfurt, Ireland and London), Asia Pacific (Mumbai, Seoul, Singapore, Sydney and Tokyo).</p><p>Read the announcement here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-quicksight-apis-automate-accelerate-assets-deployment/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-quicksight-apis-automate-accelerate-assets-deployment/</a></p><h4>Amazon Athena for Apache Spark now supports custom Java libraries</h4><p><em>Released: Jun 8, 2023</em></p><p>Amazon Athena for Apache Spark was first released at re:Invent 2022 conference. Amazon Athena for Apache Spark is a feature of Amazon Athena lets you run interactive analytics on Apache Spark in under a second to analyze petabytes of data. So basically it is Athena but turbo-charged. With the new release, you can now include your own Java libraries and modules as JAR files in Spark workloads to connect to different data sources and run advance calculations using user defined functions to perform feature exploration.</p><p>The release includes also a set of reference connector packages for Amazon CloudWatch logs, CloudWatch metrics and Amazon DynamoDB so that you can use data from the services in your insights.</p><p>The new features are currently supported in 9 AWS regions where Amazon Athena for Apache Spark is available: US East (Ohio), US East (N. Virginia), US West (Oregon), Europe (Ireland), Europe (Frankfurt), Asia Pacific (Tokyo), Asia Pacific (Singapore), Asia Pacific (Sydney), and Asia Pacific (Mumbai). To learn more: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-athena-apache-spark-custom-java-libraries/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-athena-apache-spark-custom-java-libraries/</a></p><h4>Amazon Athena for Apache Spark now supports Apache Hudi, Apache Iceberg, and Delta Lake</h4><p><em>Released: Jun 8, 2023</em></p><p>Amazon Athena for Apache Spark now supports open-source data lake storage frameworks Apache Hudi 0.13, Apache Iceberg 1.2.1, and Linux Foundation Delta Lake 2.0.2. These frameworks simplify incremental data processing of large data sets using ACID (atomicity, consistency, isolation, durability) transactions and make it simpler to store and process large data sets in your data lakes.</p><p>Apache Iceberg, Apache Hudi and Delta Lake support is available in all AWS regions where Amazon Athena for Apache Spark is available. Read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-athena-apache-spark-hudi-iceberg-delta-lake/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-athena-apache-spark-hudi-iceberg-delta-lake/</a></p><h4>Amazon Kinesis Data Firehose adds support for data stream delivery to Amazon Redshift Serverless</h4><p><em>Released: Jun 19, 2023</em></p><p>This release is part of the “Zero-ETL” initiative announced by AWS CEO Adam Selipsky at re:Invent 2022. He stated that AWS is putting their efforts to connect the various AWS services so that builders can concentrate on creating value instead of spending their time trying to get services integrated.</p><p>With the new release, Amazon Kinesis Data Firehose can now deliver streaming data directly to Amazon Redshift Serverless. With few clicks, you can more easily ingest, transform, and reliably deliver streaming data into Amazon Redshift Serverless without building and managing your own data ingestion and delivery infrastructure.</p><p>Amazon Kinesis Data Firehose with Amazon Redshift Serverless is generally available in the regions here under Redshift Serverless API section.</p><p>Read more from the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-kinesis-data-firehose-data-stream-delivery-redshift-serverless/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-kinesis-data-firehose-data-stream-delivery-redshift-serverless/</a></p><h4>AWS Glue now can detect 250 sensitive entity types from over 50 countries</h4><p><em>Released: Jun 23, 2023</em></p><p>Sensitive data detection feature in AWS Glue can now detect over 250 sensitive entity types from 50 countries out-of-the-box — all Nordic countries included!</p><p>Sensitive data detection feature in AWS Glue identifies a variety of sensitive data elements like social security numbers, credit card numbers, names, driver license numbers and other entities. Once detected, customers can take actions to redact the sensitive information before writing records into their data repositories. Customers can also create custom detectors to detect entities specific to their organizations.</p><p>This feature is available in the commercial Regions as AWS Glue. Check the supported countries here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-glue-250-entity-types-50-countries/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-glue-250-entity-types-50-countries/</a></p><h4>AWS announces Amazon Aurora MySQL zero-ETL integration with Amazon Redshift (Public Preview)</h4><p><em>Released: Jun 28, 2023</em></p><p>Yes, another Zero-ETL announcement!</p><p>Amazon Aurora MySQL zero-ETL integration with Amazon Redshift is now available in public preview. The feature enables near real-time analytics and machine learning (ML) on petabytes of transactional data stored in Amazon Aurora MySQL-Compatible Edition. Data written into Aurora is available in Amazon Redshift within seconds, so you can quickly act on it without having to build and maintain complex data pipelines. Amazon Aurora MySQL zero-ETL integration with Amazon Redshift is available for Amazon Aurora Serverless v2 and Provisioned as well as Amazon Redshift Serverless and RA3 instance types.</p><p>Check the details: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-aurora-mysql-zero-etl-integration-redshift-public-preview/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-aurora-mysql-zero-etl-integration-redshift-public-preview/</a></p><h4>Amazon Athena now supports querying restored data in S3 Glacier</h4><p><em>Released: Jun 29, 2023</em></p><p>This is fun! You can now use Amazon Athena to query data stored in Amazon S3 Glacier (Glacier Flexible Retrieval &amp; Deep Archive storage classes supported). With this launch, you can use Athena to directly query restored data in the S3 Glacier for use cases such as log analytics and long-term trend analysis, saving you time by removing the need to move and duplicate data.</p><p>This feature is available with Athena Engine V3 in all Amazon Athena supported regions. To learn more: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-athena-querying-restored-data-s3-glacier/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-athena-querying-restored-data-s3-glacier/</a></p><h4>Amazon OpenSearch Service now supports OpenSearch version 2.7</h4><p><em>Released: Jul 10, 2023</em></p><p>You can now run features from open source OpenSearch version 2.7 in Amazon OpenSearch Service. Key improvements include introduction of a unified schema for OpenSearch, ability to add map visualisations to Dashboard panels, ability to filter geospatial data. The new version also includes support for five new security log types.</p><p>Read the annoncement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-opensearch-service-opensearch-version-2-7/">https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-opensearch-service-opensearch-version-2-7/</a></p><h4>Amazon Redshift announces automatic mounting of AWS Glue Data Catalog</h4><p><em>Released: Jul 25, 2023</em></p><p>Amazon Redshift released automatic mounting of AWS Glue Data Catalog, making it easier for customers to run queries in their data lakes. So no need to anymore create an external schema in Amazon Redshift to use the data lake tables cataloged in AWS Glue Data Catalog. Now, you can query data lake tables directly from Amazon Redshift Query Editor v2 or your favorite SQL editors. Again, a release that makes the life of data specialists much more fun!</p><p>Read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-redshift-automatic-mounting-aws-glue-data-catalog/">https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-redshift-automatic-mounting-aws-glue-data-catalog/</a></p><h4>AWS Glue Studio now supports Amazon Redshift Serverless</h4><p><em>Released: Jul 25, 2023</em></p><p>AWS Glue Studio now supports Amazon Redshift Serverless as a data source or target out-of-the-box. Earlir, only Amazon Redshift clusters were supported out-of-the-box in AWS Glue Studio. As serverless edition of Redshift takes the space among customers, this update is for sure well anticipated.</p><p>To learn more, here’s the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/aws-glue-studio-amazon-redshift-serverless/">https://aws.amazon.com/about-aws/whats-new/2023/07/aws-glue-studio-amazon-redshift-serverless/</a></p><h4>Amazon EMR Serverless now supports retrieving secrets from AWS Secrets Manager</h4><p><em>Released: Jul 27, 2023</em></p><p>A small but very important update. No more playing around with passwords and other secrets with your Amazon EMR Serverless. You can now get to the good side by utilizing AWS Secrets Manager for secrets like passwords, API keys an so forth.</p><p>Read here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-emr-serverless-retrieving-secrets-aws-secrets-manager/">https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-emr-serverless-retrieving-secrets-aws-secrets-manager/</a></p><h4>Amazon SageMaker announces a new direct integration with Salesforce Data Cloud</h4><p><em>Released: Aug 4, 2023</em></p><p>August started with an announcement on Amazon SageMaker having a direct integration with Salesforce Data Cloud. What it means is that now you can without any extra hassle access Salesforce Data Cloud from SageMaker with OAuth-2.0-based authentication to build, train and deploy ML models on SageMager. So you can easily train ML models with SalesForce data, and turbo-charge Salesforce Einstein with ML-driven wisdom.</p><p>Salesforce Data Cloud direct integration is supported in all AWS regions where SageMaker is available. To learn more, read the announcement here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/08/amazon-sagemaker-direct-integration-salesforce-data-cloud/">https://aws.amazon.com/about-aws/whats-new/2023/08/amazon-sagemaker-direct-integration-salesforce-data-cloud/</a></p><h4>AWS IAM Identity Center integration is now generally available for Amazon QuickSight</h4><p><em>Released: Aug 14, 2023</em></p><p>This is again one of those announcements that many have been waiting for! As said already earlier, QuickSight has been a quite isolated island inside AWS account, having its own user and group management. With this update, QuickSight administrators can now configure QuickSight to use IAM Identity Center to enable their users to login using their existing credentials. Administrators can select IAM Identity Center to configure QuickSight with their organization’s supported identity provider or with the IAM Identity Center identity store without requiring additional single sign-on configuration in QuickSight. Furthermore, they can use their identity provider groups to assign QuickSight roles (administrator, author and reader) to users.</p><p>This new feature is available in all AWS Regions where QuickSight and IAM Identity Center are available. Read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/08/aws-iam-identity-center-integration-amazon-quicksight/">https://aws.amazon.com/about-aws/whats-new/2023/08/aws-iam-identity-center-integration-amazon-quicksight/</a></p><h3>Serverless architecture &amp; app development</h3><h4>AWS Lambda adds support for Ruby 3.2</h4><p><em>Released: Jun 7, 2023</em></p><p>AWS Lambda now supports Ruby 3.2 as both a managed runtime and a container base image. The new Ruby version brings new features such as endless methods, a new Data class, improved pattern matching, and performance improvements. The Ruby 3.2 runtime is available in all regions where Lambda is available. The announcement can be found here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-lambda-support-ruby-3-2/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-lambda-support-ruby-3-2/</a></p><h4>Amazon SQS announces support for dead-letter queue redrive via AWS SDK or CLI</h4><p><em>Released: Jun 8, 2023</em></p><p>Amazon Simple Queue Service (SQS) announced support for dead-letter queue redrive via AWS SDK or Command Line Interface (CLI). The new feature is an enhanced capability to improve the dead-letter queue management by giving users a possibility to move messages from the dead-letter queue, and programmatically manage the lifecycle of the unconsumed messages at scale.</p><p>To programmatically automate dead-letter queue message redrive workflows, customers can now use the following actions:</p><ol><li>StartMessageMoveTask, to start a new message movement task from the dead-letter queue;</li><li>CancelMessageMoveTask, to cancel the message movement task;</li><li>ListMessageMoveTasks, to get 10 most recent message movement tasks for a specified source queue.</li></ol><p>See SQS Documentation for more information.</p><p>Dead-letter queue redrive via AWS SDK and CLI is available in all AWS Regions where Amazon SQS is available. Announcement can be found here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-sqs-dead-letter-queue-redrive-aws-sdk-cli/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-sqs-dead-letter-queue-redrive-aws-sdk-cli/</a></p><h4>AWS Step Functions adds integration for 7 services including Amazon VPC Lattice</h4><p><em>Released: Jun 15, 2023</em></p><p>The more integrations the better. AWS Step Functions really has a momentum, and now they released seven new integrations available through SDK. Overall, Step Functions have over 12,000 API actions from over 320 AWS services. That is really impressive and brings considerable advantage when building solutions that connect different AWS services. The new integrations include services such as Amazon VPC Lattice, Amazon CloudWatch Internet Monitor, AWS IoT TwinMaker, and Amazon OpenSearch Ingestion.</p><p>These enhancements are now generally available in all regions where AWS Step Functions is available. Please read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-step-functions-7-services-vpc-lattice/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-step-functions-7-services-vpc-lattice/</a></p><h4>AWS Step Functions launches Versions and Aliases</h4><p><em>Released: Jun 22, 2023</em></p><p>Yet another major update for AWS Step Functions. AWS Step Functions announced in July 2023 the availability of Versions and Aliases, improving resiliency for deployments of serverless workflows. The new set of capabilities makes it easier to set up continuous deployment, to help you iterate faster and release safely into production. You can now maintain multiple versions of your workflows, track which version was used for each execution, and create aliases that route traffic between workflow versions. You can deploy your workflows gradually using industry standard techniques such as blue-green and canary style deployments with fast rollbacks to your Step Functions workflows, increasing deployment safety and reducing downtime and risk.</p><p>More info here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-step-functions-versions-aliases/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-step-functions-versions-aliases/</a></p><h4>Announcing general availability for watchOS and tvOS support on AWS Amplify Library for Swift</h4><p><em>Released: Jun 27, 2023</em></p><p>Normally I tend to bypass news about UI development but this one really caught my eye. You can now use AWS Amplify to build applications for Apple Watch and Apple TV! In late June 2023, they announced general availability of watchOS and tvOS support for AWS Amplify for Swift (&gt;= v2.12.0). This launch enables developers to build cloud-connected apps for Apple Watch (watchOS) and Apple TV (tvOS) devices, in addition to iOS and macOS platforms.</p><p>Learn more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/watchos-tvos-aws-amplify-library-swift/">https://aws.amazon.com/about-aws/whats-new/2023/06/watchos-tvos-aws-amplify-library-swift/</a></p><h4>Amazon ECS now launches tasks faster alongside tasks with prolonged shutdown</h4><p><em>Released: Jun 30, 2023</em></p><p>Amazon ECS is a platform that takes care of running containerized services called tasks. If a task becomes unhealthy, it is stopped and a new task is launched based on your configurations. Sometimes shutdown of a task takes a long time, and new task launches could get blocked on the instance. To overcome the situation, Amazon ECS now enables faster task launches on container instances that have tasks with prolonged shutdown. This enables customers to scale their workloads faster and improve infrastructure utilization.</p><p>Previously, to enable higher task provisioning throughput, ECS optimistically considered instance resources (e.g. cpu, memory, ports) as free for launching new tasks whenever a running task transitioned to the stopping state. In cases when a stopping task takes a long time to shutdown, new tasks launches could get blocked on the instance. This happened because ECS Agent waited for all stopping tasks to shutdown before starting new tasks. With the new release from the end of June 2023, ECS Agent can start new tasks on an instance if requisite resources are available even if there are tasks pending shutdown, enabling faster task launches and improving infrastructure utilization.</p><p>The new experience is available for customers using Amazon ECS on EC2 or ECS Anywhere in all AWS regions on Amazon ECS Optimized AMIs with ECS Agent version 1.73.0 or later. To learn more, read the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-ecs-tasks-faster-prolonged-shutdown/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-ecs-tasks-faster-prolonged-shutdown/</a></p><h4>AWS Lambda now detects and stops recursive loops in Lambda functions</h4><p><em>Released: Jul 13, 2023</em></p><p>This is a small but yet very important update. I’m sure everyone who has by mistake developed a solution that recursively calls the same Lambda over and over again, has included this feature in their evening prayers.</p><p>AWS Lambda can now detect and stop recursive loops in Lambda functions. Lambdas are really popularly used to process events from sources like Amazon SQS and Amazon SNS. However, in certain scenarios, due to resource misconfiguration or code defect, a processed event may be sent back to the same service or resource that invoked the Lambda function. This can cause an unintended recursive loop, and result in unintended usage and costs for customers. With this launch, Lambda will stop recursive invocations between Amazon SQS, AWS Lambda, and Amazon SNS after 16 recursive calls.</p><p>When facing the recursive calls situation, Lambda will stop the 17th invocation and sends the event to a Dead-Letter Queue or on-failure destination, if configured. Customers will also receive an AWS Health Dashboard notification with troubleshooting steps.</p><p>Please see more details and available regions here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/aws-lambda-detects-recursive-loops-lambda-functions/">https://aws.amazon.com/about-aws/whats-new/2023/07/aws-lambda-detects-recursive-loops-lambda-functions/</a></p><h4>AWS Fargate enables faster container startup using Seekable OCI</h4><p><em>Released: Jul 17, 2023</em></p><p>Nice development again from ECS team! Customers running applications on Amazon ECS with AWS Fargate can now leverage Seekable OCI (SOCI), a technology open sourced by AWS that helps applications deploy and scale out faster by enabling the containers to start without waiting for the entire container image to be downloaded.</p><p>In many cases, waiting for the entire container image to download from container image repository is unnecessary as in many cases only a small portion of it is needed for startup. SOCI reduces this wait time by lazily loading the image data in parallel to application startup, enabling containers to start with only a fraction of the image.</p><p>To SOCI-enable your container images, start from this announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/aws-fargate-container-startup-seekable-oci/">https://aws.amazon.com/about-aws/whats-new/2023/07/aws-fargate-container-startup-seekable-oci/</a></p><h4>Amazon SNS now supports mobile push notifications in twelve new AWS regions</h4><p><em>Released: Jul 20, 2023</em></p><p>Mobile client communications just got more comprehensive as Amazon SNS mobile push notifications are now available in twelve additional AWS regions, including Africa (Cape Town), Asia Pacific (Hong Kong), Asia Pacific (Jakarta), Asia Pacific (Osaka), Canada (Central), Europe (London), Europe (Milan), Europe (Paris), Europe (Stockholm), Middle East (Bahrain), Middle East (UAE), and US East (Ohio). With this expansion, Amazon SNS now supports the ability to send mobile push notifications from 24 regions.</p><p>Amazon SNS can send mobile push notifications on your behalf to mobile devices and desktops using one of the following supported push notification services: Amazon Device Messaging (ADM), Apple Push Notification Service (APNs) for iOS and Mac OS X, Baidu Cloud Push (Baidu), Firebase Cloud Messaging (FCM) to Android devices, Microsoft Push Notification Service for Windows Phone (MPNS), and Windows Push Notification Services (WNS).</p><p>Read the news: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-sns-mobile-notifications-twelve-regions/">https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-sns-mobile-notifications-twelve-regions/</a></p><h4>AWS Lambda adds support for Python 3.11</h4><p><em>Released: Jul 27, 2023</em></p><p>Yet another Lambda programming language update: AWS Lambda now supports creating serverless applications using Python 3.11. Developers can use Python 3.11 as both a managed runtime and a container base image, and AWS will automatically apply updates to the managed runtime and base image as they become available.</p><p>The Python 3.11 runtime is available in all Regions where Lambda is available, except for China and GovCloud Regions. Read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/aws-lambda-python-3-11/">https://aws.amazon.com/about-aws/whats-new/2023/07/aws-lambda-python-3-11/</a></p><h4>Announcing preview of JSON protocol support for Amazon SQS</h4><p><em>Released: Jul 28, 2023</em></p><p>This is huge! The grand old SQS is turning from XML to JSON! At the end of July 2023, Amazon SQS announced a preview of JSON protocol support, enabling lower latency and improved performance for SQS customers. Based on AWS performance tests for a 5KB message payload, JSON protocol for Amazon SQS reduces end-to-end message processing latency by up to 23% and reduces application client side CPU and memory usage.</p><p>Amazon SQS customers can take advantage of lower latency when using the specified AWS SDK version. The specified SDK version achieves these latency gains by upgrading the default communication protocols to JSON wire protocol when they make SQS API requests. Customers can upgrade their AWS SDK to specified SDK version to use JSON protocol. Customers can also revert back to the AWS Query protocol by changing the SDK version.</p><p>For more information, here’s the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/json-protocol-support-amazon-sqs/">https://aws.amazon.com/about-aws/whats-new/2023/07/json-protocol-support-amazon-sqs/</a></p><h4>Amazon EventBridge Scheduler adds schedule deletion after completion</h4><p><em>Released: Aug 2, 2023</em></p><p>Amazon EventBridge Scheduler can invoke more than 270 AWS services and over 6,000 API operations, and scales out enabling scheduling of millions of tasks. No wonder it has become a de-facto scheduler for different time-based or recurring solutions on AWS platform. EventBridge Scheduler’s new delete upon completion helps manage and clean-up schedules that have completed its last invocation. It removes the need for manual processes or custom code to delete completed schedules saving you time and making it easier to scale.</p><p>If interested, start with the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/08/amazon-eventbridge-scheduler-deletion-completion/">https://aws.amazon.com/about-aws/whats-new/2023/08/amazon-eventbridge-scheduler-deletion-completion/</a></p><h3>AWS management &amp; DevOps &amp; IaC</h3><h4>Single Region Terraform support now available for AWS Control Tower Account Factory</h4><p><em>Released: Jun 8, 2023</em></p><p>AWS Control Tower is a great tool for managing AWS Organizations with multiple organization units, AWS accounts and related guardrails. With the new release, AWS Control Tower now offers a possibility to configure account templates with Terraform and utilize those templates when provisioning new or existing accounts from AWS Control Tower.</p><p>To get started, you can use the AWS-provided Terraform Reference Engine on GitHub that conﬁgures the code and infrastructure required for the Terraform open source engine. After the one-time setup, customers can define their account requirements using Terraform and deploy them to their accounts as part of the well-defined account factory workflow.</p><p>Read more from the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/single-region-terraform-control-tower-account-factory/">https://aws.amazon.com/about-aws/whats-new/2023/06/single-region-terraform-control-tower-account-factory/</a></p><h4>AWS Control Tower adds 10 new AWS Security Hub controls</h4><p><em>Released: Jun 12, 2023</em></p><p>Another news related to Control Tower! AWS has added 10 new AWS Security Hub detective controls to the AWS Control Tower controls library. These new controls target services such as Amazon APIGateway, AWS CodeBuild, Amazon Elastic Compute Cloud, Amazon Elastic Load Balancer, Amazon Redshift, Amazon SageMaker, and AWS WAF. These new controls help you meet control objectives, such as establish logging and monitoring, limiting network access and encrypting data at rest, enhancing your governance posture.</p><p>With this addition, AWS Control Tower now supports over 170 detective controls from AWS Security Hub. Read more from the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-control-tower-new-aws-security-hub-controls/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-control-tower-new-aws-security-hub-controls/</a></p><h4>Announcing general availability of AWS Control Tower’s integration with Security Hub</h4><p><em>Released: Jun 19, 2023</em></p><p>And one more to the AWS Control Tower! In July 2023 AWS announced the general availability of the integration between AWS Control Tower and AWS Security Hub. You can enable over 170 Security Hub detective controls that map to related control objectives from AWS Control Tower. With the new release, AWS Control Tower now detects when you disable a control from Security Hub which results in a ‘Drifted’ control state. With this drift detection capability, it is simpler for you to monitor the deployment state of your controls and take appropriate actions to manage the security posture of your AWS Control Tower environment.</p><p>The drift detection capability for Security Hub controls requires updating to the new version of the AWS Control Tower Landing Zone 3.2. The new Landing Zone verion also includes updates to the Region Deny control for multiple AWS services.</p><p>Read all about the announcement here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-control-tower-account-integration-security-hub/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-control-tower-account-integration-security-hub/</a></p><h4>AWS CloudFormation accelerates dev-test cycle with new ChangeSets parameter</h4><p><em>Released: Jun 20, 2023</em></p><p>Sometimes a small update is actually a BIG one. AWS CloudFormation launched a new parameter OnStackFailure for the CreateChangeSet API that allows customers to control the rollback behavior of ChangeSets. Customers use ChangeSets to preview the impact of a stack operation on active resources. With this launch, customers can modify the actions that CloudFormation will take when ChangeSet execution is unsuccessful.</p><p>Customers can set OnStackFailure to ROLLBACK, DELETE, or DO_NOTHING, where ROLLBACK is the default option for OnStackFailure and it reverts the stack to its last stable state if ChangeSet execution fails. When setting OnStackFailure to DELETE, CloudFormation deletes the new stack if ChangeSet execution fails. This eliminates the need for manual clean-up of stacks and allows customers to retry stack creation with CI/CD actions. DO_NOTHING preserves the state of the stack if ChangeSet execution fails.</p><p>To learn more about OnStackFailure, click here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-cloudformation-accelerates-dev-test-cycle-changesets-parameter/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-cloudformation-accelerates-dev-test-cycle-changesets-parameter/</a></p><h4>AWS CodeBuild now supports GitHub Actions</h4><p><em>Released: Jul 7, 2023</em></p><p>AWS CodeBuild customers can now use GitHub Actions during the building and testing of software packages. AWS CodeBuild is a fully managed continuous integration service that compiles source code, runs tests, and produces ready-to-deploy software packages. Customers’ CodeBuild projects are now able to leverage many of the pre-built actions available in GitHub’s marketplace. With CodeBuild’s integration with GitHub Actions, you can now extend your buildspec definition to invoke third-party solutions. There is no need to author and maintain custom integrations, or learn how integrate others’ solutions into your build process.</p><p>Read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/aws-codebuild-github-actions/">https://aws.amazon.com/about-aws/whats-new/2023/07/aws-codebuild-github-actions/</a></p><h4>Amazon CodeCatalyst now supports workflows triggered by GitHub pull requests</h4><p><em>Released: Jul 19, 2023</em></p><p>Another AWS DevOps tool integrating with GitHub! AWS announced in July 2023 their support for starting Amazon CodeCatalyst workflows based on pull request events in linked GitHub repositories. When a workflow is triggered by a GitHub-based pull request, users will also be able to see the name of the PR that triggered it in the CodeCatalyst workflows UI, and click a link that takes them directly to the pull request in GitHub.</p><p>To learn more, see the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-codecatalyst-workflows-triggered-github-pull-requests/">https://aws.amazon.com/about-aws/whats-new/2023/07/amazon-codecatalyst-workflows-triggered-github-pull-requests/</a></p><h4>AWS Control Tower launches additional proactive controls</h4><p><em>Released: Jul 24, 2023</em></p><p>Trust is good, control is better! In July 2024, AWS announced a launch of 28 new proactive controls in AWS Control Tower. This launch enhances AWS Control Tower’s governance capabilities with services such as Amazon CloudWatch, Amazon Neptune, Amazon ElastiCache, AWS Step Functions, and Amazon DocumentDB. Read more here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/aws-control-tower-proactive-controls/">https://aws.amazon.com/about-aws/whats-new/2023/07/aws-control-tower-proactive-controls/</a></p><h4>Accelerate your CloudFormation authoring experience with looping function</h4><p><em>Released: Jul 26, 2023</em></p><p>This might be the biggest announcement for AWS CloudFormation fans for time being. AWS CloudFormation announced at the end of July 2023 looping capability with Fn::ForEach intrinsic function. With Fn::ForEach, you can replicate parts of your templates with minimal lines of code.</p><p>To use Fn::ForEach you have to declare AWS::LanguageExtensions transform. The language extensions transform expands the functionality of the base CloudFormation JSON/YAML template language. With this launch, you can use Fn::ForEach in your Resources, Resource properties, Conditions, and Outputs sections of your templates. Here’s an example of CloudFormation YAML script that creates four different SNS Topics with different TopicNames:</p><pre>AWSTemplateFormatVersion: 2010-09-09<br>Transform: &#39;AWS::LanguageExtensions&#39;<br>Resources:<br>  &#39;Fn::ForEach::Topics&#39;:<br>    - TopicName<br>    - - Success<br>      - Failure<br>      - Timeout<br>      - Unknown<br>    - &#39;SnsTopic${TopicName}&#39;:<br>        Type: &#39;AWS::SNS::Topic&#39;<br>        Properties:<br>          TopicName: !Ref TopicName<br>          FifoTopic: true</pre><p>Read the whole announcement here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/07/accelerate-cloudformation-authoring-experience-looping-function/">https://aws.amazon.com/about-aws/whats-new/2023/07/accelerate-cloudformation-authoring-experience-looping-function/</a></p><h4>AWS CodePipeline now supports GitLab</h4><p><em>Released: Aug 14, 2023</em></p><p>Yet one more AWS DevOps service that integrate with popular 3rd party platform. You can now use your GitLab.com source repository to build, test, and deploy code changes using AWS CodePipeline. Connect your GitLab.com account using AWS CodeStar Connections, and use the connection in your pipeline to automatically start a pipeline execution on changes in your repository.</p><p>More here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/08/aws-codepipeline-supports-gitlab/">https://aws.amazon.com/about-aws/whats-new/2023/08/aws-codepipeline-supports-gitlab/</a></p><h3>Security</h3><h4>AWS WAF now supports Header Order match statement for request inspection</h4><p><em>Released: Jun 5, 2023</em></p><p>AWS WAF now supports the Header Order match statement, enabling customers to specify the order in which HTTP headers appear in a request. With this feature, customers can further strengthen their access control measures by verifying additional dimensions of request metadata.</p><p>There is no additional cost for using this feature, however, standard AWS WAF charges still apply. It is available in all AWS Regions where AWS WAF is available and for each supported service, including Amazon CloudFront, Application Load Balancer, Amazon API Gateway, AWS AppSync, and Amazon Cognito. To learn more, see here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-waf-header-order-match-statement-request-inspection/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-waf-header-order-match-statement-request-inspection/</a></p><h4>AWS KMS now supports importing asymmetric and HMAC keys</h4><p><em>Released: Jun 5, 2023</em></p><p>You can now import asymmetric and HMAC keys into AWS Key Management Service (AWS KMS) and use them within supported KMS-integrated AWS services and your own applications. Importing your own key gives you direct control over the generation, lifecycle management, and durability of your keys. You can control the availability of your imported keys by setting an expiration period, or deleting and re-importing them at any time. These controls help you meet your specific compliance requirements if you must generate and store copies of keys outside of AWS.</p><p>Importing your own keys to AWS KMS can also be useful in situation where keys need to exist in multiple environments, including hybrid (on-premise) and multi-cloud workflows. This lets you safely migrate workloads to AWS while expanding options on how you authorize, audit, and protect keys through AWS KMS.</p><p>Check more details at: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-kms-importing-asymmetric-hmac-keys/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-kms-importing-asymmetric-hmac-keys/</a></p><h4>AWS introduces container image signing</h4><p><em>Released: Jun 6, 2023</em></p><p>From early days of June 2023, AWS Signer and Amazon Elastic Container Registry (ECR) launched image signing, a new feature that enables you to sign and verify container images. You can now use AWS Signer to validate that only container images you have approved are deployed in your Amazon Elastic Kubernetes Service (EKS) clusters.</p><p>For more information: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-container-image-signing/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-container-image-signing/</a></p><h4>AWS announces AWS Payment Cryptography</h4><p><em>Released: Jun 12, 2023</em></p><p>An interesting new service release touching eCommerce space! AWS announced in June 2023 a new service called AWS Payment Cryptography. This service simplifies your implementation of cryptography operations used to secure data in payment processing applications for debit, credit, and stored-value cards in accordance with various payment card industry (PCI), network, and ANSI standards and rules. Financial service providers and processors can replace their on-premises hardware security modules (HSMs) with this elastic service and move their payments-specific cryptography and key management functions to the cloud.</p><p>AWS Payment Cryptography is currently available only in the following US Regions: US East (N. Virginia) and US West (Oregon).</p><p>Read more about the service launch here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-payment-cryptography/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-payment-cryptography/</a></p><h4>Amazon Verified Permissions is now generally available</h4><p><em>Released: Jun 13, 2023</em></p><p>Announced originally back in AWS re:Invent 2022, AW has now released the general availability of Amazon Verified Permissions, service for fine-grained authorization and permissions management for applications that you build. Verified Permissions uses <a href="https://www.cedarpolicy.com/"><strong>Cedar</strong></a>, an open-source language for access control, allowing you to define permissions as easy-to-understand policies. Use Verified Permissions to support role — and attribute-based access control in your applications.</p><p>Read more about Amazon Verified Permissions here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-verified-permissions-generally-available/">https://aws.amazon.com/about-aws/whats-new/2023/06/amazon-verified-permissions-generally-available/</a></p><h4>AWS IAM Identity Center now supports automated user provisioning from Google Workspace</h4><p><em>Released: Jun 13, 2023</em></p><p>This is big news for all organization using Google Workspace! It has earlier been possible to integrate Google Workspace to AWS IAM Identity Center and single sign-on to AWS services with Google identities, but managing those identities between Google and AWS has required either manual administrative work or additional custom integration service to be developed.</p><p>The new integration features help administrators simplify AWS access management across multiple accounts while maintaining familiar Google Workspace experiences for end users as they sign in. IAM Identity Center and Google Workspace use now Google auto-provisioning to securely provision users into IAM Identity Center, saving administrative time.</p><p>Read more about the new feature here: <a href="https://aws.amazon.com/about-aws/whats-new/2023/06/aws-iam-identity-center-automated-user-provisioning-google-workspace/">https://aws.amazon.com/about-aws/whats-new/2023/06/aws-iam-identity-center-automated-user-provisioning-google-workspace/</a></p><h4>Network Load Balancer now supports security groups</h4><p><em>Released: Aug 10, 2023</em></p><p>Network Load Balancers (NLB) now supports security groups, enabling you to filter the traffic that your NLB accepts and forwards to your application. Using security groups, you can configure rules to help ensure that your NLB only accepts traffic from trusted IP addresses, and centrally enforce access control policies. This improves your application’s security posture and simplifies operations.</p><p>To learn more, please read the announcement: <a href="https://aws.amazon.com/about-aws/whats-new/2023/08/network-load-balancer-supports-security-groups/">https://aws.amazon.com/about-aws/whats-new/2023/08/network-load-balancer-supports-security-groups/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd96c9b8234a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/whats-new-and-noteworthy-on-aws-summer-2023-edition-cd96c9b8234a">What’s new and noteworthy on AWS — Summer 2023 edition</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A practical guide for encrypting data with AWS KMS]]></title>
            <link>https://medium.com/nordhero/a-practical-guide-for-encrypting-data-with-aws-kms-327f8d1c49a6?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/327f8d1c49a6</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[aws-kms]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Teemu Niiranen]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 09:45:15 GMT</pubDate>
            <atom:updated>2023-04-28T09:45:15.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yk690XP7hZeC5VWafL7ZAA.jpeg" /></figure><p><em>I’ve always been interested in different ciphers and puzzles. Breaking the puzzle or following the code-breaking process in a Sherlock Holmes story or Dan Brown’s Da Vinci Code is fascinating. Even the history of data encryption is interesting and I recommend studying the classic ciphers, such as the </em><a href="https://en.wikipedia.org/wiki/Caesar_cipher"><em>Caesar Cipher</em></a><em> from ancient Rome. Of course, traditional ciphers from the pen-and-paper era are much simpler than modern computer-era algorithms, where you have the computer chip’s calculation power to scramble the message. In this article, I will demonstrate in practice how modern cloud-era encryption with AWS Key Management Service, or KMS, works.</em></p><h3>Key terminology</h3><p>First, some terminology, what is <em>encryption</em>? It takes unencrypted data, called <em>plaintext</em>, and performs an algorithmic cipher function with a secret value called <em>the key</em> to create a piece of encrypted <em>ciphertext</em>. KMS works exactly like this, and that’s why I think the name Key Management Service is somewhat misleading; KMS is actually a data encryption service. The name comes from the various options you have with the encryption key management compared to the leave-it-to-AWS mentality with other encryption alternatives, but the <em>key management</em> is a topic for an own article.</p><p>I would describe the KMS key as a logical container for the actual encryption key, also called <em>key material</em>. The container also contains other metadata such as key policy — the permissions for the key usage, deletion and rotation policy, etc. This article concentrates on the core encryption functionality — the key material and actual encryption and decryption commands. Steps we will take:</p><ul><li>We will create a KMS key, the container, to hold our custom key material</li><li>We will generate random key material with OpenSSL on your own machine, outside of AWS</li><li>We import the key material to the KMS key</li><li>We use our newly created key to encrypt and decrypt data</li><li>We go through the concept of data keys and envelope encryption, and encrypt and decrypt data with a data key</li></ul><h3>Prerequisites</h3><p>I’m using my Mac laptop with a Z shell terminal, so you might need to adjust the tooling for your operating system. The following is required:</p><ol><li>AWS account created; I use the eu-west-1 region (Ireland) in demonstrations, but you can select something closer to you.</li><li>AWS CLI tools installed and credentials configured for your AWS account.</li><li>OpenSSL installed. It’s used for generating the plaintext encryption key material and decrypting the key material with AWS offered public key. OpenSSL is also used for encrypting data with KMS-generated data keys.</li><li>Base64 command line tool installed to decode the AWS CLI responses.</li></ol><h3>Create a KMS key with custom key material</h3><ol><li>Go to KMS service in AWS Console and select “Customer managed keys” from the left, which is the section for your own keys (“AWS managed keys” is for keys created by AWS when you select an AWS managed option with different services).</li><li>From the top right corner, press the “Create key” button.</li></ol><figure><img alt="Create a KMS key with custom key material" src="https://cdn-images-1.medium.com/max/1024/0*RGCWD1R6fNCn92x-" /><figcaption><em>Create a KMS key with custom key material</em></figcaption></figure><h3>Step 1. Configure Key</h3><p>Choose “Symmetric” for a key type (same key used for encryption and decryption) and “Encrypt and decrypt” for key usage. Extend “Advanced options” and select:</p><ol><li>Key material origin: External (Import Key material)</li><li>Check “I understand the security, availability, and durability implications of using an imported key.” (I recommend checking the link provided for your responsibilities with the imported key material).</li><li>Regionality: Single-Region key</li></ol><p>Press the “Next” button in the lower right corner.</p><figure><img alt="Configure key" src="https://cdn-images-1.medium.com/max/1024/0*8p8KKxy0ChjnTb6k" /><figcaption>Configure key</figcaption></figure><h3>Step 2. Add labels</h3><p>We are using an alias to reference our key instead of the Amazon resource name, the ARN, of the KMS key. So add alias “mykey” to the key. Leave other fields as default and press the “Next” button in the lower right corner.</p><figure><img alt="Add an alias to the key" src="https://cdn-images-1.medium.com/max/1024/0*JfFQmTSsHWLSGRQW" /><figcaption><em>Add an alias to the key</em></figcaption></figure><h3>Step 3. Define key administrative permission</h3><p>Leave everything as default and press the “Next” button in the lower right corner.</p><p><strong>Note:</strong> This is for demonstration purposes only! The default policy allows the key usage for everyone inside the AWS account, so this is not a production recommendation.</p><h3>Step 4. Define key usage permissions</h3><p>Leave everything as default and press the “Next” button in the lower right corner.</p><h3>Step 5. Review</h3><p>Press the “Next” button in the lower right corner.</p><h3>Step 6. Download the wrapping key and import token</h3><p>After creating the key, you are most likely forwarded to the import key material page. You can download the wrapping key there, but all this is also located under your key: KMS -&gt; Customer managed keys -&gt; mykey -&gt; Key material.</p><figure><img alt="Download wrapping key and import token" src="https://cdn-images-1.medium.com/max/1024/0*JS_91l_9uBBAkmLb" /><figcaption><em>Download wrapping key and import token</em></figcaption></figure><p>Select the RSAES_OAEP_SHA_1 algorithm, default by the OpenSSL tool to encrypt the key in the next phase, and press the “Download wrapping key and import token” button.</p><h3>Generate the encryption key material</h3><p>This section will generate a plaintext random key and encrypt it with AWS wrapping key.</p><h3>Step 1. Extract the wrapping key and import token</h3><p>Extract the downloaded zip archive. At the time of writing, the file name was ImportParameters.zip.</p><h3>Step 2. Generate the plaintext random key</h3><p>You need the OpenSSL command line tool installed on your machine for this step. Generate 32 pseudo-random bytes with the rand command and output the result to the file named PlaintextKeyMaterial.bin with the following command:</p><pre>openssl rand -out PlaintextKeyMaterial.bin 32</pre><h3>Step 3. Encrypt the plaintext key with AWS wrapping key</h3><p>We are encrypting next your plaintext key with a wrapping key, a 2048-bit RSA public key, which is unique to your AWS account. When AWS KMS receives your encrypted key material, it uses the corresponding private key to decrypt it (asymmetric encryption). Command:</p><pre>openssl rsautl -encrypt \<br>-in PlaintextKeyMaterial.bin \<br>-oaep \<br>-inkey wrappingKey_… \<br>-keyform DER \<br>-pubin \<br>-out EncryptedKeyMaterial.bin</pre><p>Replace the “wrappingKey_…” with your correct file name from the extracted zip archive. The file name should start with “wrappingKey_”. It will create a new file named EncryptedKeyMaterial.bin.</p><h3>Upload the encrypted key material back to AWS with the import token</h3><p>Back to the AWS Console and your key’s “Key material” tab! This time choose the “Upload key material” button.</p><h3>Step 1. Upload wrapped key material</h3><p>First, press the “Choose file” button under the “Wrapped key material title” and select the EncryptedKeyMaterial.bin file.</p><p>Next, press the “Choose file” button under the “Import token” title and select the extracted file starting with “importToken_”.</p><p>Finally, press the “Upload key material” button in the lower right corner.</p><figure><img alt="Upload key material" src="https://cdn-images-1.medium.com/max/1024/0*KLae23pNkvwjuc1T" /><figcaption><em>Upload key material</em></figcaption></figure><h3>Now let’s encrypt some data!</h3><p>Next, we will demonstrate the encryption and decryption features with AWS Command Line Interface.</p><h3>Step 1. Create a text file to encrypt with your favorite editor</h3><p>Name it my_secret_message.txt and add “This is my secret message” as content.</p><h3>Step 2. Encrypt the contents of the file</h3><p>Next, we encrypt the content and output the resulting ciphertext to a new file named my_encrypted_secret_message.enc. The result is on top of encryption base64 encoded, so we are also piping the result to the base64 command for decoding:</p><pre>aws kms encrypt \<br>--key-id alias/mykey \<br>--plaintext fileb://my_secret_message.txt \<br>--query CiphertextBlob \<br>--output text \<br>| base64 -d &gt; my_encrypted_secret_message.enc</pre><p>To validate that the content is a ciphertext, so gibberish, you can check the file contents:</p><pre>cat my_encrypted_secret_message.enc</pre><h3>Step 3. Decrypt the ciphertext</h3><p>To decrypt, we are using the decrypt command. Again the result is base64 encoded, so piping is needed:</p><pre>aws kms decrypt \<br>--ciphertext-blob fileb://my_encrypted_secret_message.enc \<br>--query Plaintext \<br>--output text \<br>| base64 -d &gt; my_decrypted_secret_message.txt</pre><p>To validate, check the file contents:</p><pre>cat my_decrypted_secret_message.txt</pre><p>Note that no key identifier or alias is specified this time! AWS KMS stores the key identifier in the ciphertext blob. If you delete the KMS key, this link is gone, and you can’t decrypt your data anymore. If you want to change the logical KMS key, or the imported key material, create a new KMS key and use the re-encrypt operation with a new KMS key to change the metadata — this is also known as <em>manual key rotation</em>. Imported key material is permanently associated with your KMS key. Because of this destructive and dangerous nature, KMS keys have a waiting period of 7–30 days, defaulting 30 days, before the deletion.</p><p><strong>Caveats:</strong> You called an HTTPS endpoint of the KMS and requested encryption in the AWS multi-tenant cluster of hardware security modules. So we have a network latency factor to consider. Also, there is a limit of 4 KB to encrypt. For both limitations, the answer is a data key — so-called <em>envelope encryption</em>. But before that, let’s play a little with the key material, the actual encryption key.</p><h3>Let’s delete the key material!</h3><p>An exciting advantage or opportunity of using your own key material is the possibility to delete the actual encryption key from the logical KMS key container, instantly removing the ability to decrypt the data. You can then later on import back the original key material, it needs to be the original or the import fails, and gain back the ability to decrypt the data! Let’s demonstrate this part.</p><h3>Step 1. Delete the key material</h3><p>Go back to the AWS console and press the “Delete key material” button on the key material tab of the page.</p><figure><img alt="Delete key material" src="https://cdn-images-1.medium.com/max/1024/0*I5y7uxQQdqlZDoAI" /><figcaption><em>Delete key material</em></figcaption></figure><p><strong>Note the warning:</strong> “Deleting key material makes all data encrypted under the AWS KMS key unrecoverable unless you re-import the same key material into the same KMS key. The KMS key is not affected by this operation.”</p><p>Confirm by checking the box next to the label “Confirm that you want to delete this key material.” Press the “Delete key material” button.</p><h3>Step 2. Try to decrypt our secret message</h3><p>Let’s copy-paste the same CLI decrypt command that we used before:</p><pre>aws kms decrypt \<br>--ciphertext-blob fileb://my_encrypted_secret_message.enc \<br>--query Plaintext \<br>--output text \<br>| base64 -d &gt; my_decrypted_secret_message.txt</pre><p>You should now get an error message similar to this:</p><blockquote>An error occurred (KMSInvalidStateException) when calling the Decrypt operation: arn:aws:kms:eu-west-1:xxxxxxxxxxxx:key/a73c3a7f-46f8–4477-a0fa-19a9690c0bfb is pending import.</blockquote><h3>Step 3. Import the material back</h3><p>Import the material back to your KMS key as described in the “Upload the encrypted key material back to AWS with the import token.” section.</p><h3>Step 4. Try to decrypt it again</h3><p>It takes a little moment for the status to change back to Enabled, but you should quickly be able to decrypt your data again.</p><h3>Envelope Encryption</h3><p>Envelope encryption is the practice of encrypting plaintext data with a data key and then encrypting the data key under another key. We can then store the encrypted data key together with the actual data. That’s why it’s called envelope encryption — both are held in the same physical place! You can use AWS KMS to generate, encrypt, and decrypt the data keys that you use outside of AWS KMS to encrypt your data. Remember that KMS keys are created in AWS KMS and never leave AWS KMS unencrypted!</p><h3>Step 1. Generate the data key</h3><pre>aws kms generate-data-key --key-id alias/mykey --key-spec AES_256</pre><p>Supported algorithms (key-spec parameter) are AES_128 and AES_256, 128-bit, and 256-bit length AES keys. The response contains both plaintext and ciphertext versions of the key, but again both are base64 encoded. The response is a JSON document that has a similar structure to this:</p><pre>{<br>  &quot;CiphertextBlob&quot;: &quot;AQIDAHhg…==&quot;,<br>  &quot;Plaintext&quot;: &quot;cRN7COdX…=&quot;,<br>  &quot;KeyId&quot;: &quot;arn:aws:kms:eu-west-1:xxxxxxxxxxxx:key/a73c3a7f-46f8–4477-a0fa-19a9690c0bfb&quot;<br>}</pre><p>Remember that the plaintext version should never be stored; it’s there, so you can straight encrypt the data without calling the KMS service for data key decryption. The plaintext version should be discarded after use. I will do a quick demonstration by storing both in to own files, but this is not the best practice. At least delete the plaintext files after use!</p><h3>Step 2. Store keys as files</h3><p>Copy the value of the CiphertextBlob property to a file named ciphertext_datakey.base64 and the value of the Plaintext property to plaintext_datakey.base64.</p><h3>Step 3. Decode the keys</h3><p>Decode the keys with base64 and store them to new files:</p><pre>base64 -d -i plaintext_datakey.base64 &gt; plaintext_datakey<br>base64 -d -i ciphertext_datakey.base64 &gt; ciphertext_datakey</pre><h3>Step 4. Encrypt the data outside AWS using OpenSSL</h3><pre>openssl enc -e -aes256 -kfile plaintext_datakey \<br>-in my_secret_message.txt \<br>-out my_secret_message.enc</pre><h3>Step 5. Decrypt the data using OpenSSL</h3><pre>openssl enc -d -aes256 -kfile plaintext_datakey \<br>-in my_secret_message.enc \<br>-out new_plaintext_message.txt</pre><p>Validate the content of new_plaintext_message.txt</p><pre>cat new_plaintext_message.txt</pre><h3>Step 6. Later on, decrypt the data key</h3><p>We can decrypt the data key stored with our encrypted data with the KMS decrypt command. Again the result is base64 encoded, so we are piping it for decoding:</p><pre>aws kms decrypt \<br>--ciphertext-blob fileb://ciphertext_datakey \<br>--query Plaintext \<br>--output text | base64 -d &gt; plaintext_datakey_2</pre><p>And you are ready to decrypt the data like in step 5 with your new plaintext_datakey_2 file!</p><h3>Summary</h3><p>We covered the AWS KMS service’s basic building blocks of the core functionality — encryption and decryption using the encryption key. We didn’t cover how other AWS services use the KMS when you select it as an encryption option; there’s some variety. We didn’t discuss the various other key material options or key management. We didn’t discuss the auditability of the key usage, which is the key feature in a compliance sense. Hopefully, this still helps to clarify the core of the KMS and helps diving into these other topics.</p><p>Encryption using your key material brings you a lot of new challenges because you are responsible for keeping the material safe and backed up. Also, the randomness of the material is not trivial, and dedicated hardware has been developed to calculate these cryptographic operations, usually called Hardware Security Modules (HSM). The external key store is the latest addition to key material options, and I think it’s the preferred choice if you need to have your key material generated outside AWS. If you don’t have such compliance requirements, consider the AWS-managed options.</p><h3>References</h3><p><a href="https://docs.aws.amazon.com/kms/latest/developerguide/overview.html">https://docs.aws.amazon.com/kms/latest/developerguide/overview.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=327f8d1c49a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/a-practical-guide-for-encrypting-data-with-aws-kms-327f8d1c49a6">A practical guide for encrypting data with AWS KMS</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AWS deployments with Terragrunt]]></title>
            <link>https://medium.com/nordhero/mastering-aws-deployments-with-terragrunt-c830e0f69d14?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/c830e0f69d14</guid>
            <category><![CDATA[terragrunt]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Pekka Malmirae]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 05:50:08 GMT</pubDate>
            <atom:updated>2022-09-16T07:26:11.083Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Terraform</em></strong><em> offers a robust, declarative way to describe your cloud infrastructure as code. And unlike some other IaC tools, Terraform also does a decent job comparing differences between your current version of IaC code, the last deployment stored in Terraform state, and the current state of the deployed cloud resources. But when it comes to managing and deploying multiple copies of the same infrastructure, an additional tool is needed. And that tool has the name </em><strong><em>Terragrunt</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxCA5ydmj4CZ2ikEYNBD0g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NASA</a> on <a href="https://unsplash.com/s/photos/nasa-q1p7bh3shj8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, I assume that you understand the basics of Terraform. If you’d like to check the Terraform basics first, this article is for you (article in Finnish): <a href="https://www.nordhero.com/posts/google-cloud-terraformilla/">https://www.nordhero.com/posts/google-cloud-terraformilla/</a>.</p><p>Alright. So first, let’s get two acronyms right before moving forward.</p><p><strong>IaC</strong> means Infrastructure as Code. The idea is that you don’t have to manually log in to the AWS Console and set up the infrastructure by selecting services in the console and clicking the systems up. The manual approach could be acceptable if you only had one environment for testing purposes. But if you would need to set it up again, or if you had more than one environment that should have the same resources and configurations (e.g., development, testing, and production environments), you shouldn’t try to manage those manually. Instead, you probably would like to use an IaC tool like Terraform to set up the infrastructure configurations as code to be deployed quickly and repeatably.</p><p><strong>DRY</strong> means Don’t Repeat Yourself. The downside of a declarative language like Terraform is that it’s not that easy to manage variations of the same code if you need the deploy the same infrastructure with a few different flavors depending on the use case. You quickly end up making multiple copies of the infrastructure code to manage various similar kinds of deployments. And that’s what Terragrunt is here to solve.</p><h3>How to keep Terraform code DRY?</h3><p>The key idea of Terragrunt is to write needed infrastructure code only once utilizing Terraform (TF files) and to separate environment-specific values as variables to be defined in Terragrunt configuration files (HCL files). I prefer a folder structure where I have the Terraform infrastructure code in the project’s <strong>infrastructure</strong> folder and Terragrunt configurations in the <strong>deployments</strong> folder.</p><p>A typical Terragrunt configuration setup is to save environment-specific configuration files in a three-level folder structure that describes the AWS Accounts, AWS Regions under the accounts, and deployable environments under the regions. Each folder level can contain Terragrunt configuration files for account, region, or environment-specific variables.</p><p>The following figure illustrates an imaginary deployments folder setup where one production account has production environments both in the us-east-1 (N. Virginia) and eu-central-1 (Frankfurt) regions and an additional demo environment in the eu-central-1 region. There’s also a staging environment on its own account utilizing the eu-central-1 region and a dev account with a similar setup. As I’m working with both feature development and performance testing, I have two environments deployed on my sandbox account. The sandbox-pekka-perftest environment has production-kind infrastructure resources configured on it — for example, having larger Fargate clusters or heavier EC2 instances with provisioned IOPS SSD volumes. As the performance testing environment has more resources, it also generates more costs. Therefore it is easy for me to tear down the stack when the test session ends and re-deploy it again when needed without affecting the standard sandbox environment residing on the same account and region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*ytnQG6tItmXKfst6.jpg" /><figcaption><em>An example deployment folder structure for Terragrunt</em></figcaption></figure><h3>Install Terraform and Terragrunt</h3><p>First, install Terraform on your desktop. I have macOS, and I like to use the Homebrew package manager (<a href="https://brew.sh/">https://brew.sh/</a>) for the job, so the commands below use <strong>brew</strong>. There are multiple ways to install the Terraform on different operating systems, and you can find the right ingredients from <a href="https://www.terraform.io/">https://www.terraform.io/</a>.</p><p>Here are the magic commands for macOS/Homebrew installation of Terraform:</p><pre>brew tap hashicorp/tap<br>brew install hashicorp/tap/terraform<br>terraform -version</pre><p>If you get a Terraform version info, you have succeeded in the installation.</p><p>And next one goes for Terragrunt (more installation options at <a href="https://terragrunt.gruntwork.io/):">https://terragrunt.gruntwork.io/):</a></p><pre>brew install terragrunt<br>terragrunt -version</pre><p>If you get the Terragrunt version number, you are good to go to the next phase.</p><h3>The infrastructure with Terraform IaC</h3><p>Let’s first create our infrastructure code. In our example I have a small stack including only one S3 Bucket with data encryption utilizing a customer-managed KMS Key. I have included only a few lines of Terraform code here to point out how Terraform works with Terragrunt. If you wish to try out with my example code, you can find the whole Terraform code example in the <a href="https://github.com/pmalmirae/terragrunt-demo">GitHub repository</a>.</p><p>First, create a new folder on your computer for our project (you can name it as you wish) and create a folder <strong>infrastructure</strong> in the project root. Under the newly created folder, add all needed Terraform files. For example here is the code for the S3 bucket configurations (in file <strong>infrastructure/s3.tf</strong>):</p><pre>/******************************<br>S3 bucket with encryption and public access block configurations <br>******************************/</pre><pre># The S3 bucket<br>resource &quot;aws_s3_bucket&quot; &quot;demo_bucket&quot; {<br>  bucket_prefix = &quot;${var.name}-${var.environment}-demo-bucket&quot;<br>}</pre><pre># Let&#39;s make the bucket private<br>resource &quot;aws_s3_bucket_acl&quot; &quot;demo_bucket_acl&quot; {<br>  bucket = aws_s3_bucket.demo_bucket.id<br>  acl    = &quot;private&quot;<br>}</pre><pre>/******************************<br>More configurations in the actual file, please check the Github repo.<br>******************************/</pre><p>As you see, I have used Terraform variables <strong>name</strong> and <strong>environment</strong> in the bucket’s prefix. That will let us automatically change the bucket prefix per environment. And as you might already guess, those variables are managed with Terragrunt.</p><p>In addition to utilizing variables in Terraform code, we need to define the variables from Terraform perspective. Create a file named <strong>infrastructure/vars.tf</strong>:</p><pre>/******************************<br>Variables to be used with the infrastructure code<br>******************************/</pre><pre>variable &quot;name&quot; {<br>  type        = string<br>  description = &quot;Name of the company or the platform to build, etc.&quot; <br>}</pre><pre>variable &quot;environment&quot; {<br>  type        = string<br>  description = &quot;Name of the environment/stack&quot;<br>}</pre><pre>/******************************<br>More variables in the actual file, please check the Github repo<br>******************************/</pre><p>Next to the main course!</p><h3>Set up Terragrunt configurations</h3><p>Let’s start the Terragrunt part by creating a folder named <strong>deployments</strong> in the project root. As you remember from the DRY chapter, a typical Terragrunt configuration set has a three-level folder structure: <em>account/region/environment</em>. So, create the folder structure under the <strong>deployments</strong> folder for your first environment. In my example, I have created a folder structure <strong>deployments/sandbox-pekka/eu-central-1/sandbox-pekka</strong>.</p><p>The <strong>deployments/terragrunt.hcl</strong> file is a key configuration file for Terragrunt. Please go ahead and create the file with the following contents:</p><pre>/******************************<br>TERRAGRUNT CONFIGURATION<br>******************************/</pre><pre>locals {<br>  # Load account, region and environment variables <br>  account_vars      = read_terragrunt_config(find_in_parent_folders(&quot;account.hcl&quot;))<br>  region_vars       = read_terragrunt_config(find_in_parent_folders(&quot;region.hcl&quot;))<br>  environment_vars  = read_terragrunt_config(find_in_parent_folders(&quot;env.hcl&quot;))</pre><pre>  # Extract the variables we need with the backend configuration<br>  aws_region      = local.region_vars.locals.aws_region<br>  environment     = local.environment_vars.locals.environment<br>  state_bucket    = local.environment_vars.locals.state_bucket<br>  dynamodb_table  = local.environment_vars.locals.dynamodb_table<br>}</pre><pre>/******************************<br>Configure the Terragrunt remote state to utilize a S3 bucket and state lock information in a DynamoDB table. <br>And encrypt the state data.<br>******************************/<br>remote_state {<br>  backend   = &quot;s3&quot;<br>  generate  = {<br>    path      = &quot;backend.tf&quot;<br>    if_exists = &quot;overwrite&quot;<br>  }<br>  config    = {<br>    bucket         = &quot;${local.state_bucket}&quot;<br>    key            = &quot;${path_relative_to_include()}/terraform.tfstate&quot;<br>    region         = &quot;${local.aws_region}&quot;<br>    encrypt        = true<br>    dynamodb_table = &quot;${local.dynamodb_table}&quot;<br>  }<br>}</pre><pre>/******************************<br>Combine all account, region and environment variables as Terragrunt input parameters.<br>The input parameters can be used in Terraform configurations as Terraform variables.  <br>******************************/<br>inputs = merge(<br>  local.account_vars.locals,<br>  local.region_vars.locals,<br>  local.environment_vars.locals,<br>)</pre><p>The <strong>deployments/terragrunt.hcl</strong></p><ul><li>loads account, region, and environment level variables (we will create those files next)</li><li>extracts the variables that are needed in Terragrunt backend configurations</li><li>configures the Terragrunt backend to utilize the state bucket and state lock table</li><li>merges all variables as input parameters to be fed to Terraform.</li></ul><p>Next, let’s create the needed files for Terragrunt variables. Please create the following .hcl files and replace the folder names and variable values with your own <em>account/region/environment</em> information:</p><p><strong>deployments/sandbox-pekka/account.hcl:</strong></p><pre># Set AWS Account -wide variables<br>locals {<br>  account_name   = &quot;sandbox-pekka&quot;<br>  aws_account_id = &quot;REPLACE_WITH_YOUR_ACCOUNT_ID&quot;<br>}</pre><p><strong>deployments/sandbox-pekka/eu-central-1/region.hcl:</strong></p><pre># Set common variables for the AWS Region<br>locals {<br>  aws_region = &quot;eu-central-1&quot;<br>}</pre><p><strong>deployments/sandbox-pekka/eu-central-1/sandbox-pekka/env.hcl:</strong></p><pre># Set common variables for the environment<br>locals {<br>  name           = &quot;nordhero&quot;<br>  environment    = &quot;sandbox-pekka&quot;<br>  state_bucket   = &quot;nordhero-terragrunt-demo-state-sandbox-pekka&quot; # Replace with your preferred unique S3 bucket name <br>  dynamodb_table = &quot;nordhero-terragrunt-demo-locks-sandbox-pekka&quot; # Replace with your preferred dynamodb table name<br>}</pre><p>The <strong>name</strong> and <strong>environment</strong> variables will be utilized in the Terraform code created in the chapter <em>The infrastructure with Terraform IaC</em>. And the <strong>state_bucket</strong> and <strong>dynamodb_table</strong> values will be used to create the Terragrunt state bucket and state lock table for the environment.</p><p>And one last thing to the Terragrunt configurations. Create one more folder and file: <strong>deployments/sandbox-pekka/eu-central-1/sandbox-pekka/infra/terragrunt.hcl</strong>:</p><pre>/******************************<br>TERRAGRUNT CONFIGURATIONS<br>******************************/</pre><pre>/******************************<br>Include the root terragrunt.hcl configurations gathering together<br>the needed variables and backend configurations<br>******************************/<br>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}</pre><pre>locals {<br>  # Expose the base source path<br>  base_source = &quot;${dirname(find_in_parent_folders())}/..//infrastructure&quot;<br>}</pre><pre># Set the location of Terraform configurations<br>terraform {<br>  source = local.base_source<br>}</pre><p>This is the Terragrunt configuration file that we will execute later on. What it does is that it first takes in the common <strong>terragrunt.hcl</strong> configurations we created in the <strong>deployments</strong> folder and then configures the Terraform infrastructure folder to use with the deployment. As you see, it is possible to configure different versions of Terraform code, having different <strong>base_source</strong> to use with different environments (not that DRY approach, thou). Or, more importantly, you could split your Terraform code into multiple modules and select which modules to deploy to this particular environment. For example, if your full stack includes the OpenSearch service (formerly ElasticSearch), but you don’t need OpenSearch in your development sandbox, you could choose to deploy all other modules but not to deploy the module that contains OpenSearch configurations.</p><p>Now we are ready. You should now have the following kind of folder structure and following files in your <strong>deployments</strong> folder:</p><ul><li>deployments/terragrunt.hcl</li><li>deployments/sandbox-pekka/account.hcl</li><li>deployments/sandbox-pekka/eu-central-1/region.hcl</li><li>deployments/sandbox-pekka/eu-central-1/sandbox-pekka/env.hcl</li><li>deployments/sandbox-pekka/eu-central-1/sandbox-pekka/infra/terragrunt.hcl</li></ul><h3>Deploying with Terragrunt</h3><p>Deploying the infrastructure with Terragrunt is very similar to deploying with Terraform. You have the same commands in use. The main difference is that you need to run the Terragrunt commands from the respective <strong>deployments/your_account/your_region/your_env/infra</strong> folder you wish to deploy. So please cd to your infra folder:</p><pre>cd deployments/sandbox-pekka/eu-central-1/sandbox-pekka/infra</pre><p>Before running any Terragrunt commands, we must ensure we have successfully connected to the right AWS Account with AWS CLI. If you don’t already have the AWS CLI configured, please follow the instructions: <a href="http://docs.aws.amazon.com/cli/latest/userguide/">http://docs.aws.amazon.com/cli/latest/userguide/</a>. After configuring AWS CLI, test the connection by running the following command:</p><pre>aws sts get-caller-identity</pre><p>You should get a response containing your UserId, AWS Account Id, and an IAM Role ARN if successfully connected. Check once more that the Account is the one you desire to deploy infrastructure to and that you have the same information in your <strong>deployments/your_account/account.hcl</strong> file.</p><p>Next, we are ready to rock ‘n roll. Let’s first initialize the Terragrunt:</p><pre>terragrunt init</pre><p>When running the init for the first time, Terragrunt recognizes that the S3 state bucket does not yet exist and asks whether Terragrunt should create the bucket for you. Please allow Terragrunt to create the state bucket. Terragrunt will automatically create also the state lock DynamoDB table at the same time. When everything is ready, you should receive a green response stating that the backend has been successfully configured to use S3 and that Terraform has been successfully initialized to use the hashicorp/aws provider plugin.</p><p>Next, let’s plan our deployment and save the plan in the <strong>tfplan</strong> file:</p><pre>terragrunt plan -out tfplan</pre><p>Terragrunt will now describe the resources it plans to create. Please check that there are six resources to be added and that no errors or warnings have been raised. If everything looks ok, we can next deploy the infrastructure plan saved in the <strong>tfplan</strong> file:</p><pre>terragrunt apply &quot;tfplan&quot;</pre><p>You should now get a green message stating “Apply complete!” with the number of resources created, changed and destroyed.</p><p>Congratulations! You have now successfully set up Terragrunt and deployed your first infrastructure stack.</p><h3>Deploying the infrastructure to another region</h3><p>Now to the desserts. The benefits of Terragrunt start accumulating when setting up the next copy of the infrastructure. Let’s assume we would like to set up the same infrastructure for the same account but in a different region. The greatness is that we don’t need to touch the <strong>infrastructure/*.tf</strong> files at all.</p><p>What we need to do is:</p><ol><li>Copy the current <strong>deployments/your_account/your_region</strong> folder and rename the copied folder with the new region name, e.g. <strong>eu-north-1</strong></li><li>Edit the <strong>deployments/your_account/new_region/region.hcl</strong> file and replace <strong>aws_region</strong> value with the new region name</li><li>Edit <strong>deployments/your_account/new_region/your_environment/env.hcl</strong> file and replace the <strong>state_bucket</strong>, and <strong>dynamodb_table</strong> values with new bucket and table names to store the state of the new environment</li><li>Cd to the <strong>deployments/your_account/new_region/your_environment/infra</strong> folder and repeat the <strong>terragrunt init/plan/apply</strong> commands</li></ol><p>Now try it yourself!</p><h3>Last lines</h3><p>That was a nice ride! We needed to create a bunch of configuration files. Still, in a typical development project where you have multiple sandbox environments and a deployment pipeline with development, staging, production, and demo environments, it starts to pay off quickly. And in real life, you would probably like to automate the deployment pipeline from your source code repository so that, depending on the repository branch, you would automatically select the deployment folder to use with Terragrunt deployment.</p><p>NordHero is there to help you set up the infrastructure, manage the multi-environment platforms and automate the deployments with your selected GitOPS platform. Give us a call/email/LinkedIn message if you would like to hear more!</p><p>P.S. You can download the whole demo project in the <a href="https://github.com/pmalmirae/terragrunt-demo">Github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c830e0f69d14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/mastering-aws-deployments-with-terragrunt-c830e0f69d14">Mastering AWS deployments with Terragrunt</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical sustainability in AWS cloud]]></title>
            <link>https://medium.com/nordhero/practical-sustainability-in-aws-cloud-a02fc818a78a?source=rss----7e48f9ef5db8---4</link>
            <guid isPermaLink="false">https://medium.com/p/a02fc818a78a</guid>
            <category><![CDATA[climate-action]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[carbon-footprint]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sustainability]]></category>
            <dc:creator><![CDATA[Pekka Malmirae]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 07:44:34 GMT</pubDate>
            <atom:updated>2022-04-04T07:44:33.921Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Sustainability has become an essential factor of almost all businesses, and there are things we all can affect, whether it relates to our everyday or work life. Sustainability was also raised to AWS Well-Architected framework as the new sixth pillar, stating that sustainability is at least partly an architectural challenge when it comes to IT systems. This article summarizes a few key actions every AWS customer can take to drive sustainability with cloud workloads.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FobiewlkmRn2o9v5JK6DIw.jpeg" /></figure><h3>Who’s responsible for carbon emissions in the cloud?</h3><p>The AWS Well-Architected Framework organizes the carbon emissions related to cloud computing to the following scopes:</p><ul><li>Scope 1: All direct emissions from the activities of an organization or under its control. For example, fuel combustion by data center backup generators.</li><li>Scope 2: Indirect emissions from electricity purchased and used to power data centers and other facilities. For example, emissions from commercial power generation.</li><li>Scope 3: All other indirect emissions from activities of an organization from sources it doesn’t control. AWS examples include emissions related to data center construction and the manufacture and transportation of IT hardware deployed in data centers.</li></ul><p>Each workload deployed generates a fraction of the total AWS emissions from each of the previous scopes. The actual amount varies per workload and depends on several factors, some depending on our choices, and others are more related to AWS’s choices. As for some other pillars in AWS Well-Architected Framework, the sustainability pillar also has its <a href="https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/the-shared-responsibility-model.html">shared responsibility model</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2qSok-sncNjlmTPr.jpeg" /></figure><p><em>AWS shared responsibility model on cloud sustainability. Image source: https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/the-shared-responsibility-model.html</em></p><p>So let’s dive a bit deeper into the choices we as AWS customers can make and how to optimize the carbon emissions from our side.</p><h3>Best practices for sustainable workloads in AWS</h3><h3>Location matters</h3><p>There are over 20 AWS Regions all over the globe on which we can choose to deploy and run our workloads. Of course, it makes sense to utilize a region geographically close to our users. Still, for example, there are six AWS Regions available only in Europe. In most use cases, the latency from any of those Regions will be acceptable for our business case. So there is a chance to make the Region selection based on sustainability.</p><p>Amazon has published a website to showcase its sustainability actions, like wind farm and solar farm projects. To drive sustainability, we can check the renewable energy projects on a map and choose Regions near those projects: <a href="https://sustainability.aboutamazon.com/about/around-the-globe?energyType=true">https://sustainability.aboutamazon.com/about/around-the-globe?energyType=true</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BJnwhlQsZakRvn_L.jpg" /></figure><p><em>Amazon renewable energy projects map. Image source: </em><a href="https://sustainability.aboutamazon.com/about/around-the-globe?energyType=true"><em>https://sustainability.aboutamazon.com/about/around-the-globe?energyType=true</em></a></p><p>In addition to the region selection, there are also other sustainability aspects to the geographical placement of workloads. AWS provides excellent solutions to extend your reach without having to clone the full-scale service to each region where we have users. Depending on our use case, it might be possible to have the service running in only one region and still offer low latencies and sustainability benefits throughout the globe. This could be achieved, for example, by utilizing local caching, connection pooling, edge caching, and distributed data stores.</p><h3>Scale the services for sustainability</h3><p>The apparent path to sustainability is to stop wasting resources (and money) and optimize our infrastructure to meet actual needs. Resource management is typically quite well managed if we are utilizing serverless architectures. But if we manage the workloads ourselves, it requires analyzing the effect of users on load and capacity utilization and responding to changes by scaling the resources as needed. To drive sustainability, choose the right-sized EC2 instance types for the job and leverage auto-scaling mechanisms to scale the resources up and down as needed.</p><h3>People are equal; services and data are not</h3><p>It also pays off from a sustainability point of view to define SLAs for our services and data. Not all parts of our service are of the same business criticality. Everything doesn’t have to be load-balanced. By leveraging asynchronous design patterns, our system can still stay operative and respond according to our SLAs even if some service parts are occasionally down.</p><p>And same applies to data. By scoping the data by SLAs, we can define which data needs to be available in milliseconds and which data could be retrieved from the archive in minutes or hours instead of milliseconds. As you can imagine, the services providing millisecond request times are far more energy-consuming than the services used to retrieve data in hours. So it’s our choice again. And it also pays off to eliminate assets that we don’t need anymore — we all have those old reports, images, data sets, and so forth, slumbering forgotten on our platforms.</p><h3>Optimize software and architecture for cutting emissions</h3><p>One of the most efficient ways to drive sustainability is asynchronous design patterns. By leveraging queues, pipelines, serialization, and scheduled jobs for requests that don’t require immediate processing, we can optimize the resource consumption so that services do the heavy-lifting with optimal resources and very high utilization. We can utilize many excellent AWS services for asynchronous tasks depending on the use case, such as Amazon SQS, Amazon MQ, AWS Step Functions, AWS Lambda, Amazon EventBridge, AWS Glue, and AWS Batch.</p><p>There’s also one crucial sustainability aspect of microservices architecture, especially for the ones built on resources we manage ourselves. There is always some overhead for running any workload, especially when running the workloads on dedicated EC2 instances. Therefore we should pay attention to and analyze the usage of each microservice in our architecture. If there are microservices that we aren’t utilizing anymore, shut those down. And if there are microservices that have the same kind of SLA and have low resource requirements, it might be a resource-wise decision to combine those services as one larger microservice.</p><p>The next one might sound quite obvious but still is not in the cloud era, having virtually endless capacity at our fingertips. Optimize the code to use more efficient algorithms to do the job, utilize a code profiler for optimizing the resources, monitor the performance of the code, and utilize hardware acceleration where applicable. Also, pay attention to data transfer patterns. Transfer data only when needed. And learn to take advantage of more effective file formats for data processing, such as Parquet, and pay attention to database indexes to ensure efficient query execution.</p><h3>Final tips</h3><p>The list of optimization targets could continue for a while. The fun fact with sustainability in the cloud is that being sustainable is typically cheaper than not being sustainable. The thing that costs here is lifting the stuff — making the change happen.</p><p>Did you know that you can see the estimated carbon footprint of your workloads in AWS? You can find the tool in AWS Console under Billing Dashboard/Cost &amp; Usage Reports. Read more about the tool here: <a href="https://aws.amazon.com/blogs/aws/new-customer-carbon-footprint-tool/">https://aws.amazon.com/blogs/aws/new-customer-carbon-footprint-tool/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hkDitlQO4YpdzgOv.png" /></figure><p><em>AWS Customer Carbon Footprint Tool. Image source: </em><a href="https://aws.amazon.com/blogs/aws/new-customer-carbon-footprint-tool/"><em>https://aws.amazon.com/blogs/aws/new-customer-carbon-footprint-tool/</em></a></p><p>Thank you for reaching here! Let us know if you would like NordHero to help you with your carbon footprint on AWS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a02fc818a78a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/practical-sustainability-in-aws-cloud-a02fc818a78a">Practical sustainability in AWS cloud</a> was originally published in <a href="https://medium.com/nordhero">NordHero</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>