<?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[Stories by Teemu Niiranen on Medium]]></title>
        <description><![CDATA[Stories by Teemu Niiranen on Medium]]></description>
        <link>https://medium.com/@teemu.niiranen?source=rss-2f5d17f3c7ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FhYxfr03OfjOiCnC</url>
            <title>Stories by Teemu Niiranen on Medium</title>
            <link>https://medium.com/@teemu.niiranen?source=rss-2f5d17f3c7ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:18:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@teemu.niiranen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <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-2f5d17f3c7ae------2</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 08:57:49 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-2f5d17f3c7ae------2</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 08:57:32 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-2f5d17f3c7ae------2</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 08:57:05 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-2f5d17f3c7ae------2</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 08:56:43 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-2f5d17f3c7ae------2</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 08:56:09 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[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-2f5d17f3c7ae------2</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>Tue, 18 Apr 2023 05:19:22 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[10 years of cloud infrastructure as code — history and trends]]></title>
            <link>https://medium.com/nordhero/10-years-of-cloud-infrastructure-as-code-history-and-trends-d307f8c4ce31?source=rss-2f5d17f3c7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d307f8c4ce31</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Teemu Niiranen]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 08:59:27 GMT</pubDate>
            <atom:updated>2021-02-23T08:59:27.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uhe30v0xm59Ms-SPDynNlQ.jpeg" /><figcaption>Photo by Umit Yildirim on Unsplash.</figcaption></figure><h3>10 years of cloud infrastructure as code — history and trends</h3><p>The number of Infrastructure as Code tools for provisioning public cloud resources has grown significantly over the last few years. What new tools do better than the old ones? What are they suitable for, what not? It is confusing even for cloud veterans, but definitely for those who have just started the journey. This article will not explain why IaC is used; my colleague Janne Kuha has already done it in his <a href="https://www.nordhero.com/posts/google-cloud-terraformilla/">article about Google Cloud &amp; Terraform</a>. In turn, I aim to describe the ten-year path of tooling and some of those that are adding value to more specific areas, serverless microservices development or application development in general.</p><h3>Declarative and imperative</h3><p>Traditionally, Infrastructure as Code has been divided into declarative and imperative approaches. The declarative approach is about describing the eventual target; it defines the desired state of your resources. The declarative approach answers the question of what needs to be created — for example, I need two virtual machines. Imperative way responds to question how the infrastructure needs to be changed to achieve the goal, usually by a sequence of different commands. <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html">Ansible playbooks</a> are an excellent example of an imperative approach.</p><h3>A brief history of cloud infrastructure as code</h3><blockquote><em>“You have to know the past to understand the present.” ‑Carl Sagan</em></blockquote><p>The foundation of IaC in the public clouds is these three cloud vendor-specific tools: <a href="https://aws.amazon.com/cloudformation/">AWS CloudFormation</a> in AWS, <a href="https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/overview">Azure Resource Manager</a> (ARM) in Azure, and <a href="https://cloud.google.com/deployment-manager">Cloud Deployment Manager</a> in GCP. These are YAML or JSON based, declarative tools and have been in cloud toolboxes for a long time. In this month, February 2021, AWS CloudFormation is celebrating its 10th birthday! Azure Resource Manager was launched in April 2014 (at Build 2014 with the new Azure portal) and Cloud Deployment Manager in July 2015.</p><p>AWS S3 bucket example with AWS CloudFormation:</p><pre>AWSTemplateFormatVersion: 2010-09-09<br>Resources:<br>  S3Bucket:<br>    Type: &#39;AWS::S3::Bucket&#39;<br>    DeletionPolicy: Retain<br>    Properties:<br>      BucketName: DOC-EXAMPLE-BUCKET</pre><p>With the declarative approach, over time in practice, templates accumulate, and copy-pasting becomes more common. What if you have used the very same template or snippet in ten projects and you notice some improvement? Yes — the same fix is needed for each separately.</p><p>From third-party tools, <a href="https://www.terraform.io/">Terraform</a> by HashiCorp has been a popular cloud-agnostic choice. Terraform has also been there for a while. It was published in June 2014. It uses its domain-specific language HCL (Hashicorp Configuration Language), which allows a bit more complex business logic than the aforementioned tools. There is also a demonstration of use with GCP in Kuha’s excellent writing referenced at the beginning of the article.</p><h3>Tools designed for Serverless Applications — the first wave</h3><p>These classic declarative tools require a fair amount of markup code. Tools with shortcuts or “conventions over configuration” were developed to boost productivity and make distributed microservice applications seem more like a traditional monolithic application or a framework. These tools provide best-practice defaults and enable building and testing your serverless applications locally on your machine. The first and still prevalent tool was the cloud-agnostic <a href="https://www.serverless.com/">Serverless Framework</a> by Serverless Inc, released in October 2015. The deployment process of Serverless Framework is based on template generation so that native IaC templates are compiled during the deploy command.</p><p>Serverless Framework — AWS Lambda + S3 example:</p><pre>org: my-company<br>app: my-app<br>service: image-processor</pre><pre>functions:<br>   imageResizer:<br>      runtime: node.js8.10<br>      handler: index.imageResizer<br>      event:<br>         - s3:<br>            bucket: images<br>               event: s3:ObjectCreated:*</pre><p>Shortly after, in November 2016, AWS launched their own native <a href="https://aws.amazon.com/serverless/sam/">Serverless Application Model</a> or AWS SAM in November 2016. AWS SAM extends AWS CloudFormation with specific AWS::Serverless namespace types that are <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html">transformed</a> to CloudFormation syntax. These types are shortcuts for defining standard serverless application components like AWS Lambda functions or API Gateway endpoints.</p><p>AWS SAM example:</p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31<br>Description: &gt;<br>  sam-app<br>​<br>Parameters:<br>  AppBucketName:<br>    Type: String<br>    Description: &quot;REQUIRED: Unique S3 bucket name to use for the app.&quot;<br>​<br>Resources:<br>  S3JsonLoggerFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: src/handlers/s3-json-logger.s3JsonLoggerHandler<br>      Runtime: nodejs12.x<br>      MemorySize: 128<br>      Timeout: 60<br>      Policies:<br>        S3ReadPolicy:<br>          BucketName: !Ref AppBucketName<br>      Events:<br>        S3NewObjectEvent:<br>          Type: S3<br>          Properties:<br>            Bucket: !Ref AppBucket<br>            Events: s3:ObjectCreated:*<br>            Filter:<br>              S3Key:<br>                Rules:<br>                  - Name: suffix<br>                    Value: &quot;.json&quot;<br>  AppBucket:<br>    Type: AWS::S3::Bucket<br>    Properties:<br>      BucketName: !Ref AppBucketName</pre><p>Note the first two rows, SAM is a CloudFormation extension and transformed into CloudFormation. You can use CloudFormation types (row 34) or SAM specific Serverless types under AWS::Serverless namespace (row 13).</p><h3>Serverless Infrastructure as programming language code — the second wave</h3><p>Declarative language has always boundaries when you need to do more complex business logic than their parameters, conditions, mappings, and loops (Terraform only) allows. Sometimes, you might need to do some tricks by using external scripting, etc. A programming language could get you around these boundaries and limitations. This generation of tools generates the declarative markup code with the programming language code or bypasses it and utilizes cloud APIs. Tools with programming language support is a rising and trending approach at the moment.</p><p>An example of a generative tool is the <a href="https://aws.amazon.com/cdk/">AWS Cloud Development Kit</a> or AWS CDK (Jul 2019). AWS CDK uses the term synthesizing instead of generation. Speakers on behalf of the template generation say it’ll bring benefits in both declarative and imperative approaches. Exciting additions to AWS CDK, an open-source framework, in AWS re:Invent 2020 were alpha releases of <a href="https://github.com/hashicorp/terraform-cdk">CDK for Terraform</a> (cdk tf) and <a href="https://github.com/awslabs/cdk8s">CDK for Kubernetes</a> (cdk8s). The CDK for Terraform provides the CDK constructs for defining Terraform HCL files in TypeScript or Python and cdk8s for defining Kubernetes configuration in TypeScript, Python, or Java.</p><p>AWS CDK example:</p><pre>import * as cdk from &#39;@aws-cdk/core&#39;;<br>import * as s3 from &#39;@aws-cdk/aws-s3&#39;;<br>​<br>export class HelloCdkStack extends cdk.Stack {<br>  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {<br>    super(scope, id, props);<br>​<br>    new s3.Bucket(this, &#39;MyFirstBucket&#39;, {<br>      versioned: true<br>    });<br>  }<br>}</pre><p>Examples of non-generative cloud-agnostic tools in this programming language genre are <a href="https://www.pulumi.com/">Pulumi</a> (Sep 2019) and <a href="https://www.serverless.com/components/">Serverless Components</a> by HashiCorp (Apr 2020).</p><p>Pulumi AWS S3 bucket example:</p><pre>import * as pulumi from &quot;@pulumi/pulumi&quot;;<br>import * as aws from &quot;@pulumi/aws&quot;;<br>import * as awsx from &quot;@pulumi/awsx&quot;;<br>​<br>// Create an AWS resource (S3 Bucket)<br>const bucket = new aws.s3.Bucket(&quot;my-bucket&quot;);<br>​<br>// Export the name of the bucket<br>export const bucketName = bucket.id;</pre><p>Serverless Components even states that it bypasses the restraints of AWS CloudFormation and builds reusable templates that are inspired by component-based React. The actual usage of Serverless Components is a YAML declaration.</p><p>Creation of a Serverless Component example:</p><pre>const { Component } = require(&#39;@serverless/core&#39;)</pre><pre>class MyBlog extends Component {<br>   async default(inputs) {<br>      this.context.status(&#39;Deploying a serverless blog&#39;)<br>      const website = await this.load(&#39;@serverless/website&#39;) // Load a component<br>      const outputs = await.website({ code: { src: &#39;./blog-code&#39; } }) // Deploy it<br>      this.state.url = outputs.url<br>      return outputs<br>   }<br>}</pre><pre>module.exports = MyBlog</pre><h3>Tools specialized in more narrow use</h3><p>There are also plenty of others. AWS offers more native specialized tools than other vendors, even overlapping ones, for various infrastructure purposes. Good examples are <a href="https://aws.amazon.com/amplify/">AWS Amplify</a> (Nov 2018) and <a href="https://aws.amazon.com/containers/copilot/">AWS Copilot</a> (Jul 2020). Both are wizard-like command-line interfaces to handle the infrastructure.</p><p>AWS Amplify offers a holistic model (in short, infrastructure code in the same repository as the application and DevOps pipelines for both) and its own Amplify admin web interface for developing web and mobile applications with their serverless services. For example, a ready registration and login process on top of AWS Cognito, including UI components and code examples to start with. AWS Amplify CLI generates the CloudFormation code. Previously it was in JSON, but nowadays YAML.</p><p>AWS Amplify CLI commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mcNB6oxTywq2R1E7.png" /></figure><p>AWS Copilot is for launching and managing container applications on Amazon ECS and AWS Fargate. It has a way to export the CloudFormation template with the “copilot svc package” command. It is not mandatory, and you can use it in a more imperative style.</p><p>AWS Copilot commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s61Ha5U-gpvnMp6k.png" /></figure><p>The pros of purpose-built IaC tools are immediate benefits, but on the other hand, models and frameworks tend to bind hands. For example, in AWS Amplify, you don’t have much control over AWS CloudFront. I still have great personal experiences with AWS Amplify, both in native mobile applications and web applications.</p><h3>Conclusion</h3><p>To summarise, there is the traditional division into two approaches — declarative and imperative. Modern tooling with programming language support combines them, while some tools are bypassing the template generation. There are pros and cons in each, and I wouldn’t say that, for example, the CDK is always a better choice than Terraform, SAM, or AWS Amplify. It depends on the case and is also a bit of a matter of taste. However, the CDK approach is a step forward in IaC code reusability. It is an easier way to share solutions starting points both in house via code artifact repository and with the community with <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html">AWS Construct</a> and <a href="https://aws.amazon.com/solutions/constructs/">AWS Solutions Construct</a> libraries.</p><p>The programming style needs a different mindset and programming skills and can be a problematic extra layer without. Roughly the division could be programming language-based tools for software development to avoid context switching between markup language and programming language, declarative tools for others, and third-party cloud-agnostic tools for hybrid cloud use cases. Reality is not that black and white.</p><p>We need to remember that all these tools are continually evolving. For example, the ten-year-old CloudFormation got a nice new feature last year — <a href="https://aws.amazon.com/blogs/mt/introducing-aws-cloudformation-modules/">AWS CloudFormation modules</a>. Experiment with what suits you, your team, and the purpose the best. You can always mix and match and cherry-pick the best ones. The most important — stop clicking and start writing the infrastructure!</p><p>Mentioned tools sorted by GA release date:</p><ul><li>AWS CloudFormation (Feb 2011)</li><li>Azure Resource Manager (Apr 2014)</li><li>Terraform (Jun 2014)</li><li>GCP Cloud Deployment Manager (Jul 2015)</li><li>Serverless Framework (Oct 2015)</li><li>AWS SAM (Nov 2016)</li><li>AWS Amplify (Nov 2018)</li><li>AWS CDK (Jul 2019)</li><li>Pulumi (Sep 2019)</li><li>Serverless Components (Apr 2020)</li><li>AWS Copilot (Jul 2020)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d307f8c4ce31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nordhero/10-years-of-cloud-infrastructure-as-code-history-and-trends-d307f8c4ce31">10 years of cloud infrastructure as code — history and trends</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>