Tag Archives: Technical How-to

Make post-quantum cryptography updates routine with AWS-LC

Post Syndicated from Josh Williams original https://aws.amazon.com/blogs/security/make-post-quantum-cryptography-updates-routine-with-aws-lc/

As your organization plans upgrades to post-quantum cryptography (PQC), you should also think about cryptographic agility to more easily update algorithms used to protect your data. Changes to cryptography and related protocols aren’t new, but PQC is accelerating the pace at which organizations must add new algorithms and remove old ones to keep up with changing regulations and evolving business risk. AWS believes our key to success is standardizing on one cryptographic library that embodies three key properties: compatibility, assurance, and performance. In this blog post, you’ll learn how we think of the cost and friction of ongoing cryptographic updates in terms of these properties. You’ll learn how AWS built AWS-LC to embody these properties, thus making cryptographic upgrades straightforward and low-impact for ourselves and our customers. For custom applications where you can’t yet use AWS services and must operate your own stacks, this post also shares why you might consider using AWS-LC as your standardized library.

Every cryptographic algorithm used to protect your data today has an expiration date, even if no regulator has set one yet. Algorithms that were once the standard, such as MD5 and SHA-1, have been retired. Standards are revised and flaws are found in implementations. The move to post-quantum cryptography is the current wave of changes, with dates set by governments and regulators to complete the transition. PQC itself will progress in phases to enable hybrid and pure post-quantum algorithms and then deprecate traditional cryptography. Each change reaches your systems as a software library update, so the practical question is how often you can roll out a new version of your cryptographic library, and what each rollout costs. At AWS, we think of this cost in terms of three properties. Compatibility means an update doesn’t require application changes. Assurance means new code can be trusted when it ships, without a long bake period. Performance means a new algorithm doesn’t add so much computational overhead or latency that it gives teams a reason to wait. This post describes how AWS-LC provides each property, and how you can apply the same approach to the cryptography you own.

AWS-LC is the general-purpose cryptographic library that AWS maintains and uses across its services. It is derived from BoringSSL, which originated from OpenSSL. If you’ve called an AWS API, AWS-LC was used on the server side. Through s2n-tls, it provides hybrid post-quantum key exchange on AWS service endpoints and in services like Application Load Balancer and Network Load Balancer. It’s also the cryptography under aws-lc-rs for Rust, the default provider for rustls, and under the Amazon Corretto Crypto Provider for Java. Because so much of AWS depends on one library, we built it to be updated often. AWS-LC keeps an OpenSSL-compatible API so applications can replace algorithms without a rewrite. It uses formal verification to prove selected algorithm implementations correct. It optimizes algorithm implementations to reduce the latency and compute costs that new algorithms add. The same properties work outside AWS. For example, 1Password used AWS-LC to move its clients to hybrid post-quantum key exchange with no application code changes.

Hand off what you can, standardize what you keep

Each piece of cryptography you own is one more thing to change at every transition. By owning as little of your cryptographic stack as your constraints or requirements allow, and using AWS services to manage the rest, you can minimize your ongoing responsibility and operational risk.

If your workload relies solely on managed services like AWS Key Management Service (AWS KMS) and managed resources like Elastic Load Balancer or Amazon Relational Database Service (Amazon RDS), you’re already reaping the benefits of AWS-LC and the AWS shared responsibility model. You only need to keep your clients and resource configurations updated. Many organizations can rely on AWS to provide the infrastructure and basic automation, but still own and manage the endpoints and applications where most of the work happens. For these components, it’s helpful to standardize on as few cryptographic libraries as possible. With fewer libraries, your team learns each one well: how to configure it, run it, and update it. The library you standardize on also decides how often you can update it. If an update requires application changes, ships new code that no one trusts yet, or adds compute and latency, teams have a reason to wait. In the rest of this post, we show you how AWS-LC removes each of those reasons through compatibility, assurance, and performance.

Compatibility

The best library update is one that doesn’t impact your application and that your users don’t notice. Code changes happen at three points: adopting a library, adding an algorithm, and updating the library. AWS-LC keeps each one small.

  • Adopting AWS-LC  – For TLS, AWS-LC libssl keeps an OpenSSL-compatible API, so most applications that use OpenSSL for TLS build against it with small changes. Applications that call libcrypto directly might need more work, because the AWS-LC libcrypto API differs from OpenSSL’s in places. See the porting guide for where behavior differs.
  • Adding an algorithm  – When new algorithms are added in AWS-LC behind interfaces applications already call, s2n-tls, s2n-quic, aws-lc-rs, and the Amazon Corretto Crypto Provider adopt them automatically. Hybrid ML-KEM key exchange, for example, is enabled through existing TLS configuration APIs. For 1Password, that meant a one-line Cargo.toml change and no application code changes.
  • Updating the library – AWS-LC long-term support (LTS) releases keep a stable application binary interface (ABI). Applications link once, then take library updates without a rebuild. One update reaches every application on the host when each process restarts. The Amazon Linux 2027 preview uses this method to ship AWS-LC as a system library.

We built these properties so AWS services could move to AWS-LC with minimal effort. aws-lc-rs is also used by open source projects; it’s the default cryptography provider for rustls with over 100 million downloads in the past 90 days, CPython tests against AWS-LC in continuous integration, and HAProxy publishes packages built on it. Each new use surfaces problems earlier in the update process, and every fix is recorded in one codebase.

Assurance

Every new algorithm arrives as new code, and new code is where bugs and security vulnerabilities are usually found. If you can’t trust new code when it ships, you wait, and each wait delays the next change. Tests check the inputs you run, and proofs check every input. AWS-LC uses machine-checked proofs for its most critical code, including its post-quantum algorithms and parts of its classical algorithms, such as its 25519 elliptic-curve code.

AWS-LC contributes to and takes its ML-KEM and ML-DSA code from two open source projects: mlkem-native and mldsa-native. The algorithmic implementations in these projects already incorporate formal verification safeguards such as ensuring no out of bound memory access, no integer overflows, constant assembly run time, and functional correctness using tools like CBMC and HOL Light (for more information, see Verifying and optimizing post-quantum cryptography at Amazon). AWS-LC imports this code from upstream without changing it. The proofs don’t depend on instruction order, so the assembly can be re-optimized without redoing them. That prevents verification from becoming the reason a faster implementation waits. Other cryptographic implementations of the library are verified in s2n-bignum.

We use these proofs alongside testing and FIPS validation. For workloads that require FIPS 140-3, a validated module is required to allow new code to be deployed. AWS-LC FIPS 3.0 was the first cryptographic library to include ML-KEM in a FIPS 140-3 validation. ML-DSA, the NIST post-quantum signature standard (FIPS 204), is in the AWS-LC FIPS 4.0 module, and the FIPS 5.0 module includes the faster, formally verified mldsa-native implementation. Both have been submitted to NIST for validation.

Performance

A new algorithm that costs more to run gives teams a reason to delay, and across many connections a small cost per connection adds up. AWS-LC optimizes each algorithm it adds so that cost doesn’t delay the update. Amazon Science reports 2.0 to 2.4 times more ML-KEM operations per second than the reference implementations across Amazon Elastic Compute Cloud (Amazon EC2) instance types. Earlier work applied the same approach to 25519 elliptic-curve cryptography. The optimized code is covered by the proofs described in the previous section, so speed doesn’t reduce assurance.

ML-DSA followed the same path. AWS-LC moved from its original implementation to mldsa-native, with optimized assembly for AArch64 and x86_64 platforms, and it now signs and verifies faster on both Graviton and x86 EC2 instance types. As a result, compute is no longer the main cost of post-quantum signatures: in the measurements in the following section, we show that ML-DSA-44 certificates lowered average TLS handshake latency compared with RSA-2048. What remains is size, which the next section measures.

What it costs to move

AWS services handle billions of requests every second, so anything that could affect those requests must be carefully considered. Post-quantum cryptography impacts the performance of every new TLS connection, so before we adopted ML-KEM and ML-DSA, we invested heavily in making them fast. Figure 1 shows the resulting reduction in time for both key exchange and authentication. Today, moving to PQ confidentiality has no net cost for most AWS use-cases, and PQ authentication takes less compute than the RSA certificates we use today.

Figure 1. ML-KEM-768 and ML-DSA-87 time per handshake, before and after AWS-LC’s native implementations, on AWS Graviton4

Figure 1. ML-KEM-768 and ML-DSA-87 time per handshake, before and after AWS-LC’s native implementations, on AWS Graviton4

ML-KEM-768 key exchange decreased by over 50 percent on both the client and the server (as shown in Figure 1); we described how in Verifying and optimizing post-quantum cryptography at Amazon. In this post, we’re focusing on ML-DSA. In AWS-LC v1.49.1, ML-DSA used the original AWS-LC implementation, adapted from the reference code. In v5.10.0, it runs on mldsa-native, which implements the performance-critical kernels in hand-written Arm64 Neon assembly for AWS Graviton, including: the number-theoretic transform (NTT) and its inverse, tuned for Arm cores with the SLOTHY superoptimizer, along with pointwise multiplication, rejection sampling, and the decompose, hint, and norm-check steps of signing and verification. It also expands the public matrix four entries at a time using the AWS-LC four-way parallel SHA-3 (Keccak). These optimizations, as shown in the right half of Figure 1, reduced ML-DSA-87 signing time on the server and verification time on the client, and the same assembly is covered by the formal proofs described earlier. mldsa-native is open source, part of the PQ Code Package in the Linux Foundation’s Post-Quantum Cryptography Alliance (PQCA), and the AWS Cryptography team and Amazon Automated Reasoning Group contribute to it.

Figure 2. TLS 1.3 connection setup time by algorithm, between two AWS Graviton4 hosts in the same Availability Zone

Figure 2. TLS 1.3 connection setup time by algorithm, between two AWS Graviton4 hosts in the same Availability Zone

Figure 2 shows total handshake time for various configurations, when the client and server are in the same AWS Region. For a baseline, we used TLS performance when the server prioritized ECDHE with P-256 for key exchange and RSA-2048 certificates for authentication. With the optimizations to ML-KEM, there is negligible overhead from moving to hybrid ML-KEM key exchange (the second bar from left). The hybrid key exchange preferred in AWS systems today pairs X25519 with ML-KEM-768. X25519 is faster than P-256, and that saving covers the remaining ML-KEM work, so a full connection setup takes roughly 12 microseconds more, which doesn’t meaningfully impact throughput or latency. It’s worth noting here that ML-KEM-768 introduces approximately 2.3 KB to the handshake.

PQ authentication carries more risk, because authentication is more of the handshake cost. The server signs once for each handshake, and the client verifies three signatures: the server’s handshake signature, the signature on the leaf, and the signature on the intermediate certificate. RSA-2048 signing is expensive and verification is inexpensive. ML-DSA-87 reverses that balance, shifting some work from the server to the client.

ML-DSA keys and signatures are also much larger, so the server’s handshake messages grow from 4–7 KB to 17–24 KB depending on the chosen certificate parameters. That adds certificate parsing on the client and more data to encrypt and send on the server. Within an Availability Zone, those messages still arrive in one round trip, and we measured no difference in network time between configurations.

Compared to RSA 2048, which is still prevalent today, ECDSA offers faster processing. However, both must be replaced by ML-DSA for post-quantum authentication. With the optimizations in AWS-LC, ML-DSA-44 comes close to ECDSA, and every ML-DSA parameter set is significantly faster than RSA-2048, as shown in Figure 2. As a result, we’re confident in managing the performance impact from migrating to post-quantum certificates.

Another facet of our investments in reducing performance impact is session resumption. Handshake costs apply only to new connections. Session resumption reduces how often that cost is paid. A resumed TLS 1.3 handshake authenticates with a key from the earlier session and sends no certificates or signatures, so the larger ML-DSA keys and signatures apply only to full handshakes. We’ll note here that in psk_dhe_ke mode, the resumed handshake still runs a fresh hybrid ML-KEM key exchange, which preserves forward secrecy. Now, resumption only helps if the client can present its ticket to any server behind the endpoint, so AWS has been extending support for resumption across the hosts behind its service endpoints. AWS SDKs can reuse connections across many requests, and session resumption can skip certificates and signatures entirely, which gives the most performance benefit for workloads using AWS managed services. If you’re using AWS-LC directly in your own custom applications, consider keeping session tickets enabled, prefer TLS 1.3 with psk_dhe_ke, and reuse clients so that they keep their tickets between connections.

Conclusion

Every cryptographic choice has an expiration date, so the goal isn’t to pick the right algorithm once and never replace or update it, but to make each replacement routine. Start by handing off what you can to AWS services and standardizing what you keep on as few libraries as possible. For the cryptography you own, three properties decide how quickly and how often you can implement each update. For compatibility, new algorithms arrive behind the APIs your applications already call, and long-term support releases keep a stable ABI, so adopting one takes a library update and a restart, not a rebuild. For assurance, machine-checked proofs cover a library’s most critical code, ML-KEM is inside a FIPS 140-3 validated module, and ML-DSA is in modules submitted for validation. For performance, optimized implementations keep each new algorithm from adding compute or latency that might give teams a reason to wait. Post-quantum cryptography is the change in front of us now, and it won’t be the last.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Josh Williams

Josh Williams

Josh is a Software Engineering Manager in AWS Cryptography, where he leads the team that builds AWS-LC. His team’s work spans post-quantum algorithms, formal verification, and performance optimization. He previously led teams in AWS Networking and Amazon Aurora DSQL and brings broad experience in ecommerce and distributed systems.

Jake Massimo

Jake Massimo

Jake is an Applied Scientist on the AWS Cryptography team, where he bridges Amazon with the global cryptographic community through active participation in international conferences, academic research, and standards organizations. His work focuses on advancing the adoption of post-quantum cryptographic technology at cloud scale. Currently, he leads the development of optimized and formally verified post-quantum algorithms within the AWS cryptographic library.

Rohit Panjala

Rohit is a Senior Security Specialist at AWS, driving go-to-market (GTM) strategy on a global scale for AWS data protection services, including keys, certificates, secrets, and post-quantum cryptography. He brings 7 years of experience in cybersecurity and cloud, with a background in security product management at IBM and electrical engineering.

Secure agentic access to AWS with Enterprise-Managed Authorization

Post Syndicated from Vaibhav Chowla original https://aws.amazon.com/blogs/security/secure-agentic-access-to-aws-with-enterprise-managed-authorization/

AWS Sign-In is introducing support for Enterprise-Managed Authorization (EMA) using the Identity Assertion JWT Authorization Grant (ID-JAG), enabling organizations to securely authorize AI agents to access AWS MCP Server through their existing enterprise identity providers (IdPs), such as Okta. With this capability, organizations can centrally manage which applications can access Amazon Web Services (AWS) resources on behalf of their employees, without requiring users to manage additional long-term credentials or complete separate consent flows.

In our previous blog post, Introducing OAuth Support for AWS MCP Server, we introduced OAuth-based authorization, enabling AI agents to securely access AWS MCP Server through interactive sign-in or programmatic authentication using AWS credentials. EMA builds on these capabilities by enabling organizations to authorize AI agents through their existing enterprise IdPs. Because authentication to an AI application doesn’t automatically grant access to AWS resources, EMA provides a way to authorize access across these separate trust domains while maintaining existing AWS Identity and Access Management (IAM) permissions.

In this post, we explain how EMA and ID-JAG work with AWS Sign-In, discuss security best practices, and walk you through configuring Okta to authorize AI agents to access AWS MCP Server.

How Enterprise-Managed Authorization works with AWS Sign-In

Enterprise-Managed Authorization (EMA) is an extension of the Model Context Protocol (MCP) that enables organizations to centrally manage how AI applications access protected resources on behalf of employees. EMA uses the Identity Assertion JWT Authorization Grant (ID-JAG), an OAuth-based authorization grant that enables enterprise IdPs to authorize access across different trust domains. Rather than requiring employees to individually authorize each MCP server, administrators can define policies in their existing IdP to control which AI applications can access specific resources.

When an employee signs in to an AI application such as Claude using their enterprise IdP, the authentication establishes their identity within Claude but doesn’t automatically grant access to AWS resources. When the AI application requests access to an MCP server, the enterprise IdP evaluates its configured access policies and issues a short-lived, signed ID-JAG assertion for the intended resource. The AI application then exchanges this assertion with the authorization server configured for the MCP server to obtain an OAuth access token, without requiring the employee to complete an additional interactive authorization flow.

For AWS MCP Server, AWS Sign-In serves as the configured OAuth authorization server. The AI application presents the ID-JAG assertion to the AWS Sign-In OAuth token endpoint. As part of the authorization process, AWS validates the assertion against the trusted IdP and uses AWS Security Token Service (AWS STS) to evaluate the IAM role’s trust policy and establish the authorized role session. AWS Sign-In then issues an OAuth access token associated with the IAM role. IAM policies attached to the role determine which AWS operations the agent can perform, allowing organizations to manage agent authorization through their enterprise IdP while enforcing existing AWS permissions.

Figure 1 illustrates how an AI application, such as Claude, uses EMA with Okta and AWS Sign-In to obtain an OAuth access token and securely access AWS MCP Server using IAM role-based permissions.

Figure 1: Enterprise-Managed Authorization flow using Okta, AWS Sign-In, and AWS MCP Server

Figure 1: Enterprise-Managed Authorization flow using Okta, AWS Sign-In, and AWS MCP Server

The authorization flow consists of the following steps, as illustrated in Figure 1:

  1. Employee authentication: The employee signs in to the AI application, such as Claude, using their enterprise IdP, such as Okta, through single sign-on (SSO).
  2. ID-JAG request: When the AI application needs to access AWS MCP Server, it requests an ID-JAG from Okta for the intended resource.
  3. Enterprise authorization: Okta evaluates the configured access policies to determine whether the employee and AI application are authorized to access AWS MCP Server. If authorized, Okta issues a short-lived, signed ID-JAG assertion.
  4. Token exchange with AWS Sign-In: The AI application sends the ID-JAG to the AWS Sign-In OAuth token endpoint. AWS Sign-In validates the assertion, including its issuer, signature, audience/tenant, expiration, and intended resource, and verifies the associated IAM role authorization before issuing an OAuth access token.
  5. Access AWS MCP Server: The AI application presents the AWS-issued OAuth access token to AWS MCP Server. The server validates the token, and access to AWS resources is governed by the permissions associated with the IAM role.

Configure Enterprise-Managed Authorization using Okta and AWS Sign-In

In this section, we walk you through configuring Enterprise-Managed Authorization (EMA) to enable an AI application, such as Claude, to securely access AWS MCP Server using an enterprise identity managed in Okta.

The configuration establishes trust between Okta and AWS, defines IAM permissions for accessing AWS resources, and configures enterprise authorization policies that govern AI application access. This walkthrough uses AWS MCP Server in the US West (Oregon) AWS Region (us-west-2).

Prerequisites

Before you begin, make sure you have the following:

  • An AWS account with permissions to configure IAM IdPs, roles, and policies.
  • An Okta organization with administrative permissions to manage applications and configure Cross-App Access policies.
  • An AI application, such as Claude, that supports EMA and ID-JAG.
  • Access to AWS MCP Server with support for OAuth-based Enterprise-Managed Authorization.
  • The AWS Region where you will configure the integration.

Step 0: Configure the AI application in Okta

Configure an application in Okta so that employees can sign in to the AI application through enterprise single sign-on (SSO). For this walkthrough, we use Claude as the AI application. If your organization already uses Claude with Okta SSO, you can use the existing application. This application is the requesting application when you configure Cross-App Access in Step 3.

  1. Create the Claude SSO application: In the Okta Admin Console, go to Applications, choose Create App Integration, and create an OIDC web application, for example Claude SSO, as shown in Figure 2.
    • If your agent was imported through an Okta AI Agent Provider, create the OIDC application by going to Directory, AI Agents, then navigating to User access from the selected agent.
  2. Choose the grant types: Select Authorization Code and Refresh Token. Claude uses the refresh token to request new ID-JAG assertions without asking employees to sign in again.
  3. Add the redirect URI: Set Sign-in redirect URIs to Claude’s SSO callback URL.
  4. Assign employees: Under Assignments, select which employees or groups can access the application.
  5. Confirm SSO works: Check that employees can sign in to Claude through Okta before you continue.
Figure 2: Creating the Claude SSO app integration in Okta

Figure 2: Creating the Claude SSO app integration in Okta

Step 1: Configure Okta as an OIDC IdP in IAM

Create an OpenID Connect (OIDC) IdP so that AWS trusts the ID-JAG assertions that Okta issues, as shown in Figure 3.

  1. Add the IdP: In the AWS Management Console for IAM, go to Identity providers, choose Add provider, and select OpenID Connect.
  2. Enter the provider URL: For Provider URL, enter your Okta org URL, for example https://integrator-1234567.okta.com. Okta issues ID-JAG assertions from the org authorization server, not from a custom authorization server.
  3. Enter the audience: For Audience, enter the AWS Sign-In authorization server for your Region, for example https://us-west-2.oauth.signin.aws, and choose Add provider.
Figure 3: Adding Okta as an OpenID Connect identity provider in IAM

Figure 3: Adding Okta as an OpenID Connect identity provider in IAM

Step 2: Create an IAM role and configure permissions

Create an IAM role that defines the AWS permissions granted to the AI application, as shown in Figure 4.

  1. Create the role: In the IAM console, go to Roles, choose Create role, and select Web identity as the trusted entity type. Choose the Okta IdP from Step 1 and its audience. This creates a trust policy that allows access only through assertions from that provider.
  2. Attach the AWS MCP Server permissions: Attach the AWS managed policy AWSMCPSignInOAuthAccessPolicy. It grants the signin:CreateOAuth2Token permission required for OAuth access to AWS MCP Server.
  3. Attach the AWS permissions the AI application needs: Attach other IAM policies that grant only the AWS permissions required by the AI application. For this walkthrough, we use a read-only role.
  4. Name and create the role: Enter a role name, for example OktaAwsMcpReadOnly, and choose Create role.
  5. Copy the role ARN: You’ll enter the role Amazon Resource Name (ARN) as the Audience/tenant ID in Okta in Step 3.
Figure 4: Reviewing the IAM role and its trust policy

Figure 4: Reviewing the IAM role and its trust policy

Step 3: Configure Cross-App Access in Okta

In the Okta Admin Console, create a resource application that represents AWS MCP Server, and then connect Claude to it. The Claude SSO App from Step 0 stays the requesting application, so you don’t enable Cross-App Access on it.

  1. Create the AWS MCP resource application: Go to Applications, choose Create App Integration, and create an OIDC web application, for example AWS MCP (us-west-2). Okta doesn’t use this application’s sign-in redirect URI, so you can keep the default value.

    Figure 5: Creating the AWS MCP resource application in Okta

    Figure 5: Creating the AWS MCP resource application in Okta

  2. Enable Cross-App Access on the resource application: On the Machine Assignments tab, edit the access method and enable Cross-App Access. Set Issuer URL to https://us-west-2.oauth.signin.aws and set Audience/tenant ID to the IAM role ARN from Step 2.

    Figure 6: Enabling Cross-App Access on the AWS MCP resource application

    Figure 6: Enabling Cross-App Access on the AWS MCP resource application

  3. Assign employees: On the Assignments tab, assign the employees or groups who can access AWS MCP Server through Claude.
  4. Register Claude as an AI agent: Go to Directory, AI Agents, and choose Register AI agent. Under User access, choose Select an existing app and pick the Claude SSO App from Step 0.
  5. Connect the AI agent to AWS MCP Server: On the AI agent page, add a resource connection with the Application resource type. Set Application instance to the AWS MCP resource application. Set the client ID registered in AWS MCP to the client ID that you configure in Claude in Step 4, for example anthropic-claude. Set Resource identifier to https://aws-mcp.us-west-2.api.aws/mcp.
    Figure 7: Connecting the Claude AI agent to the AWS MCP resource application

    Figure 7: Connecting the Claude AI agent to the AWS MCP resource application

When Claude requests access, Okta checks that the employee is assigned access and issues an ID-JAG for AWS Sign-In that carries the IAM role ARN. AWS Sign-In validates the assertion and issues an OAuth access token associated with the IAM role.

Step 4: Configure Claude to access AWS MCP Server

  1. Add a custom connector: In Claude, open Admin settings, choose Connectors, and then choose Add, Custom connector. Enter a name and the AWS MCP Server endpoint, for example https://aws-mcp.us-west-2.api.aws/mcp.
  2. Configure OAuth authentication: For Authentication, choose Sign in when needed. For OAuth client, choose Use your own OAuth client, enter the client ID from the resource connection in Step 3 and leave the client secret blank.
    Figure 8: Adding AWS MCP Server as a custom connector in Claude

    Figure 8: Adding AWS MCP Server as a custom connector in Claude

  3. Set up managed authorization: Open the connector, and on the Configuration tab, choose Set up next to Managed authorization.
    Figure 9: The connector’s Configuration tab

    Figure 9: The connector’s Configuration tab

  4. Configure IdP-managed access: Choose IdP-managed as the identity source and confirm that the connection checks pass. Then choose Continue, select the Claude roles that connect through managed authorization, and choose Save.
    Figure 10: Setting up managed authorization with Okta as the identity source

    Figure 10: Setting up managed authorization with Okta as the identity source

When an employee accesses AWS MCP Server, Claude requests an ID-JAG assertion from Okta. Following successful policy evaluation, Okta issues the assertion, which Claude exchanges at the AWS Sign-In OAuth token endpoint for an OAuth access token associated with the configured IAM role. Claude uses this token to access AWS MCP Server without requiring an additional AWS sign-in.

Step 5: Validate access to AWS MCP Server

To validate the configuration:

  1. Sign in using enterprise SSO: Sign in to the AI application using your Okta identity.
    Figure 11: Signing in to Claude with SSO

    Figure 11: Signing in to Claude with SSO

  2. Connect to AWS MCP Server: Connect the AI application to AWS MCP Server.
  3. Verify OAuth token issuance: Confirm that Claude successfully connects to AWS MCP Server without requiring a separate AWS authorization flow. You can verify successful OAuth token issuance using AWS CloudTrail, as described in Step 6.
  4. Validate authorized access: Perform an AWS operation permitted by the configured IAM role.
    Figure 12: Calling AWS MCP Server from Claude Code

    Figure 12: Calling AWS MCP Server from Claude Code

  5. Verify access restrictions: Attempt an operation outside the IAM role’s permissions and confirm that access is denied.

You can also validate enterprise authorization policies by attempting access using an employee who is not authorized in Okta and verifying that the ID-JAG request is denied.

Step 6: Verify authorization activity using AWS CloudTrail

AWS Sign-In and AWS MCP Server integrate with AWS CloudTrail to help organizations monitor OAuth authorization activity and API requests made by AI applications. CloudTrail provides visibility into token issuance, the applications requesting access, and operations performed through AWS MCP Server.

After successfully connecting your AI application to AWS MCP Server, you can verify the authorization activity in CloudTrail:

  1. Open the CloudTrail console and navigate to Event history.
  2. Select the AWS Region used for the integration.
  3. Filter events by Event source signin.amazonaws.com or Event name CreateOAuth2Token to locate OAuth token issuance activity.
  4. Review the event details, including the OAuth client identifier, target resource, authorization grant type, and token issuance status, where recorded.
  5. To review subsequent MCP activity, examine events from aws-mcp.amazonaws.com with the same session ARN and verify that the operations performed by the AI application match the permissions configured for the IAM role. Calls to global services such as IAM are recorded in US East (N. Virginia).

Example 1: AWS Sign-In OAuth token issuance

The following example illustrates the CloudTrail fields used to examine an OAuth token issuance event.

{
  "eventVersion": "1.11",
  "userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROA1234567890EXAMPLE:IDAAG.nM5xzagNal2jb_tdJucKeDBJHAU6XtsjXoSpIzOqvoE",
    "arn": "arn:aws:sts::123456789012:assumed-role/OktaAwsMcpReadOnly/IDAAG.nM5xzagNal2jb_tdJucKeDBJHAU6XtsjXoSpIzOqvoE",
    "accountId": "123456789012",
    "sessionContext": {
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AROA1234567890EXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/OktaAwsMcpReadOnly",
        "accountId": "123456789012",
        "userName": "OktaAwsMcpReadOnly"
      },
      "webIdFederationData": {
        "federatedProvider": "arn:aws:iam::123456789012:oidc-provider/integrator-1234567.okta.com",
        "attributes": {}
      },
      "attributes": {
        "creationDate": "2026-11-12T00:10:30Z",
        "mfaAuthenticated": "false"
      }
    }
  },
  "eventTime": "2026-11-12T00:10:31Z",
  "eventSource": "signin.amazonaws.com",
  "eventName": "CreateOAuth2Token",
  "awsRegion": "us-west-2",
  "sourceIPAddress": "10.0.0.25",
  "userAgent": "python-httpx/0.28.1",
  "requestParameters": {
    "resource": "https://aws-mcp.us-west-2.api.aws/mcp",
    "client_id": "arn:aws:signin:::external-client/jwt-bearer/anthropic-claude"
  },
  "responseElements": null,
  "additionalEventData": {
    "signInSessionArn": "arn:aws:signin:us-west-2:123456789012:session/318c7829-2be1-4c7d-b693-538685cc1d49",
    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
    "success": "true"
  },
  "requestID": "0a475993-9f25-4198-9ed6-a8a141a05e99",
  "eventID": "21a99293-1659-49de-ad69-143c81c3e7a6",
  "readOnly": true,
  "eventType": "AwsApiCall",
  "managementEvent": true,
  "recipientAccountId": "123456789012",
  "eventCategory": "Management",
  "tlsDetails": {
    "tlsVersion": "TLSv1.3",
    "cipherSuite": "TLS_AES_128_GCM_SHA256",
    "clientProvidedHostHeader": "us-west-2.oauth.signin.aws"
  }
}

Example 2: AWS API call performed through AWS MCP Server

The following example illustrates the CloudTrail fields used to examine an AWS API call performed through AWS MCP Server.

{
  "eventVersion": "1.11",
  "userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROA1234567890EXAMPLE:IDAAG.nM5xzagNal2jb_tdJucKeDBJHAU6XtsjXoSpIzOqvoE",
    "arn": "arn:aws:sts::123456789012:assumed-role/OktaAwsMcpReadOnly/IDAAG.nM5xzagNal2jb_tdJucKeDBJHAU6XtsjXoSpIzOqvoE",
    "accountId": "123456789012",
    "accessKeyId": "ASIA123456789EXAMPLE",
    "sessionContext": {
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AROA1234567890EXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/OktaAwsMcpReadOnly",
        "accountId": "123456789012",
        "userName": "OktaAwsMcpReadOnly"
      },
      "webIdFederationData": {
        "federatedProvider": "arn:aws:iam::123456789012:oidc-provider/integrator-1234567.okta.com",
        "attributes": {}
      },
      "attributes": {
        "creationDate": "2026-11-12T00:10:30Z",
        "mfaAuthenticated": "false"
      },
      "signInSessionArn": "arn:aws:signin:us-west-2:123456789012:session/318c7829-2be1-4c7d-b693-538685cc1d49"
    },
    "invokedBy": "aws-mcp.amazonaws.com"
  },
  "eventTime": "2026-11-12T00:11:20Z",
  "eventSource": "iam.amazonaws.com",
  "eventName": "ListUsers",
  "awsRegion": "us-east-1",
  "sourceIPAddress": "aws-mcp.amazonaws.com",
  "userAgent": "aws-mcp.amazonaws.com",
  "requestParameters": null,
  "responseElements": null,
  "requestID": "43c45638-b0ee-4f04-a30f-10e4012c85be",
  "eventID": "ed17577a-8d85-405d-9796-9a296a1f59b4",
  "readOnly": true,
  "eventType": "AwsApiCall",
  "managementEvent": true,
  "recipientAccountId": "123456789012",
  "eventCategory": "Management"
}

Together, these events help administrators audit OAuth token issuance and subsequent AWS MCP Server activity, supporting security investigations, compliance monitoring, and access reviews.

For more information, see Monitoring OAuth activity and Logging AWS MCP Server API calls using AWS CloudTrail.

Best practices for securing AI agent access with EMA and AWS IAM

When configuring Enterprise-Managed Authorization (EMA), consider the following security recommendations to help protect AI agent access to AWS resources:

  • Use short-lived ID-JAG assertions: Configure your enterprise IdP to issue ID-JAG assertions with short expiration periods. This limits the time during which an assertion can be exchanged for an OAuth access token and reduces the risk associated with token exposure.
  • Use tenant-specific IdP issuers: In multi-tenant environments, configure tenant-specific issuer URLs to establish explicit trust relationships between AWS and the intended enterprise IdP. This helps prevent assertions issued for one tenant from being accepted in another tenant’s authorization context.
  • Restrict OAuth authorization using IAM condition keys: Use IAM condition keys to limit OAuth token issuance to approved AI applications, authorization flows, and AWS resources. For example, use signin:OAuthClientId to restrict access to approved AI applications, such as arn:aws:signin:::external-client/jwt-bearer/anthropic-claude and signin:OAuthGrantType to restrict the permitted grant type to urn:ietf:params:oauth:grant-type:jwt-bearer. Scope these permissions to the AWS MCP Server service principal to prevent unintended access to other AWS services.
  • Apply least-privilege IAM permissions: Grant the IAM role only the permissions required by the AI application. Use managed policies to control which AWS operations the agent can perform through AWS MCP Server, reducing the impact of unauthorized or unintended actions.

For more information about available IAM condition keys and permissions, see the AWS Sign-In condition keys reference and the AWSMCPSignInOAuthAccessPolicy documentation.

Conclusion

Enterprise-Managed Authorization (EMA) with AWS Sign-In enables organizations to securely connect AI agents to AWS resources using their existing enterprise IdPs. By combining centralized authorization policies with IAM permissions, organizations can control which AI applications access their resources while reducing the need for employees to manage AWS credentials or complete additional authorization flows.

Using ID-JAG, AWS Sign-In exchanges enterprise-issued identity assertions for short-lived OAuth access tokens associated with IAM roles. This approach helps organizations enforce least-privilege access, reduce credential exposure, and simplify how employees securely access AWS resources through AI agents.

To get started, see the Sign-in with OAuth 2.0, Configure EMA for MCP servers, and Introducing OAuth Support for AWS MCP Server to learn more about OAuth-based access to AWS resources.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Vaibhav Chowla

Vaibhav Chowla

Vaibhav is a Senior Technical Product Manager at AWS, specializing in AWS Identity products. He focuses on enhancing user authentication and security, helping customers of all sizes solve complex identity and access management challenges. Outside of technology, Vaibhav enjoys traveling and exploring new cultures and cuisines.

Jaimin Bhatt

Jaimin Bhatt

Jaimin is a Principal Software Engineer at AWS. He works on AWS Identity and Access Management (IAM) across sign-in, threat detection, and the authentication and authorization that secures access to AWS. Previously, he led work on data perimeter controls for AWS Management Console sign-in, multi-session support for the console, a simplified AWS CLI sign-in experience, and the internal Amazon identity provider.

Seling Chen

Seling Chen

Seling is a Senior Software Engineer on the AWS Identity Sign-In team, which focuses on securing access to the AWS Management Console, the AWS CLI, and MCP servers. Her contributions include OAuth 2.0 Token Exchange, data perimeter enforcement in AWS Sign-In, and multi-session support for the console.

Planning for 99.99 percent availability with the Amazon Cognito Plus feature plan

Post Syndicated from Brian Song original https://aws.amazon.com/blogs/security/planning-for-99-99-percent-availability-with-the-amazon-cognito-plus-feature-plan/

Amazon Cognito handles sign-in and access control for users, AI agents, and microservices with managed user directories, social and enterprise federation, and passwordless sign-in with passkeys or one-time passwords.

Sign-in is the front door to your application. If your customer identity and access management (CIAM) layer is unavailable, users can’t sign in or refresh their sessions, and they can’t reach the rest of your application. Your application’s availability directly depends on the availability of your identity layer.

Starting November 1, 2026, the Amazon Cognito Service Level Agreement (SLA) commits to a Monthly Uptime Percentage of 99.99 percent for user pools on the Plus feature plan, up from 99.9 percent. A user pool is a multi-tenant user directory that stores your users’ profiles and settings. User pools on Essentials and Lite feature plans remain at the 99.9 percent Service Commitment, while user pools already on Plus receive the new Service Commitment automatically.

This post explains why we made the change, how availability is measured, what’s in the updated SLA, how the SLA measures availability, historical availability data, and how to switch a user pool to Plus.

Why we raised the Service Commitment

Many customers use Amazon Cognito for sign-in to applications with strict availability requirements, such as patient portals and retail checkout flows. They need the services they build on to support high availability. We raised the Service Commitment for the Plus feature plan to 99.99 percent so that their identity layer is backed by an SLA that matches their commitments.

The new Service Commitment and Service Credits

For each AWS Region, during each monthly billing cycle, AWS commits to a Monthly Uptime Percentage of at least 99.99 percent for user pools on Plus, and at least 99.9 percent for user pools on Essentials and Lite. If Amazon Cognito doesn’t meet the Service Commitment for your feature plan, you may be eligible for a Service Credit, as shown in Tables 1 and 2. For full terms and exclusions, see the Amazon Cognito SLA.

Table 1: Service Credit percentage for the Plus Feature Plan

Monthly Uptime Percentage Plus
Less than 99.99% but equal to or greater than 99.0% 10%
Less than 99.0% but equal to or greater than 95.0% 25%
Less than 95.0% 100%

Table 2: Service Credit percentage for the Essentials and Lite Feature Plan

Monthly Uptime Percentage Essentials and Lite
Less than 99.9% but equal to or greater than 99.0% 10%
Less than 99.0% but equal to or greater than 95.0% 25%
Less than 95.0% 100%

What 99.99 percent means in practice

The 99.99 percent Service Commitment is a 10-times improvement over 99.9 percent. In a 30-day month, the allowable monthly downtime drops from about 43 minutes to about 4.3 minutes. For teams that set availability targets for their own applications, this gives a stronger baseline to plan against and to share with stakeholders.

How Amazon Cognito measures availability

The SLA measures availability separately for each AWS Region. Amazon Cognito divides each monthly billing cycle into 5-minute intervals and calculates the percentage of requests in each interval that don’t return an HTTP 500 or 503 error. Intervals with no requests count as 100 percent available. The Monthly Uptime Percentage is the average of these interval values over the billing cycle, minus downtime covered by the exclusions in the SLA. For the full definitions and exclusions, see the Amazon Cognito SLA.

Historical availability over the past 12 months

As we introduce the new SLA, we also looked back at the past 12 months to show how Amazon Cognito performed against the new Service Commitment. Table 3 shows monthly availability for Amazon Cognito user pools from November 2025 through October 2026.

Availability was at or above 99.99 percent in 10 of the 12 months. It was below 99.99 percent in January (99.988 percent) and March (99.979 percent), but stayed above the previous 99.9 percent Service Commitment in both months and was at or above 99.99 percent the following month.

Table 3: Amazon Cognito user pools monthly availability, November 2025 to October 2026

Month Monthly availability
November 2025 99.999%
December 2025 99.999%
January 2026 99.988%
February 2026 99.999%
March 2026 99.979%
April 2026 99.999%
May 2026 99.999%
June 2026 99.999%
July 2026 99.993%
August 2026 99.999%
September 2026 99.998%
October 2026 99.997%

We calculated availability for each Region using the Monthly Uptime Percentage method in the SLA, then combined the Regional results into one monthly figure weighted by each Region’s request volume. These are aggregate figures, so the availability an individual account experienced might differ.

Switch to the Plus feature plan

If your user pools use the Plus feature plan, the 99.99 percent Service Commitment applies to them starting November 1, 2026, with no action needed. If your user pools use Essentials or Lite feature plans, you can switch them to Plus in the AWS Management Console for Amazon Cognito or programmatically. Before you switch, see user pool feature plans and Amazon Cognito pricing to compare features and costs. To learn more about the features that Plus adds, see the advanced security features with threat protection.

To switch a user pool to the Plus feature plan (AWS Management Console):

  1. Sign in to the Amazon Cognito console.
  2. Choose User pools and then choose your user pool.
  3. Choose Settings.
  4. Choose the Feature plans tab.
  5. Choose Switch to Plus.
  6. Review your choice and then choose Confirm.
Figure 1: Amazon Cognito console Feature plans tab with the Switch to Plus button

Figure 1: Amazon Cognito console Feature plans tab with the Switch to Plus button

To switch a user pool to Plus feature plan (AWS CLI):

Important: The Update-user-pool command and the UpdateUserPool API operation reset any parameter that you don’t include in the request to its default value. To avoid unintended changes to your user pool, retrieve your existing configuration first and include it in your update request.

  1. Use the AWS Command Line Interface (AWS CLI) to retrieve your current user pool configuration with describe-user-pool:
    aws cognito-idp describe-user-pool \
    --user-pool-id <your-user-pool-id>
    

  2. Run the update-user-pool command, including your existing configuration parameters and the Plus tier:
    aws cognito-idp update-user-pool \
    --user-pool-id <your-user-pool-id> \
    --user-pool-tier PLUS \
    <your existing configuration parameters>
    

If you use an AWS SDK, set UserPoolTier to PLUS in an UpdateUserPool request, and include your existing settings in the same way.

Conclusion

In this post, we shared the updated Service Commitment for Amazon Cognito user pools on the Plus feature plan, how availability is measured, and 12 months of historical data. Starting November 1, 2026, user pools on Plus are covered by a 99.99 percent Monthly Uptime Percentage Service Commitment, with no action required if you already use Plus. We plan to keep investing in the availability and resilience of Amazon Cognito.

To review the full terms, see the Amazon Cognito SLA. To learn more about the features in each plan, see user pool feature plans and advanced security features with threat protection.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Brian Song

Brian Song

Brian is a Senior Product Manager at Amazon Web Services, where he’s passionate about making customer identity simple, secure, and dependable for builders of all sizes. Brian is usually planning his next trip, catching a live show, or first in line for a movie on opening night.

Chris Simmons

Chris Simmons

Chris is a Senior Software Manager at Amazon Web Services. When he’s not improving the security of the cloud, Chris enjoys running, martial arts, and old-school RPGs.

Introducing context-aware rules for AWS Network Firewall

Post Syndicated from Lawton Pittenger original https://aws.amazon.com/blogs/security/introducing-context-aware-rules-for-aws-network-firewall/

AWS Network Firewall now supports context-aware rules, which match traffic by the AWS resources that send and receive it instead of by IP address. A rule can name a virtual private cloud (VPC), a subnet, a security group, or a transit gateway attachment. Rules that match on IP addresses have to keep up with every workload that scales out, is replaced, or moves. Short-lived workloads are the hardest to keep up with. A VPC-attached AWS Lambda function can scale out and start sending traffic before an updated IP list reaches the firewall. With context-aware rules, you can filter a function’s traffic by the security group attached to it.

With context-aware rules, you can:

  • Write rules that follow your workloads – A rule that names a security group applies to each new resource whose network interface has that security group attached. A rule that names a subnet or VPC applies to each new resource that you launch in it. A rule that names a transit gateway attachment applies to traffic that enters through that attachment.
  • Apply one policy across accounts – One context store tracks the resources in the accounts that attach to a shared transit gateway. A rule can name context from any of those accounts.
  • See which resources are behind each connection – Your firewall logs record the resources on each side of a flow, along with their IP addresses.

In this post, we explain how context-aware rules work, set them up across accounts, and show what the logs record.

How context-aware rules work

Context-aware rules require transit gateway-attached firewalls, and they combine a control path and a data path (Figure 1). On the control path, a context store tells the firewall which AWS resources exist. On the data path, the transit gateway adds the context of the sender to each packet. The firewall brings the two together and matches that context against your rules.

Figure 1: How context-aware rules work across accounts

A context store tracks your resources. A context store is a catalog of the AWS resources that can send and receive traffic through a transit gateway. You create it in AWS Network Manager and associate it with the transit gateway that your firewall uses. When you share the transit gateway with workload accounts through AWS Resource Access Manager (AWS RAM), those accounts create transit gateway VPC attachments to it. The context of those attachments, and of the resources behind them, then appears in the same context store. The context store is designed to keep the firewall in sync as you add and remove resources.

The transit gateway tags each packet. When traffic crosses the transit gateway, the transit gateway tags each packet with the context of the resource that sent it. That context is the sender’s VPC, subnet, transit gateway attachment, and the security groups attached to the sender. The firewall gets only the security group IDs, not their rules, so a rule that names any one of those groups matches.

The firewall matches context IDs in your rules. It reads the context on each packet and matches it against your rules. You group context IDs into a context set, a named rule variable that lists resources from the context store associated with the firewall. Then you use the set in the source or destination of a rule, in a Classic or Next Generation firewall policy.

Source context works with every protocol, because each packet carries the context of its sender. Destination context requires TCP-based rules, because the firewall learns the receiving resource from return traffic. For more details, see How context-aware rules work and Matching on destination context. AWS Transit Gateway also shares context with third-party firewalls through Gateway Load Balancer. For that setup, see Introducing resource context for firewall policies with AWS Transit Gateway.

Getting started

In this example, a central networking account owns the transit gateway and the firewall, and shares the transit gateway with workload accounts through AWS RAM. You complete steps 1 and 2 once, in the account that owns the transit gateway.

1. Create a context store. In the AWS Network Manager console, select or create a global network and register your transit gateway with it. Then create a context store and associate it with the transit gateway (). Network Firewall discovers the context store on its own, so there’s nothing to configure on the firewall.

Figure 2: A context store associated with a transit gateway

2. Give Network Firewall access to the context store. In the account that owns the context store, create the AWS Identity and Access Management (IAM) role NetworkFirewallContextStoreReadOnly. Use the trust policy and permissions in Onboarding your transit gateway to a context store. You create the role once for each account that owns a context store.

3. Create a context set. In the Amazon Virtual Private Cloud (Amazon VPC) console, under Network Firewall, create a rule group. On the Rule group variables page, choose Create context set, select your context store, and select the resources for the set. One set can mix context IDs of different resource types, from the accounts in the context store.

Figure 3: Creating a context set from the resources that the context store tracks

4. Check the sync state. Before you write rules, open the firewall’s details page and check the Context store sync state section. It shows the context store that the firewall discovered and its sync state.

Figure 4: The context store sync state on the firewall’s details page

5. Use the context set in your rules. The sample rule from Writing context-aware rules blocks SSH from PROD_RESOURCES to destinations outside your home networks. In a Next Generation firewall rule group, on the Configure rules page, use the Visual rule builder. Choose Drop and TCP. For Sources, choose Match specific criteria, select Context sets, and choose PROD_RESOURCES. For Destinations, choose Match specific criteria, select Destination IP, and enter $EXTERNAL_NET. Set the destination port to 22. Then add the rule group to your firewall policy.

Figure 5: Choosing a context set as a rule’s source in the Next Generation rule builder

The same rule in Suricata-compatible syntax follows. drop:flow is the action and its scope, tcp:all the protocol and connection state, and the rest is the source, destination, and port. In raw rules, you reference a context set with $ and its name; in the console, you pick it from a list.

drop:flow tcp:all $PROD_RESOURCES any -> $EXTERNAL_NET 22 (msg:"Block SSH from production to external"; sid:2001;)

Because the rule names resources and not addresses, it covers each new resource that you launch in those VPCs or attach that security group to.

For Classic policies, the same rule looks like this:

drop tcp $PROD_RESOURCES any -> $EXTERNAL_NET 22 (msg:"Block SSH from production to external"; sid:2001; rev:1;)

What the logs record

After you associate the transit gateway with a context store, Network Firewall adds a context object to its alert log and flow log records. The following records, shortened, show one outbound TLS connection from an application instance to example.com, through a central egress VPC with a network address translation (NAT) gateway. A rule that references the application’s security group blocks the connection and writes this alert log record. The matched list names the security group that the rule matched.

{
  "event": {
    "event_type": "alert",
    "flow_id": 314246768212473,
    "src_ip": "10.1.1.25",
    "dest_ip": "203.0.113.10",
    "dest_port": 443,
    "app_proto": "tls",
    "tls": {
      "sni": "example.com"
    },
    "context": {
      "matched": [
        "sg-0a1b2c3d4e5f60031"
      ]
    },
    "alert": {
      "action": "blocked",
      "signature_id": 2002,
      "signature": "Application A: domain not on its allow list"
    }
  }
}

The flow log record for the same flow_id lists the full context on each side. The src list holds the sender’s context IDs. Flow logs record this context for every flow, even when no rule matches it.

{
  "event": {
    "event_type": "netflow",
    "flow_id": 314246768212473,
    "src_ip": "10.1.1.25",
    "dest_ip": "203.0.113.10",
    "dest_port": 443,
    "app_proto": "tls",
    "context": {
      "src": [
        "vpc-0a1b2c3d4e5f60001",
        "subnet-0a1b2c3d4e5f60011",
        "tgw-attach-0a1b2c3d4e5f60021",
        "sg-0a1b2c3d4e5f60031"
      ],
      "dst": [
        "vpc-0a1b2c3d4e5f60003",
        "subnet-0a1b2c3d4e5f60013",
        "tgw-attach-0a1b2c3d4e5f60023"
      ]
    }
  }
}

The dst list shows how destination context works for traffic to the internet. The firewall learns the destination from the response, and the response reaches the firewall from the NAT gateway. So the destination context is the egress VPC, the NAT gateway’s subnet, and the egress VPC’s transit gateway attachment, not the internet host. You can query these fields by context ID in Amazon CloudWatch Logs Insights. For example, you can see what an application already connects to before you write its rules. For the fields, see Context in your network firewall logs.

Availability and pricing

Context-aware rules are available at no additional charge. Standard AWS Network Firewall and AWS Transit Gateway charges apply to the resources that you use. For details, see AWS Network Firewall pricing and AWS Transit Gateway pricing. They work in the AWS Regions where both Network Firewall and Transit Gateway context sharing are available.

Conclusion

In this post, we showed how you can use context-aware rules in Network Firewall to match traffic on the context of the resources that send and receive traffic. A context store tracks those resources across the accounts that share your transit gateway, and the transit gateway tags each packet with its sender’s context. Your rules and logs then use that context, so your rules can keep up as workloads change. To learn more, see Context-aware rules in AWS Network Firewall.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Lawton Pittenger

Lawton Pittenger

Lawton is a Worldwide Security Specialist Solutions Architect at AWS, based in New York City. He helps customers design and implement effective network security controls, and works with AWS service teams to improve security services based on customer feedback. Outside of work, he enjoys skateboarding, snowboarding, and spending time in nature.

Santosh Shanbhag

Santosh Shanbhag

Santosh is a seasoned product leader, specializing in security, data protection, and compliance. At AWS, he focuses on securing workloads through Network and Application Security services, including AWS Network Firewall and active threat defense.

Rahi Patel

Rahi Patel

Rahi is a Startups Technical Account Manager at AWS specializing in Networking. He architects cloud networking solutions, optimizing performance across global AWS deployments. Previously a network engineer with Cisco Meraki, he holds an MS in Engineering from San Jose State University. Outside work, he enjoys tennis and pickleball.

Mahesh Elireddy

Mahesh Elireddy

Mahesh is a Senior Software Development Engineer at AWS, where he has spent 10 years building the network. He has been a part of the teams that built Network Load Balancer, Gateway Load Balancer, and NAT Gateway, and now works on AWS Network Firewall. Outside of work, he likes spending time outdoors in the Pacific Northwest with his family.

Introducing AWS Network Firewall Next Generation policy

Post Syndicated from Lawton Pittenger original https://aws.amazon.com/blogs/security/introducing-aws-network-firewall-next-generation-policy/

When it comes to inspecting network traffic, many security teams want two things from a firewall. They want to allow only the traffic each application needs, and they want each allowed connection checked for known threats. Today, you can do both with AWS Network Firewall, a stateful, managed network firewall and intrusion detection and prevention service. In a Classic policy, your access rules and your threat rules run together in one stateful engine and share one rule capacity.

With Next Generation policies, access control and threat protection each get their own engine in the same firewall. A firewall engine allows the traffic you approve and drops the rest. An intrusion prevention system (IPS) engine checks the allowed traffic with AWS managed rule groups or with rules that you write. Each engine has its own rule capacity, so adding access rules doesn’t take capacity away from threat protection.

In this post, we walk through what Next Generation policies are, how they evaluate traffic, and the new concepts they introduce. We use sample records to cover what each engine logs and how to validate a policy with the new monitor mode. To put it all together, we walk through creating an example Next Generation policy.

How a Next Generation policy works

A Next Generation policy inspects traffic with two engines, in sequence. Traffic that the firewall engine allows moves to the IPS engine, and traffic that the firewall engine blocks goes no further. The firewall engine is drop by default, and the IPS engine is pass by default.

If you already write Suricata rules, the two engines will feel familiar. The firewall engine is built on Suricata 8 firewall mode, which follows each connection as it progresses and evaluates rules at each step. The IPS engine uses the Suricata compatible intrusion detection system (IDS) and IPS rules that you already know from the stateful engine in a Classic policy, with one difference: it evaluates rules in action order and doesn’t support Classic options such as strict order.

A Classic policy uses a stateless engine and then a stateful engine that evaluates access rules and threat rules together. In a Next Generation policy, both engines are stateful, so each rule is evaluated with full connection context, which helps keep traffic handling consistent and predictable. The firewall engine works up to the application layer. It follows each connection for its entire flow, from the first packet through the TCP handshake and application layer exchanges such as the TLS client hello, and evaluates your access rules along the way (Figure 1).

Figure 1: Classic and Next Generation policy engines and their rule capacity.

Figure 1: Classic and Next Generation policy engines and their rule capacity.

This separation changes how you design a policy. Because each engine has one job, you can plan access control and threat protection on their own, and different teams can work independently. For example, a networking team can manage access rules while a security team handles threat detection, and neither has to rewrite the other’s rules.

The firewall engine controls access

You configure access control by specifying an action for a protocol, along with a source and destination. Rules run in the order that you set. Traffic that no rule allows gets the policy’s firewall default action, which is drop unless you change it. In a Next Generation policy, the drop default action applies from the first packet, so for TCP traffic the firewall can drop the initial SYN. Unlike the drop established default action in a Classic policy, it doesn’t wait for a connection to be established.

A few terms explain how the firewall engine evaluates traffic. Connection states are the protocol states that a connection progresses through, such as the TCP handshake and the TLS client hello. A hook is the point at a connection state where your rules attach, so a rule’s hook sets when the firewall engine evaluates it. Each rule also has an action, such as accept, drop, or reject. Its action scope sets how much of the traffic the action applies to, from one packet or one transaction up to the whole connection, called the flow. For more details, see Firewall engine hooks.

When you build a rule in the console, you choose a protocol and then two settings: Connection state, which sets the rule’s hook, and Action scope. For example, to allow a domain over TLS, you match its server name at the Client Hello connection state with the This flow action scope.

Because the firewall engine is drop by default, a connection advances to the next connection state only while your rules keep accepting it. For example, a connection can pass the TCP handshake and still be dropped at the TLS client hello. That happens when its server name isn’t on your approved list (Figure 2).

Figure 2: A connection is accepted at the TCP handshake hook and dropped at the TLS client hello hook.

Figure 2: A connection is accepted at the TCP handshake hook and dropped at the TLS client hello hook.

In Figure 2, the rule for www.amazon.com accepts the flow when it matches the server name at the TLS client hello hook. No rule accepts example.com at that hook, so the firewall default action drops it.

You don’t have to write every rule in raw Suricata syntax. You can build rules in the console rule builder, or, as in the example later in this post, enter your domains in a domain list rule group, and Network Firewall builds the rules for you.

Action scope also sets where an accepted connection goes next. An accept with the hook scope allows the connection to advance to the next connection state, where the rules at that hook evaluate it. An accept with the flow scope lets the connection skip the remaining hooks and move to the IPS engine (Figure 3). A firewall rule can also bypass the IPS engine for specific traffic when you choose. For the valid combinations of action and scope at each type of hook, see Firewall engine actions and scopes.

Figure 3: An accept with the hook scope compared with an accept with the flow scope.

Figure 3: An accept with the hook scope compared with an accept with the flow scope.

The IPS engine looks for threats

Traffic that the firewall engine allows then reaches the IPS engine, which inspects it with Suricata compatible rules. The IPS engine is designed to look for specific threats, so it blocks only traffic that matches a threat rule. IPS rules evaluate in action order. Pass rules go first, then drop, reject, and alert rules, regardless of the order in which you define them. For the full path through both engines, see How Network Firewall filters traffic with a Next Generation policy.

We recommend that you start with the AWS managed rule groups. Because the IPS engine is built on the industry standard Suricata engine, you can also run Suricata compatible rule sets from specialized security providers, alongside rules that you write yourself.

Referenced rule groups and embedded rules

Each engine gets its rules from its own section of the policy. You can add rules in two ways and mix both in one section.

Referenced rule groups are separate resources, and they’re the only kind of rule group that Classic policies support. You create a rule group once and add it to as many policies as you need. You can also share it with other accounts through AWS Resource Access Manager (AWS RAM). For details, see Sharing AWS Network Firewall resources. When you update the rule group, each policy that references it picks up the change. You set a referenced rule group’s capacity when you create it, and you can’t change it afterward, so leave room for it to grow.

Embedded rules are new with Next Generation policies. You write them directly inside one policy, and they belong to that policy only, so you can’t share them with another policy. Use them to add rules quickly that are specific to that policy. They use that engine’s rule capacity, and you don’t set a capacity up front. Embedded rules in both engine sections share a combined limit. For all limits, see AWS Network Firewall quotas.

Read what each engine logs

Whichever way you add rules, both engines write to the same alert and flow logs, which you configure in the logging configuration. Each alert record carries new fields that show which engine wrote it and, for the firewall engine, the hook where the decision happened.

The following record came from a test, in enforce mode, of the example policy that you build later in this post. A host tried to reach example.com, which isn’t on the allow list.

{
  "firewall_name": "example-fw",
  "availability_zone": "us-east-1a",
  "event_timestamp": "1794341434",
  "event": {
    "event_type": "alert",
    "app_proto": "tls",
    "src_ip": "10.0.1.25",
    "src_port": 42698,
    "dest_ip": "203.0.113.10",
    "dest_port": 443,
    "proto": "TCP",
    "tls": {
      "sni": "example.com"
    },
    "alert": {
      "engine": "fw",
      "action": "blocked",
      "signature_id": 2201001,
      "signature": "SURICATA FW default app policy",
      "severity": 3
    },
    "firewall": {
      "hook": "tls:client_hello",
      "policy": "drop:flow,alert"
    },
    "verdict": {
      "action": "drop"
    },
    "aws_metadata": {
      "resource_arn": "arn:aws:network-firewall:us-east-1:111122223333:firewall-policy-v2/example-policy"
    },
    "timestamp": "2026-11-10T20:10:34.141643+0000"
  }
}

The following table explains the key fields in this record.

Field Value What it tells you
alert.engine fw The firewall engine wrote this record.
firewall.hook tls:client_hello The decision happened at the TLS client hello, where the client sends the server name example.com.
alert.signature SURICATA FW default app policy No rule matched, so the firewall default action applied. The default action logs its drops on its own, so you don’t need an alert rule to see what it blocks.
firewall.policy drop:flow,alert The action and scope that applied. The default action dropped the whole flow and wrote an alert.
aws_metadata.resource_arn arn:aws:network-firewall:us-east-1:111122223333:firewall-policy-v2/example-policy The policy itself is the source, because the record doesn’t come from one of your rule groups.

When a connection that the firewall engine allowed matches a threat rule, the IPS engine writes its own record. In this test, the firewall engine allowed TLS to one test server by IP address. The IPS section also held the following embedded rule, which drops TLS connections with a JA4 fingerprint that your threat intelligence flags. The fingerprint in this rule is a sample value:

drop tls $HOME_NET any -> $EXTERNAL_NET any (msg:"Example: flagged TLS client fingerprint (JA4)"; flow:to_server,established; ja4.hash; content:"t13d1516h2_aaaaaaaaaaaa_bbbbbbbbbbbb"; classtype:trojan-activity; sid:900002; rev:1;)

This is a sample rule to show the IPS engine at work. In your own policies, we recommend that you start with the AWS managed threat signature rule groups and add custom rules where you need them.

A test client with that fingerprint connected to that server without a server name, and the IPS engine wrote the following record.

{
  "firewall_name": "example-fw",
  "availability_zone": "us-east-1a",
  "event_timestamp": "1794377726",
  "event": {
    "event_type": "alert",
    "app_proto": "tls",
    "src_ip": "10.0.1.25",
    "src_port": 38342,
    "dest_ip": "198.51.100.7",
    "dest_port": 443,
    "proto": "TCP",
    "tls": {
      "version": "TLS 1.3",
      "ja4": "t13d1516h2_aaaaaaaaaaaa_bbbbbbbbbbbb"
    },
    "alert": {
      "engine": "td",
      "action": "blocked",
      "signature_id": 900002,
      "signature": "Example: flagged TLS client fingerprint (JA4)"",
      "category": "A Network Trojan was detected",
      "severity": 1
    },
    "verdict": {
      "action": "drop"
    },
    "aws_metadata": {
      "resource_arn": "arn:aws:network-firewall:us-east-1:111122223333:firewall-policy-v2/example-policy"
    },
    "timestamp": "2026-11-11T06:15:26.671435+0000"
  }
}

Field Value What it tells you
alert.engine td The IPS engine wrote this record. IPS records have no firewall object, because IPS rules don’t use hooks.
tls.ja4 t13d1516h2_aaaaaaaaaaaa_bbbbbbbbbbbb The JA4 fingerprint of the client, which matches the fingerprint in the rule.
alert.signature Example: flagged TLS client fingerprint (JA4) The IPS rule that matched, from the rule’s msg option.
alert.category A Network Trojan was detected The rule’s classtype, trojan-activity, sets this category.
verdict.action drop The IPS engine dropped the connection.
aws_metadata.resource_arn arn:aws:network-firewall:us-east-1:111122223333:firewall-policy-v2/example-policy The rule is embedded in the policy, so the record shows the policy ARN. A match from an AWS managed rule group or one of your referenced rule groups carries that rule group’s ARN instead.

To separate access control events from threat events in your queries, filter on the engine field. To find which rule group produced an event, use resource_arn. Embedded rules and the default action show the policy ARN.

Validate in monitor mode, then enforce

Each Next Generation policy has a policy mode, enforce or monitor. In enforce mode, the engines apply their actions. In monitor mode, both engines evaluate your traffic and log what they would do. Your rules and the default action don’t drop or reject traffic.

Monitor mode also turns on alert logging for your rules and the default action, so each firewall rule that would block traffic logs its matches. That makes monitor mode a lower-risk way to stage a rollout of a new policy or a change to an existing one. Monitor logs are close to enforce mode but can differ. When a firewall rule would block a connection, monitor mode lets the connection through but sends it past the IPS engine, just as a blocked connection never reaches the IPS engine in enforce mode. So the monitor logs don’t show IPS alerts for that connection. For the full list of differences, see Policy mode: enforce and monitor.

To validate a policy in monitor mode:

  1. Set Policy mode to Monitor, and confirm that alert logging is on for the firewall. Amazon Route 53 Resolved IP Validation still applies its configured action in monitor mode, so if your policy uses it, set its action to Alert.
  2. Send representative traffic for long enough to cover your normal patterns.
  3. In your alert logs, filter on engine = fw. Check the FirewallDefaultActionApplied metric in Amazon CloudWatch. Traffic that you meant to allow shouldn’t be reaching the default action.
  4. When the results look right, switch Policy mode to Enforce during a maintenance window. Changing the policy mode or the firewall default action restarts stateful inspection on the firewall, which interrupts established connections.

Example policy with a domain allow list and threat protection

The following example puts the engines, logs, and monitor mode together. It allows outbound traffic only to approved domains and checks that allowed traffic for known threats. The firewall engine holds the domain allow list, and the IPS engine runs the AWS active threat defense managed rule group. Figure 4 shows the policy and where each of the earlier log records comes from. Log record 2 comes from the sample embedded rule, which isn’t part of the policy that you create in the following steps.

Figure 4: The example policy, with the sample embedded rule behind log record 2.

Figure 4: The example policy, with the sample embedded rule behind log record 2.

To create the domain list rule group:

  1. In the Network Firewall console, choose Network Firewall rule groups, and then choose Create rule group. Choose Next Generation as the rule group version, Firewall rule group as the type, and Domain list as the format.

    Figure 5: Choosing the rule group version, type, and format for the domain list.

    Figure 5: Choosing the rule group version, type, and format for the domain list.

  2. Enter one domain per line, for example .amazon.com and checkip.amazonaws.com, and under Protocols, select HTTPS only. For HTTPS, the firewall matches the TLS Server Name Indication (SNI) without decrypting traffic. SNI is the server name that a client sends at the start of a TLS connection. To include a domain and its subdomains, start the name with a dot.
  3. For Capacity sizing, choose Allow room to grow, and then create the rule group.

To create the policy:

  1. Choose Firewall policies, and then choose Create firewall policy. Select Next Generation as the policy version and Drop as the firewall default action, so the firewall blocks traffic that you don’t allow. Set Policy mode to Monitor. We recommend rolling out a new policy in monitor mode first, then switching to enforce after you validate it. Enable Active Threat Defense is selected by default. Active threat defense is optional. Additional charges apply; for details, see AWS Network Firewall pricing.
    Figure 6: The policy details page, with Next Generation, Drop, and Monitor selected.

    Figure 6: The policy details page, with Next Generation, Drop, and Monitor selected.

  2. On the Add firewall rule groups step, add the domain list rule group that you created in the previous procedure.
  3. On the Add IPS rule groups step, the active threat defense managed rule group, listed as AttackInfrastructure, is already added. It comes from the Enable Active Threat Defense default that Figure 6 shows. Choose Add rule group to add more AWS managed rule groups, your own rule groups, or embedded rules.
  4. Create the policy, associate it with your firewall, and turn on alert and flow logging.
  5. After you validate the policy, as described in Validate in monitor mode, then enforce, switch Policy mode to Enforce.

For more detail, see Creating a rule group for a Next Generation policy and Generating firewall rules from domain names.

Already using Classic policies?

Classic Network Firewall policies remain supported, and your existing firewalls keep running as they are. Each firewall uses one policy type at a time, either a Classic policy or a Next Generation policy. For new firewalls, we recommend Next Generation policies. We’re working on migration guidance for existing policies, so you can plan a move when it suits you.

To try one now, create a test firewall with a Next Generation policy and start it in monitor mode. To compare the two policy types, see AWS Network Firewall firewall policy versions. Next Generation policies are available at no additional charge. You pay the standard Network Firewall charges for your firewall endpoints and the traffic they process. For Regions and pricing, see AWS Services by Region and AWS Network Firewall pricing.

Conclusion

In this post, we showed you how a Next Generation policy gives access control and threat protection separate engines, each with its own rule capacity, so you can grow your firewall rules and IPS rules independently. We also showed what each engine logs, how to validate a policy in monitor mode, and how to build a policy that allows only approved domains and checks the allowed traffic for threats. To learn more, see Getting started with a Next Generation policy, and to automate your policies, use the AWS Command Line Interface (AWS CLI) or the AWS SDKs.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Lawton Pittenger

Lawton Pittenger

Lawton is a Worldwide Security Specialist Solutions Architect at AWS, based in New York City. He helps customers design and implement effective network security controls, and works with AWS service teams to improve security services based on customer feedback. Outside of work, he enjoys skateboarding, snowboarding, and spending time in nature.

Santosh Shanbhag

Santosh is a seasoned product leader, specializing in security, data protection, and compliance. At AWS, he focuses on securing workloads through Network and Application Security services, including AWS Network Firewall and active threat defense.

Aneesh Patel

Aneesh Patel

Aneesh is a Software Development Engineer at AWS, based in Herndon, Virginia. He builds and maintains AWS Network Firewall, a managed service that helps customers protect their VPC networks. Outside of work, he enjoys snowboarding, working out, and playing video games.

AWS Network Firewall introduces automated internet firewall mode (Preview)

Post Syndicated from Lawton Pittenger original https://aws.amazon.com/blogs/security/aws-network-firewall-introduces-automated-internet-firewall-mode-preview/

AWS Network Firewall now offers automated internet firewall mode (Preview). In this mode, Network Firewall applies your centrally defined rules to traffic at the internet gateway of each of your virtual private clouds (VPCs). It also performs built-in network address translation (NAT) for outbound-only connections. A subnet that reaches the internet needs only one route, directly to the internet gateway. You no longer need to deploy firewall endpoints and NAT gateways in each VPC and configure the routes between them and the subnets. If you’re new to internet traffic inspection, you can start with AWS managed rule groups for Network Firewall. AWS security experts maintain and update these rule groups to help protect your workloads against changing threats. You can deploy these managed rule groups centrally across your environment.

With automated internet firewall mode, you can:

  • Inspect traffic at the internet gateway – Each VPC gets its own firewall for inbound and outbound IPv4 and IPv6 traffic, with built-in NAT for outbound-only IPv4 connections.
  • Manage centrally, inspect in each VPC – You define policies in AWS Network Security Manager or start from an AWS managed template. Each VPC’s traffic passes its own firewall, so each VPC you add brings its own inspection capacity. The same central policy also works for VPCs with overlapping Classless Inter-Domain Routing (CIDR) ranges.
  • Extend coverage to new VPCs – You can create a scope that includes all existing and future VPCs, so your policy applies to new VPCs when teams create them.

In this post, we explain how automated internet firewall mode works and how it fits your existing architecture. We also walk through the steps to deploy it across your environment.

How automated internet firewall mode works

In automated internet firewall mode, Network Firewall applies your rules at the internet gateway of each VPC. Before this launch, inspecting a VPC’s internet traffic meant routing each subnet through a firewall endpoint. Resources that needed outbound-only connectivity also went through a NAT gateway. This mode helps simplify that model by moving inspection to each VPC’s internet gateway. Each subnet now has one route to the internet gateway, where the firewall inspects the traffic and performs built-in NAT (Figure 1).

Figure 1: Outbound traffic before and after automated internet firewall

Figure 1: Outbound traffic before and after automated internet firewall

Each VPC gets its own firewall, not a share of one. When you use VPC endpoint associations to protect multiple VPCs with one firewall, those VPCs share that firewall’s capacity in each Availability Zone. In automated internet firewall mode, each VPC’s firewall supports throughput of up to 100 Gbps in each Availability Zone (Service quotas). It also works when VPCs have overlapping CIDR ranges, because their traffic doesn’t meet in a shared inspection network where the addresses would conflict.

The firewall inspects inbound and outbound traffic. For outbound-only connectivity, the firewall first inspects the traffic and then performs NAT, so your rules and logs see each workload’s private IP address. Built-in NAT translates outbound IPv4 connections from resources without a public IP address, and IPv6 traffic isn’t translated. If your destinations accept only allowlisted source addresses, an Amazon VPC IP Address Manager (IPAM) policy lets you choose the NAT addresses that automated internet firewall mode uses (NAT for outbound traffic).

The firewall uses Network Firewall Next Generation firewall policies. You can start from AWSManagedTemplateIGWFirewallBaseline, an AWS managed template that AWS security experts maintain. You can then add AWS managed rule groups and your own rule groups.

Automated internet firewall mode only inspects traffic that crosses the internet gateway. For traffic between VPCs and to on-premises networks over AWS Direct Connect or AWS Site-to-Site VPN, we recommend a transit gateway-attached Network Firewall.

Subnet connectivity options

Before this launch, a public subnet had a direct route to the internet gateway, and its resources used public IP addresses, so they could connect out and accept inbound connections. A private subnet had no direct route, and its resources reached the internet through a NAT gateway. With automated internet firewall mode, a subnet that reaches the internet can route 0.0.0.0/0 directly to the internet gateway, so the route table no longer separates public from private. Instead, each subnet’s connectivity type decides how its resources reach the internet. You set it in the Network Security Manager policy, not on the subnet. Table 1 maps each type to the model you know.

Connectivity type Works like What happens
Flexible (recommended) A public and a private subnet in one A resource with a public IP address, such as an Elastic IP address, gets bidirectional access, as in a public subnet. A resource without one gets outbound-only access through built-in NAT, similar to a private subnet.
Bidirectional A public subnet Resources with a public IP address connect out and accept inbound connections. Resources without one can’t reach the internet.
Outbound-only A private IPv4 subnet behind a NAT gateway, or an IPv6 subnet behind an egress-only internet gateway Unsolicited inbound connections are dropped. Resources without a public IP address connect out through built-in NAT, and resources with one keep their own address.
Excluded A subnet without a firewall Traffic bypasses the firewall and built-in NAT.

The firewall inspects traffic in each type except excluded (Figure 2). Each policy sets one default connectivity type for all subnets in scope. You can override it for specific subnets based on tags or on Amazon Resource Name (ARN). When a subnet matches more than one override, the first one in the list applies.

Figure 2: Flexible, bidirectional, and outbound-only subnets are inspected. Excluded subnets aren’t.

Figure 2: Flexible, bidirectional, and outbound-only subnets are inspected. Excluded subnets aren’t.

Connectivity types also decide which inbound connections reach your resources. The firewall inspects inbound connections to resources with a public IP address in flexible and bidirectional subnets, such as the Network Load Balancer for a non-HTTP service in Figure 3. Figure 3 also shows the outbound path, where instances without a public IP address connect out through the firewall and then built-in NAT. For web applications and APIs, we still recommend AWS WAF on Amazon CloudFront in front of an Application Load Balancer. You can set that load balancer’s subnet to excluded so Network Firewall doesn’t inspect the same request again. Keep in mind that excluded applies in both directions, so any outbound traffic from that subnet also bypasses the firewall.

Figure 3: Inbound and outbound traffic showing inbound, outbound, and excluded connections

Figure 3: Inbound and outbound traffic showing inbound, outbound, and excluded connections

Managing automated internet firewall mode

You manage automated internet firewall mode in AWS Network Security Manager. With AWS Organizations, a central security team deploys policies from the Network Security Manager administrator account to the whole organization, to organizational units (OUs), or to specific accounts. Network Security Manager also supports a single-account model, where it applies policies only to that account’s VPCs. You can start from the Network Firewall console or the Network Security Manager console, but the firewall itself is read-only outside Network Security Manager.

Network Security Manager uses three components (Figure 4):

  • Policy – Combines rules and templates with the connectivity type, enforcement mode, logging, and priority. Rules are the building blocks. A traffic inspection rule decides how the firewall handles traffic, and a firewall configuration rule sets options such as the enforcement mode or logging. A template is an ordered, reusable group of rules, such as AWSManagedTemplateIGWFirewallBaseline, that you can share across policies.
  • Scope – Selects your organization, OUs, accounts, or VPCs.
  • Deployment – Binds a policy to a scope. Network Security Manager then creates and manages a firewall in each VPC in scope.
Figure 4: A deployment binds a policy to a scope, and Network Security Manager creates a firewall in each VPC in scope

Figure 4: A deployment binds a policy to a scope, and Network Security Manager creates a firewall in each VPC in scope

This model matters most when you manage many VPCs. Because Network Security Manager applies the policy at the internet gateway, the firewall is designed so that VPC owners and subnet owners without the proper privileges can’t bypass inspection by changing routes. Subnets set to excluded and Availability Zones where automated internet firewall mode isn’t supported aren’t inspected.

Many organizations want one security baseline everywhere, while some accounts, organizational units, or applications need rules in addition to the baseline. To do this, you create two policies, each deployed to its own scope. The organization policy holds a baseline template, and the Account A policy holds the same baseline template plus Account A’s rules (Figure 5). The template lets you maintain the baseline rules once and reuse them in both policies. Where policies overlap, the policy with the lower priority number applies in full, and the policies don’t merge. In Account A, the Account A policy (priority 100) wins over the organization policy (priority 1000), so it must include the baseline template. Its enforcement mode, logging, and connectivity type also replace the organization policy’s. To learn more, see How AWS Network Security Manager works.

Figure 5: The Account A policy, priority 100, takes priority in Account A. Other accounts get the organization policy, priority 1000.

Figure 5: The Account A policy, priority 100, takes priority in Account A. Other accounts get the organization policy, priority 1000.

Getting started

We recommend starting in monitor mode, especially in VPCs with existing workloads. In monitor mode, the firewall logs what your rules would do but doesn’t drop traffic because of them. After the logs show the results you expect, switch the policy to enforce. In this example, we create a policy in monitor mode in six steps.

  1. Start from the AWS Management Console for Network Firewall. On the Firewalls page, open the Internet firewalls tab and choose Create in AWS Network Security Manager. The Quick create and deploy page opens in the Network Security Manager console. Select Network Firewall automated internet firewall as the firewall type.

    Figure 6: Create a new internet firewall

    Figure 6: Create a new internet firewall

  2. Define protections. Choose Manage templates and add AWSManagedTemplateIGWFirewallBaseline. Under Enforcement mode, select Monitor, and choose destinations for alert logs and flow logs.

    Figure 7: Define protections and set destinations for logs

    Figure 7: Define protections and set destinations for logs

  3. Enter a name for the policy and check its Policy priority. Where policies overlap, the lower number takes priority. The new policy gets a priority that evaluates after your existing policies of the same firewall type, and you can change it later in the policy editor.

    Figure 8: Set the policy details

    Figure 8: Set the policy details

  4. Set the scope. For example, you can set the scope for Accounts and OUs to include the entire organization and the scope for VPCs to include all existing and future VPCs. To learn more about scopes, see How AWS Network Security Manager works.

    Figure 9: Set the scope

    Figure 9: Set the scope

  5. Choose the Subnet connectivity type. For example, select Flex (recommended).

    Figure 10: Choose the subnet connectivity type

    Figure 10: Choose the subnet connectivity type

  6. Review your settings and choose Create and deploy. Cross-account visibility lets Network Security Manager see resources in the accounts in the scope.

    Figure 11: Review and deploy

    Figure 11: Review and deploy

Network Security Manager then creates a firewall at the internet gateway of each VPC in scope. For the full steps, including the organization baseline with account-specific rules, see Getting started with automated internet firewall.

Migrating existing VPCs to automated internet firewall mode

When you deploy automated internet firewall mode to an existing VPC, you might not need to change routes on day one. With the flexible type, the firewall inspects existing resources and keeps the addresses they already use (Figure 12):

  • Instance with an Elastic IP address – The firewall inspects its traffic, and the instance keeps its Elastic IP address.
  • Instance behind a NAT gateway – The firewall inspects the traffic after the NAT gateway translates it and doesn’t translate it again. Your rules and logs see the NAT gateway’s private IP address as the source.
  • Instance with no public IP address in a subnet that routes to the internet gateway – The firewall inspects its traffic, and built-in NAT gives it outbound-only access, which it didn’t have before. To keep resources without a public IP address isolated from the internet, set the subnet’s connectivity type to bidirectional instead. Resources with a public IP address then keep bidirectional connectivity, and resources without one can’t reach the internet.
Figure 12: Day-one source addresses in an existing VPC with Flexible subnets

Figure 12: Day-one source addresses in an existing VPC with Flexible subnets

Later, at your own pace, you can retire each NAT gateway by routing its subnets directly to the internet gateway. Built-in NAT then takes over. The source address changes to one that automated internet firewall mode assigns or one from your IPAM policy pool, so update allow lists that name the NAT gateway’s address first. Your logs then show each workload’s private IP address. If you inspect inbound or outbound internet traffic today with Network Firewall endpoints, automated internet firewall mode can take over that inspection. After you confirm that your new policy covers the same rules, you can remove the endpoints and routes that you use for internet traffic. For each architecture, see Working with existing architectures.

Availability and pricing

Automated internet firewall mode (Preview) is available in all AWS commercial Regions. For pricing, see AWS Network Firewall pricing. During the preview, some features and instance types aren’t supported. For the list, see Automated internet firewall. Features, service quotas, and console labels can change during the preview. Your use of the preview is subject to the Betas and Previews section of the AWS Service Terms.

Conclusion

In this post, we showed you how automated internet firewall mode applies Network Firewall inspection and built-in NAT at the internet gateway of your VPCs. You define and control policies centrally in Network Security Manager. It is designed so that VPC owners without the proper privileges can’t route around it, and your policy applies to new VPCs in scope when teams create them. To learn more, see Automated internet firewall in the Network Firewall Developer Guide.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Lawton Pittenger

Lawton Pittenger

Lawton is a Worldwide Security Specialist Solutions Architect at AWS, based in New York City. He helps customers design and implement effective network security controls, and works with AWS service teams to improve security services based on customer feedback. Outside of work, he enjoys skateboarding, snowboarding, and spending time in nature.

Akshay Choudhry

Akshay Choudhry

Akshay is a Principal Product Manager in the Networking and Security Services Team at Amazon Web Services. He’s focused on making virtual private clouds more intuitive and secure for the millions of customers running their workloads on AWS. In his free time, he enjoys exploring the outdoors, trying out new restaurants, and spending time with friends and family.

Know the identity behind the role: Authorize and audit with trusted identity propagation

Post Syndicated from Laura Reith original https://aws.amazon.com/blogs/security/know-the-identity-behind-the-role-authorize-and-audit-with-trusted-identity-propagation/

Today, AWS is making it easier to grant access and audit activity based on the user or workload (a non-human caller, such as an application, service, or an automated workflow) behind an AWS Identity and Access Management (IAM) role. Trusted identity propagation (TIP) carries the identity of the user or workload with each AWS request, so you can grant permissions to that user or workload and trace its actions in AWS CloudTrail. Until now, TIP was available only for users who access AWS through AWS IAM Identity Center. We’ve extended TIP to IAM federation and AWS IAM Roles Anywhere, making it work for users and workloads that federate directly into IAM roles or use X.509 certificates to obtain AWS credentials. We’ve also made TIP simpler to use with IAM Identity Center.

This post explains how TIP works and what’s new with this launch. It then shows two examples of how TIP improves auditability and access control based on the user or workload behind an IAM role. The post ends with how to get started depending on your preferred federation path into AWS.

How trusted identity propagation works

Customers have told us they want to control access to AWS resources and audit activity based on the user or workload behind an IAM role. Today, access control decisions apply to the role, and CloudTrail attributes each action to the role session. To give two users or workloads different access, you either create a separate role or share one role and write policies that check session attributes. Separate roles lead to role proliferation. Session attributes carry across role sessions only when you grant additional permissions, and the session doesn’t record who set each attribute.

TIP addresses this gap by attaching identity context from a trusted source, such as your identity provider (IdP), to the role session at the time of credential issuance. This identity context identifies the user or workload behind a request and can include optional claims for the session, such as a risk score or a continuous integration and delivery (CI/CD) workflow name. Trusted sources include external SAML or OIDC IdPs configured for IAM federation, IAM Identity Center, and X.509 certificates configured for IAM Roles Anywhere.

After AWS attaches identity context to a role session, the context can’t be changed for the lifetime of the session. This approach gives IAM policies and audit records a stable reference to the user or workload behind each request. The context also carries forward to supported downstream requests. When a TIP session (a role session that carries identity context) assumes another role, AWS Security Token Service (AWS STS) carries the context into the new role session. Similarly, when an AWS service makes a downstream request on your behalf, the request uses forward access sessions (FAS), and the FAS credentials carry the identity context from your session.

Note: TIP context propagates to a new role session only when the target role is in the account where the identity provider is configured, or if the target role is in another account in the same AWS organization. To learn how account and organization boundaries determine TIP context propagation, see Understand where TIP context propagates in the IAM User Guide.

Figure 1 shows how this flow works end-to-end. A user or workload obtains AWS credentials through one of three paths. With IAM federation, the source is a SAML assertion or OIDC token for a user or workload. With IAM Identity Center, the source is the username that IAM Identity Center receives from your identity source. With IAM Roles Anywhere, the source is an X.509 certificate for a user or workload. AWS validates the source and attaches identity context to the role session. That context stays with the session’s requests, whether the session calls an AWS service directly, assumes another role, or causes an AWS service to make downstream requests through FAS. IAM policies then evaluate the identity context to authorize requests, as the Amazon Simple Storage Service (Amazon S3) bucket policy example later in this post shows, and AWS CloudTrail records it, as the AWS Lambda example shows. With IAM outbound identity federation, the session can also request a signed JSON Web Token (JWT) that carries identity context to an external service.

Figure 1: How TIP carries identity information into authorization and audit workflows

Figure 1: How TIP carries identity information into authorization and audit workflows

AWS represents the identity context carried in a TIP session through three groups of context keys. The following table summarizes their purpose and points to the corresponding documentation. For details about what these context keys contain and when they appear in a TIP session, see TIP context keys in IAM policies.

Context keys Purpose
aws:OriginIdentity/* Identifies the user or workload that started the request and the source that issued its identity.
aws:TransactionContext/IdentityProvider/* Carries optional claims from your IdP, such as a risk score or a CI/CD workflow name. Available only for IAM federation.
aws:IdentityCenterInstanceArn and aws:IdentityStoreArn Identifies the IAM Identity Center instance and identity store behind a session. If you use IAM Identity Center permission sets or IAM account access manager, you can use these keys in IAM policy conditions. For example, you can allow access only to workforce users from a specific instance.

Table 1: TIP context key categories and what they represent.

aws:OriginIdentity/* is the common namespace for identity information from IAM federation, IAM Identity Center, and IAM Roles Anywhere. Across all three paths, aws:OriginIdentity/Subject identifies the user or workload that started the request, aws:OriginIdentity/SubjectType indicates whether the request was started by a user or workload, and aws:OriginIdentity/Issuer identifies the source that issued the identity. For IAM federation and IAM Roles Anywhere, aws:OriginIdentity/FederatedProviderArn also contains the Amazon Resource Name ARN) of the IAM IdP or IAM Roles Anywhere trust anchor that authenticated the identity.

IAM policies can evaluate TIP context keys when those keys are present in the request. CloudTrail records identity context in the userIdentity element of events. The userIdentity.onBehalfOf section records the user or workload identity from aws:OriginIdentity context keys, and the userIdentity.transactionContext section records IdP claims from aws:TransactionContext/IdentityProvider context keys. For field definitions and examples see Logging TIP activity with AWS CloudTrail.

Key benefits of trusted identity propagation

TIP gives you the following benefits for authorizing and auditing access based on the user or workload behind an IAM role.

  • Audit by identity, not only by role – CloudTrail records the user or workload behind each request.
  • Authorize based on who’s asking – IAM policies can grant or restrict access based on the user or workload, or on optional claims from your IdP, such as a risk score. This gives you precise access control for each session.
  • Rely on identity you can trust – AWS attaches identity context from a trusted source when it issues credentials. That context can’t be changed for the life of the session, and it carries forward when the session assumes another role or an AWS service makes requests on your behalf.
  • Use one model across federation paths – IAM federation, IAM Identity Center, and IAM Roles Anywhere share the same core aws:OriginIdentity context keys, so you write policies and review CloudTrail consistently across more than 250 supported AWS services. Across supported workflows, identity context propagates without adding the sts:SetContext permission to role trust policies.

What’s new with this launch

This launch extends TIP to IAM federation and IAM Roles Anywhere, and simplifies TIP in IAM Identity Center. You can also share identity context with services outside AWS through IAM outbound identity federation.

  • AWS IAM Identity Center – TIP already allows AWS applications integrated with IAM Identity Center, such as AWS Lake Formation and Amazon S3 Access Grants, to audit user activity and control access based on the user’s identity. When you enable the simplified experience, Identity Center adds a username, an identifier from your identity source, alongside the system-generated identity store user ID. This identity information is carried consistently across all access paths, including application access, account access through IAM Identity Center permission sets, and IAM account access manager. With this launch, you can now use the propagated username, mapped to the aws:OriginIdentity/Subject context key, in IAM policy conditions and view it in CloudTrail events. For more information, see Simplified experience for trusted identity propagation.
  • IAM federation – For users and workloads that use direct SAML or OIDC federation into IAM roles, you choose the SAML assertion field or OIDC token claim that identifies the user or workload, and TIP attaches it to the role session. You can also map optional SAML attributes or OIDC claims, such as a risk score or a CI/CD workflow name, into aws:TransactionContext/IdentityProvider/* context keys. TIP is turned on by default for new IAM IdPs, and you can turn it on for existing providers. For more information, see TIP for IAM Federation.
  • IAM Roles Anywhere – For users and workloads outside AWS that use X.509 certificates with IAM Roles Anywhere, TIP attaches the identity from the certificate to the role session. After IAM Roles Anywhere validates the certificate against the configured trust anchor, AWS sets aws:OriginIdentity/Subject to the certificate’s Subject common name by default, or to its URI Subject Alternative Name. TIP is turned on by default for new IAM Roles Anywhere profiles, and you can turn it on for existing profiles. For details, see Trusted identity propagation with IAM Roles Anywhere.
  • IAM outbound identity federation – A TIP session can now use the AWS STS GetWebIdentityToken API operation to request a signed JSON Web Toke that includes TIP session identity context for an external service. The external service validates the token and determines how to use the information. For details, see Federating AWS identities to external services.

Use identity context for auditability and access control

The following examples demonstrate two core benefits of TIP: auditability—tracing actions back to the user or workload—and access control based on that identity. In the first example, AnyCompany uses identity context logged in CloudTrail to identify the GitHub Actions workflow run that deployed new code to a production AWS Lambda function. In the second, AnyCompany uses an Amazon Simple Storage Service (Amazon S3) bucket policy that grants read access only to low-risk sessions initiated from a specific IdP.

Trace a Lambda deployment to its GitHub Actions run

This example shows how TIP improves auditability: identity context in CloudTrail identifies the workload, and the specific workflow run, behind an action taken with a shared role. AnyCompany stores the backend code for its payment-processing application in the anycompany/payments-api GitHub repository. A code change merged into the repository’s main branch triggers the GitHub Actions workflow defined in .github/workflows/deploy.yml. The workflow uses GitHub OIDC federation to assume a shared CICDDeployRole role, then calls the Lambda UpdateFunctionCode API operation to deploy the new code to the production payments-api-prod function. CloudTrail records this operation as an UpdateFunctionCode20150331v2 management event.

Before TIP, the CloudTrail event shows that the CICDDeployRole/GitHubActions role session updated payments-api-prod. It doesn’t identify the GitHub repository, workflow file, or workflow run that performed the update. Investigators must match the event timestamp with GitHub records to find the responsible workflow run.

Figure 2: How TIP enables attribution of a production Lambda code update to the GitHub Actions run that performed it

Figure 2: How TIP enables attribution of a production Lambda code update to the GitHub Actions run that performed it

AnyCompany enables TIP on its GitHub OIDC IdP. It maps the GitHub OIDC token subject to aws:OriginIdentity/Subject, configures aws:OriginIdentity/SubjectType as workload, and maps the repository, workflow_ref, and run_id claims into aws:TransactionContext/IdentityProvider/* context keys. The resulting role session identifies the workload and carries the information needed to trace the deployment to its GitHub Actions run.

With TIP, the CloudTrail management event for the Lambda UpdateFunctionCode API operation on payments-api-prod now contains the workload and workflow information:

{ 
  "eventSource": "lambda.amazonaws.com", 
  "eventName": "UpdateFunctionCode20150331v2", 
  "recipientAccountId": "111122223333", 
  "requestParameters": { 
    "functionName": "payments-api-prod" 
  }, 
  "userIdentity": { 
    "type": "AssumedRole", 
    "arn": "arn:aws:sts::111122223333:assumed-role/CICDDeployRole/GitHubActions", 
    "onBehalfOf": { 
      "federatedProviderArn": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com", 
      "subject": "repo:anycompany/payments-api:environment:production", 
      "subjectType": "workload", 
      "issuer": "token.actions.githubusercontent.com" 
    }, 
    "transactionContext": { 
      "IdentityProvider": { 
        "repository": "anycompany/payments-api", 
        "workflow_ref": "anycompany/payments-api/.github/workflows/deploy.yml@refs/heads/main", 
        "run_id": "19283746550" 
      } 
    } 
  } 
} 

An investigator can now see that GitHub Actions run 19283746550 from the anycompany/payments-api repository updated the production payments-api-prod function through the deploy.yml workflow. The shared role, its trust policy, and its permissions remain unchanged. TIP adds workload and workflow attribution to the existing deployment model.

Authorize access based on session risk

This example shows how TIP supports access control: an Amazon S3 bucket policy uses a runtime risk signal from an IdP to decide, per session, whether a user of a shared role can read sensitive data. AnyCompany’s workforce users federate to AWS through an OIDC IdP and use a shared DataAccessRole to read objects from an Amazon S3 bucket. AnyCompany configures its IdP to evaluate each authentication and add a numeric risk score, from 0 to 100, to the OIDC token as a custom claim. AnyCompany enables TIP on the IAM OIDC IdP and maps the riskScore claim to the aws:TransactionContext/IdentityProvider/riskScore context key. During federation, AWS validates the token and attaches the mapped riskScore value to the role session. AWS derives aws:OriginIdentity/Issuer from the iss (issuer) claim in the OIDC token.

Before TIP, a bucket policy that grants access to DataAccessRole gives every user who assumes the role the same access, regardless of how risky their authentication was. With TIP, an S3 bucket policy can evaluate both the IdP that issued the token and the risk score carried in the session. The following policy grants read access only when the expected IdP (issuer) issued the identity, and the current session has a risk score of 30 or lower. The issuer condition prevents a riskScore value from another IdP from satisfying the policy.

Figure 3: How an S3 bucket policy uses trusted identity context to make a per-session access decision

Note: This policy example is for the IAM federation access path. Mapping SAML attributes or OIDC claims to optional aws:TransactionContext/IdentityProvider/* context keys is available only for IAM federation.

Amazon S3 bucket policy using trusted runtime context

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowLowRiskSensitiveDataRead",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:role/DataAccessRole"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/restricted/*",
      "Condition": {
        "StringEquals": {
          "aws:OriginIdentity/Issuer": "idp.example.com"
        },
        "NumericLessThanEquals": {
          "aws:TransactionContext/IdentityProvider/riskScore": "30"
        }
      }
    }
  ]
}

The policy has two conditions: the identity must come from idp.example.com, and the session’s risk score must be 30 or lower. A low-risk session from idp.example.com satisfies both conditions. A session with a risk score above 30, a missing risk score, or a different issuer doesn’t receive access from this policy. The risk score remains fixed for the lifetime of the role session, so choose a session duration appropriate for the sensitivity of the access.

Additional considerations

Missing TIP context keys. A TIP context key is missing when the session carries no identity context or the request goes to an AWS service that doesn’t support TIP. To prevent an Allow statement from granting access when a required key is missing, use operators without IfExists, such as StringEquals or NumericLessThanEquals, as the preceding bucket policy does. Avoid operators such as StringEqualsIfExists in an Allow statement because they evaluate to true when the key is missing. In a Deny statement, add IfExists when the Deny should also apply if the key is missing. Such a Deny also applies to requests sent to AWS services that don’t support TIP, so confirm service support before adding TIP conditions. For more information, see Condition operators.

TIP conditions with cached AWS KMS data keys. Some AWS services, such as Amazon SQS, reuse cached AWS KMS data keys across requests from different sessions of the same IAM role, because the cache key is based on the role and does not include TIP context. When an AWS service reuses a cached data key, it does not send a new authorization request to AWS KMS, so AWS KMS does not evaluate the later session’s TIP context. If you use TIP context to control access to encrypted data, enforce the TIP conditions in the policy for the encrypted resource, such as an Amazon S3 bucket policy, rather than relying only on the AWS KMS key policy. For more information, see AWS KMS guidance for cached data keys.

Choose your TIP approach and get started

Your first step to getting started with TIP depends on how your users and workloads obtain AWS credentials. Use the following table to find the TIP option for your use case and get started.

Use case TIP option How to start
Centrally managed workforce access IAM Identity Center All IAM Identity Center instances can upgrade to the simplified experience for TIP. Before you upgrade, review the considerations for the simplified experience. For more information, see Simplified experience for trusted identity propagation.
Direct SAML or OIDC federation into IAM roles IAM federation New IAM IdPs have TIP turned on by default. For an existing IdP, turn on TIP on that provider, then map the claim that identifies the user or workload, and any optional claims your policies need, to TIP context keys. For more information see TIP for IAM Federation.
X.509-based access for users and workloads outside AWS IAM Roles Anywhere New profiles have TIP turned on by default. For an existing profile, enable TIP on the profile. For details, see Trusted identity propagation with IAM Roles Anywhere.

Conclusion

With this launch, TIP carries the identity of the user or workload from a trusted identity source into the role session for IAM federation, IAM Identity Center, and IAM Roles Anywhere. You can grant access based on the user or workload making the request and use CloudTrail to trace actions across more than 250 supported AWS services back to that identity. This gives you a consistent authorization and audit model across federation paths, without creating a separate role for every identity or adding the sts:SetContext permission to role trust policies.

To get started, find your federation path in the preceding table and follow the steps in the How to start column.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Laura Reith

Laura Reith

Laura is an Identity Solutions Architect at AWS, where she thrives on helping customers overcome security and identity challenges. In her free time, she enjoys wreck diving and traveling around the world.

Rishi Tripathy

Rishi Tripathy

Rishi is a Principal Product Manager on the AWS Identity and Access Management (IAM) team. He focuses on access control mechanisms that help enterprises secure their AWS environments at scale. He is passionate about building security primitives that are straightforward to adopt and hard to misconfigure.

Songzhi Liu

Songzhi Liu

Songzhi is a Principal Big Data Architect with the AWS Identity Solutions team. In this role, he collaborates closely with AWS customers and cross-functional teams to design and implement scalable data architectures, focusing on integrating big data and machine learning solutions to enhance identity awareness within the AWS ecosystem.

Shweta Motwani

Shweta Motwani

Shweta is a Senior Product Manager on the AWS IAM Identity Center team, focused on increasing identity awareness across AWS services to allow for improved auditing and access control. Shweta joined AWS in 2017 and has previously worked as a product manager in Amazon EBS, driving Provisioned IOPS growth and with software partners in the AWS Partner Network.

Handling large volume of transactions with AWS Lambda Managed Instances

Post Syndicated from Mythili Annamalai Sekar original https://aws.amazon.com/blogs/compute/handling-large-volume-of-transactions-with-aws-lambda-managed-instances/

Pre-scheduled events like concert ticket on-sales and product launches can drive a load spike 100 times higher than the baseline. The spike persists for a few hours while the inventory clears, then traffic returns to normal. If you miss the first minute of the on-sales, customers experience errors while competitors keep selling, and the event’s reputation takes a hit. Over-provision for the burst, and you pay for peak capacity 24 hours a day, 365 days a year. The actual peak lasts 10 minutes and happens 10 times a year.

In this post, you will see how AWS Lambda Managed Instances, a capability of AWS Lambda, handles predictable traffic bursts. It keeps compute capacity warm before the on-sales event opens and scales it back down afterward. You will see a reference ticketing implementation that sustains 40,000 transactions per second (TPS) for 120 seconds.

Understanding Lambda Managed Instances

Lambda Managed Instances runs your Lambda functions on Amazon Elastic Compute Cloud (EC2) instances in your account, including Graviton4 and memory-optimized instance types. AWS handles the underlying infrastructure lifecycle (provisioning, scaling, patching, and routing), while you benefit from EC2 pricing including Compute Savings Plans and Reserved Instances.

Lambda Managed Instances provides several benefits. With pre-provisioned execution environments (EE), capacity is already warm before traffic arrives, so there are no cold starts when a burst hits. Scaling bounds are configurable with MinExecutionEnvironments and MaxExecutionEnvironments for each function, and each new EE comes online in 1–2 seconds. With multi-concurrent invocations, one EE handles multiple requests at once, which improves utilization for I/O-heavy handlers. You also get EC2 pricing, so Compute Savings Plans and Reserved Instances apply instead of per-request Lambda pricing.

Lambda Managed Instances is well suited for predictable, spike-shaped workloads that need sustained compute capacity during the peak and can scale back down when traffic returns to the baseline.

Predictable burst workloads work best with Lambda Managed Instances

This post focuses on one of the key capabilities of Lambda Managed Instances: absorbing scheduled traffic bursts without provisioning for peak year-round. Some of the use cases where Lambda Managed Instances helps are ticket and event on-sales (concerts, sports, festivals), live streaming and voting events, and scheduled batch and report generation nightly or hourly jobs that consume steady compute during a defined window.

Use case: High-throughput ticket booking with Lambda Managed Instances

To demonstrate Lambda Managed Instances handling predictable traffic bursts, we built a concert ticketing backend. The solution implements the industry-standard queue-plus-hold-and-confirm booking flow, a pattern that ticketing platforms, airlines, and hotels use to prevent overselling during large traffic spikes. It separates user traffic management from the critical database transactions required to lock inventory.

The following diagram presents the detailed architecture of the solution we built.

Architecture of the ticketing solution: API Gateway routes to three Lambda Managed Instances handlers backed by ElastiCache and DynamoDB

Figure 1: Architecture of the concert ticketing solution across two AWS CloudFormation stacks

The solution deploys two AWS CloudFormation stacks in a single AWS Region. In the first stack, Amazon API Gateway routes public HTTPS traffic through three ticketing handlers hosted in Lambda Managed Instances on a shared capacity provider. Amazon ElastiCache Serverless for Valkey holds the atomic queue counter. Amazon DynamoDB holds durable per-seat state across a write-sharded inventory table (500 shards) and a bookings table. WarmThroughput is pre-provisioned to absorb the burst without waiting for adaptive capacity. A separate simulation stack drives synthetic load through a three-tier Lambda fan-out, reproducing the on-sales burst shape at any target TPS.

Public traffic and load-generation traffic take completely separate code paths, so the load generator’s own scaling behavior does not affect measurements on the ticketing stack. Each successful booking traverses three Lambda handlers. Handler queue-position assigns an atomic virtual queue number using an INCR on a single ElastiCache key. Handler inventory-lock places a time-bounded hold on a specific seat through a DynamoDB conditional UpdateItem, moving it from AVAILABLE to HELD with a time to live (TTL) of 180 seconds. Handler booking-confirm executes a single TransactWriteItems call that atomically transitions the seat from HELD to CONFIRMED and writes a durable booking record. Either both writes succeed or neither does.

All three handlers are stateless, because each request they receive is treated as an independent, standalone transaction. The mutable state lives in ElastiCache and DynamoDB, stored with safety features like conditional writes and atomic operations to avoid collisions, race conditions, and overwrites. This is why the multi-concurrent EE model of Lambda Managed Instances can serve thousands of simultaneous invocations per instance safely.

What makes this solution better with Lambda Managed Instances

With Lambda Managed Instances, you keep the same Lambda programming model, one function per handler, and the same deployment story, while Lambda Managed Instances handles the fleet. Raise MinExecutionEnvironments a few minutes before an on-sales opens, let it burst inside the Min to Max range while traffic is live, and scale back down when the window closes.

Deploy the application

For the full deployment instructions, refer to the README file in the GitHub repository after you have cloned it.

Prerequisites

Run the application

Once deployed, all test traffic goes through the simulation API. The sample includes an optional single-page web user interface (UI) (see the demo-ui/ folder in the repository) that wraps the same endpoints and renders the per-burst results interactively.

Read the “Cost considerations” section before running a simulation to understand the cost you will incur in the process.

1. Smoke test – low TPS to verify the pipeline end-to-end:

By default, deploy.sh provisions a cost-safe baseline of three warm EEs (Min=1, Max=3 per handler). The following smoke test works on this baseline.

curl -X POST https://<sim-api>/v1/simulation/start \
-H 'Content-Type: application/json' \
-d '{"run_id": "smoke-1", "target_tps": 50, "ramp_duration_seconds": 10, "sustain_duration_seconds": 60}'

2. Peak-load test

To reproduce the headline result, scale the Lambda handlers to the per-handler Min and Max values before firing the peak-load test. Refer to the Peak-load testing section of the GitHub repository before firing the burst. This also requires an EC2 vCPU and an API Gateway account-throttle quotas increase above the default.

3. View results

curl “https://<sim-api>/v1/dashboard?run_id=onsale-1”

The response includes total requests, total bookings written to DynamoDB, delivered peak TPS, and end-to-end latency percentiles.

Interactive demo UI

The sample repository ships an optional single-page web UI (in the demo-ui/ folder) that wraps the same simulation and dashboard endpoints as the preceding curl examples. Point it at your simulation API endpoint, then fire bursts and view results interactively without leaving the browser.

Configure and start the UI:

# In demo-ui/config.js, set SIMULATION_API_URL to your simulation endpoint.
cd demo-ui && python3 serve.py
# Serving on http://localhost:8000/

Fire a burst. Choose a target load (a preset button or a custom TPS value), set the sustain duration and ramp, then choose Start burst. The UI sends a POST request to /simulation/start and stores the returned run_id and event_id, so you can query DynamoDB directly if you want to drill deeper.

View results. After the burst completes, choose View results. The UI queries API Gateway metrics, DynamoDB, CloudWatch Logs Insights, and CloudWatch Lambda metrics in parallel to reconstruct the run: total requests received, durable bookings written, and a per-handler table showing EEs used, Lambda throttles, and p95/p99 latency.

Demo UI results panel showing 4,804,200 API Gateway requests and 1,750,886 durable bookings with per-handler latency

Figure 2: Demo UI results panel from a 40,000 TPS, 120-second run

The panel shows 4,804,200 API Gateway requests and 1,750,886 durable bookings, plus a per-handler table with the baseline EE pool (50/100/150 for queue-position, inventory-lock, and booking-confirm). During the burst, 36 additional EEs are pre-emptively warmed on booking-confirm, with zero Lambda throttles and p99 latencies of 4.7, 15.8, and 39.8 ms.

The identifiers panel at the top exposes the burst’s run_id (the partition key in the simulation metrics table) and event_id (used in both the inventory and bookings tables), so you can locate them directly in DynamoDB or CloudWatch Logs Insights for the specific burst you ran.

What we measured

Across a load range from 5,000 to 40,000 requests per second, the pre-warmed EE pool served every burst without cold-start impact. Key results from the headline 40,000 TPS × 120-second burst:

Metric Value
Delivered peak throughput 40,035 req/sec
Total HTTP requests 4,804,200
Durable bookings written to Amazon DynamoDB 1,750,886
End-to-end p50 / p99 latency 44 ms / 121 ms
AWS Lambda errors 0
AWS Lambda concurrency throttles 0
Amazon DynamoDB write throttles 0

The tested range spanned 5,000 to 40,000 requests per second, an 8× spread in delivered load. Across it, p99 latency stayed within a 3 ms band. Doubling sustained throughput from 20,000 to 40,000 requests per second held at exactly 121 ms, which confirms that the pre-warmed pool had substantial headroom throughout the tested range.

Observability

Lambda Managed Instances automatically publishes metrics to CloudWatch and structured logs to CloudWatch Logs, giving you visibility into function performance and capacity utilization without additional code. During a burst, the metrics that matter most are:

  • Duration percentiles per handler to confirm p99 latency stays flat as load rises.
  • ConcurrencyThrottles to detect if any handler hits its MaxExecutionEnvironments ceiling.
  • Errors for handler-side failures.
  • EE count (log-derived) to observe how quickly Lambda Managed Instances adds warm capacity above Min.

The sample repository includes a demo dashboard endpoint that queries CloudWatch metrics, CloudWatch Logs Insights, and DynamoDB in parallel to reconstruct a per-burst report, API Gateway request count, durable bookings landed, distinct EEs used, and per-handler latency percentiles. Reconciling the simulation-side counts against the AWS ground truth catches load-generator artifacts and confirms the system-under-test numbers.

Cost considerations

Lambda Managed Instances uses EC2 instance pricing plus a 15% management fee. Compute Savings Plans and Reserved Instances apply to the underlying instance cost.

The Lambda Managed Instances configuration runs a small always-on baseline and uses a scaling script to pre-warm to 50/100/150 EEs in the minutes leading up to each event, then scales back down to baseline afterward.

To simulate a peak load under controlled conditions, the fleet is pre-warmed for a 7-minute window (5-minute ramp and 2-minute burst) then scaled back down. The cost breakdown can be as follows.

Component Volume Rate Cost
API Gateway requests 4.8 M $3.50 per 1 M $16.80
DynamoDB writes 8.8 M WCU $1.25 per 1 M $11.00
Lambda Managed Instances compute (peak window) 75 × c7i.4xlarge × 7 min $0.821 / instance-hr $7.18
Lambda Managed Instances request charges 4.8 M $0.20 per 1 M $0.96
CloudWatch Logs (~2 GB) ingestion $0.50 per GB $1.00
Amazon ElastiCache Serverless for Valkey 4.8 M INCR operations ECPU-based $0.30
Total per burst ~$37.00

The estimated cost for simulating each burst is around $37.

Best practices

Based on experience building this solution, here are key recommendations:

  • Pre-warm before scheduled events. Raise MinExecutionEnvironments using an Amazon EventBridge Scheduler rule or a manual scaling script when you expect major spikes, giving Lambda Managed Instances enough time to scale the underlying instances. Restore the low baseline after the event.
  • Set MaxExecutionEnvironments aggressively. Lambda Managed Instances adds new EEs to your capacity provider. A high MaxExecutionEnvironments value costs nothing while idle but absorbs unexpected demand during the burst.
  • Write-shard hot DynamoDB tables. For workloads writing thousands of items per second to one logical entity (a single event, a single product SKU), spread writes across a synthetic sharded partition key. This sample uses 500 shards per event.
  • Use WarmThroughput on DynamoDB tables. Pre-provision physical partitions before the burst rather than waiting for adaptive capacity to expand during the first minute of the on-sales.
  • Keep hot atomic counters out of DynamoDB. Single-row atomic increments in DynamoDB cap at approximately 1,000 operations per second.
  • Make write endpoints idempotent. The sample uses a caller-provided booking_id on the confirmation endpoint so that retries produce the same booking record instead of duplicates.

Clean up

When you are done exploring the solution, remove the provisioned resources to avoid ongoing charges. For the full cleanup commands and exact steps, refer to the GitHub repository README file.

Conclusion

Lambda Managed Instances brings the same Lambda programming model to workloads that need sustained, pre-provisioned compute during predictable bursts: ticket on-sales, product launches, registration windows, and other scheduled surge patterns. The concert ticketing example shows how a queue-plus-hold-and-confirm pattern built on Lambda Managed Instances can sustain 40,000 requests per second while costing less than an always-on EC2 fleet sized for the same peak.

Explore the Lambda Managed Instances documentation and try building your own predictable-burst serverless application. You can find the complete code for this example in the GitHub repository.


About the authors

Mythili Annamalai Sekar

Mythili Annamalai Sekar

Mythili Sekar is a Solutions Architect at Amazon Web Services (AWS) working with Independent Software Vendors (ISVs), where she guides customers in designing secure, enterprise-scale architectures built on AWS best practices. Her work centers on serverless and generative AI, helping software companies turn new cloud capabilities into real, production-ready outcomes for their businesses.

Guy Haddad

Guy Haddad

Guy is a Senior Technical Account Manager at AWS where he assists customers with leveraging their AWS entitlements and adhering to architectural and operational best practices. He specializes in AI/ML and serverless technologies and has a deep background in software development, telecommunications and complex program deliveries.

How AWS Security Incident Response triages your security findings

Post Syndicated from Anatoliy Kochetov original https://aws.amazon.com/blogs/security/how-aws-security-incident-response-triages-your-security-findings/

AWS Security Incident Response continuously triages the threat findings from Amazon GuardDuty and AWS Security Hub CSPM, but most of that work never shows up as a case. If cases are all you look at, it’s hard to tell whether the service is working at all, and that’s the question I hear most often when I help customers onboard. The Proactive response dashboard gives you a high-level view of this activity, and this post takes you behind the numbers to show what happens to an individual finding.

In this post, I walk you through what happens to a finding after it’s ingested by the service, what gets triaged, where each finding is sent, and how a triage decision becomes a case. I then show you how to confirm triage is working day-to-day, so your team can focus on the findings that require attention. The process flow is shown in Figure 1.

Figure 1: AWS Security Incident Response triage flow, from ingestion through to one of three outcomes

Figure 1: AWS Security Incident Response triage flow, from ingestion through to one of three outcomes

Ingestion

AWS Security Incident Response ingests threat findings from GuardDuty through Amazon EventBridge rules that are automatically deployed to your accounts during the onboarding process.

If you send third-party detection findings to Security Hub CSPM from tools such as CrowdStrike, Trend Micro, or Lacework, their threat detection findings are also ingested. Each of those findings must carry complete payload information such as resource ID, account ID, timestamp, and threat details. GuardDuty findings are ingested directly, so these findings aren’t re-ingested through Security Hub CSPM and there’s no duplication.

Triage

The service triages findings that indicate an active threat, such as compromised credentials, cryptomining, or data exfiltration. These represent activity that’s underway or has already occurred.

Posture and compliance findings aren’t triaged. A misconfiguration or a failed benchmark check reflects the state of your environment rather than an active threat, so those findings remain for your team to address through your existing remediation process.

Outcomes

For each threat finding, the service runs an automated triage process. It evaluates the finding payload, related AWS activity from AWS CloudTrail and Amazon VPC Flow Logs, AWS threat intelligence, and the context you provide about your environment. The service then maps the finding against a profile of known-good activity. What fits the profile is treated as expected, and what doesn’t is flagged for a closer look.

What happens next depends on that outcome. A finding is sent to one of three places:

  • Archived, no action needed – Automated triage or an AWS Security Incident Response engineer confirms the activity is benign or expected. The finding is archived in GuardDuty, with no case and no customer contact.
  • A proactive case is opened – Triage can’t confirm the activity is benign. This is either Unconfirmed Activity (the service needs you to confirm whether it’s expected) or Inappropriate/Unintended Activity (confirmed activity that needs your action). A proactive case is opened, your incident response team is engaged, and the finding stays Current until it’s resolved.
  • Retained for your review, no case – Posture-related findings, such as overly permissive policies, configuration, or missing encryption, aren’t threats. By design, they stay Current without archiving and no case is created.

When a proactive case is opened, you respond to it in the AWS Management Console for AWS Security Incident Response under Cases, where you can communicate directly with the team, share context, and resolve or reopen the case. Timely responses also help the service learn your environment, which helps reduce false positives over time. For the full workflow, see Responding to an AWS generated case.

The preceding outcomes use GuardDuty terms, because it’s the primary source. Third-party findings ingested through Security Hub CSPM follow the same triage logic, but their disposition shows as a workflow-status change rather than archiving. The finding moves from NEW to NOTIFIED when triage begins, which removes it from the default Security Hub CSPM view. If triage clears it as benign, it moves to SUPPRESSED. Otherwise it stays visible for your review.

Because only benign findings are archived, it’s normal to see many findings in Current, and that isn’t a sign the service missed them. Across customers, less than 1 percent of ingested findings result in a customer-facing escalation. Most are handled automatically, without a case.

Credential exfiltration finding example

Suppose GuardDuty generates an UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS finding: temporary credentials created on an Amazon Elastic Compute Cloud (Amazon EC2) instance were used from an IP address outside AWS. Triage cross-references the payload against what it knows about your environment.

  • Cleared – The external IP belongs to a corporate virtual private network (VPN) range that your workloads regularly call through, and the service has seen this pattern before. The finding is archived in GuardDuty.
  • Escalated – The IP is in a hosting-provider range with no prior association to your accounts, and the AWS Identity and Access Management (IAM) role has never made calls from outside AWS. The service creates a proactive case, notifies your incident response team, and an engineer investigates whether the credentials were compromised.

Same finding type, two outcomes. The difference is context, and context is what triage builds by observing your environment over time.

How triage sharpens over time

The service builds a profile of what’s normal in your environment. It learns the IP ranges and domains you trust, and the IAM principals and behaviors your workloads rely on. When your team routinely connects from a known VPN range, or a specific IAM role runs nightly batch jobs, the service recognizes those patterns and measures new findings against them. Early on, engineers investigate more findings by hand as they learn your environment. Within a few weeks, automated triage handles most of those decisions on its own.

Triage is dynamic. A finding treated as expected today can be re-evaluated tomorrow if the context changes, so the service can still catch a real threat that reuses a pattern it formerly treated as safe. You can shape the profile by submitting known-good activity, such as trusted IP ranges or authorized scanning tools, through an AWS Support case. For details, see Submit known-good activity.

Archiving versus suppression

It’s possible to conflate the two mechanisms, so it’s worth separating them:

  • Archiving is the primary mechanism. When automated triage or an engineer determines a finding is benign, the service archives it in GuardDuty. The finding then stays there for 90 days.
  • Suppression rules are less common and work differently. A suppression rule acts on future findings. When the service identifies a recurring pattern of expected activity, it might create a GuardDuty suppression rule that automatically archives matching findings so they don’t generate new alerts. Suppressed findings aren’t sent to your configured export, such as an Amazon Simple Storage Service (Amazon S3) bucket or SIEM. When the service creates a rule, your incident response team is notified, and you can view and manage it in the GuardDuty console under Suppression rules.

A healthy deployment typically shows many archived findings and few or no suppression rules. That’s expected, and it means the service is handling findings dynamically rather than relying on static filters.

How to see what triage is doing

Triage runs on its own, and the service gives you a few ways to confirm it’s working.

Proactive response dashboard

The Dashboard page in the AWS Security Incident Response console has a Proactive response section. It counts how many findings were ingested, triaged, investigated, and escalated over the timeframe you select, the last 7, 30, or 90 days.

The Overview leads with two figures. Noise reduction is the share of ingested findings that automated triage resolved without opening a case, so you can see for yourself how much volume never reached your team. Time saved estimates the analyst hours that automation returned to you, counted as one hour for each ingested finding.

Below that, Finding evaluations breaks those stages down:

  • Ingest – Threat findings collected from your detection sources
  • Triage – Findings evaluated automatically to decide whether the activity is expected
  • Investigation – Findings automated triage couldn’t confirm, passed to an AWS Security Incident Response engineer for a closer look
  • Escalation – Investigations raised as a case when a genuine risk was detected or the activity couldn’t be confirmed as expected

A flow diagram on the dashboard shows how those findings move from their sources through triage and investigation, with branches for the ones closed as false positives and the ones still in progress. For more, see Viewing proactive response metrics.

Monthly report

The monthly report is the periodic companion to the dashboard. AWS Security Incident Response emails it to your incident response team a week or two after each month closes. It opens with the accounts monitored, findings processed, and investigations, then lists each investigation and its status, the triage flows that show the checks run for each finding type, and the context the service has learned about your environment, such as the trusted networks it now recognizes as normal.

Archived findings in GuardDuty

For a quick confirmation outside either view, open Findings in the GuardDuty console and filter to see Archived. That list also includes findings archived by you or by suppression rules, so look for the threat findings AWS Security Incident Response archived after triage. Each one is a finding that the service cleared as benign so your team didn’t have to.

Conclusion

AWS Security Incident Response continuously evaluates your threat findings so your team can spend its time on confirmed threats rather than alert volume. Findings that are evaluated as benign are archived automatically, the ones that need a response become proactive cases, and posture issues stay in Current for your team to handle.

Cases show only a small part of that work. When I deliver AWS Security Incident Response to customers now, I walk them through the triage flow in Figure 1, the Proactive response dashboard, and their monthly report, so they can see how triage works end to end.

To get started, see the onboarding guide. Setup takes about 10 minutes. For more information, see the AWS Security Incident Response product page or the User Guide.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Anatoliy Kochetov

Anatoliy Kochetov

Anatoliy is a Technical Account Manager and AWS Security Incident Response SME. He works with AWS Enterprise customers, providing ongoing support and technical guidance to help them build secure, resilient solutions using AWS best practices.

Amazon S3 Tables with dbt: Iceberg-based data transformations using AWS Glue

Post Syndicated from Yukiko Iwazumi original https://aws.amazon.com/blogs/big-data/amazon-s3-tables-with-dbt-iceberg-based-data-transformations-using-aws-glue/

Amazon S3 Tables, a capability of Amazon Simple Storage Service (Amazon S3), deliver a cloud object store with built-in Apache Iceberg support and streamline storing tabular data at scale. When you integrate them with dbt and AWS Glue, you can run SQL-based data transformations with the reliability and performance of a modern lakehouse, bringing software engineering best practices to the data space.

This post demonstrates how to configure and implement dbt transformations using Amazon S3 Tables with the dbt-glue adapter. Starting with version 1.12.4, the dbt-glue adapter adds incremental merge support for S3 Tables, which the patterns in this post build on. We cover the specific configuration requirements for the dbt-glue adapter and practical implementation patterns built on S3 Tables incremental models: the merge strategy to keep the latest state per record and the append strategy to build an audit-friendly change history.

Example scenario

In this walkthrough, we simulate an ecommerce system that tracks customer profiles and their orders. We first run the pipeline against an initial dataset, then simulate an update to the upstream source data and run it again to demonstrate incremental updates.

Our example scenario follows a data pipeline architecture that uses S3 Tables throughout. Raw ecommerce data (customers.csv and orders.csv) lands in a regular S3 bucket as comma-separated values (CSV). dbt then transforms it through two layers of S3 Tables. A staging layer cleanses and standardizes each source, and a mart layer produces analytics-ready dimension and fact tables. You can query the resulting mart data from a variety of analytics and business intelligence (BI) tools such as Amazon Athena and Amazon Quick Sight. In this post, we query it from Athena.

The mart layer demonstrates two incremental strategies side by side: the fact_orders model uses merge to keep the latest state per order, while fact_order_history uses append to accumulate a full change history.

The data pipeline flow looks like the following chart:

Source Data (Regular S3 - CSV)
    └─ customers.csv, orders.csv
    ↓
Staging Models (S3 Tables)
    ├─ stg_customers
    └─ stg_orders
    ↓
Mart Models (S3 Tables)
    ├─ dim_customers
    ├─ fact_orders                (incremental with merge --- latest state per order)
    └─ fact_order_history         (incremental with append --- change history)
    ↓
Consumption Layer (Athena, Quick Sight, BI tools)

The following diagram shows the architecture behind this pipeline: dbt-glue submits each model as a Spark SQL statement to an AWS Glue interactive session, which reads from the raw S3 bucket and writes the staging and mart tables as S3 Tables within the same data lake.

dbt-glue submits each model to an AWS Glue interactive session that reads the raw S3 bucket and writes staging and mart tables as S3 Tables

Figure 1: Architecture of the dbt transformation pipeline on Amazon S3 Tables with AWS Glue

Prerequisites

Before you begin, make sure that you have the following prerequisites:

Create S3 Tables namespace and AWS Glue databases

In this section, you set up the AWS infrastructure that dbt-glue needs: an S3 table bucket and namespace to hold your dbt models, and an AWS Glue database for your source data.

First, set your environment variables. Replace YOUR_ACCOUNT_ID, YOUR-REGULAR-BUCKET, and YOUR_Glue_Role_ARN with your data:

export DBT_GLUE_REGION="us-east-1"
export AWS_ACCOUNT_ID="<YOUR_ACCOUNT_ID>"
export S3_TABLES_BUCKET_NAME="dbt-glue-s3-tables-bucket"
export DBT_ROLE_ARN="<YOUR_Glue_Role_ARN>"
export DBT_S3_LOCATION="s3://<YOUR-REGULAR-BUCKET>/glue/data/"
export DBT_S3_TABLES_BUCKET="${AWS_ACCOUNT_ID}:s3tablescatalog/${S3_TABLES_BUCKET_NAME}"

The DBT_S3_TABLES_BUCKET format is AWS_ACCOUNT_ID:s3tablescatalog/BUCKET_NAME, not an Amazon Resource Name (ARN).

Second, create an S3 table bucket and namespace:

  1. Create S3 table bucket.
    aws s3tables create-table-bucket \
      --region $DBT_GLUE_REGION \
      --name $S3_TABLES_BUCKET_NAME

  2. Create namespace within the table bucket.
    aws s3tables create-namespace \
      --region $DBT_GLUE_REGION \
      --table-bucket-arn "arn:aws:s3tables:${DBT_GLUE_REGION}:${AWS_ACCOUNT_ID}:bucket/${S3_TABLES_BUCKET_NAME}" \
      --namespace dbt_glue_s3_tables

    Note that the S3 Tables namespace is where the S3 Tables corresponding to your dbt models will be created. This is different from regular S3 buckets. Because the “Integration with AWS analytics services” option for S3 Tables is enabled, creating the namespace automatically creates a corresponding AWS Glue database. Verify that it exists in the next step:

  3. Verify that the database exists.
    aws glue get-database \
      --region $DBT_GLUE_REGION \
      --catalog-id "$DBT_S3_TABLES_BUCKET" \
      --name dbt_glue_s3_tables

    Third, create an AWS Glue database for source data tables:

  4. Create an AWS Glue database for source tables.
    aws glue create-database \
      --region $DBT_GLUE_REGION \
      --database-input Name=raw_ecommerce,Description='Raw e-commerce data'

Create sample dataset

In this section, you create sample ecommerce data to transform with dbt: two CSV files (customers and orders), upload them to a general purpose S3 bucket, and register them as AWS Glue tables that your dbt models can read from.

Note: All sample data in this post is synthetic. It was generated to mimic realistic patterns for demonstration purposes only and doesn’t represent any real individuals or transactions.

Complete following steps to create a sample dataset:

  1. Create a directory for sample data and save the following two CSV files:
    customers.csv:

    1,[email protected],Alejandro,Rosalez,2024-01-15,Premium
    2,[email protected],Ana Carolina,Silva,2024-02-20,Standard
    3,[email protected],Arnav,Desai,2024-03-10,Premium
    4,[email protected],Carlos,Salazar,2024-04-05,Standard
    5,[email protected],Diego,Ramirez,2024-05-12,Basic

    orders.csv:

    1001,1,2024-06-01,150.00,completed,2024-06-01T10:00:00
    1002,2,2024-06-02,75.50,completed,2024-06-02T10:00:00
    1003,1,2024-06-03,200.00,completed,2024-06-03T10:00:00
    1004,3,2024-06-04,125.75,pending,2024-06-04T10:00:00
    1005,4,2024-06-05,89.99,completed,2024-06-05T10:00:00

  2. Create the bucket for source data if it doesn’t exist, and upload the CSV files to the S3 bucket. Replace YOUR-SOURCE-DATA-BUCKET with your bucket name.
    export SOURCE_BUCKET="<YOUR-SOURCE-DATA-BUCKET>"
    
    # Create S3 bucket for source data
    aws s3 mb s3://${SOURCE_BUCKET} --region ${DBT_GLUE_REGION}
    
    # Upload CSV files
    aws s3 cp customers.csv s3://${SOURCE_BUCKET}/raw/customers/ --region ${DBT_GLUE_REGION}
    aws s3 cp orders.csv s3://${SOURCE_BUCKET}/raw/orders/ --region ${DBT_GLUE_REGION}

  3. Create an AWS Glue database and tables for source data.
    export SOURCE_DATABASE="raw_ecommerce"
    
    # Create Glue table for customers
    aws glue create-table \
      --database-name ${SOURCE_DATABASE} \
      --table-input '{
        "Name": "customers",
        "StorageDescriptor": {
          "Columns": [
            {"Name": "customer_id", "Type": "bigint"},
            {"Name": "email", "Type": "string"},
            {"Name": "first_name", "Type": "string"},
            {"Name": "last_name", "Type": "string"},
            {"Name": "registration_date", "Type": "string"},
            {"Name": "customer_segment", "Type": "string"}
          ],
          "Location": "s3://'${SOURCE_BUCKET}'/raw/customers/",
          "InputFormat": "org.apache.hadoop.mapred.TextInputFormat",
          "OutputFormat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
          "SerdeInfo": {
            "SerializationLibrary": "org.apache.hadoop.hive.serde2.OpenCSVSerde",
            "Parameters": {
              "separatorChar": ","
            }
          }
        },
        "TableType": "EXTERNAL_TABLE"
      }' \
      --region ${DBT_GLUE_REGION}
    
    # Create Glue table for orders
    aws glue create-table \
      --database-name ${SOURCE_DATABASE} \
      --table-input '{
        "Name": "orders",
        "StorageDescriptor": {
          "Columns": [
            {"Name": "order_id", "Type": "bigint"},
            {"Name": "customer_id", "Type": "bigint"},
            {"Name": "order_date", "Type": "string"},
            {"Name": "order_amount", "Type": "double"},
            {"Name": "order_status", "Type": "string"},
            {"Name": "updated_at", "Type": "string"}
          ],
          "Location": "s3://'${SOURCE_BUCKET}'/raw/orders/",
          "InputFormat": "org.apache.hadoop.mapred.TextInputFormat",
          "OutputFormat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
          "SerdeInfo": {
            "SerializationLibrary": "org.apache.hadoop.hive.serde2.OpenCSVSerde",
            "Parameters": {
              "separatorChar": ","
            }
          }
        },
        "TableType": "EXTERNAL_TABLE"
      }' \
      --region ${DBT_GLUE_REGION}

Install dbt, the dbt CLI, and the dbt adapter

The dbt CLI is a command-line interface for running dbt projects. It’s free to use and available as an open source project. Before installing dbt-core, make sure your Python version is 3.10, 3.11, or 3.12.

  1. Install dbt and the dbt CLI with the following code:
    $ pip3 install --no-cache-dir dbt-core

    For more information, refer to How to install dbt, What is dbt?, Viewpoint, and What version of Python can I use?.

  2. Install the dbt-glue adapter with the following code:
    $ pip3 install --no-cache-dir dbt-glue

    Note that you need to install dbt-glue 1.12.4 or higher, which adds support for incremental append and merge models on S3 Tables.

Create a dbt project

In this section, you create a new dbt project using dbt init, which generates the standard directory structure (such as models, macros, and tests) that you will populate with the S3 Tables models in the next sections.

  1. Run the dbt init command to create and initialize a new empty dbt project.
    $ dbt init

  2. For a project name, enter dbt_glue_s3_tables.
  3. For a database, choose [1] glue.

Please ignore dbt_project.yml file [ERROR not found] message as we are going to create it in the next step.

Configure dbt profile

The dbt profile configuration is critical for S3 Tables integration. In this section, you create a dbt profile that connects to AWS Glue Interactive Sessions and configures Spark to read and write S3 Tables through the Iceberg catalog, then validate the connection with dbt debug.

  1. Create ~/.dbt/profiles.yml with the following structure:
    dbt_glue_s3_tables:
      target: dev
      outputs:
        dev:
          type: glue
          glue_version: "6.0"
          role_arn: "{{ env_var('DBT_ROLE_ARN') }}"
          region: "{{ env_var('DBT_GLUE_REGION') }}"
          workers: 2
          worker_type: G.1X
          schema: dbt_glue_s3_tables
    
          # S3 Tables Spark configuration (space-delimited format)
          conf: "spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions --conf spark.sql.catalog.spark_catalog=org.apache.iceberg.spark.SparkSessionCatalog --conf spark.sql.catalog.spark_catalog.type=glue --conf spark.sql.catalog.glue_catalog=org.apache.iceberg.spark.SparkCatalog --conf spark.sql.catalog.glue_catalog.warehouse={{ env_var('DBT_S3_LOCATION') }} --conf spark.sql.catalog.glue_catalog.catalog-impl=org.apache.iceberg.aws.glue.GlueCatalog --conf spark.sql.catalog.glue_catalog.io-impl=org.apache.iceberg.aws.s3.S3FileIO --conf spark.sql.catalog.glue_catalog.glue.id={{ env_var('DBT_S3_TABLES_BUCKET') }} --conf spark.sql.defaultCatalog=glue_catalog"
    
          # Enable S3 Tables support
          datalake_formats: "iceberg"

  2. Run the following command to validate the configurations:
    cd dbt_glue_s3_tables
    dbt debug --profiles-dir ~/.dbt/

    Expected output is Connection test: [OK connection ok].

Configure dbt project

The dbt_project.yml configuration determines which models use S3 Tables. Create or update dbt_glue_s3_tables/dbt_project.yml with the following structure:

name: 'dbt_glue_s3_tables'
version: '1.0.0'
config-version: 2
profile: 'dbt_glue_s3_tables'
model-paths: ["models"]
test-paths: ["tests"]
macro-paths: ["macros"]
models:
  dbt_glue_s3_tables:
    # S3 Tables for staging
    staging:
      +materialized: table
      +file_format: 's3tables'  # S3 Tables for staging
      +table_properties:
        'format': 'iceberg'
        'write.format.default': 'parquet'
        'write.parquet.compression-codec': 'snappy'

    # S3 Tables for marts
    marts:
      +materialized: table
      +file_format: 's3tables'  # S3 Tables for marts
      +table_properties:
        'format': 'iceberg'
        'write.format.default': 'parquet'
        'write.parquet.compression-codec': 'snappy'

Create dbt models

In this section, you build out the full model layer: a sources.yml that registers your raw AWS Glue tables, two staging models that clean and prepare the customer and order data, and three mart models that turn those staged data into a dimension table and two fact tables, one using incremental merge and one using incremental append.

First, create sources.yml defines your raw data tables:

  1. Delete the example folder under dbt_glue_s3_tables/models. This is an example folder created by default and unnecessary now.
  2. Define source tables in models/sources.yml with the following structure:
    version: 2
    
    sources:
      - name: raw_ecommerce
        description: "Raw e-commerce data in regular S3 buckets"
        schema: raw_ecommerce
    
        tables:
          - name: customers
            description: "Customer master data"
            columns:
              - name: customer_id
                tests:
                  - unique
                  - not_null
              - name: email
                tests:
                  - unique
                  - not_null
    
          - name: orders
            description: "Order transactions"
            columns:
              - name: order_id
                tests:
                  - unique
                  - not_null
              - name: customer_id
                tests:
                  - not_null
                  - relationships:
                      arguments:
                        to: source('raw_ecommerce', 'customers')
                        field: customer_id
              - name: updated_at
                tests:
                  - not_null

    This sources.yml defines your raw data tables, so you can reference them with the {{ source() }} function in your models. With this file, you can also define data tests like unique, not_null, and referential integrity checks in one central place.

    Second, create the staging and mart models. Staging models are where you unpack and transform raw data. Mart models are what downstream consumers actually query.

  3. Create models/staging/stg_customers.sql:
    -- Staging model as S3 Tables with incremental merge
    {{ config(
        materialized='incremental',
        incremental_strategy='merge',
        unique_key='customer_id',
        on_schema_change='sync_all_columns',
        file_format='s3tables'
    ) }}
    
    SELECT
        customer_id,
        LOWER(TRIM(email)) AS email,
        first_name,
        last_name,
        CAST(registration_date AS DATE) AS registration_date,
        customer_segment
    FROM spark_catalog.{{ source('raw_ecommerce', 'customers') }}
    WHERE customer_id IS NOT NULL

    stg_customers.sql reads from the raw customers source, applies light cleansing (email normalization, date casting, null filtering), and writes to S3 Tables using an incremental merge on customer_id to update existing records rather than duplicating them.

  4. Create models/staging/stg_orders.sql:
    -- Staging model as S3 Tables with incremental merge
    {{ config(
        materialized='incremental',
        incremental_strategy='merge',
        unique_key='order_id',
        on_schema_change='sync_all_columns',
        file_format='s3tables'
    ) }}
    
    SELECT
        order_id,
        customer_id,
        CAST(order_date AS DATE) AS order_date,
        CASE
            WHEN LOWER(TRIM(order_status)) = 'completed'  THEN 'completed'
            WHEN LOWER(TRIM(order_status)) = 'shipped'    THEN 'shipped'
            WHEN LOWER(TRIM(order_status)) = 'processing' THEN 'processing'
            WHEN LOWER(TRIM(order_status)) = 'cancelled'  THEN 'cancelled'
            ELSE 'unknown'
        END AS status,
        CAST(order_amount AS DECIMAL(10,2)) AS total_amount,
        EXTRACT(YEAR  FROM CAST(order_date AS DATE)) AS order_year,
        EXTRACT(MONTH FROM CAST(order_date AS DATE)) AS order_month,
        CAST(updated_at AS TIMESTAMP) AS updated_at
    FROM spark_catalog.{{ source('raw_ecommerce', 'orders') }}
    WHERE order_id IS NOT NULL

    stg_orders.sql reads from the raw orders source, normalizes status to a fixed set of values (defaulting to unknown for anything unexpected), casts order_date, total_amount, and updated_at to their proper types, and derives order_year and order_month for downstream partitioning.

  5. Create models/marts/dimensions/dim_customers.sql:
    -- Dimension table using S3 Tables
    {{ config(
        materialized='table',
        file_format='s3tables',
        partition_by=['registration_year'],
        table_properties={
            'format': 'iceberg',
            'write.format.default': 'parquet'
        }
    ) }}
    
    SELECT
        customer_id,
        email,
        first_name,
        last_name,
        registration_date,
        YEAR(registration_date) as registration_year,
        customer_segment,
        CASE
            WHEN customer_segment = 'Premium' THEN 1
            WHEN customer_segment = 'Regular' THEN 2
            ELSE 3
        END as segment_priority,
        CURRENT_TIMESTAMP() as dbt_updated_at
    FROM {{ ref('stg_customers') }}

  6. Create models/marts/facts/fact_orders.sql:
    -- Fact table using S3 Tables with incremental merge
    {{ config(
        materialized='incremental',
        file_format='s3tables',
        incremental_strategy='merge',
        unique_key='order_id',
        partition_by=['order_year', 'order_month'],
        table_properties={
            'format': 'iceberg',
            'write.format.default': 'parquet'
        }
    ) }}
    
    SELECT
        o.order_id,
        o.customer_id,
        o.order_date,
        YEAR(o.order_date)  AS order_year,
        MONTH(o.order_date) AS order_month,
        o.status,
        o.total_amount,
        c.customer_segment,
        c.segment_priority,
        CURRENT_TIMESTAMP() AS dbt_updated_at
    FROM {{ ref('stg_orders') }} o
    LEFT JOIN {{ ref('dim_customers') }} c
      ON o.customer_id = c.customer_id

  7. Create models/marts/facts/fact_order_history.sql:
    -- Fact table using S3 Tables with incremental append
    {{ config(
        materialized='incremental',
        file_format='s3tables',
        incremental_strategy='append',
        partition_by=['event_year', 'event_month'],
        table_properties={
            'format': 'iceberg',
            'write.format.default': 'parquet'
        }
    ) }}
    
    SELECT
        order_id,
        customer_id,
        status,
        order_date,
        total_amount,
        updated_at,
        CURRENT_TIMESTAMP() AS recorded_at,
        YEAR(updated_at)    AS event_year,
        MONTH(updated_at)   AS event_month
    FROM {{ ref('stg_orders') }}
    
    {% if is_incremental() %}
        WHERE updated_at > (SELECT MAX(updated_at) FROM {{ this }})
    {% endif %}

Run the dbt project

Now it’s time to run the dbt project. Complete following steps:

  1. To run the project dbt, you should be in the project folder:
    cd dbt_glue_s3_tables

  2. Run the dbt command:
    dbt run --profiles-dir ~/.dbt/ --full-refresh

This command starts an AWS Glue interactive session, compiles the dbt models, and materializes all five tables (stg_customers, stg_orders, dim_customers, fact_orders, and fact_order_history) in your S3 Tables namespace. The --full-refresh flag rebuilds the incremental models from scratch, so it’s the right choice for the first run.

Query using Amazon Athena

Before testing the incremental merge and append behavior in the next section, confirm what the initial --full-refresh run loaded into the mart tables. Query the target tables.

  1. In the Athena console, choose the data source and database that correspond to your S3 Tables catalog:
    • Catalog: s3tablescatalog/dbt-glue-s3-tables-bucket.
    • Database: dbt_glue_s3_tables.
  2. Run the following query to view the data loaded into the fact_orders table:
    SELECT * FROM dbt_glue_s3_tables.fact_orders ORDER BY order_id;

    The result returns the five order records:

    #    order_id    customer_id    order_date    order_year    order_month    status    total_amount    customer_segment    segment_priority    dbt_updated_at
    1    1001    1    2024-06-01    2024    6    completed    150.00    Premium    1    2026-10-16 09:41:46.590373 UTC
    2    1002    2    2024-06-02    2024    6    completed    75.50    Standard    3    2026-10-16 09:41:46.590373 UTC
    3    1003    1    2024-06-03    2024    6    completed    200.00    Premium    1    2026-10-16 09:41:46.590373 UTC
    4    1004    3    2024-06-04    2024    6    unknown    125.75    Premium    1    2026-10-16 09:41:46.590373 UTC
    5    1005    4    2024-06-05    2024    6    completed    89.99    Standard    3    2026-10-16 09:41:46.590373 UTC

  3. Run the following query to view the data loaded into the fact_order_history table:
    SELECT * FROM dbt_glue_s3_tables.fact_order_history ORDER BY updated_at;

    The result returns the five order history records.

    #    order_id    customer_id    status    order_date    total_amount    updated_at    recorded_at    event_year    event_month
    1    1001    1    completed    2024-06-01    150.00    2024-06-01 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    2    1002    2    completed    2024-06-02    75.50    2024-06-02 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    3    1003    1    completed    2024-06-03    200.00    2024-06-03 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    4    1004    3    unknown    2024-06-04    125.75    2024-06-04 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    5    1005    4    completed    2024-06-05    89.99    2024-06-05 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6

Incremental merge and append on Iceberg table

After the initial --full-refresh run succeeds, verify that the merge and append incremental strategies behave as expected when the source data changes. This demonstrates the row-level update capability that Iceberg on S3 Tables provides.

Update the sample source data

To simulate a real-world scenario where upstream source data changes over time (for example, a customer updating their profile, or new customers signing up), modify customers.csv to include both an update to an existing record and a new record.

    1. Update two CSV files:

customers.csv:

1,[email protected],Alejandro,Rosalez,2024-01-15,Premium
2,[email protected],Ana Carolina,Silva,2024-02-20,Standard
3,[email protected],Arnav,Desai,2024-03-10,Premium
4,[email protected],Carlos,Salazar,2024-04-05,Standard
5,[email protected],Diego,Ramirez,2024-05-12,Basic
6,[email protected],Jane,Doe,2024-07-01,Premium

Changes:

      • customer_id=1: email updated to [email protected] (to test the merge UPDATE).
      • customer_id=6: new record added (to test the merge INSERT).

orders.csv:

1001,1,2024-06-01,150.00,completed,2024-06-01T10:00:00
1002,2,2024-06-02,75.50,completed,2024-06-02T10:00:00
1003,1,2024-06-03,200.00,completed,2024-06-03T10:00:00
1004,3,2024-06-04,125.75,completed,2024-06-11T09:30:00
1005,4,2024-06-05,89.99,completed,2024-06-05T10:00:00
1006,6,2024-07-02,45.00,completed,2024-07-02T10:00:00

Changes:

    • order_id=1004: status updated from pending to completed with a later updated_at (to test the merge UPDATE).
    • order_id=1006: new record added with a later updated_at, associated with the new customer customer_id=6 (to test both the merge INSERT in fact_orders and the append in fact_order_history).
  1. Upload the updated files to S3.
    # Upload CSV files
    aws s3 cp customers.csv s3://${SOURCE_BUCKET}/raw/customers/ --region ${DBT_GLUE_REGION}
    aws s3 cp orders.csv s3://${SOURCE_BUCKET}/raw/orders/ --region ${DBT_GLUE_REGION}

Re-run dbt project

  1. Run the following command.
    dbt run --profiles-dir ~/.dbt/

By running without --full-refresh, dbt runs its normal incremental logic instead of rebuilding the tables from scratch. In the staging layer, stg_customers and stg_orders apply the changes with a MERGE INTO statement that updates customer_id=1 and order_id=1004 in place and inserts customer_id=6 and order_id=1006. Downstream, fact_orders (merge) reflects the 1004 update and the 1006 insert as the latest state, while fact_order_history (append) records both 1004 and 1006 as new history rows.

Verify the results in Amazon Athena

After the re-run completes, use Athena to confirm that the merge and append strategies behaved as expected.

  1. Run the following query to view the updated data in the fact_orders table:
    SELECT * FROM dbt_glue_s3_tables.fact_orders ORDER BY order_id;

    fact_orders returns 6 rows (one per order), with 1004 now completed and 1006 added.

    #    order_id    customer_id    order_date    order_year    order_month    status    total_amount    customer_segment    segment_priority    dbt_updated_at
    1    1001    1    2024-06-01    2024    6    completed    150.00    Premium    1    2026-10-16 10:06:55.944983 UTC
    2    1002    2    2024-06-02    2024    6    completed    75.50    Standard    3    2026-10-16 10:06:55.944983 UTC
    3    1003    1    2024-06-03    2024    6    completed    200.00    Premium    1    2026-10-16 10:06:55.944983 UTC
    4    1004    3    2024-06-04    2024    6    completed    125.75    Premium    1    2026-10-16 10:06:55.944983 UTC
    5    1005    4    2024-06-05    2024    6    completed    89.99    Standard    3    2026-10-16 10:06:55.944983 UTC
    6    1006    6    2024-07-02    2024    7    completed    45.00    Premium    1    2026-10-16 10:06:55.944983 UTC

  2. Run the following query to view the updated data in the fact_order_history table:
    SELECT * FROM dbt_glue_s3_tables.fact_order_history ORDER BY updated_at;

    fact_order_history grows from 5 rows to 7 rows on the second run (the 2 rows whose updated_at advanced: 1004 and 1006). Order 1004 now has two history rows: the original unknown status and the new completed status.

    #    order_id    customer_id    status    order_date    total_amount    updated_at    recorded_at    event_year    event_month
    1    1001    1    completed    2024-06-01    150.00    2024-06-01 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    2    1002    2    completed    2024-06-02    75.50    2024-06-02 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    3    1003    1    completed    2024-06-03    200.00    2024-06-03 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    4    1004    3    unknown    2024-06-04    125.75    2024-06-04 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    5    1005    4    completed    2024-06-05    89.99    2024-06-05 10:00:00.000000 UTC    2026-10-16 09:41:22.801835 UTC    2024    6
    6    1004    3    completed    2024-06-04    125.75    2024-06-11 09:30:00.000000 UTC    2026-10-16 10:06:35.291993 UTC    2024    6
    7    1006    6    completed    2024-07-02    45.00    2024-07-02 10:00:00.000000 UTC    2026-10-16 10:06:35.291993 UTC    2024    7

Clean up

To avoid ongoing charges, clean up the resources you created during this walkthrough. Complete these steps in the specified order to facilitate proper resource deletion.

  1. Drop the tables dbt created in the S3 Tables namespace.
  2. Remove the namespace from the table bucket.
  3. Delete the table bucket.
  4. Delete the Data Catalog database.
  5. Delete the data this walkthrough wrote to your S3 bucket: the dbt warehouse data under s3://<YOUR-REGULAR-BUCKET>/glue/data/ and the sample CSV files under s3://<YOUR-REGULAR-BUCKET>/raw/. Leave the bucket itself in place if you use it for other workloads.
  6. (Optional) Remove the local dbt project directory (dbt_glue_s3_tables) and the sample customers.csv / orders.csv files.

Conclusion

In this post, we showed how to build an end-to-end dbt transformation pipeline on Amazon S3 Tables with AWS Glue 6.0, using a staging and mart architecture. At the core of this pipeline are incremental models on S3 Tables, which let us transform and maintain data incrementally with SQL. We demonstrated two incremental strategies working together: the merge strategy to keep the latest state per order in fact_orders, and the append strategy to build an audit-friendly change history in fact_order_history.

S3 Tables support in the dbt-glue adapter is currently experimental (as of version 1.12.4) and will continue to evolve in upcoming releases. As with any experimental feature, we recommend thoroughly testing it in your own environment before use.

To learn more, see Amazon S3 Tables and the dbt-glue adapter.


About the authors

Yukiko Iwazumi

Yukiko Iwazumi

Yukiko is a Cloud Support Engineer on the AWS Big Data Support team. She enjoys helping customers build and optimize their ETL workloads. In her spare time, she enjoys taking walks and playing games.

Chiho Sugimoto

Chiho Sugimoto

Chiho is a Go-to-market Data & AI solutions architect at AWS in Japan. She is passionate about helping customers build data lakes using ETL workloads. She loves planetary science and enjoys studying the asteroid Ryugu on weekends.

Neela Kulkarni

Neela Kulkarni

Neela is a Senior Solutions Architect at Amazon Web Services (AWS). She primarily serves independent software vendors (ISVs), helping them build and scale solutions in the Data, Analytics space by providing architectural guidance and best-practice recommendations for new and existing workloads.

Yota Hamaoka

Yota Hamaoka

Yota is a Senior Big Data Specialist Solutions Architect at Amazon Web Services. He helps customers accelerate their analytics journeys by leveraging his expertise in data lakes, big data processing, and data warehousing.

Srishti Mittal

Srishti Mittal

Srishti is a Product Manager at AWS, with a focus on making open data lakes performant and interoperable across analytics engines. She leads product strategy for open table formats such as Apache Iceberg, partnering with customers and field teams to turn real-world data lake challenges into product capabilities.

Get more from your Kiro investment with credit pooling: A guide for admins

Post Syndicated from Kirankumar Chandrashekar original https://aws.amazon.com/blogs/devops/get-more-from-your-kiro-investment-with-credit-pooling-a-guide-for-admins/

You’ve turned on credit pooling, or you’re about to, and now the decisions are yours: how many seats to keep, how many additional credits to buy, and what limit each developer gets. Set limits too tight and developers get blocked in the middle of a task. Set them too loose and one runaway automation job can drain the pool and pause Kiro for everyone. The data to make these calls is already in your AWS account, in your Kiro user activity reports. This post shows you how to read it.

The launch post, Share Kiro credits across your team with credit pooling, published November 4, 2026, introduced credit pooling: a shared pool of Kiro credits that every user in the pool draws from. Credits one developer doesn’t need automatically become available to a teammate who does.

Credit pooling is for organizations. It works with Kiro profiles that use AWS IAM Identity Center, Okta, or Microsoft Entra ID. Individual Kiro subscriptions, such as a personal account with a social login, can’t share credits through a pool, and credit pooling isn’t available in AWS GovCloud (US).

This post is a hands-on guide for admins. It describes how the credit pool behaves day to day and how to size it and dial in your limit settings from your own usage data. It also covers the best practices that keep it running smoothly.

How credit pooling works

In credit pooling, a seat is one user’s access to the pool, and each seat adds 500 monthly credits. When someone leaves, removing them frees their seat for someone else. For details, see Manage seats.

The following diagram shows how each seat’s 500 monthly credit inclusion flows into one shared pool, together with any additional credits you buy, and how every user draws from that pool. It also compares pooling with per-user credits.

How credit pooling works: each seat adds 500 monthly credits to one shared credit pool, additional credits can be bought at any time and are good for 12 months, and every user draws from the pool. Before pooling, each user’s credits are set by their subscription tier and credits a user doesn’t need go unused. With pooling, heavy users draw on credits light users don’t need before you buy anything extra.

Figure 1: How each seat’s 500 monthly credits flow into one shared pool that every user draws from, compared with per-user credits

Here’s a short summary of the core mechanics and how they play out once your pool is running. Each billing cycle, every $20 seat adds 500 credits to the pool, so 100 seats add 50,000. Every seated user draws from the pool, including users that run Kiro in headless mode, such as continuous integration and continuous delivery (CI/CD) pipelines. These credits continue to reset at the end of each billing cycle, but now they’re available for anyone in the pool to use.

When the pool runs out

Admins can buy additional credits at any time in the Kiro console. Additional credits roll over and are good for 12 months after purchase.

Which credits are used first

Monthly credits are used first because they reset at the end of each billing cycle. After the monthly credits run out, Kiro draws from additional credits, starting with the oldest purchase.

Where the savings come from

Credit pooling can help you save in three ways:

  • Shared credits absorb uneven usage. Your heaviest users draw on credits teammates don’t need before you buy anything extra.
  • Seats follow your team. Add seats as people join, and remove a user to release their seat when they leave.
  • Additional credits only when you need them. Buy them at any time, and they roll over for 12 months.

Walkthrough

Today, all you have is a daily report of each user’s consumption. This walkthrough turns that report into a plan in four steps. Step 1 loads the reports into Amazon Athena. Step 2 shows how each month used the pool. Step 3 recommends a seat count and a buffer of additional credits. Step 4 suggests a limit for each user.

Prerequisites

Before you start, confirm that the following are in place.

  • User activity reports turned on for your Kiro profile. The analysis in this post is based on the daily user activity CSV reports that Kiro writes to an Amazon Simple Storage Service (Amazon S3) bucket. To set them up, including the bucket policy Kiro needs to write to the bucket, see Turn on the CSV report.
  • Access to Amazon Athena, with permission to read the report location and write query results. For example, attach the AWS managed policy AmazonAthenaFullAccess, and allow s3:GetObject and s3:ListBucket on your report bucket.
  • The number of seats you bought for a prepaid pool, or the number of users in a postpaid pool. You manage seats under Access management > Credit sharing in the Kiro console. The activity report can’t give you this number.
  • An administrator role with the credit pooling permissions, so you can change seats, limits, and additional credits after the analysis.

Right-size your pool from your usage data

Your per-user activity reports record each user’s consumption.

Where to start depends on whether you already have data. If your team already uses Kiro, the activity report has recorded every user’s consumption all along, and the following queries run on that history as-is. Run Steps 2 and 3 now, before you pick a seat count. Step 3 tells you what that count needs to be.

If you are new to Kiro, there is nothing to analyze. Buy one seat for each person who needs access. That is the license, and the pool follows from it at 500 credits per seat. Keep a small buffer of additional credits (best practice 4), and start with generous limits (best practice 2). Either way, run one full billing cycle on pooling and come back to Step 2.

Step 1: Create the table and view

In the LOCATION line, replace the four capitalized placeholders. Use the Amazon S3 location you chose when you turned on the CSV report.

  • YOUR-BUCKET: the bucket name from your Amazon S3 location, for example amzn-s3-demo-bucket.
  • YOUR-PREFIX: the folder after the bucket name, for example user-activity-reports.
  • ACCOUNT-ID: the 12-digit AWS account where your users are subscribed.
  • REGION: the Region where you installed your Kiro profile, for example the US East (N. Virginia) Region (us-east-1).

For example, if your S3 location is s3://amzn-s3-demo-bucket/user-activity-reports/, the LOCATION line becomes s3://amzn-s3-demo-bucket/user-activity-reports/AWSLogs/111122223333/KiroLogs/user_report/us-east-1/. Keep the AWSLogs/.../KiroLogs/user_report/ part exactly as written. Kiro creates those folders itself.

CREATE EXTERNAL TABLE kiro_user_activity_raw (
c1 STRING, c2 STRING, c3 STRING, c4 STRING, c5 STRING,
c6 STRING, c7 STRING, c8 STRING, c9 STRING, c10 STRING,
c11 STRING, c12 STRING, c13 STRING, c14 STRING, c15 STRING,
c16 STRING, c17 STRING, c18 STRING, c19 STRING, c20 STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES ('separatorChar' = ',', 'quoteChar' = '"')
LOCATION 's3://YOUR-BUCKET/YOUR-PREFIX/AWSLogs/ACCOUNT-ID/KiroLogs/user_report/REGION/';

Then create the view that the queries in the next steps read from:

CREATE OR REPLACE VIEW kiro_user_activity AS
WITH headers AS (
-- The first row of each report file names its columns.
SELECT "$path" AS report_file,
ARRAY[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10,
c11, c12, c13, c14, c15, c16, c17, c18, c19, c20] AS names
FROM kiro_user_activity_raw
WHERE c1 = 'Date'
),
report_rows AS (
SELECT "$path" AS report_file,
ARRAY[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10,
c11, c12, c13, c14, c15, c16, c17, c18, c19, c20] AS vals
FROM kiro_user_activity_raw
WHERE c1 <> 'Date'
)
-- Pick each value by its column name in that file's header.
-- A column the file doesn't have comes back NULL.
SELECT TRY(vals[array_position(names, 'Date')]) AS report_date,
TRY(vals[array_position(names, 'UserId')]) AS user_id,
TRY(vals[array_position(names, 'Client_Type')]) AS client_type,
TRY(vals[array_position(names, 'Credits_Used')]) AS credits_used,
TRY(vals[array_position(names, 'User_Email')]) AS user_email,
TRY(vals[array_position(names, 'Usage_Limit')]) AS usage_limit,
TRY(vals[array_position(names, 'Subscription_Tier')]) AS subscription_tier
FROM report_rows
JOIN headers USING (report_file);

Three details in that setup are worth knowing:

  • OpenCSVSerde, not ROW FORMAT DELIMITED. Kiro quotes some fields, and the simpler row format leaves the quote marks on, which breaks any join on user id.
  • The view finds columns by name, not position. Kiro has added columns to the report over time, so a position can hold a different column in an older file. The view reads each file’s header row and picks values by name. A column a file doesn’t have, like usage_limit in older reports, comes back empty.
  • The table reads the first 20 columns, all as text. They must be text, because the first row of each file holds column names. Everything the queries use is within the first 14 columns, and anything past 20 is ignored. If a column the queries need ever moves past 20, add c21 and up to both the table and the view.

Confirm it worked before going further:

SELECT COUNT(DISTINCT user_id) AS users,
ROUND(SUM(CAST(credits_used AS DOUBLE)), 2) AS credits,
MIN(report_date) AS first_day,
MAX(report_date) AS last_day
FROM kiro_user_activity;

For an example 100-seat team with six months of reports, that returns:

users | credits | first_day | last_day
-------+-----------+------------+------------
90 | 245990.46 | 2026-05-01 | 2026-10-23

If that returns zero users, the LOCATION prefix is wrong. If user_id values come back wrapped in quote marks, the table was created with ROW FORMAT DELIMITED.

Step 2: Re-run every cycle and let the data correct your estimate

This is the query you come back to each cycle. It returns one row per closed month at today’s seat count, so one run shows your whole history. Change only the seat count. It answers the right-sizing question directly: at the seats I pay for now, which months overflow the pool, and how much sat unused?

WITH
-- ========================= EDIT ME =========================
inputs AS (
SELECT 100 AS seats -- the seats you pay for today, from the console
),
-- ======================= END EDIT ME =======================

-- Closed months only: the current month is not a full billing cycle yet.
per_user_month AS (
SELECT substr(a.report_date, 1, 7) AS month,
a.user_id,
SUM(CAST(a.credits_used AS DOUBLE)) AS credits
FROM kiro_user_activity a
WHERE date(a.report_date) < date_trunc('month', current_date)
GROUP BY substr(a.report_date, 1, 7), a.user_id
),

totals AS (
SELECT month,
COUNT(*) AS active_users,
SUM(credits) AS consumed,
SUM(GREATEST(credits - 500.0, 0)) AS beyond_own_seat,
approx_percentile(credits, 0.50) AS p50,
approx_percentile(credits, 0.90) AS p90,
MAX(credits) AS max_user
FROM per_user_month
GROUP BY month
)

SELECT
t.month,
i.seats,
t.active_users,
GREATEST(i.seats - t.active_users, 0) AS seats_never_used,
ROUND(t.consumed, 0) AS credits_consumed,
ROUND(GREATEST(i.seats * 500.0 - t.consumed, 0), 0) AS pool_credits_unused,
ROUND(GREATEST(i.seats * 500.0 - t.consumed, 0) * 0.04, 2) AS unused_credit_value_usd,
ROUND(t.beyond_own_seat
- GREATEST(t.consumed - i.seats * 500.0, 0), 0) AS credits_covered_by_sharing,
ROUND(GREATEST(t.consumed - i.seats * 500.0, 0), 0) AS additional_credits_needed,
ROUND(i.seats * 20.0
+ GREATEST(t.consumed - i.seats * 500.0, 0) * 0.04, 2) AS estimated_monthly_cost,
ROUND(t.active_users * 20.0
+ GREATEST(t.consumed - t.active_users * 500.0, 0) * 0.04, 2)
AS cost_if_never_used_seats_reclaimed,
ROUND(t.p90, 0) AS p90_credits_per_user,
ROUND(t.max_user, 0) AS max_credits_per_user
FROM totals t CROSS JOIN inputs i
ORDER BY t.month;

Sample output for the same team, one column per closed month. The current month is left out because it isn’t a full cycle:

month | 2026-05 | 2026-06 | 2026-07 | 2026-08 | 2026-09
------------------------------------+---------+---------+---------+---------+---------
seats | 100 | 100 | 100 | 100 | 100
active_users | 85 | 89 | 83 | 79 | 83
seats_never_used | 15 | 11 | 17 | 21 | 17
credits_consumed | 41863.0 | 44528.0 | 48003.0 | 38274.0 | 41943.0
pool_credits_unused | 8137.0 | 5472.0 | 1997.0 | 11726.0 | 8057.0
unused_credit_value_usd | 325.49 | 218.86 | 79.9 | 469.05 | 322.26
credits_covered_by_sharing | 10225.0 | 11214.0 | 13816.0 | 7654.0 | 9687.0
additional_credits_needed | 0.0 | 0.0 | 0.0 | 0.0 | 0.0
estimated_monthly_cost | 2000.0 | 2000.0 | 2000.0 | 2000.0 | 2000.0
cost_if_never_used_seats_reclaimed | 1700.0 | 1781.14 | 1920.1 | 1580.0 | 1677.74
p90_credits_per_user | 897.0 | 932.0 | 761.0 | 762.0 | 749.0
max_credits_per_user | 2022.0 | 2601.0 | 2368.0 | 1748.0 | 2768.0

For this team, credits that light users didn’t need covered 7,654 to 13,816 credits of heavier users’ demand every month, so it never bought additional credits. That’s how pooling can work. Even so, 2,000 to 11,700 credits went unused each month and 11 to 21 seats sat idle, which Step 3 turns into a plan.

Read it across, not down. If pool_credits_unused stays large for a couple of cycles, the seats behind it are not a one-off. Reclaim them from people who no longer need access and re-run next month to confirm.

If additional_credits_needed is climbing, buy additional credits earlier in the cycle rather than adding seats (see best practice 7). credits_covered_by_sharing, multiplied by $0.04, estimates what sharing saved you each month. When p90_credits_per_user and max_credits_per_user settle into a stable range, that is your signal to set limits with headroom above them.

seats_never_used counts seats with no activity that month, and cost_if_never_used_seats_reclaimed is your cost if you reclaimed them all. Treat it as a bound, not a target. Step 3 looks across several months before it recommends cuts.

The percentiles are your starting point for limits. p90_credits_per_user reflects your heavy users, and max_credits_per_user is the person who reaches a limit first. With fewer than a few dozen active users, lean on max. Step 4 suggests a limit for each person.

Step 3: Turn the numbers into a resizing plan

Step 2 shows what happened. This query turns that into a plan: seats to keep and reclaim, additional credits to hold, and what the change saves. In the EDIT ME block, set your seat count and how many closed months to look back over. Three months is a sensible default, because one quiet month doesn’t mean a seat is unneeded.

WITH
-- ========================= EDIT ME =========================
inputs AS (
SELECT 100 AS seats, -- the seats you pay for today, from the console
3 AS lookback_months -- closed months to base the plan on
),
-- ======================= END EDIT ME =======================

bounds AS (
SELECT i.seats,
date_trunc('month', current_date) AS this_month,
date_add('month', -i.lookback_months,
date_trunc('month', current_date)) AS since
FROM inputs i
),

-- Everyone who used Kiro since the window started, this month included,
-- needs a seat. Seats nobody used in that time are the ones to reclaim.
users AS (
SELECT COUNT(DISTINCT a.user_id) AS active_users
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
),

-- Credits consumed in each closed month of the window.
months AS (
SELECT substr(a.report_date, 1, 7) AS month,
SUM(CAST(a.credits_used AS DOUBLE)) AS consumed
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
AND date(a.report_date) < b.this_month
GROUP BY substr(a.report_date, 1, 7)
),

-- Never recommend more seats than you have, so every result stays sensible.
sized AS (
SELECT b.seats,
u.active_users,
LEAST(b.seats, u.active_users) AS rec
FROM bounds b
CROSS JOIN users u
),

-- Each window month at today's seats and at the recommended seats, with
-- anything past the pool bought as additional credits.
plan AS (
SELECT s.seats,
s.active_users,
s.rec,
MAX(m.consumed) AS busiest,
AVG(s.seats * 20.0
+ GREATEST(m.consumed - s.seats * 500.0, 0) * 0.04) AS cost_now,
AVG(s.rec * 20.0
+ GREATEST(m.consumed - s.rec * 500.0, 0) * 0.04) AS cost_resized
FROM sized s
CROSS JOIN months m
GROUP BY s.seats, s.active_users, s.rec
)

SELECT
seats,
active_users AS active_users_in_window,
rec AS recommended_seats,
seats - rec AS seats_to_reclaim,
ROUND(busiest, 0) AS busiest_month_credits,
rec * 500 AS recommended_pool_credits,
ROUND(GREATEST(busiest - rec * 500.0, 0), 0) AS additional_credits_to_keep,
ROUND(cost_now, 2) AS avg_monthly_cost_now,
ROUND(cost_resized, 2) AS avg_monthly_cost_resized,
ROUND(cost_now - cost_resized, 2) AS avg_monthly_savings
FROM plan;

Sample output for the same team at 100 seats, looking back over July through September:

seats | 100
active_users_in_window | 86
recommended_seats | 86
seats_to_reclaim | 14
busiest_month_credits | 48003.0
recommended_pool_credits | 43000
additional_credits_to_keep | 5003.0
avg_monthly_cost_now | 2000.0
avg_monthly_cost_resized | 1786.7
avg_monthly_savings | 213.3

recommended_seats is one seat for everyone who used Kiro in the lookback or so far this month, however lightly, and seats_to_reclaim is the rest. The report can’t tell you who joined last week or is on leave, so check the names in the Kiro console before you reclaim anything.

additional_credits_to_keep is how far your busiest month ran past the recommended pool. Keep at least that many additional credits on hand going into each cycle (best practice 4). That’s a balance to hold, not an amount to buy every month, so check what’s already in your pool on the Kiro dashboard and buy only the difference. If Step 2 shows consumption climbing, keep more than this.

The cost columns compare the lookback months at your current seats with their cost at the recommended seats, averaged per month. Each month costs $20 per seat plus $0.04 per credit used beyond the pool, counted in the month it’s used. For this example team, reclaiming 14 idle seats would save about $213.30 a month on average, roughly $2,600 a year if the pattern holds. In July, the busiest month, about $200 of the $280 in seat savings came back as additional credits, which is why the buffer matters.

Step 4: Find users whose limits need to change

Seats and the pool are half of right-sizing. Per-user limits are the other half. This query lists the people whose limit is out of step with what they use. It flags anyone whose busiest month in the lookback reached 80% of their limit, anyone who stayed under 25% of their limit every month, and anyone with no limit set. For each one it suggests a new limit: their busiest month plus 25%, rounded up to the nearest 100 and never below the 500 credits a seat adds to the pool. It only lowers limits for people active in every month of the lookback, so a new joiner isn’t cut after one quiet month. Adjust the thresholds in the EDIT ME block.

WITH
-- ========================= EDIT ME =========================
inputs AS (
SELECT 3 AS lookback_months, -- closed months to look back over
0.80 AS raise_at, -- raise if the busiest month reached 80% of the limit
0.25 AS lower_below, -- lower if every month stayed under 25% of the limit
1.25 AS headroom -- new limit = busiest month plus 25%
),
-- ======================= END EDIT ME =======================

bounds AS (
SELECT date_add('month', -i.lookback_months,
date_trunc('month', current_date)) AS since
FROM inputs i
),

-- Credits per user in each month of the window, this month so far included,
-- so a suggested limit is never below what someone has already used.
per_user_month AS (
SELECT a.user_id,
substr(a.report_date, 1, 7) AS month,
ROUND(SUM(CAST(a.credits_used AS DOUBLE)), 2) AS credits
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
GROUP BY a.user_id, substr(a.report_date, 1, 7)
),

-- Each user's plan, limit and email from their most recent report. On a pool,
-- Usage_Limit is the pool limit (999999 means none is set). On a subscription
-- (Pro, Pro+, Pro Max, Power), it's the tier's monthly credit allowance.
-- If one day has both, the pool row wins. Older reports have no limit
-- column, so the view returns NULL and they're skipped.
latest AS (
SELECT a.user_id,
max_by(a.user_email, a.report_date || IF(upper(a.subscription_tier) = 'POOLING', '1', '0')) AS user_email,
max_by(replace(upper(a.subscription_tier), '_', ''),
a.report_date || IF(upper(a.subscription_tier) = 'POOLING', '1', '0')) AS plan,
max_by(TRY_CAST(a.usage_limit AS DOUBLE),
a.report_date || IF(upper(a.subscription_tier) = 'POOLING', '1', '0')) AS lim
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
AND a.usage_limit IS NOT NULL
AND COALESCE(a.subscription_tier, '') <> ''
GROUP BY a.user_id
),

-- Suggested limit: the busiest month plus headroom, rounded up to the
-- nearest 100, and never below the 500 credits one seat brings to the pool.
-- months_active counts the closed months in the lookback with any use.
scored AS (
SELECT l.user_email,
l.plan,
COALESCE(l.lim, 999999) AS lim,
MAX(m.credits) AS busiest,
COUNT_IF(m.month < date_format(current_date, '%Y-%m')) AS months_active,
GREATEST(ceiling(MAX(m.credits) * i.headroom / 100) * 100, 500) AS new_limit,
i.lookback_months,
i.raise_at,
i.lower_below
FROM per_user_month m
JOIN latest l ON m.user_id = l.user_id
CROSS JOIN inputs i
GROUP BY l.user_id, l.user_email, l.plan, l.lim,
i.lookback_months, i.headroom, i.raise_at, i.lower_below
),

-- Lower a limit only for someone who used Kiro in every closed month of the
-- lookback, so a new joiner or someone back from leave isn't cut after one
-- quiet month.
flagged AS (
SELECT *,
CASE
WHEN plan <> 'POOLING' THEN 'limit when pooled'
WHEN lim >= 999999 THEN 'set limit'
WHEN busiest >= raise_at * lim THEN 'raise'
WHEN busiest < lower_below * lim
AND new_limit < lim
AND months_active = lookback_months THEN 'lower'
END AS action
FROM scored
)

SELECT user_email,
CASE plan WHEN 'POOLING' THEN 'Pool' WHEN 'PRO' THEN 'Pro' WHEN 'PROPLUS' THEN 'Pro+'
WHEN 'PROMAX' THEN 'Pro Max' WHEN 'POWER' THEN 'Power' ELSE plan END AS plan,
CAST(ROUND(busiest) AS BIGINT) AS busiest_month,
IF(lim >= 999999, 'none',
CAST(CAST(lim AS BIGINT) AS VARCHAR)) AS usage_limit,
IF(lim >= 999999, NULL,
ROUND(100.0 * busiest / lim, 0)) AS pct_of_limit,
action,
CAST(new_limit AS BIGINT) AS new_limit
FROM flagged
WHERE action IS NOT NULL
ORDER BY CASE action WHEN 'raise' THEN 1 WHEN 'set limit' THEN 2 WHEN 'lower' THEN 3 ELSE 4 END,

user_email;

Sample output for the same team, looking back over July through October so far:

user_email | plan | busiest_month | usage_limit | pct_of_limit | action | new_limit
---------------------+------+---------------+-------------+--------------+-------------------+-----------
[email protected] | Pool | 2768 | 3000 | 92.0 | raise | 3500
[email protected] | Pool | 994 | 1000 | 99.0 | raise | 1300
[email protected] | Pool | 913 | 1000 | 91.0 | raise | 1200
[email protected] | Pool | 838 | 1000 | 84.0 | raise | 1100
[email protected] | Pool | 471 | 500 | 94.0 | raise | 600
[email protected] | Pool | 513 | 3000 | 17.0 | lower | 700
[email protected] | Pool | 372 | 3000 | 12.0 | lower | 500
[email protected] | Pool | 144 | 1000 | 14.0 | lower | 500
[email protected] | Pool | 96 | 1000 | 10.0 | lower | 500
[email protected] | Pro | 1210 | 1000 | 121.0 | limit when pooled | 1600

The raise rows are the people closest to being blocked. In their busiest month, user021 used 994 of their 1,000 credits, so one heavy week might stop them. Raising it to 1,300 gives them room. A higher limit adds no cost until the credits are used.

The lower rows are people who use a small share of their limit, like user006, whose busiest month was 513 credits against a 3,000-credit limit. Lowering a limit doesn’t save money, because a credit costs the same whoever uses it. It limits the impact of a runaway automation job, so one person is less likely to drain the pool and block everyone. new_limit is never below what the user has already used this month, so lowering it doesn’t block them right away.

The limit when pooled rows are people still on a Pro, Pro+, Pro Max, or Power subscription. Their usage_limit is the tier’s monthly allowance, so above 100% means they need more than their tier includes, like user091. new_limit is the individual limit to allocate when you add them to the pool. Their usage is already counted in Step 3’s additional_credits_to_keep, so the buffer covers them too.

If several people in one group need the same change, change the group’s limit.

For the exceptions, set new_limit as an individual limit in the Kiro console. It takes priority over group and profile limits (best practice 2). Re-run this query each cycle to catch limits that need to move again.

Best practices for making credit pooling effective

These practices build on the numbers from the walkthrough and help you keep the pool sized without blocking anyone.

1. Learn your usage pattern first

Collect several months of data before you fine-tune anything. A couple of billing cycles show you who your heavy and light users are, how usage rises and falls through a sprint, and how quickly the pool draws down. Once you can see the trend, use the preceding analysis to size the pool and set limits.

2. Use the limit hierarchy strategically

With credit pooling, you can set per-user limits at three levels:

Level Priority Use it for
Individual Highest Setting a per-user limit that applies to a specific user (for example, a user that runs automations, or someone testing heavily)
Group Medium Setting a per-user limit that applies to all members of a group
Profile Lowest Setting a default limit applicable to all users

All limits are per-user. There are no aggregate caps at the group or profile level. A group limit sets the per-user cap for everyone in that group.

Where to start: If your team already uses Kiro, start from the limits Step 4 suggests. If you are new to Kiro, start with generous group and profile limits and tighten them after your first billing cycle, only where the data shows you need to. Over-constraining on day one creates friction and support tickets.

3. Group users by usage pattern

Consider grouping users by how they consume credits rather than only by org chart. For example, put heavy users (senior developers, machine learning engineers) in a group with a higher per-user limit, and light users (managers, reviewers) in a group with a lower one.

Grouping users by usage pattern: heavy users in a group with a higher per-user limit and light users in a group with a lower per-user limit, each drawing from the shared pool

Figure 2: Grouping users by usage pattern to apply different per-user limits

If you sync groups from your identity provider: Your existing synced groups likely mirror your org chart. Create groups for credit pooling. For example, keep your synced “Engineering” group for access management, but create separate “Kiro-Heavy-Users” and “Kiro-Standard-Users” groups to apply different per-user limits. Users can belong to multiple groups, and the highest limit wins.

4. Keep a buffer of additional credits

When the pool is empty, everyone stops. Watch your pool threshold alerts and buy additional credits before the pool runs low. Because additional credits roll over for 12 months, buying early doesn’t waste them. Step 3’s additional_credits_to_keep shows how many to hold, based on your busiest month.

5. Review and adjust monthly

The Kiro dashboard gives you three views for this:

  • Daily projected consumption with run-out date predictions.
  • Credit usage breakdown (monthly compared to additional credits).
  • Users sharing credits, credits left, and additional credits at a glance.

If you exhaust the monthly pool early, buy additional credits earlier in the cycle. If credits go unused, check whether some seats are inactive (best practice 7).

6. Use notifications to stay ahead

Credit pooling includes built-in alerts that notify admins at 80% and 100% by default:

  • Pool threshold alerts: Get notified when the pool drops below configured levels.
  • User usage alerts: Know when individual users approach their limits.
  • Seat utilization alerts: Know when assigned seats near the number you bought.

Send these to the people who can act on them.

7. Right-size seats, and use credits rather than seats for headroom

A seat is an access license first and a credit contribution second. Treat them as two separate questions.

Seats with zero usage are the first place to look. You pay $20/month for a seat whether anyone signs in or not, and the seats_to_reclaim figure from Step 3 shows how many have gone unused for the whole lookback. Reclaim those from people who no longer need access.

Lightly used seats are a different matter. Don’t cut a license from someone who uses Kiro occasionally because their consumption is low. Their unused credits already go to the pool.

For headroom, buy credits rather than seats. If demand runs ahead of your pool, buy additional credits. Monthly credits reset at the end of the cycle. Additional credits last 12 months.

Things to keep in mind

  • When the pool runs out, usage stops for everyone in it. Kiro blocks further usage, whatever each user’s limit, until you add credits.
  • Mid-cycle limit changes take effect immediately. If you lower a user’s limit below their current consumption, they’re blocked right away. If you increase their limit, they can immediately resume their AI use. Plan limit changes at the start of a billing cycle when possible.
  • In a prepaid pool, seats are billed whether occupied or not. Every seat contributes credits and costs $20/month. Factor in your idle seats when calculating return on investment.

Getting started

If you have a Kiro profile with users signing in through single sign-on (SSO), you’re ready to go:

  1. In the Kiro console, go to Access management.
  2. On the Subscriptions tab, choose Switch to credit sharing.
  3. Follow the wizard to select users or groups.

Switching is irreversible: a user you move can’t go back to an individual subscription. Have each user’s Step 4 limit ready to apply once they’re in the pool.

Key details at a glance

The following table summarizes the numbers and rules covered in this post.

Item Detail
Credits per seat 500/month (shared)
Cost per seat $20/month
Additional credits $0.04 per credit, good for 12 months
Monthly credit reset End of billing cycle
Consumption order Monthly → Additional (oldest purchase first)
Limit hierarchy Individual > Group > Profile

Start sharing

Credit pooling turns unused individual capacity into a shared resource. Teams with uneven usage can get more from the same spend, and limits at every level help you stay in control.

Ready to try it? Head to the Kiro console and turn on credit sharing under Access management. For details on seats, limits, and monitoring, see Credit pooling in the Kiro documentation.

 


About the authors

Kirankumar Chandrashekar

Kirankumar Chandrashekar

Kirankumar Chandrashekar is a Generative AI Specialist Solutions Architect at AWS, focusing on Kiro. Bringing deep expertise in AWS cloud services, DevOps, modernization, and infrastructure as code, he helps customers accelerate their development cycles and elevate developer productivity through innovative AI-powered solutions. By leveraging Kiro, he enables teams to build applications faster, automate routine tasks, and streamline development workflows. Kirankumar is dedicated to enhancing developer efficiency while solving complex customer challenges, and enjoys music, cooking, and traveling.

Austin Butler

Austin Butler

Austin is a Senior Go-To-Market Specialist at Amazon Web Services (AWS) focusing on generative AI across the software development lifecycle. He works with strategic customers and partners to understand their software development practices and how AWS services like Kiro can deliver value in their SDLC. Prior to joining AWS, Austin spent 10 years working in Finance & Accounting.

Step-up authentication: how to right-size authentication to risk

Post Syndicated from Abrom Douglas original https://aws.amazon.com/blogs/security/step-up-authentication-how-to-right-size-authentication-to-risk/

Not every action a user takes in an application carries the same risk. Viewing an account balance in a banking application isn’t the same as wiring several thousand dollars to a new payee. In practice, though, many applications ask users to prove their identity once at sign-in and then treat every action the same from that point on, whether that sign-in used a password alone or included multi-factor authentication (MFA). That creates a tension: if the sign-in is strict enough for the most sensitive operation, everyday tasks carry unnecessary friction. If it’s easy enough for everyday tasks, the most sensitive operations might not be protected well enough. Even a strong sign-in from hours earlier says little about who is at the keyboard when a high-risk request arrives.

Amazon Cognito now resolves that trade-off by supporting step-up authentication, which records the authentication assurance level and the methods used, and including both in the JSON web tokens (JWTs) it issues. You ask for a target assurance level when a user signs in. Amazon Cognito returns the level the user reached in an acr claim (authentication context class reference) and the methods they completed in an amr claim (authentication methods reference). These claims are part of the OpenID Connect Core specification, so your application can reason about authentication strength in a standard way and match it to the potential risk of what the user is trying to do. In this post, I explain how the claims support step-up authentication and walk through four patterns that put them to use: transaction-level step-up in a banking app, varying risk postures across a portfolio of applications, step-up enforced on API and SDK sign-in, and authentication assurance carried across a federated third-party OpenID Connect (OIDC) identity provider.

You can request authentication levels through Amazon Cognito managed login using the standard OIDC acr_values and max_age parameters, and through the SDK and API using the USER_AUTH flow with TARGET_ACR_VALUES and MAX_AGE. Requesting step-up authentication requires the Essentials or Plus feature plan. ; For the complete list of features, behaviors, and limitations, see the Authentication levels with ACR and AMR claims.

What ACR and AMR tell your application

Amazon Cognito defines four assurance levels, and the factor combinations that satisfy each one are fixed. You can use the default names as is or rename the level URIs to fit your organization’s own naming scheme. Renaming changes only the label. If you need to relate Amazon Cognito levels to a framework such as NIST SP 800-63 or eIDAS, make that mapping in your application. The following are the default Amazon Cognito defined levels.

  • Level 1 (urn:cognito:loa:1) is password only.
  • Level 2 (urn:cognito:loa:2) is a single one-time password (OTP) over SMS or email.
  • Level 3 (urn:cognito:loa:3) is a passkey on its own, or a password combined with an SMS or email OTP.
  • Level 4 (urn:cognito:loa:4) is the highest: a password with a time-based one-time password (TOTP) code from an authenticator app.

Amazon Cognito assigns the highest level the user’s completed factors fully satisfy, so a user who signs in with a password and a TOTP code lands at level 4, even though they also met the assurance requirements for every level below it.

Four claims in the token facilitate a step-up decision. The acr claim is the level the sign-in reached and is what your application compares against what the operation requires. The amr claim lists the methods behind that level, so you can confirm a specific factor was used. The auth_time claim records when the user last authenticated interactively and is what max_age is measured against. The iat claim only records when the token was issued, so a refreshed token carries a new iat but keeps its old auth_time. Finally, send a nonce in the request and verify it on the returned ID token, so the result is tied to the request you made.

The following is an example access token for a user completing a level 4 authentication. Notice the four claims I’ve discussed: acr, amr, auth_time, and iat.

{ 
    "sub": "387173a0-60c1-700a-4a02-e84b49bcc7a9", 
    "iss": "https://cognito-idp.<region>.amazonaws.com/<region>_123abc", 
    "aud": "123abcn2ci4a99a4ieno123abc", 
    "exp": 1445470140, 
    "iat": 499163700, 
    "auth_time": -446666160, 
    "token_use": "access", 
    "acr": "urn:cognito:loa:4", 
    "amr": ["pwd", "otp", "mfa"], 
    "email": "[email protected]", 
    "cognito:username": "387173a0-60c1-700a-4a02-e84b49bcc7a9" 
}

Two important behaviors are worth understanding before you build on this. First, a token refresh preserves the acr and amr values, so a user who reached level 4 keeps level 4 across refreshes and isn’t asked to prove it again on every rotation. Second, a refresh doesn’t reset the auth_time claim. That field records when the user interactively authenticated, not from a non-interactive token refresh. This is what lets you reason about freshness of authentication separately from assurance strength.

At a high level, every step-up interaction in this post follows the same loop: the application checks the token it already holds, redirects for a stronger level only when the operation requires more than the user has, and re-validates the acr claim on the freshly issued token before it proceeds. The following diagram provides a general step-up authentication flow.

Figure 1: General step-up authentication flow to access a sensitive operation

Figure 1: General step-up authentication flow to access a sensitive operation

How you request a level, and what stays your responsibility

The request side is deliberately straightforward. On managed login you add acr_values and optionally max_age to the or endpoint. In the SDK and API, you pass TARGET_ACR_VALUES and MAX_AGE in the USER_AUTH flow of the API. Both acr_values and TARGET_ACR_VALUES accept an ordered list of target levels. The same parameters work whether you’re setting the level for an initial sign-in or raising the level of a user who is already signed in; the patterns later in this post show both. Amazon Cognito acts only on what you send. It doesn’t infer the level you meant, so if you omit the parameter or request the wrong level, the user might not be stepped up the way you intended.

That points to the part your application and API owns: what assurance authentication level is needed. Amazon Cognito issues a token that honestly reports the level the user reached based on what your application requested. For example, deciding that a given operation requires an assurance level 3, checking the token’s acr against that requirement, and refusing the operation when it falls short is enforcement your application and API performs. Amazon Cognito produces the evidence; your code acts on it. In practice, that means checking the token you already hold before you redirect, so you don’t send a user to re-authenticate who already meets the bar, and validating the acr and auth_time claims on the tokens Amazon Cognito returns before you grant access. Amazon Cognito computes these claims itself, so you can’t customize, add to, or suppress them with a pre-token-generation Lambda trigger.

There is one more detail that saves debugging time later. If you rename your acr level URIs after tokens have already been issued, an older token might carry an acr value that no longer matches any configured level. Amazon Cognito treats that as an unrecognized level rather than an error. It still honors the token’s amr values and prompts only for factors not already present, without crediting any particular level. The amr list, in other words, remains meaningful even when a renamed level string goes stale. See Configuring ACR level names to learn how to configure this.

With the claims and the division of responsibility in place, the following four patterns show how they work in practice. Each one applies the same loop from Figure 1 to a different situation: a single application, a portfolio of applications, API-driven sign-in, and federation.

Pattern 1: Transaction-level step-up in a banking app

Consider a retail banking application. Signing in and viewing balances is routine, and the bank is comfortable requiring a moderate assurance level for it. Moving money is considered a privileged action, and a large transfer deserves stronger proof that the person at the keyboard is really the account holder.

The bank sets its baseline at level 2, so a user signs in with a one-time code over SMS or email and can see balances, statements, and pending transactions. When that same user initiates a transfer above $1,000, the application’s own policy says the operation requires level 4. Before it shows the transfer initiation screen, the application inspects the acr claim in the token it already holds. The user authenticated at level 2, level 2 is below the required level 4, so the application redirects the user to managed login with acr_values=urn:cognito:loa:4.

GET https://auth.example-bank.com/oauth2/authorize 
    ?response_type=code 
    &client_id=abc123def456 
    &redirect_uri=https://app.example-bank.com/callback 
    &scope=openid 
    &acr_values=urn:cognito:loa:4

Amazon Cognito now requires the user to complete a factor combination that satisfies level 4, for example entering their password and then a TOTP code from their authenticator app. When authentication finishes, Amazon Cognito issues fresh tokens with acr set to urn:cognito:loa:4, amr set to ["pwd", "otp", "mfa"], and a fresh updated auth_time claim. The application validates that the new token meets its requirement and only then lets the transfer proceed. A transfer under the threshold never triggers any of this, so the everyday experience stays light and the friction lands exactly where the risk is.

The application logic reads naturally, here’s a pseudo JavaScript snippet:

// Use your own URIs here, if different than defaults.
const ACR_RANK = {
  "urn:cognito:loa:1": 1,
  "urn:cognito:loa:2": 2,
  "urn:cognito:loa:3": 3,
  "urn:cognito:loa:4": 4,
};
const REQUIRED_LEVEL = "urn:cognito:loa:4";
const HIGH_VALUE_THRESHOLD = 1000;

function canAuthorizeTransfer(accessTokenClaims, amount) {
  if (amount < HIGH_VALUE_THRESHOLD) {
    return true; // baseline session is sufficient
  }
  // High-value transfer: require level 4.
  // An unrecognized acr ranks 0, so it never passes.
  const achieved = ACR_RANK[accessTokenClaims.acr] ?? 0;
  return achieved >= ACR_RANK[REQUIRED_LEVEL];
}

You can extend the same idea to freshness. A bank might accept a level 4 session for a high-value transfer only if the user authenticated within the last 5 minutes, which you express by adding max_age=300 to the request. Amazon Cognito compares that window against the auth_time claim in the access token and reauthenticates the user if the window has passed, even if the token was refreshed seconds ago.

Pattern 2: A portfolio of applications with different risk postures

Assurance levels are just as useful across a set of applications as they are within one. Suppose an organization runs five applications from a single Amazon Cognito user pool using managed login, and each one carries a different risk posture.

An internal cafeteria menu is low risk, so it’s fine with level 1, password only. An employee directory and an expense viewer hold personal data but nothing that moves money, so they require level 2: a one-time code over SMS or email on top of the password. A source code portal warrants a passkey or a password plus a one-time code, which is level 3. The production financial console is the crown jewel, so it demands level 4: a password with a TOTP code.

Each application requests its own floor by setting acr_values to the level that matches its risk, and each validates the acr claim on the returned token before granting access. Because the applications share a user pool, managed login keeps a single sign-on (SSO) session across them. A user who has already reached level 4 for the financial console is redirected to managed login when they open another application, finds the existing session, and receives tokens for that application without another prompt, provided the application doesn’t send a max_age that the session has outlived. Each application then compares levels by rank, so a level 4 token satisfies a level 2 floor. Someone who signed in at level 1 for the cafeteria menu, on the other hand, is stepped up the first time they open the expense viewer, because level 1 doesn’t meet the level 2 floor that the application enforces. The user pool stays single and central; the assurance requirement travels with each application’s own policy.

Renaming the level URIs helps here. If the organization already classifies systems against an internal assurance standard, it can set AcrConfiguration on the user pool so that, say, level 3 reports as urn:example-corp:assurance:standard and level 4 as urn:example-corp:assurance:high. The factor combinations behind each level stay fixed; only the names change, so every application validates against strings its developers already recognize.

Pattern 3: Step-up on API and SDK sign-in

Managed login covers browser-based flows, including federation, but plenty of clients authenticate directly against the Amazon Cognito API, and the same assurance model applies there, such as using the USER_AUTH flow with the InitiateAuth API. This matters for a mobile app, a desktop client, or a service that drives sign-in programmatically and needs to raise assurance before a sensitive call.

Take a mobile trading app that signs its users in with the SDK. A user opens the app with a password and reaches level 1, which is enough to browse watchlists and market data. When they place a trade, the app’s policy requires level 4. Because the app authenticates through the API rather than a browser redirect, it starts a new USER_AUTH flow and passes the access token it already holds along with TARGET_ACR_VALUES, requesting the level it needs. Amazon Cognito drives the user through a factor combination that satisfies level 4, then returns tokens whose acr claim the app validates before it submits the order. The InitiateAuth request would look similar to the following API call.

{
  "AuthFlow": "USER_AUTH",
  "ClientId": "abc123def456",
  "AuthParameters": {
    "USERNAME": "[email protected]",
    "ACCESS_TOKEN": "eyJraWQiOi...",
    "TARGET_ACR_VALUES": "urn:cognito:loa:4",
    "MAX_AGE": "300"
  }
}

Passing the access token the app already holds lets Amazon Cognito step the user up from the factors in that token; without it, Amazon Cognito authenticates the user from scratch. The MAX_AGE parameter behaves the same way it does on managed login. It ties the requirement to auth_time, so a trade placed after the window elapses forces a fresh authentication even if the app refreshed its tokens in the meantime. One behavior specific to the API path is worth knowing when you test on a lower Cognito feature plan. If you request step-up through InitiateAuth on a user pool that isn’t on the Essentials or Plus plan, the API returns a FeatureUnavailableInTierException. Managed login handles the same situation differently: the authorize endpoint silently ignores acr_values and proceeds with normal authentication rather than raising an error.

Pattern 4: Carrying assurance across a federated OIDC identity provider

The three patterns so far assume Amazon Cognito is where the user authenticates and the authoritative source for the identity. Many organizations federate sign-in to a third-party OIDC provider, so the person proving who they are is doing it against an external identity provider (IdP), while Amazon Cognito brokers the session. The assurance model follows them there.

When your application requests a level, it sends acr_values and optionally max_age to the Amazon Cognito authorize endpoint exactly as before. If that user is configured to federate through an OIDC IdP, Amazon Cognito sends the authorization request to that IdP on the user’s behalf. It translates the level you requested into the acr value the IdP expects, using the mapping you configured, and passes max_age along with it. A standards-compliant OIDC IdP honors acr_values the same way Amazon Cognito does: it drives the user through an authentication that satisfies the requested level, and it returns its own acr value describing what the user reached. max_age carries forward in the same way, so a freshness requirement is enforced at the provider that actually authenticates the user rather than being lost at the broker. Keep in mind that this is only supported with OIDC identity providers.

The request is unchanged from the application’s point of view. It still directs to Amazon Cognito:

GET https://auth.example.com/oauth2/authorize
  ?response_type=code
  &client_id=abc123def456
  &redirect_uri=https://app.example.com/callback
  &scope=openid
  &identity_provider=PartnerOIDC
  &acr_values=urn:cognito:loa:3
  &max_age=300

The interaction gains a third participant, the downstream IdP, but the assurance requirement is persisted through the entire federated authentication flow as shown in figure 2.

Figure 2: Federation with an OIDC third-party IdP, persisting the acr_values and max_age request parameters

Figure 2: Federation with an OIDC third-party IdP, persisting the acr_values and max_age request parameters

The value that comes back from a partner IdP won’t use Amazon Cognito’s level URIs, so this lets you map the provider’s acr values onto its own levels with the AcrMapping field on the OIDC IdP configuration. A partner IdP that reports, say, https://partner.example/assurance/strong can be mapped to Amazon Cognito level 3 (urn:cognito:loa:3), so that by the time the token reaches your application the acr claim speaks the same vocabulary regardless of whether the user authenticated locally or through a federated provider. Your resource server keeps a single enforcement rule and authorization logic and doesn’t need to have special handling depending on where the user ultimately authenticated. See Step-up authentication for federated users to learn how to map external OIDC IdP acr levels to Cognito.

This is the same pattern that RFC 9470, the OAuth 2.0 Step Up Authentication Challenge Protocol, describes: the assurance level is requested at the edge of your application, travels through Amazon Cognito to whatever provider authenticates the user, and returns normalized to a vocabulary your code already understands. A user federating from a corporate IdP and a user signing in against the same user pool directly both arrive at your resource server carrying an acr claim that means the same thing.

Conclusion

In this post, I showed you how the acr and amr claims in Amazon Cognito let you match authentication strength to the risk of what a user is doing, instead of settling for one bar at the front door. Your application requests a target level with acr_values and max_age (or TARGET_ACR_VALUES and MAX_AGE in the USER_AUTH flow), Amazon Cognito reports the level reached and the methods used, and your application enforces what each operation requires. The four patterns, from a banking transfer to a federated third-party IdP, follow that same loop, and one enforcement rule at your resource server covers every sign-in path.

The larger shift is that assurance is now something Amazon Cognito expresses in a standard way and your application reasons about directly, without building your own step-up tracking. To get started, move your user pool to the Essentials or Plus feature plan, decide the level each operation requires, and add acr_values to your existing authorize requests. For the complete parameter reference and federated behavior, see the Amazon Cognito Developer Guide.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Abrom Douglas III

Abrom is a Senior Solutions Architect within AWS Identity with over 20 years of software engineering and security experience, specializing in identity and access management. He loves speaking with customers about how identity and access management can provide secure outcomes that enable both business and technology initiatives. In his free time, he enjoys cheering for Arsenal FC, photography, travel, volunteering, and competing in duathlons.

Detecting cross-cloud lateral movement with AWS Security Hub

Post Syndicated from Kyle Shields original https://aws.amazon.com/blogs/security/detecting-cross-cloud-lateral-movement-with-aws-security-hub/

Most organizations run a multicloud estate, and so do the attackers targeting them. An adversary who compromises an identity in one provider follows that identity wherever it leads, including across a federated trust into a second cloud service provider. The signals enumerating this scenario are rarely missing; the problem is that they live in separate consoles, in different schemas, owned by different teams. No one has visibility into the whole picture, so no one can decide what to fix first.

AWS Security Hub addresses prioritization and triage with exposure findings. Security Hub correlates reachability, blast radius, vulnerabilities, misconfigurations, and effective permissions, providing a strong correlation layer with an attack-path visualization, providing the context needed to generate risks from findings. That analysis now extends to Microsoft Azure. Security Hub records and analyzes your Azure resources with the same correlation engine used for Amazon Web Services (AWS) resources. The resulting details and meta-data land in the same console, ranked in the same queue, providing holistic, multicloud visibility into your security risks.

In this blog post, you learn how to configure the Azure integration for Security Hub and use exposure findings to prioritize attack paths across both clouds from one console. We follow a realistic scenario: a compromised identity that threatens both an Azure and an AWS environment through a shared, federated identity plane. We show you how the critical exposures along that path are presented as ranked findings that you can triage together, and we map each one to the MITRE ATT&CK framework. We also cover the prerequisites that teams commonly overlook.

Why prioritizing multicloud risk is difficult

Consider an organization whose Microsoft Entra ID tenant is federated into an AWS account, so identities in the tenant can assume an AWS role. This is an ordinary and intentional configuration used to avoid having to manage a second set of credentials. It also means the two clouds share an identity plane: a single compromised Entra identity is both an Azure threat and—through the federation—an AWS threat.

An attacker exploits this, but the defensive signals land in different places:

Where the risk lives Traditionally visible in Owned by
Weak Entra identity controls: over-privileged identities, no multi-factor authentication (MFA), vulnerable conditional access policies (CAP) Entra ID and Microsoft Defender for Cloud Identity team
Internet-reachable Azure host with admin rights Defender for Cloud Azure platform team
Federated trust into AWS AWS Identity and Access Management (IAM) Cloud security team
Sensitive data and over-exposed resources in AWS AWS security tooling Cloud security team

Each team sees one fragment, and in isolation each fragment appears low severity. You see the risk only when you correlate all of it together and discover the same identity plane ties the attack path together. Exposure findings provide that severity within AWS; extending it to Azure closes the multicloud visibility gap.

How the Azure integration works

You create the Azure connector in the AWS Management Console for Security Hub. It authenticates to your Entra ID tenant through an application registration, records and evaluates your Azure resource configurations, and streams Microsoft Defender for Cloud alerts and Entra ID audit logs through an Azure Event Hubs namespace. Your Azure resources then flow into the same correlation engine that analyzes signals from AWS Security Hub Cloud Security Posture Management (CSPM), Amazon Inspector, Amazon Macie, and Amazon GuardDuty. That engine produces two kinds of findings:

  • Control findings against standards such as the CIS Microsoft Azure Foundations Benchmark.
  • Exposure findings, which are ranked, attack-path findings that correlate traits such as reachability, effective permissions, and misconfiguration, with a severity based on how discoverable and exploitable the risk is.

Both use the Open Cybersecurity Schema Framework (OCSF) and appear in the same console as your AWS findings. However, one filtering detail matters: because Security Hub produces the finding, its top-level cloud.provider is AWS, while the evaluated resource carries resources[].provider = Azure. Filter on resources.provider to scope to a single cloud.

Prerequisites

To follow along with this post, you need:

  • An AWS account with Security Hub enabled. If you use a delegated administrator account for Security Hub, create the connector there, in the AWS Region where you aggregate findings.
  • An Entra ID tenant with a Microsoft Azure subscription. You need privileges in Azure to create an application registration, assign roles at the tenant root management group, and create a subscription-level diagnostic setting.
  • The Azure CLI, authenticated to the target subscription with az login command.
  • Activity log export. Azure resource recordings are change-driven and depend on activity logs reaching the event hub that the connector reads. The onboarding process assigns an Azure policy to create the required diagnostic setting, but it only remediates existing subscriptions after you create a remediation task. If the connector reports healthy status but resources never appear, run az monitor diagnostic-settings subscription list to confirm the export exists, and create a remediation task if the list is empty.

Configuration

The following steps detail how to connect your Azure environment to Security Hub v2: Registering the Azure application, establishing federated identity credentials, and assigning the roles required for AWS to evaluate your Azure resources.

Step 1: Create the Azure connector in Security Hub

The first step in this configuration is to create the Azure connector in Security Hub. The connector establishes trust with your Azure tenant and defines which subscriptions and regions Security Hub v2 will evaluate.

  1. Open the Security Hub console and choose Integrations.
  2. Choose Create Azure connector.
  3. Enter your Azure Tenant ID and the Application (client) ID of the application registration you created for the integration.
  4. For Subscriptions and Regions, select all. Attack paths cross subscription and Region boundaries, so partial coverage leaves blind spots where a compromised identity can pivot unseen. Scope to specific IDs or Regions only when data-residency rules require it.
  5. Run the generated setup script in your Azure environment, then choose Create connector.

Include the global region scope. Controls that evaluate Entra ID and Microsoft Graph resources require it, and those identity exposures are central to this scenario. If you also create an Amazon Inspector or Security Hub CSPM connector for the same tenant, keep its subscriptions and regions consistent with this one.

Step 2: Verify the connector and its recording activity

Health status alone doesn’t tell you whether recording is flowing. Confirm both.

AWS Command Line interface (AWS CLI) command 1: Verify connector health and recording state

aws securityhub list-connectors-v2 --region <REGION> \

--query "Connectors[?ProviderSummary.ProviderName=='AZURE']" --output json

aws securityhub get-resources-v2 --region <REGION> --max-results 50 \

--filters '{"CompositeFilters":[{"StringFilters":[{"FieldName":"ResourceType",

"Filter":{"Value":"microsoft.compute/virtualmachines","Comparison":"EQUALS"}}]}],

"CompositeOperator":"AND"}' \

--query "Resources[].{id:ResourceId, captured:ResourceDetailCaptureTimeDt}" --output table

Step 3: Query exposure findings for Azure resources

Scope to Azure by filtering on the resource provider.

AWS CLI command 2: Retrieve exposure findings for Azure resources

​​aws securityhub get-findings-v2 --region <REGION> --max-results 50 \ --filters '{"CompositeFilters":[ {"StringFilters":[{"FieldName":"resources.provider","Filter":{"Value":"Azure","Comparison":"EQUALS"}}]}, {"StringFilters":[{"FieldName":"metadata.product.feature.uid","Filter":{"Value":"security-hub/Exposure","Comparison":"EQUALS"}}]}], "CompositeOperator":"AND"}' \ --query "Findings[].{sev:severity, title:finding_info.title}" --output table​

Step 4 (optional): Add Amazon Inspector for Azure vulnerability scanning

To add vulnerability findings for Azure virtual machines (VMs), function apps, or container registry images, create an Amazon Inspector connector for the same tenant. VM scanning requires each target VM to have a system-assigned managed identity, which you can enforce with an Azure Policy. Figure 1 shows a correctly configured Azure integration inside Security Hub, with vulnerability management and posture management deployed.

Figure 1: Successful configuration of the Azure integration with Security Hub

Step 5: Prerequisites for Microsoft Azure

See the AWS documentation for the prerequisites for Microsoft Azure.

Walk-through: Prioritizing a cross-cloud attack path

In this example, the organization has one identity plane across two clouds, comprising a Microsoft Entra ID tenant with a federated trust into an AWS account. An adversary who compromises the right Entra identity gains an initial foothold in Azure and a path into AWS, because both clouds trust the same identity plane. The following sections trace that path. Each step is a real, high-severity exposure finding that Security Hub ranked on its own. The point of the walk-through is to demonstrate a real-life scenario and examine all findings in one unified security console.

Phase 1: A compromised identity (Azure)

ATT&CK: Phishing (T1566), Valid Accounts: Cloud Accounts (T1078.004)

The path begins with an Entra identity that is both over-privileged and unprotected. You’ll find this in the Security Hub console under Exposures, where Security Hub raises it as an identity exposure finding and maps the attack path stemming from it:

Potential Unauthorized Access: Azure RBAC user with administrative access has MFA disabled (high). It correlates the user, the role assignment that grants administrative access, and the organization.

The tenant’s authorization policies let an attacker broaden that foothold, and Security Hub CSPM reports each policy as a failed control (high): Microsoft Entra ID authorization policies should prohibit default users from registering applications…should restrict user consent for applications, and Azure authorization policies should restrict guest invitations to admin roles only. Each finding expands what a single compromised, non-privileged identity can do without an administrator.

Phase 2: Foothold and privilege escalation (Azure)

ATT&CK: Exploit Public-Facing Application (T1190), Valid Accounts: Cloud Accounts (T1078.004)

The tenant contains an internet-reachable VM whose network security group allows inbound from any address, and whose attached identity holds administrative rights over the subscription. Security Hub surfaces this under Exposures, correlating reachability and effective permissions into one finding that shows why it matters: anyone reaching the VM inherits admin control of the subscription.:

Potential Initial Access: Potentially internet reachable Azure virtual machine with open network security group has administrative access (high). It correlates the VM, the role assignment, the network security group, and the public IP address.

The finding’s analysis reads like an attack path. The resource “may be reachable from the public internet,” “overly permissive network security group (NSG) rules allow unintended inbound access,” and “the Owner or Contributor role grants extensive permissions… enabling a threat actor to escalate privileges.” Security Hub evaluates this from configuration and network-path modeling, so it surfaces whether or not the VM is running. Figure 2 shows the correlated attack path for that virtual machine.

Figure 2: An Azure attack-path exposure, analyzed by the same correlation engine as AWS exposures

The cross-cloud bridge: Federation into AWS

The tenant from Phases 1 and 2 is federated into the AWS account through an IAM SAML identity provider. As shown in Figure 2, a role trusts that provider and grants read access to every bucket in Amazon Simple Storage Service (Amazon S3). This trust is what expands the risk across clouds from the same adversary: a compromised Entra identity can assume this role and reach AWS data.

This one hop lives in IAM rather than in Security Hub. Security Hub doesn’t not raise a finding for a role that trusts your own federated identity provider. Confirming it is a normal investigative pivot: the role trusts a SAML identity provider that represents your Entra tenant, the same tenant whose exposures you triaged when you added Amazon Inspector in Step 4.

Figure 3: The federated trust that links the two clouds through a shared identity plane

Phase 3: The impact (AWS)

ATT&CK: Data from Cloud Storage (T1530), Transfer Data to Cloud Account (T1537)

On the AWS side, the correlation engine has already categorized the resources this identity can reach. Under Exposures in the Security Hub console, the sensitive-data objective surfaces this finding because that reachable set includes data at risk; a compromised identity could destroy it:

Potential Sensitive Data Destruction: S3 bucket has sensitive data and versioning disabled and Object Lock disabled and MFA delete disabled (high). A Macie finding, The S3 object contains personal information, is a contributing signal, and the control S3 general purpose buckets should be encrypted at rest with AWS KMS keys fails alongside it.

The same account carries related AWS attack-path exposures. Two examples are Potential Resource Hijacking: Internet reachable EC2 instance with open security group has software vulnerabilities with limited effective permissions and Potential Unauthorized Access: IAM user has weak password policies. In the exposure queue, these sit next to the Azure findings, ranked by the same severity model.

Prioritizing across both clouds in the console

Here is the operational benefit. An analyst is notified of generated exposure findings and opens the dashboard and filters to High severity. In one prioritized list, without switching tools or opening a ticket for another team, they see the Azure admin identity without MFA, the internet-reachable Azure VM with subscription-admin rights, and the AWS sensitive data exposure. Together, these show the full scope of what a single vector, sharing an identity plane, might target. The analyst confirms the connecting federation with one pivot into IAM. The multicloud triage that used to require two products and two teams now occurs in one place. Figure 4 shows that single ranked queue.

Figure 4: Cross-cloud exposure prioritization in a single console

Phase-to-exposure summary

The following table traces each phase of the attack path to its MITRE ATT&CK techniques, the cloud where it plays out, and the ranked Security Hub exposure that surfaces it — following the pivot from Azure into AWS across the shared identity plane.

Phase ATT&CK Cloud Ranked exposure in Security Hub
1. Compromised identity T1566, T1078.004 Azure Potential Unauthorized Access: Azure RBAC user with administrative access has MFA disabled (High)
2. Foothold and privilege escalation T1190, T1078.004 Azure Potential Initial Access: internet reachable Azure VM with open NSG has administrative access (High)
2.1 Bridge T1550 (Use Alternate Authentication Material) Azure to AWS Federated trust, confirmed in AWS IAM (shared identity plane)
3. Data objective T1530, T1537 AWS Potential Sensitive Data Destruction: S3 bucket has sensitive data… (High), plus Macie

Conclusion

A cross-cloud attack is difficult to prioritize because signals are generated across separate consoles, schemas, and teams. In this post, you saw how the Azure integration for AWS Security Hub brings Azure resources into the same exposure engine and the same queue as your AWS resources. One analyst can prioritize an attack path that spans a compromised Microsoft Entra ID identity, across a federated trust, to sensitive data in Amazon S3, without leaving Security Hub.

To recap why this workflow is practical and effective:

  • Security Hub records and analyzes your Azure security findings and displays them in the same unified console as your AWS resources, and produces ranked, attack-path exposure findings for both clouds.
  • Findings from both clouds share the OCSF schema, so you filter, group, and prioritize them in one place. Filter on resources.provider to scope an individual cloud.
  • Security Hub correlates signals into attack paths within each cloud. The analysis creates a cross-cloud narrative, such as a shared federated identity plane, while co-locating ranked correlation findings across both Azure and AWS, creating efficient scoping and remediations.
  • Confirm your prerequisites. Include the global region scope for Entra ID controls, know that sign-in log signals require an Entra ID P1 or P2 license, and confirm that the subscription diagnostic setting that exports Activity Logs to the connector’s event hub is in place. A connector can report a healthy status while it records nothing.

To get started, see Enabling Microsoft Azure integration in Security Hub and Exposure findings in Security Hub.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Kyle Shields

Kyle Shields

Kyle is a Security Specialist Solutions Architect focused on threat detection and incident response at AWS. Today, he’s focused on helping enterprise AWS customers adopt and operationalize AWS Security Incident Response and improve their security posture.

Marshall Jones

Marshall Jones

Marshall is a Worldwide Security Specialist Solutions Architect at AWS. His background is in AWS consulting and security architecture and focused on a variety of security domains including edge, threat detection, and compliance. Today, he’s focused on helping enterprise AWS customers adopt and operationalize AWS security services to increase security effectiveness and reduce risk.

Orchestrate DuckDB analytics pipelines with Amazon MWAA

Post Syndicated from Vinod Jayendra original https://aws.amazon.com/blogs/big-data/orchestrate-duckdb-analytics-pipelines-with-amazon-mwaa/

Apache Airflow orchestrates data pipelines ranging from data ingestion and machine learning to SQL-based analytics. Some analytical workloads, such as daily rollups and usage reports, process bounded datasets and can run within the resources of a single worker. For these workloads, deploying a distributed query cluster can add unnecessary infrastructure and operational complexity.

DuckDB is an open source in-process analytical database that runs within an application without requiring a separate database server. Its columnar, vectorized execution engine supports analytical SQL operations, including scans, joins, and aggregations.

Amazon Managed Workflows for Apache Airflow (Amazon MWAA) runs Apache Airflow as a managed service, so you can schedule, run, and monitor workflows without managing the underlying Airflow infrastructure. Combined with DuckDB, you can add SQL transformations to your pipelines that run inside the Airflow task itself.

In this post, you learn how to run DuckDB with an Amazon MWAA Provisioned environment.

How DuckDB and Amazon MWAA work together

In Apache Airflow, a directed acyclic graph (DAG) defines tasks and their dependencies, along with scheduling, retry, and concurrency settings. Amazon MWAA runs the tasks on workers and publishes configured task logs to Amazon CloudWatch Logs.

DuckDB runs in the Airflow task process, using the CPU, memory, and local storage of the Amazon MWAA worker container. Amazon MWAA orchestrates the workflow, while DuckDB performs the SQL processing.

This walkthrough uses DuckDB 2.0.0, which includes asynchronous I/O for reading from object storage and first-class VARIANT support for semi-structured data. DuckDB 2.0.0 also supports a client-server mode through the Quack protocol, which lets other processes connect to a DuckDB database over the network. This walkthrough runs DuckDB in-process because each Airflow task performs a self-contained transformation.

Introducing the Apache Airflow DuckDB provider

The Apache Airflow DuckDB provider provides the DuckDBExecuteQueryOperator. The operator runs DuckDB locally in the worker container and executes SQL without starting a separate query service.

The DuckDB integration in the Amazon provider adds the AWS aware duckdb_aws connection type. On supported Amazon MWAA Provisioned environments, the DuckDB packages are preinstalled, and Amazon MWAA creates the default connection, as described later in this post.

Solution overview

An engineering team operates a shared inference service that product teams use for their applications. As usage grows, the team needs to understand which applications and teams are driving inference activity and the estimated cost of that usage. Showback provides an itemized view of usage and estimated cost without charging teams directly.

To build the showback pipeline without a separate analytics cluster, the team uses Amazon MWAA to orchestrate Airflow tasks that run DuckDB. DuckDB reads source files from Amazon Simple Storage Service (Amazon S3), performs SQL transformations, and publishes the results as Apache Iceberg tables in Amazon S3 Tables. This pattern suits bounded, SQL-oriented workloads that run reliably within the resources of a single worker.

Five-stage architecture of the AI inference showback pipeline. Amazon S3 stores the source Parquet files. Amazon MWAA orchestrates two Airflow tasks in which DuckDB reads, cleans, combines, publishes, and validates the data. The pipeline commits the output to Apache Iceberg tables in Amazon S3 Tables.

Figure 1: Amazon MWAA orchestrates two DuckDB tasks across five stages, from reading Parquet data in Amazon S3 through publishing and validating Iceberg tables in Amazon S3 Tables

The workflow has five logical stages, implemented by two Airflow tasks, as shown in Figure 1.

  • Stage 1: Store the source data – An Amazon S3 bucket stores the Parquet files for inference events, model rates, and application ownership records.
  • Stage 2: Trigger the DAG – A manual action starts this example DAG. Amazon MWAA orchestrates both tasks, tracks their status, and sends task logs to Amazon CloudWatch Logs. You can configure a schedule for recurring runs.
  • Stage 3: Read, clean, and combine the records – The transform_and_publish_showback task uses DuckDB to read the Parquet files directly from Amazon S3, deduplicate events, and apply the model rate and ownership record effective at each invocation timestamp.
  • Stage 4: Publish the result – In the same transform_and_publish_showback task, DuckDB merges the processed records into the costed_invocations Iceberg table in Amazon S3 Tables and commits the update. The task also creates the daily_application_showback and team_budget_status summary tables.
  • Stage 5: Validate published tables – After publication, the second Airflow task, validate_showback, uses DuckDB to check the row count, confirm that event IDs are unique, and verify the expected allocation states.

The sample rates and cost_credits values are synthetic and are provided only to demonstrate allocation logic. They do not represent AWS pricing, Amazon Bedrock charges, or customer billing records.

Prerequisites

Before you begin, make sure you have the following resources and permissions:

  • An Amazon MWAA Provisioned environment running Apache Airflow 3.3.1 with Python 3.12. See Apache Airflow versions on Amazon MWAA for the currently supported versions.
  • An Amazon S3 bucket for the source Parquet files and an Amazon S3 Tables table bucket for the outputs.
  • An Amazon MWAA execution role with read access to the source bucket and permissions to create, read, and update tables and table data in the target table bucket. For the required actions, see Accessing Amazon S3 Tables using open source applications. If the table bucket uses a customer managed AWS Key Management Service (AWS KMS) key, the role also needs permission to use that key.
  • Network connectivity from the Amazon MWAA private subnets to Amazon S3 and Amazon S3 Tables. This sample installs the DuckDB Iceberg extension at runtime, so it also requires access to the official DuckDB extension repository unless the matching extension is already available.
  • The sample bundle containing the DAG, SQL, and synthetic-data generator used in this walkthrough.
  • Python 3, the dependencies listed in generator-requirements.txt, and the AWS Command Line Interface (AWS CLI) configured on the workstation where you generate and upload the sample data.

In the test environment used for this post, Amazon MWAA included apache-airflow-providers-amazon 9.38.0, apache-airflow-providers-duckdb 0.2.0, and DuckDB 2.0.0. These versions might change in future Amazon MWAA releases.

Use the built-in DuckDB providers and connection

Amazon MWAA Provisioned environments running Apache Airflow 3.3.1 include DuckDB, the Apache Airflow DuckDB provider, and the DuckDB integration in the Amazon provider. Amazon MWAA also creates a connection named duckdb_default with the connection type duckdb_aws. You do not need to add packages to requirements.txt or create the connection manually.

To confirm that the connection exists, choose Admin, then Connections in the Airflow UI. Look for duckdb_default.

Note: When a DuckDBExecuteQueryOperator task doesn’t specify conn_id, it uses duckdb_default. The AWS aware hook obtains temporary credentials from the Amazon MWAA execution role and creates a DuckDB S3 secret for the task. Don’t put AWS access keys in the DAG or create a separate S3 secret in the SQL, because doing so can conflict with the secret the hook creates. If duckdb_default doesn’t appear under Admin, Connections, update your Amazon MWAA environment without changing any settings to apply the latest Amazon MWAA image.

Prepare the sample data

Use generate_ai_inference_data.py from the sample bundle to create Parquet files containing inference events, model rates, and application ownership records. A fixed random seed makes the input reproducible. The dataset includes duplicate events and changes to rates and ownership, allowing you to demonstrate deduplication and effective-dated attribution.

Run the generator and upload the resulting files to Amazon S3:

python3 -m pip install -r generator-requirements.txt

python3 generate_ai_inference_data.py \
    --output sample_ai_inference \
    --start-date 2026-09-01 \
    --days 30 \
    --events-per-day 10000 \
    --seed 42

aws s3 cp sample_ai_inference/ \
    s3://<SOURCE-BUCKET>/ai-showback/ \
    --recursive

The default settings generate approximately 300,000 unique events across daily partitions. The generated manifest.json records the expected unique-event count for subsequent validation.

Build the DuckDB transformation

See publish_showback.sql in the sample bundle for the complete transformation SQL. The following excerpts highlight three operations used in the pipeline.

Read Parquet files and remove duplicates

The read_parquet function reads daily Parquet partitions directly from Amazon S3. The union_by_name option aligns columns across files with different schemas. A ROW_NUMBER window function retains the record with the most recent ingestion timestamp for each event ID.

CREATE OR REPLACE TEMP TABLE latest_events AS
SELECT *
FROM read_parquet(
    's3://<SOURCE-BUCKET>/ai-showback/'
    'inference_events/ingest_date=*/*.parquet',
    hive_partitioning = true,
    union_by_name = true
)
QUALIFY ROW_NUMBER() OVER (
    PARTITION BY event_id
    ORDER BY ingested_at DESC
) = 1;

Apply rates and ownership at the event time

Model rates and application ownership can change over time. Using only the current reference record would misattribute historical events. The DuckDB ASOF LEFT JOIN selects the latest reference record whose effective timestamp is no later than the event timestamp.

CREATE OR REPLACE TEMP TABLE events_with_rates AS
SELECT
    e.*,
    r.input_credits_per_million,
    r.output_credits_per_million
FROM latest_events AS e
ASOF LEFT JOIN read_parquet(
    's3://<SOURCE-BUCKET>/ai-showback/reference/model_rates.parquet'
) AS r
ON e.model_id = r.model_id
AND e.event_ts >= r.effective_from;

CREATE OR REPLACE TEMP TABLE costed_batch AS
SELECT
    e.*,
    o.team_id,
    o.cost_center,
    (
        e.input_tokens * e.input_credits_per_million
        + e.output_tokens * e.output_credits_per_million
    ) / 1000000.0 AS cost_credits
FROM events_with_rates AS e
ASOF LEFT JOIN read_parquet(
    's3://<SOURCE-BUCKET>/ai-showback/'
    'reference/application_ownership.parquet'
) AS o
ON e.application_id = o.application_id
AND e.event_ts >= o.effective_from;

The full sample retains events without matching reference records and assigns an allocation status. This makes missing rate or ownership data visible during validation rather than excluding those events.

Publish retry-safe Iceberg output

Set the DuckDB session timezone to UTC, attach the Amazon S3 Tables table bucket as an Iceberg catalog, then merge the transformed records using a stable event ID:

INSTALL iceberg;
LOAD iceberg;
SET TimeZone = 'UTC';

ATTACH 'arn:aws:s3tables:<REGION>:<ACCOUNT-ID>:bucket/<TABLE-BUCKET>'
AS s3t (TYPE iceberg, ENDPOINT_TYPE s3_tables);

CREATE SCHEMA IF NOT EXISTS s3t.ai_showback;

MERGE INTO s3t.ai_showback.costed_invocations AS target
USING costed_batch AS source
ON target.event_id = source.event_id
WHEN MATCHED THEN UPDATE SET
    ingested_at = source.ingested_at,
    team_id = source.team_id,
    cost_center = source.cost_center,
    cost_credits = source.cost_credits
WHEN NOT MATCHED THEN INSERT BY NAME;

For daily_application_showback, use every grouped dimension in the MERGE condition. Use null-safe comparisons for nullable dimensions so that a retry cannot match multiple grouped source rows to one target row:

ON target.usage_date = source.usage_date
AND target.application_id = source.application_id
AND target.team_id IS NOT DISTINCT FROM source.team_id
AND target.cost_center IS NOT DISTINCT FROM source.cost_center
AND target.model_id = source.model_id
AND target.use_case IS NOT DISTINCT FROM source.use_case

The sample uses an unpartitioned tutorial table because support for update and delete operations can vary by DuckDB and Iceberg version. Validate table creation, the write pattern, partition design, partial-failure behavior, and reruns with the versions you deploy. An Iceberg snapshot commit is atomic for one table, but commits to the three output tables are not a single transaction.

Create the Amazon MWAA DAG

The duckdb_ai_inference_showback.py file in the sample bundle contains the complete Apache Airflow 3.3.1 DAG. It uses the public airflow.sdk import and a timezone-aware start date. Because schedule=None, you trigger it manually. You can add a schedule for recurring runs. The publication task runs before validation. Setting max_active_runs=1 prevents overlapping runs of this DAG. The detailed-table merge matches on event_id to avoid duplicate inserts during unchanged-input retries. Test partial failures, summary-table updates, and external concurrent writers separately.

# PUBLISH_SQL, VALIDATE_SQL, and the URI constants are defined in the sample bundle.
import pendulum

from airflow.sdk import DAG
from airflow.providers.duckdb.operators.duckdb import (
    DuckDBExecuteQueryOperator,
)

with DAG(
    dag_id="duckdb_ai_inference_showback",
    start_date=pendulum.datetime(2026, 9, 1, tz="UTC"),
    schedule=None,
    catchup=False,
    max_active_runs=1,
) as dag:
    # Transform the source records and publish the Iceberg output.
    transform_and_publish = DuckDBExecuteQueryOperator(
        task_id="transform_and_publish_showback",
        sql=PUBLISH_SQL,
        split_statements=True,
        params={
            "events_uri": EVENTS_URI,
            "rates_uri": RATES_URI,
            "ownership_uri": OWNERSHIP_URI,
            "table_bucket_arn": TABLE_BUCKET_ARN,
        },
        hook_params={
            "memory_limit": "2GB",
            "threads": 2,
            "temp_directory": "/tmp/duckdb-ai-showback-spill",
        },
        retries=1,
    )

    # Verify the detailed and summary outputs after publication.
    validate = DuckDBExecuteQueryOperator(
        task_id="validate_showback",
        sql=VALIDATE_SQL,
        split_statements=True,
        retries=1,
    )

    transform_and_publish >> validate

Because the operators omit conn_id, they use the built-in duckdb_default connection. The hook_params settings only limit DuckDB memory and threads and select a local spill directory.

In duckdb_ai_inference_showback.py, replace the source bucket and table bucket ARN placeholders, then upload the file to the Amazon S3 DAG folder configured for your Amazon MWAA environment.

Run and validate the pipeline

See validate_showback.sql in the sample bundle for the complete validation SQL. In the Airflow user interface, unpause duckdb_ai_inference_showback and trigger the DAG manually. The graph should show transform_and_publish_showback running before validate_showback.

The validation checks the row count and logical-key uniqueness of both summary tables in addition to the detailed-table manifest, event-ID uniqueness, and allocation-state checks. These assertions make an unchanged-input rerun fail if it creates duplicate summary rows.

Airflow graph showing the transform_and_publish_showback task followed by the validate_showback task.

Figure 2: The Airflow DAG runs transformation and publication before validation

We tested the walkthrough on a new mw1.small Amazon MWAA Provisioned environment in the Canada (Central) Region. The environment had no requirements or plugins file. In the representative run, the pipeline processed 303,543 source rows, removed 3,543 later-arriving duplicates, and published 300,000 unique events. The transform-and-publish task completed in about 11 seconds, and validation completed in about 6 seconds. These measurements describe this test run. Performance varies with worker capacity, data layout, and concurrent workloads.

Airflow grid showing the representative run and two successful unchanged-input reruns of the AI inference showback DAG.

Figure 3: The representative run and two unchanged-input reruns completed successfully

Review the transform-and-publish task log to confirm that DuckDB loaded the required extensions, read the inputs, and committed the Iceberg tables.

Successful transform_and_publish_showback task and its Airflow log.

Figure 4: The AWS aware hook creates the DuckDB S3 secret from temporary Amazon MWAA execution-role credentials before publication

The validation task confirmed unique event IDs, a detailed row count matching the generator manifest, all expected allocation states, and unique logical keys in both summary tables. The result contained 272,728 allocated events, 3,683 events missing a rate, 5,522 events missing ownership, and 18,067 non-success events. The summary tables contained 8,949 daily application rows and 9 team budget rows.

Airflow validation log showing three PASS results and 300,000 unique events.

Figure 5: The validation task reports PASS for uniqueness, row count, and allocation coverage

Trigger the DAG twice more without changing the source files. In our test, all three runs retained 300,000 unique events, 8,949 daily application rows, 9 team budget rows, the same allocation counts, and zero duplicate logical keys. This demonstrates repeatability for unchanged input, but does not establish recovery from partial failures or concurrent external writes.

The pipeline published a detailed costed_invocations table and two summary tables, daily_application_showback and team_budget_status, in the ai_showback namespace.

Amazon S3 Tables inventory showing the three tables in the ai_showback namespace.

Figure 6: Amazon S3 Tables contains the detailed output and two summary tables

If you configure Amazon S3 Tables integration with AWS analytics services, you can query the output from Amazon Athena. Because the output is stored as Iceberg tables, other Iceberg-compatible engines can read it.

Considerations

When you run DuckDB with Amazon MWAA, each task runs in an Amazon MWAA worker container whose CPU and memory depend on the environment class. Because Amazon MWAA uses the Celery executor, a single worker can run multiple Airflow tasks concurrently. Keep the following in mind:

  • Worker capacity: Set the DuckDB memory limit, thread count, and temporary spill space, then test with representative data. Joins, sorting, and data skew can affect peak resource use more than compressed input size alone.
  • Concurrency: Concurrent tasks on a worker share its CPU and memory, and each DuckDB task can also use multiple threads. Use Airflow pools and max_active_runs to limit how many DuckDB tasks run together and to prevent overlapping writes to the same tables.
  • Processing boundary: Use this pattern when SQL processing completes reliably within one worker. If a step needs horizontal scaling, high write concurrency, or more resources than one worker provides, run it with AWS Glue or Amazon EMR. Amazon MWAA can continue to orchestrate it.

For operational and security best practices, see the Amazon MWAA shared responsibility model.

Clean up

To avoid ongoing charges, pause the DAG and remove its file from the Amazon MWAA DAG folder. Delete the synthetic source data and drop the tutorial Iceberg tables. Remove the table bucket, source bucket, and Amazon MWAA environment only if you created them exclusively for this walkthrough. Remove any tutorial-specific permissions that are no longer needed.

Conclusion

In this post, you used Amazon MWAA to orchestrate an embedded DuckDB analytics pipeline. DuckDB ran inside the Airflow tasks to transform Parquet data from Amazon S3, publish the results as Apache Iceberg tables in Amazon S3 Tables, and validate the output. The DAG defined the task dependencies, while Amazon MWAA ran and monitored the tasks.

This pattern suits bounded, SQL-oriented transformations that fit within one worker. Start with representative data, set DuckDB memory and thread limits, and test retries, concurrency, and multi-table write behavior. If a task outgrows one worker, Amazon MWAA can continue orchestrating the workflow while a distributed service performs that step.

We thank Kamen Sharlandjiev (Principal Specialist Solutions Architect) and Aritra Ghosh (Senior Product Manager) for their contributions to this post.


About the authors

Vinod Jayendra

Vinod Jayendra

Vinod is a Senior Solutions Architect at Amazon Web Services, where he helps ISV customers address architectural, scalability, and operational challenges. He specializes in analytics and AI/ML and draws on his extensive application development experience to design practical, effective solutions. Outside of work, Vinod enjoys spending time with his family, cycling, and coaching youth sports teams.

Suba Palanisamy

Suba Palanisamy

Suba is an Enterprise Support Lead, helping customers achieve operational excellence on AWS. Suba is passionate about all things data and analytics. She enjoys traveling with her family and playing board games.

Niko Oliveira

Niko Oliveira

Niko is a Principal SDE at Amazon Web Services. He helped build and launch the Amazon MWAA services, and spends most of his time leading Amazon’s open source efforts on upstream Apache Airflow, where he is a committer and PMC member. Outside of work, Niko enjoys hiking, rock climbing and skiing in the mountains, watching sports, and he is currently diving deep into chess.

Varsha Gowda

Varsha Gowda

Varsha is a Senior Manager of Solution Architecture at AWS. She leads teams that help organizations modernize their data and analytics foundations, turning complex data into insights that drive real business outcomes. She focuses on helping customers evolve their data strategies so they can get the most out of analytics and AI. Outside of work, you’ll find her hiking, skiing, or traveling to experience new cultures.

Securely exposing Amazon Bedrock AgentCore Runtime

Post Syndicated from Meriem SMACHE original https://aws.amazon.com/blogs/security/securely-exposing-amazon-bedrock-agentcore-runtime/

Amazon Bedrock AgentCore Runtime delivers a secure serverless environment to deploy AI agents and tools at scale. When you start talking to your agent, the runtime launches a dedicated isolated session that runs in its own dedicated microVM with a completely sandboxed CPU, memory, and filesystem allocation. This provides strict data governance, helps to prevent cross-tenant data leakage, and preserves context while isolating stateful reasoning from external sessions.

To govern access control across these environments, Amazon Bedrock AgentCore Identity provisions distinct workload identities to let your agents run. By federating directly with an OpenID Connect identity provider like Amazon Cognito, Okta, or others, the users can only see and interact with agents they’re authorized to use.

But securing the runtime alone doesn’t protect the ingress path perimeter. When you expose your agent to users through a web or mobile application, the AWS Shared Responsibility Model dictates that you should provide a dedicated access layer that enforces tight control over the origin and intent of every request before any traffic reaches the runtime.

The access layer acts as a trusted bridge to authenticate each incoming request, enforce authorization rules, preserve user identity through the request lifecycle, and securely channel all user traffic into the isolated runtime.

This post walks through two architectures for securing access to AgentCore Runtime and provides guidance to help you decide which architecture best fits your organization.

Why propagating identity is important

In an agentic workflow, downstream data access should remain tied to the invoking user’s identity, and each segment in the execution chain is permissioned only for the immediate next hop. Using a single static credential, even one linked to the original requester, grants every immediate component identical, broad access. This directly violates the principle of least privilege, because the ingress gateway, the proxy, and the agent’s tool execution context each require only enough permission to reach the next component.

Recent real-world incidents have demonstrated that agentic workloads can bypass internal prompt guardrails, escape the software sandboxes, and abuse static credentials to move across applications and layers. In a multi-chain agentic architecture, scoping each hop as tightly as possible is key to preventing these exploits.

However, long-running, unattended execution poses a fundamental identity challenge for extended agentic workloads. If an agent runs a complex task that takes hours, the user’s interactive session will expire before the workload ends, making their short-lived OAuth 2.0 access token invalid mid-execution. Refreshing the tokens won’t solve this problem and storing a long-lived, user-scoped credential inside the agent’s runtime environment might reintroduce exactly the broad, standing credential attack surface that the zero-trust architectures are intentionally designed to mitigate.

To mitigate this, identity propagation acts as a critical bridge between authentication at the perimeter and authorization at the data layer. The agent must operate within the invoking user’s authorization scope. Every session receives a short-lived, user-scoped token that provides only the permissions granted to that specific user and authorization is enforced at each hop. If any single segment is compromised, then the exposure is contained in that hop scope. This security model also strengthens a continuous verification process where the tokens are validated at every hop from the ingress endpoint through AgentCore to the downstream resource, so no segment operates with unverified or elevated privileges.

Protecting AgentCore Runtime: What does it need?

We explained in the previous section why identity must follow the user through every hop. However, identity propagation alone isn’t enough to secure the ingress path; it must be integrated within a broader set of ingress controls that together protect the path into the runtime.

AgentCore Runtime provides infrastructure isolation, per session microVMs, per session tool registration, and enforces the application of Amazon Bedrock Guardrails. These features and resources protect the execution environment. However, they don’t control who reaches the runtime, how they’re authenticated, or whether their identity is preserved through the chain. That responsibility falls on the ingress control layer that you build. Securing this path requires a defense-in-depth architecture that binds every request to the user’s identity before it ever reaches the agent’s reasoning loop.

To protect and control data access, any architecture exposing AgentCore Runtime to users must satisfy the following requirements:

  • Authentication: Continuously verify the identity of every requester at the perimeter by validating tokens against the identity provider’s public keys.
  • Authorization: Determine what the authenticated subject is allowed and authorized to do, which actors they can invoke, which scopes they hold and which operations they can perform.
  • Per-hop least privilege: Make sure each component in the chain holds only enough permission to call the next hop, eliminating broad-scope credentials. Each hop must exchange the inbound token for a down-scoped, short-lived credential valid only for the immediate downstream call.
  • Identity propagation: Preserve the user’s identity through the full execution chain, so the agent operates within the user’s authorization scope. For long running or unattended workloads where the user’s session closes mid-flight, the ingress must seamlessly transition the active user token into an encrypted, short lived session context key from AgentCore Runtime. This allows the microVM to securely assert a restricted, cryptographic snapshot of the user’s identity even when the user is completely offline.
  • Edge security: Inspect and filter traffic before it reaches the application logic, by applying the needed WAF rules, bot control, IP-based rate limiting, and so on.
  • Network perimeter: Restrict runtime access to a single secure, controlled network path. Traffic arriving from any unexpected origin must be rejected regardless of the token’s validity.
  • Content protection: Enforce the Guardrails on both incoming prompts for injection attacks and outgoing tool arguments for malicious payload before execution.
  • Audit and logging: Log every authentication outcome, the authorization decision on the tool invocations, and any security event to an externalized system for compliance and incident response.

These security requirements are mandatory baselines to expose any agentic workloads to users. Any missing requirement might create a potential attack vector. By applying this full set of guardrails, you help contain the impact of a potential malicious exploit to a single user, a single session and a single execution hop.

In the next section, we provide two architecture patterns that implement this propagation differently:

  • The first architecture validates the user’s token independently at each layer while preserving it for the runtime to verify directly.
  • The second architecture exchanges the user’s token at the gateway boundary for scoped machine credentials, attesting the user’s identity through verified claims. This pattern is uniquely suited for handling the session context keys required by asynchronous, unattended workloads.

Both approaches achieve the same result: the agent acts as the user rather than with elevated privileges.

The AgentCore Gateway patterns

Each of the following patterns is presented the same way: the layered controls a request passes through before reaching the agent, followed by how user identity is carried to the runtime. As you explore, please note where each pattern places the trust boundary as that difference is what drives the trade-offs summarized at the end.

Pattern A: Expose through API Gateway

We expose AgentCore Runtime through Amazon API Gateway, which acts as a dedicated ingress point that terminates each client connection. Before any request reaches the agent, it must pass through layered security controls:

  • A Lambda authorizer: An AWS Lambda authorizer validates the Amazon Cognito-issued JSON Web Token (JWT) by verifying the signature, issuer claim and token expiration, to confirm the requester’s identity.
  • AgentCore Identity: Independently, AgentCore Identity performs a second validation inherent to the Lambda authorizer through its OAuth 2.0 inbound authentication flow. This helps to confirm the user’s identity before the request reaches the runtime to be processed.

Because the client-provided session ID is treated as untrusted input, the Lambda authorizer creates a composite session ID by appending the user identifier to the client-provided session ID. Even if two different users submit the same session ID, they resolve to unique composite IDs at the AgentCore Runtime level, preventing any cross-user session leakage.

To prevent denial of service attempts, we suggest using Amazon DynamoDB as a lightweight session counter. While the AWS WAF rate-based rules attached to the API Gateway stage protect against IP-level volumetric abuse, they evaluate requests before authentication. The Lambda authorizer checks and increments a per-user counter in DynamoDB after validating the user’s identity, helping prevent a single authenticated user from exhausting agent capacity, even if they connect from multiple IP addresses. This design scales cleanly by using a composite session ID. The Lambda Authorizer combines the user identifier and the client session ID, routing each user’s counter to a distinct partition. This naturally distributes write traffic and reduces the risk of hot keys.

Each session can sustain roughly 1,000 counter updates per second before reaching DynamoDB’s per-partition write limit, which is far beyond what any legitimate session would ever generate. That same limit is exactly what makes the counter an effective throttle. Meanwhile, total capacity across all users scales horizontally, growing with the number of active sessions. For high-volume production deployments, on-demand capacity mode absorbs sudden spikes automatically, and CloudWatch Contributor Insights lets you confirm traffic stays evenly distributed.

After the Lambda authorizer approves the request, as shown in the Figure 1:

  1. API Gateway forwarding: Passes the approved request to Lambda proxy that runs within an isolated environment with no internet egress.
  2. VPC endpoint routing: The proxy Lambda function forwards the request to AgentCore Runtime through an Amazon Virtual Private Cloud (Amazon VPC) endpoint, making sure that all traffic remains strictly within the private network.
  3. Token preservation and identity propagation: The proxy Lambda function forwards the user’s token unchanged in the authorization header; this maintains the original user identity throughout the entire flow of AgentCore Runtime.

API Gateway forwards the request to a Lambda proxy running on a private VPC with no internet egress. The role of this Lambda proxy is to relay the request to AgentCore Runtime through a VPC endpoint, so that all communication remains within the private network. The Lambda proxy forwards the user’s token (unchanged) in the Authorization header, which preserves the user’s identity all the way to AgentCore Runtime.

Figure 1: Pattern A architecture for exposing AgentCore Runtime through Amazon API Gateway

Figure 1: Pattern A architecture for exposing AgentCore Runtime through Amazon API Gateway

This VPC endpoint enforces a strict network perimeter using two independent controls:

  • Security groups: The VPC endpoint security group restricts ingress solely to the proxy Lambda function on port 443, so no other compute in the account can reach the endpoint.
  • Resource-based policy: The runtime resource-based policy is configured with principal "*" and a condition that allows invocations only when the request carries aws:SourceVpc and aws:SourceVpce values matching this stack’s VPC and endpoint. Authentication happens at the AgentCore Identity level, so there is no AWS Identity and Access Management (IAM) principal to match, and the network path is the only meaningful gate and condition that remains. AgentCore Runtime rejects requests sent directly from outside the VPC with an AccessDeniedException, even with a valid JWT.

Beyond the network boundary, Amazon Bedrock Guardrails evaluates each model’s invocation for prompt injection attacks, helping catch malicious inputs even after an invocation has passed identity and network verification. This adds content protection as a defensive layer independent of identity and network controls.

Your stack logs and tracks every authorization outcome along this path as structured JSON to Amazon CloudWatch, with an INVALID_JWT alarm. The full walkthrough and a deployable AWS Cloud Development Kit (AWS CDK) sample are linked at the end of this post.

Before production deployment, we recommend configuring an AWS WAF Web ACL at the API Gateway stage to inspect requests before they reach the Lambda authorizer. You should include AWSManagedRulesCommonRuleSet and AWSManagedRulesKnownBadInputsRuleSet for generic OWASP Top 10 protections and known exploit patterns, AWSManagedRulesSQLiRuleSet to catch injection signatures, a per-IP rate-based rule ahead of the DynamoDB throttle counters, and custom rules to reject oversized requests or malformed session IDs early. For a step-by-step integration guide including two deployment patterns for placing AWS WAF in front of the AgentCore Runtime, see Securing Amazon Bedrock AgentCore Runtime with AWS WAF.

This first pattern satisfies the ingress security requirements discussed earlier. It achieves defense in depth by applying the authentication at two independent layers, enforcing authorization through session binding and controlling traffic through per-user throttling. The architecture maintains per-hop least privilege from the API Gateway through the AgentCore Runtime while preserving end-user identity propagation by passing the user’s token through unchanged. The edge filtering is managed with AWS WAF and the network perimeter is enforced by VPC endpoint controls. The design includes the application of Amazon Bedrock Guardrails for content security with a tamper-proof audit trail in Amazon CloudWatch. The deployable CDK sample for pattern A is available on GitHub.

Pattern B: Expose through AgentCore Gateway

With Pattern B, you expose AgentCore Runtime through Amazon Bedrock AgentCore Gateway, a managed service purpose-built for agentic traffic that combines ingress authentication, token exchange and Runtime routing without requiring a proxy Lambda function or custom VPC networking.

Before any request reaches the agent, it passes the following layered security controls:

  • Inbound authentication: A custom JWT inbound authorizer is configured on AgentCore Gateway that validates the Amazon Cognito JWT by verifying its signature, issuer, and expiration before any logic runs.
  • Identity extraction, session binding and guardrails: A REQUEST interceptor for Lambda, invoked directly by AgentCore Gateway, extracts the verified user identity claims from the validated token for downstream injection. For asynchronous or unattended workloads, this interceptor securely binds these claims into an encrypted, short lived session context key. This helps ensure that even if the user’s interactive session expires hours later, a secure snapshot of their identity remains intact. It mirrors the role of the Lambda authorizer in Pattern A, enforcing the same session-binding and throttling logic.
  • Perimeter authorization (AgentCore Policy): AgentCore Gateway uses a deterministic Cedar-based policy engine to evaluate each request against defined policies before allowing tool access. It also enforces Amazon Bedrock Guardrails through AgentCore Policy for screening prompt injection and content violations at the gateway level, before the request reaches the agent. This declarative enforcement is an advantage over the API Gateway pattern where guardrails must be invoked programmatically from within the agent code.

After the authorization succeeds, the gateway manages the outbound call to AgentCore Runtime by using a strict workload isolation mechanism as shown in Figure 2:

  1. Token exchange: The gateway requests a machine-to-machine (M2M) token from AgentCore Identity using a dedicated Amazon Cognito M2M app client and attaches it to the request.
  2. Workload verification: The AgentCore Runtime validates this token against the allowedWorkloadConfiguration parameter, confirming the request originated from the gateway.
  3. On-behalf-of access: The runtime unpacks the session context key, allowlists the injected user identity passed by the interceptor and forwards it directly to the agent to enable secure, context-aware execution on behalf of the user, even during completely unattended background execution loops.
Figure 2: Pattern B architecture for exposing AgentCore runtime through AgentCore Gateway

Figure 2: Pattern B architecture for exposing AgentCore runtime through AgentCore Gateway

If a client attempts to bypass the gateway by sending a valid user token directly to the runtime, the request is automatically rejected because it lacks the required workload identity.

For more operational efficiency, AgentCore Gateway integrates AWS WAF directly at the single gateway access point, protecting the entire ingress path in one place, without the need to manage separate authorizers, proxy Lambda functions or VPC endpoints.

While API Gateway also supports AWS WAF, the AgentCore Gateway pattern simplifies management by consolidating all ingress controls behind a single component.

The AgentCore Gateway also supports native rate limiting, removing the need for custom DynamoDB-based throttle tables, for your production environments. The interceptor writes a structured audit trail to CloudWatch, with an INVALID_JWT alarm to flag spikes in authentication failures.

Before production deployment, we strongly recommend that you enable AWS WAF on the AgentCore gateway with the same rule sets described in the API Gateway pattern, including the OWASP protections, SQL injection, and custom rules for oversized or malformed requests.

To summarize, this second architecture satisfies the ingress security requirements defined earlier. It achieves defense in depth by applying a managed CUSTOM_JWT authorizer directly at the entry point, enforcing authorization through interceptor-based session binding and using rate limiting to control traffic. This pattern maintains per-hop least privileges from AgentCore Gateway through to the runtime by automating M2M token exchange, while propagating user identity for on-behalf-of execution. The edge security is managed by AWS WAF, coming directly with the gateway’s single-entry point, and secure workload isolation strictly enforces the perimeter. Finally, this design applies declarative Amazon Bedrock Guardrails for early content safety, and a tamper-proof audit trail and alarms in CloudWatch. The complete CDK sample for Pattern B is available on GitHub.

Choosing your AgentCore Runtime patterns

As explained earlier, securing access to AgentCore Runtime can be achieved through two different patterns: The AgentCore Gateway pattern or the Amazon API Gateway pattern. The right choice depends on your existing AWS infrastructure, workload constraints, and operational preferences.

Choose the Amazon API Gateway pattern if:

  • You have existing API infrastructure: Your team already runs an established Amazon API Gateway and AWS WAF deployment
  • You need a single entry point: You prefer to fold agentic traffic into your existing pipelines rather than introducing a separate entry point to operate and secure.
  • Your security model is VPC centric: Your security and compliance teams rely on VPCs and security groups as their primary network control layer
  • Your agent sessions are short-lived: While API Gateway has increased its integration timeout beyond 29 seconds, long running agentic workloads with streaming tool calls might still exceed it. This isn’t a concern if your sessions are brief.

Choose the AgentCore Gateway pattern if:

  • You’re building a new gateway: Your organization has no existing API Gateway
  • You have long run workloads: Your agents use streaming or long running tool calls that require strict API timeouts
  • You need low operational overhead: You prefer a fully managed perimeter over manually wired infrastructure
  • You require advanced AI routing: You want built-in capabilities to convert APIs and Lambda functions into Model Context Protocol (MCP) tools, handle Agent to Agent (A2A) traffic and route inference across different model providers.

The following table summarizes the key elements that help you make the right architectural decision:

Consideration API Gateway (Pattern A) AgentCore Gateway (Pattern B)
Suited to Teams already standardized on API Gateway Teams starting fresh who want less infrastructure to operate.
Perimeter control Runtime resource policy with aws:SourceVpc and VPC endpoint security group Runtime workload lock (allowedWorkloadConfiguration).
Components to operate API Gateway, Lambda authorizer, Amazon VPC, VPC endpoints, proxy Lambda function AgentCore Gateway and Lambda REQUEST interceptor.
User identity to agent User JWT forwarded unchanged (no SigV4) Interceptor-injected verified headers (OAuth outbound M2M token).
AWS WAF Attach directly to the API stage Attach directly to the gateway.
Request timeout Inherits the API Gateway integration timeout Not subject to this limitation.
Public endpoint Can be fully private (API Gateway PRIVATE endpoint type) Supports AWS PrivateLink ingress and VPC Lattice egress, but keeps a public endpoint active. Access relies on the JWT authorizer and resource policy rather than removing the endpoint

Conclusion

By securing access to the AgentCore Runtime with a defense in depth, an agent can be both highly usable and secure. The two patterns in this post complete the shared responsibility model for you: they authenticate every request against the identity provider, authorize it at each step and propagate the user’s identity end-to-end from the edge through the token exchange into the isolated microVM (AgentCore Runtime) and down to the agent’s tool calls (AgentCore Gateway). Each step only holds a short-lived credential for the next one, so the agent always works within the user’s permissions rather than with broad, long-term access. If one step is ever compromised, the design limits the impact to that single step, session and user. Whether the runtime is behind API Gateway with a VPC endpoint or in front of it with AgentCore Gateway, the design verifies each request at each step.

To get started, clone the Pattern A sample or the Pattern B sample, deploy it in your account, and test it against your requirements. Both samples are provided as a starting point, not a production-ready deployment. We recommend working with your security and legal teams to adapt to the controls before going live. From there, you can extend either pattern for multi-tenant use, add observability hooks, or tighten controls for your specific compliance requirements.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Merriem-SMACHE

Meriem SMACHE

Meriem is a Security Specialist Solutions Architect at AWS, supporting customers in the design and deployment of resilient cloud and AI solutions, from generative AI workloads to fully autonomous agentic systems, that meet their regulatory requirements and security needs.

Christian Kamwangala

Christian Kamwangala

Christian is a Senior AI/ML and Generative AI Specialist Solutions Architect at AWS, based in Paris, France. He partners with enterprise customers to architect, optimize, and deploy production-grade AI solutions using the comprehensive AWS ML stack. Christian specializes in inference optimization techniques that balance performance, cost, and latency requirements for large-scale deployments. Christian enjoys exploring nature and spending time with family and friends.

Lior Perez

Lior Perez

Lior is a Principal AI & Machine Learning Solutions Architect at Amazon Web Services, based in Toulouse, France. He helps customers speed up their digital transformation with AI. He wrote the AWS Prescriptive Guidance Governing and Architecting the Diversity of Agentic AI at Scale, which helps enterprises design and govern AI agents. He makes complex ideas simple and practical. His background in manufacturing and meteorology gives him a different way of looking at business challenges.

Charline Boulie

Charline Boulie

Charline is a Senior Solutions Architect at AWS. She helps French FinTech startups and scale-ups build and scale secure, generative AI-powered workloads, focusing on agentic AI, application development and security. She brings 15 years of software and cloud architecture experience from Thales Avionics and AWS Professional Services, and champions women in tech through mentoring and student outreach.

Enforcing zero-trust dependency policies in AWS CodeBuild with JFrog Curation

Post Syndicated from Arik Yakir original https://aws.amazon.com/blogs/devops/enforcing-zero-trust-dependency-policies-in-aws-codebuild-with-jfrog-curation/

Software supply chain attacks are rising sharply. JFrog’s 2026 research recorded a 451% year-over-year increase in malicious npm packages, yet every application that pulls open source packages during a build is still taking the same fundamental risk. When a developer runs pip install or npm install, the build environment downloads dependencies directly from public registries with no verification that those packages are safe. A vulnerable or malicious package can slip into your container image, get pushed to a registry, and reach production before anyone notices. By the time a scanner flags a critical CVE, the damage is already done.

This is a familiar situation for teams building on any continuous integration and continuous delivery (CI/CD) platform, including AWS CodeBuild. A build completes successfully, tests pass, and the artifact ships. Days or weeks later, a security review reveals that one of dozens of transitive dependencies carried a known vulnerability, or worse, was a malicious package designed to exfiltrate secrets. The fix isn’t only patching. It’s rebuilding, re-testing, and redeploying, all while assessing the scope. What teams need is a way to enforce a zero-trust dependency policy: a gate that blocks risky packages at download time, before they ever enter the build. That is exactly what JFrog Curation provides. It evaluates every package at the moment it is downloaded. When a package violates policy, it returns an HTTP 403 (Access Denied) error, failing the build before a risky dependency enters your environment.

In this post, you’ll learn how to use JFrog Curation as a policy gate inside AWS CodeBuild to block vulnerable and malicious dependencies at download time, before they ever become an artifact.

The customer problem

Your team ships a container built from open source dependencies. Weeks later, a security scan surfaces a critical vulnerability in a transitive package you didn’t even choose. Now you’re scrambling to identify which images are affected, rebuild, re-test, and redeploy, all under time pressure and with no guarantee you’ve caught everything.

The root cause is that nothing enforces policy at the moment dependencies are downloaded. When a build runs pip, npm, or Maven, it pulls whatever the manifest declares directly from a public registry. Scanning catches problems after the artifact exists, but by then the vulnerable package is already in your image and potentially in production.

Solution overview

The pipeline is an ordinary container build with one decisive change: The only route to public package registries runs through JFrog Artifactory, and Curation sits on that route. A developer commit triggers CodeBuild, which runs a Docker build. Inside that build, pip install resolves through the Artifactory virtual repository. Approved packages flow through and the image is pushed to Amazon Elastic Container Registry (Amazon ECR). A blocked package fails the build before any image exists.

For this walkthrough, the policy is “Block Critical CVEs”, which rejects any package version with a Common Vulnerability Scoring System (CVSS) score of 9.0 or above. AWS CodeBuild is the orchestration layer that resolves dependencies, and JFrog Curation is the management layer that decides, package by package and in real time, what CodeBuild is allowed to pull. The result is an Amazon ECR repository that receives only images built from policy-compliant dependencies.

On failure, a small amount of post-build scripting (shown in detail in the post-build section) queries the Curation audit API (JFrog Curated Packages Audit Events service) and reports the blocked package, its CVE identifiers and CVSS scores, and any recommended fix versions.

Deployment architecture showing AWS CodeBuild resolving dependencies through JFrog Artifactory and Curation before pushing approved images to Amazon ECR

Figure 1: Deployment architecture for the AWS CodeBuild pipeline with JFrog Curation security gate

Prerequisites

Before starting the walkthrough, make sure you have the following accounts, tools, and permissions in place.

  • An AWS account with permission to create CodeBuild projects, ECR repositories, and AWS Secrets Manager secrets.
  • A JFrog Platform instance (SaaS or self-hosted) on a tier that includes JFrog Curation (Enterprise X or Enterprise+ with the Curation add-on).
  • An Artifactory user or access token with deploy and read permissions on your virtual PyPI repository.
  • Tools (installed locally or in your build environment):
    • AWS Command Line Interface (AWS CLI) v2, configured with credentials for your target account.
    • Docker Engine 20.10 or later.
    • Git, to clone the sample repository.
    • JFrog CLI (the walkthrough installs it during pre-build, but local testing requires it beforehand).
  • JFrog Curation setup:
    • In the JFrog Platform, create a remote PyPI repository that proxies https://pypi.org.
    • Create a virtual PyPI repository that includes the remote repository you created earlier.
    • Choose Curation, then Policies, and turn on a Block Critical CVEs policy scoped to the virtual repository.
  • Clone the JFrog curation gate sample repository. All file paths referenced later are relative to the repository root.
  • Accounts and subscriptions:
    • An active AWS account with permissions to create AWS CodeBuild projects, Amazon ECR repositories, and AWS Secrets Manager secrets.
    • A JFrog Platform subscription (SaaS or self-hosted) with access to JFrog Curation. If you need an account, JFrog offers a free trial.

Walking through the implementation

The pipeline is deliberately small. A handful of shell scripts are orchestrated by a CodeBuild buildspec.yml and a Dockerfile that does the dependency install. What makes it a security gate rather than a build is one design choice. Every pip install is forced to resolve through a curated JFrog repository instead of public PyPI and the build is only allowed to publish an image when Curation approves every package.

The following shows how the pieces fit together before we look at the code:

CodeBuild pipeline phases (pre-build, build, post-build) and the shell scripts responsible for each

Figure 2: CodeBuild pipeline phases and script responsibilities

1. Project layout

File Role
buildspec.yml CodeBuild entrypoint – wires the three phases together and sets shared env vars
scripts/setup.sh Pre-build: installs the JFrog CLI, loads secrets, configures pip + Docker auth
Dockerfile Defines the image. Its pip install is what actually gets curated
requirements.txt The pinned dependency manifest that Curation evaluates, package by package
scripts/docker-build.sh Runs the curated Docker build and captures the log
scripts/post-build.sh The gate: conditional push to the registry, or extract-and-report the block reason

2. buildspec.yml – the orchestrator

The buildspec keeps logic out of YAML and in versioned shell scripts to keep the pipeline testable locally and readable in review. Two details matter beyond the phase wiring:

  • shell: bash is set explicitly. CodeBuild defaults to sh, and the post-build gate relies on bash-only constructs like ${PIPESTATUS[0]}.
  • Secrets come from AWS Secrets Manager, which stores the JFrog token encrypted with AWS Key Management Service (AWS KMS), controls access through IAM policies, records every retrieval in AWS CloudTrail, and supports rotation without changing the buildspec. CodeBuild injects the value at runtime and masks it in build logs.
version: 0.2

env:
  shell: bash
  variables:
    JFROG_HOST: "<jfrog-host>"           # e.g. yourcompany.jfrog.io
    JFROG_REPO: "<repo-pypi-virtual>"    # curated virtual pip repo
    AWS_DEFAULT_REGION: "<region>"
    ECR_REPO: "<image-repo>"
  secrets-manager:
    JFROG_USER: "<secret-name>:username"
    JFROG_TOKEN: "<secret-name>:access_token"

phases:
  pre_build:
    commands:
      - bash ./scripts/setup.sh
  build:
    commands:
      - bash ./scripts/docker-build.sh
  post_build:
    commands:
      - bash ./scripts/post-build.sh

3. Pre-build (scripts/setup.sh) – install tooling and redirect pip

This phase does three jobs: install the JFrog CLI, authenticate to both registries, and reconfigures pip so it resolves through Artifactory.

# Install the JFrog CLI
curl -fL https://install-cli.jfrog.io | sh

# Register the JFrog server using the token from Secrets Manager
jf config add jfrog-server \
  --url="https://${JFROG_HOST}" \
  --access-token="${JFROG_TOKEN}" \
  --interactive=false
jf config use jfrog-server

# Point pip at the curated repo instead of public PyPI
jf pip-config --repo-resolve="${JFROG_REPO}" --server-id-resolve=jfrog-server

# Build the authenticated index URL the Dockerfile will use
export PIP_PROXY="https://${JFROG_USER}:${JFROG_TOKEN}@${JFROG_HOST}/artifactory/api/pypi/${JFROG_REPO}/simple"

# Authenticate to the container registry (destination for the trusted image)
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export ECR_URI="${ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${ECR_REPO}"
aws ecr get-login-password --region "${AWS_DEFAULT_REGION}" \
  | docker login --username AWS --password-stdin \
  "${ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com"

# Authenticate to the JFrog Docker registry (for base images, if pulled through JFrog)
echo "${JFROG_TOKEN}" | docker login "${JFROG_HOST}" -u "${JFROG_USER}" --password-stdin

Importantly, jf pip-config writes a pip config that swaps the default index URL pypi.org for the JFrog virtual repo. From that point on, any pip install, including the ones inside the Docker build, asks Artifactory for packages. Artifactory serves approved packages from cache or fetches them from its PyPI remote, and returns an HTTP 403 (Access Denied) error for anything a Curation policy blocks. The application code never changes. The redirection is entirely in configuration.

4. The Dockerfile – where curation is actually enforced

The following is the full Dockerfile:

# Base image is pulled from Amazon ECR Public (not Docker Hub) so the build does not
# depend on an external/uncontrolled registry.
FROM public.ecr.aws/docker/library/python:3.11-slim

# Passed in by scripts/docker-build.sh (the curated JFrog index URL)
ARG PIP_INDEX_URL
ARG PIP_TRUSTED_HOST

WORKDIR /app

COPY requirements.txt

# Upgrade pip itself from public PyPI (pip is not the curated surface here)
RUN pip install --no-cache-dir --upgrade pip --index-url https://pypi.org/simple && \
    # …then install ALL app dependencies through the curated JFrog repo.
    # The if/else lets the same Dockerfile build locally (no build args) while
    # always going through JFrog in CI (build args present).
    if [ -n "$PIP_INDEX_URL" ] && [ -n "$PIP_TRUSTED_HOST" ]; then \
      pip install --no-cache-dir --index-url "$PIP_INDEX_URL" --trusted-host "$PIP_TRUSTED_HOST" -r requirements.txt; \
    else \
      pip install --no-cache-dir -r requirements.txt; \
    fi

COPY app.py .

EXPOSE 8080
CMD ["python", "app.py"]

The gate is the pip install -r requirements.txt step and the mechanism is --index-url. During the build phase, docker-build.sh passes the curated JFrog index URL into the build as PIP_INDEX_URL. When that argument is present, pip resolves all dependencies in requirements.txt through the curated JFrog repository instead of public PyPI. JFrog evaluates each requested name==version against your Curation policies before it serves the package:

Approved packages are returned normally and the layer builds. Blocked packages get an HTTP 403 (Access Denied) error from JFrog. pip treats that as a failed download, the RUN instruction exits non-zero, and the entire docker build fails. The image is never produced, let alone pushed. The policy decision is made during the image build process at the precise moment pip resolves each dependency against the curated JFrog repository.

5. The post-build.sh – where data is collected and a fix is proposed

The post-build phase decides what happens with the build’s result. It branches on the CODEBUILD_BUILD_SUCCEEDING flag that CodeBuild sets, which is the mechanism that ties the registry push to Curation’s verdict:

source /tmp/build-env.sh  # ECR_URI, computed back in the pre-build phase
if [ "${CODEBUILD_BUILD_SUCCEEDING:-1}" = "1" ]; then
  # success path --- every dependency passed Curation
else
  # failure path --- Curation blocked a package
fi

Note the source /tmp/build-env.sh at the top. Each phase script runs in its own subshell, so values derived earlier (like ECR_URI) don’t survive across phases. The pre-build step writes them to a file that this script reads back in. If every dependency was approved, the script pushes the trusted image to ECR (both the build’s tag and latest) and triggers the downstream deploy stage. Configure it like so:

docker push "${ECR_URI}:${IMAGE_TAG}"
docker push "${ECR_URI}:latest"

if [ -f ./scripts/deploy.sh ]; then
  bash ./scripts/deploy.sh
fi

This is the only path that puts an image in the registry.

If curation blocked a package and pip only surfaced an HTTP 403 (Access Denied) error, the script reconstructs the reason in three steps. First, identify the package by grepping the failing 403 out of the captured build log. pip names the package in the download URL:

BLOCKED_PKG=$(grep -oP "HTTP error 403 while getting .*/packages/.*/\K[^/]+(?=#)" \
  /tmp/docker-build.log 2>/dev/null | head -1 || true)
PKG_NAME=$(echo "$BLOCKED_PKG" | sed 's/[-=<>!].*//')
PKG_VERSION=$(echo "$BLOCKED_PKG" | grep -oP '[-=]{1,3}\K[0-9][^,; ]*' | head -1 || true)

Second, ask the Curation audit API which policy fired for that package (the policy name, the matched condition, and the category):

jf api "/xray/api/v1/curation/audit/packages?package_name=${PKG_NAME}&package_version=${PKG_VERSION}&num_of_rows=1" \
  | jq -r '.data[]?.policies[]? | " Policy: \(.policy_name)\n Condition: \(.condition_name)\n Category: \(.condition_category)"'

Third, run jf curation-audit for a human-readable explanation and a recommended compliant version:

echo "${PKG_NAME}==${PKG_VERSION}" > /tmp/blocked-pkg.txt
jf curation-audit --requirements-file=/tmp/blocked-pkg.txt --format=json \
  | jq -r '.[0].policies[]? | " \(.explanation)\n Recommendation: \(.recommendation)"'

(That last step is also where any CVE detail comes from, but only when the remote repo has pass-through for Curation audit enabled.)

Finally, the script fails the build:

exit 1

The logic is deliberate: the push is gated on the build succeeding, and the build only succeeds if Curation approved every dependency.

Seeing it in action

STEP 2 - DOCKER BUILD WITH JFROG CURATION
All dependencies resolved through JFrog Artifactory
DOCKER BUILD SUCCESSFUL - ALL DEPENDENCIES APPROVED BY JFROG CURATION
STEP 3 - PUSH TO ECR

On the blocked path, the build declares pyyaml==5.3, which carries two CVSS 9.8 vulnerabilities. Curation returns HTTP 403 (Access Denied) and the build fails before an image is ever produced:

==========================================
BLOCKED BY JFROG CURATION
==========================================
Package: pyyaml==5.3
Policy: Block Critical CVEs
Condition: CVE with CVSS score of 9 or above
Vulnerabilities:
- CVE-2020-1747: 9.8
- CVE-2020-14343: 9.8
Recommendation:
- CVE-2020-1747: 5.3.1
- CVE-2020-14343: 5.4
==========================================
PIPELINE FAILED - SKIPPING ECR PUSH
==========================================

Nothing reached Amazon ECR. There is no vulnerable artifact to remediate, because it was never built.

Curation and scanning are complementary

JFrog Curation is the prevention layer at the gate, and JFrog Xray, a software composition analysis (SCA) tool, is the detection layer for what is already inside. Together they cover both new downloads and previously cached artifacts.

Making it your own

This pattern is workload-agnostic. The example builds a container, but the same gate applies equally to your AWS Lambda function, microservice, or front-end application that resolves dependencies during its build. Curation policy is configurable. For example, layer multiple thresholds to block at CVSS 9.0 and warn at 7.0. You can also add license-compliance and malicious-package policies. Supported package types include PyPI, npm, Maven, and Docker. The enforcement point stays constant: CodeBuild resolves through Artifactory, and Curation decides what is allowed through.

Cleaning up

To avoid ongoing charges, delete the resources you created for this walkthrough: the AWS CodeBuild project, the Amazon ECR repository and any images it holds, the AWS Secrets Manager secret storing the JFrog credentials, and any IAM roles created for the build. If you configured the repositories solely for this exercise, you can also remove the JFrog Artifactory virtual and remote repositories.

Conclusion

By moving dependency enforcement into the build itself, an image is not published to Amazon ECR unless every package it contains has passed your JFrog Curation policies. A blocked package fails the build, so no image is pushed. This walkthrough demonstrated the pattern with PyPI and pip, but as described in the previous section, you can apply the same three steps to any package ecosystem.

Without this gate, the cycle described at the start of this post repeats: a build pulls an unverified package, the image ships, and weeks later your team is rebuilding, re-testing, and redeploying under pressure. With JFrog Curation enforcing policy at the point of download, that cycle stops. Risky packages are blocked before they enter the build, so they are kept out of your registry and away from your customers. Instead of reacting to vulnerabilities after the fact, your pipeline prevents them by default.

To get started, visit the AWS CodeBuild detail page and the AWS CodeBuild documentation. You can also explore the accompanying GitHub repository for the complete source code used in this walkthrough.

 


About the authors

Arik Yakir

Arik Yakir

Arik is a Senior Partner Solutions Architect at AWS. He works with technology partners to design joint solutions and better-together architectures on AWS.

Eldad Assis

Eldad Assis

Eldad is a Principal DevOps Architect, CTO Office at JFrog. He focuses on CI/CD automation and software supply chain security.

Anantha Kalusivalingam

Anantha Kalusivalingam

Anantha is a Senior Solutions Architect at JFrog. He specializes in DevSecOps and helping JFrog customers secure their software delivery pipelines.

Analyze Anthropic usage, spend, and access with AWS Glue, Amazon S3 Tables, and AWS Quick

Post Syndicated from Daniyal Alam original https://aws.amazon.com/blogs/big-data/analyze-anthropic-usage-spend-and-access-with-aws-glue-amazon-s3-tables-and-aws-quick/

Finance teams want to allocate AI spend to the business units that use it. Engineering leaders want to know what that spend delivers. Security teams want to know who owns each API key and whether any belong to former employees. Anthropic gives administrators detailed visibility into usage and cost through Claude Code usage analytics and the Anthropic Admin API. Many enterprises want to take the next step and analyze that data alongside the business data they already manage in AWS. Until now that has meant building and maintaining a custom integration with the Admin API.

AWS Glue now offers a native connector for Anthropic. AWS Glue is a serverless data integration service that helps you discover, prepare, move, and integrate data from multiple sources for analytics, artificial intelligence and machine learning (AI/ML), and application development. The connector for Anthropic is one of 100 new native connectors that AWS Glue added for popular software as a service (SaaS) applications. It works like other AWS Glue connectors and requires no custom code. You store an Anthropic API key in AWS Secrets Manager and create an AWS Glue connection that references it. The connector handles the API calls and schema mapping for you so your team can focus on analyzing the data instead of maintaining the integration.

The connector makes AI usage another domain in your data lakehouse. With Amazon S3 Tables, fully managed Apache Iceberg tables in Amazon Simple Storage Service (Amazon S3), you can store your transformed Anthropic and business data in an open and interoperable format that AWS analytics services can read natively and other Iceberg engines can query.

In this post, we follow the fictional retailer AnyCompany Retail as it brings Anthropic data into Amazon S3 Tables and joins it with its own business data using AWS Glue materialized views stored as Apache Iceberg tables. The team uses Amazon Athena to query the data with SQL and answer leadership’s three questions about spend, value, and API key ownership. It then publishes the results to an AWS Quick dashboard that leadership reviews every week.

Solution overview

The following diagram shows the solution architecture.

Solution architecture showing AWS Glue reading Anthropic data through the connector, writing Apache Iceberg tables to Amazon S3 Tables, and Amazon Athena and AWS Quick querying the results

Figure 1: Solution architecture for analyzing Anthropic usage data with AWS Glue, Amazon S3 Tables, Amazon Athena, and AWS Quick

The workflow consists of the following steps:

  1. You store your Anthropic API keys in AWS Secrets Manager, where the AWS Glue connection references them.
  2. An AWS Glue extract, transform, and load (ETL) job uses the Glue connector for Anthropic to read entities such as usage and cost reports, users, and workspaces.
  3. The job transforms the data into fact and dimension tables like daily usage, daily cost, and writes them to Amazon S3 Tables as Apache Iceberg tables.
  4. The job joins the Anthropic data with business data that you own like workspace-to-business-unit mapping, outcome metrics, and an employee directory. In our example, this data is stored in Amazon S3.
  5. Amazon Athena queries the tables to answer the spend, value, and access questions, and AWS Quick presents the results through natural language prompting or dashboards.

Supported entities

Anthropic uses two kinds of API keys, and each provides access to different sets of data. An Admin API key reads organization-level data. A workspace API key reads data inside a single workspace. You create one AWS Glue connection for each key.

Entity API key Description
users Admin Organization members with their email, name, and role
invites Admin Pending and accepted organization invites
workspaces Admin Workspaces in the organization, including the default and archived workspaces
workspace_members Admin Members of each workspace with their workspace role
api_keys Admin API keys with status, scope, workspace, and creator
usage_report Admin Token usage per time bucket, optionally grouped by workspace, API key, model, and more
cost_report Admin Cost per daily bucket, optionally grouped by workspace and cost description
models Workspace Claude models available to the workspace
message_batches Workspace Message Batches API jobs with status and request counts
files Workspace Files uploaded to the workspace

Example scenario

The retailer uses Claude across five business units, each with its own Anthropic workspace: Customer Service, Engineering, Document Processing, Marketing, and Data Science. Every week, leadership reviews AI spend across the business units and asks three questions:

  • Which business units are driving AI spend?
  • Is the spend paying off, for example in cost per resolved customer case?
  • Are any active API keys owned by employees who have left the company?

Throughout this post, the Anthropic data comes from a demo organization. The reference datasets (business-unit mapping, support outcomes, and employee directory) are illustrative samples.

Prerequisites

To follow along, you need the following:

  • An Anthropic organization (Admin API features aren’t available for individual accounts).
  • An Anthropic Admin API key, created by an organization admin.
  • A workspace API key for each workspace you want to analyze.
  • An AWS account with AWS Identity and Access Management (IAM) permissions to use AWS Glue, Amazon Athena, Amazon S3, Amazon S3 Tables, AWS Secrets Manager, and AWS Quick.
  • An IAM role for AWS Glue with access to the secrets, your S3 bucket, and your S3 table bucket (see Part 2).
  • An S3 bucket for job scripts and reference data.

Part 1: Set up the AWS Glue connector for Anthropic

In this part, you store your Anthropic API keys in AWS Secrets Manager and create the AWS Glue connections that read your organization’s data.

Store your Anthropic API keys

Store each API key in AWS Secrets Manager as a secret with the key apiKey:

{ "apiKey": "<your-anthropic-api-key>" }

Create one secret for the Admin API key and one for each workspace API key you plan to use.

  1. Open AWS Secrets Manager.
  2. Choose Store a new secret and enter your API key.

    AWS Secrets Manager Store a new secret page with the Anthropic API key entered

    Figure 2: Storing an Anthropic API key in AWS Secrets Manager

  3. Choose Next and name your new secret.
  4. Optionally, configure automatic rotation.
  5. Afterwards, choose Next and then Store.

Create the connections

  1. On the AWS Glue console, choose Data connections, then Create connection.
  2. For Data source, choose Anthropic.

    AWS Glue Create connection page with Anthropic chosen as the data source

    Figure 3: Choosing Anthropic as the data source in AWS Glue

  3. For Authentication, choose the secret that contains your Admin API key.

    AWS Glue connection authentication step with the Admin API key secret selected

    Figure 4: Selecting the secret that holds the Admin API key

  4. Name the connection, for example anthropic-admin, and create it.
  5. Repeat the steps with a workspace API key to create a second connection, for example anthropic-workspace.

After you create a connection, choose Test connection to validate the API key. Both Admin and workspace API keys can be validated.

AWS Glue connection detail page showing a successful Test connection result

Figure 5: Validating an Anthropic connection with Test connection

Explore and preview data

In the AWS Glue console, you can browse the entities that each connection exposes and preview records and the schema for all the data available through the AWS Glue connector for Anthropic. The following screenshot showcases synthetic data.

AWS Glue console previewing Anthropic entity records and schema for a connection

Figure 6: Previewing Anthropic entities and schema in the AWS Glue console

Part 2: Build an AI usage lakehouse with Amazon S3 Tables and AWS Glue materialized views

In this part, you turn the Anthropic data from Part 1 into answers to leadership’s three questions. An AWS Glue ETL job reads Anthropic data through the connector, combines it with your business data, and writes Apache Iceberg tables to Amazon S3 Tables. A second AWS Glue job maintains AWS Glue materialized views in the AWS Glue Data Catalog, one for each question, and you query the views with Amazon Athena.

The table bucket organizes the data in four namespaces:

Namespace Contents Written by
raw Anthropic entities, as the connector returns them ETL job
reference Business data that you own, loaded from CSV files in Amazon S3 ETL job
curated Daily fact tables and dimension tables, built from the raw data ETL job
mart Materialized views, one for each business question Materialized view job

To build the pipeline, you complete the following steps.

Create the table bucket and namespaces

Create a table bucket, and then create one namespace for each layer:

aws s3tables create-table-bucket --name amzn-s3-demo-table-bucket

for ns in raw curated reference mart; do
  aws s3tables create-namespace \
    --table-bucket-arn arn:aws:s3tables:<region>:<account-id>:bucket/amzn-s3-demo-table-bucket --namespace "$ns"
done

On the Amazon S3 console, choose Table buckets and enable Integration with AWS analytics services. The integration adds your table buckets to the AWS Glue Data Catalog under the s3tablescatalog catalog, so AWS Glue and Athena can address this bucket as s3tablescatalog/amzn-s3-demo-table-bucket. This walkthrough uses IAM access control for the integration.

Amazon S3 Table buckets page with Integration with AWS analytics services turned on

Figure 7: Turning on AWS analytics integration for the table bucket

Upload your business data to Amazon S3

Anthropic data shows what each workspace and API key spends. It doesn’t show which business unit owns a workspace, what the spend produced, or whether the creator of a key still works at the company. That context lives in your own systems, so you create these datasets from your organization’s data. The datasets you need depend on the questions you want to answer. This post uses the following three sample datasets:

Dataset Columns Example row
workspace_business_unit workspace_name, business_unit Customer Service, Customer Service
support_outcomes_daily outcome_date, business_unit, conversations, completed_resolutions, qa_score_pct 2026-10-30, Customer Service, 1216, 990, 96
hr_directory email, employment_status (active or departed) [email protected], departed

Save each dataset as a CSV file with a header row. In your S3 bucket, upload each file to its own folder under a common prefix, and name each folder after its dataset:

s3://<bucket-name>/<prefix>/workspace_business_unit/workspace_business_unit.csv
s3://<bucket-name>/<prefix>/support_outcomes_daily/support_outcomes_daily.csv
s3://<bucket-name>/<prefix>/hr_directory/hr_directory.csv

The ETL job reads each folder and loads it into a table with the same name in the reference namespace.

Note: If your datasets or columns differ, update REFERENCE_DATASETS in the ETL script and the materialized view definitions to match.

Grant the AWS Glue role access

Both jobs use the IAM role for AWS Glue from the prerequisites. Make sure that the role can do the following:

  • Read the Secrets Manager secrets that store your Anthropic API keys.
  • Read the job scripts and reference data in your S3 bucket.
  • Read and write the table bucket and its tables in the AWS Glue Data Catalog, as described in Amazon S3 Tables integration with AWS analytics services.
  • Pass itself to AWS Glue. Grant iam:PassRole on the role’s own ARN for glue.amazonaws.com, because AWS Glue stores the role with each materialized view and uses it to refresh the view.

Review the ETL script

The ETL job runs the script anthropic_usage_etl.py. Download anthropic_usage_etl.py and save it on your computer. You upload it when you create the AWS Glue job in a later step.

On each run, the script does the following:

  • Reads the cost report, usage report, users, workspaces, and API keys through the Admin connection, and message batches and files through any workspace connections that you list. It writes this data unchanged to the raw namespace.
  • Reads your business data from the Amazon S3 location in the --reference_data_path job parameter and writes it to the reference namespace.
  • Flattens the usage and cost reports into daily fact tables, converts cost from cents to US dollars, and builds tables of API keys, users, and workspaces in the curated namespace.
  • Creates any table that doesn’t exist yet and adds columns when the source data gains new fields, so you don’t need to create tables in advance.

The following snippets show three important parts of the script: how it reads data through the connector, how it builds the curated tables, and how it loads new data incrementally.

Read Anthropic data through the connector

The connector reads data directly into Apache Spark DataFrames through CatalogConnectionHelper, a helper library included with AWS Glue. You pass the connection type, the AWS Glue connection name, and the read options. For every read option and the fields that support filter pushdown, see Anthropic connection options. The following example reads the cost report from October 1, grouped by workspace and cost description:

from connectivity.adapter import CatalogConnectionHelper

connector = CatalogConnectionHelper(spark)

def read_entity(entity, connection, filter_predicate=None):
    """Read one Anthropic entity through the AWS Glue connection into a Spark DataFrame."""
    options = {"ENTITY_NAME": entity}
    if filter_predicate:
        options["FILTER_PREDICATE"] = filter_predicate
    return connector.read("anthropic", connection, options) # connection type, connection name, options

def read_report(entity, starting_at, group_by):
    """Read a usage or cost report from starting_at, broken down by the group_by dimensions."""
    conditions = [f"starting_at = '{starting_at}'"] + [f"group_by = '{field}'" for field in group_by]
    report = read_entity(entity, "anthropic-admin", " AND ".join(conditions))
    return report.select("starting_at", "ending_at", "results")

cost_report = read_report("cost_report", "2026-10-01T00:00:00Z", group_by=["workspace_id", "description"])

read_report builds the filter predicate from the start date and group_by dimensions, and keeps the report columns that the job uses. The result is a Spark DataFrame, so you can use it with standard Spark transformations without converting it. The job reads cost_report and usage_report with read_report and users, workspaces, and api_keys with read_entity.

Workspace entities, such as message_batches and files, need a workspace API key, so the job reads them through each workspace connection that you list in the --workspace_connections job parameter. The job writes everything that it reads, unchanged, to the raw namespace.

Build the curated tables

The connector returns the cost report as one record per day. That record holds all of the day’s cost lines in a single field, results, as a JSON array. To analyze individual cost lines, the job parses results with a schema for the cost line fields (COST_LINE_SCHEMA) and expands the array, so that each cost line becomes its own row. Anthropic reports cost amounts in cents, so the job converts them to US dollars. Anthropic also reports activity in the Default workspace with an empty workspace_id, so the job fills in the Default workspace ID:

def build_fact_cost_daily(cost_report, default_workspace_id):
    """One row per day, workspace, and cost line, with the amount converted from cents to US dollars."""
    return (
        cost_report
        .withColumn("line", F.explode(F.from_json("results", COST_LINE_SCHEMA)))
        .select(
            F.to_date("starting_at").alias("cost_date"),
            # Anthropic reports Default workspace activity with an empty workspace_id
            F.coalesce("line.workspace_id", F.lit(default_workspace_id)).alias("workspace_id"),
            "line.description",
            "line.model",
            "line.cost_type",
            "line.token_type",
            "line.currency",
            (F.col("line.amount").cast("decimal(20,8)") / 100).alias("amount_usd"),
        )
        .groupBy(*COST_KEYS)
        .agg(F.sum("amount_usd").alias("amount_usd"))
    )

The job also parses nested fields such as the API key creator, scope, and principal. It writes the following tables to the curated namespace:

Table Contents
fact_usage_daily Token usage per day, workspace, API key, and model
fact_cost_daily Cost in US dollars per day, workspace, and cost line
dim_api_key API keys with status, workspace, creator, and key type (linked to a user, service account, or legacy)
dim_user, dim_workspace Organization members and workspaces

Load new data incrementally

The first run loads all data from the date in the --start_date job parameter. Later runs re-read only the last three days, because daily buckets close after midnight UTC and recent days can still change. The job merges those days into the fact tables, so a rerun updates rows instead of duplicating them:

MERGE INTO s3tables.curated.fact_cost_daily t
USING updates s -- the re-read days
ON t.cost_date <=> s.cost_date AND t.workspace_id <=> s.workspace_id
AND t.description <=> s.description AND t.model <=> s.model
AND t.cost_type <=> s.cost_type AND t.token_type <=> s.token_type
AND t.currency <=> s.currency
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;

The dimension and reference tables are small, so the job replaces them on every run.

Review the materialized view script

The materialized view job runs the script anthropic_usage_mvs.py. Download anthropic_usage_mvs.py and save it on your computer.

The curated tables hold clean usage, cost, and access data, but each leadership question needs joins across several of them and your business data. Instead of repeating those joins in every query and dashboard, the script saves each answer as a materialized view in the mart namespace. A materialized view stores the result of a query as an Iceberg table. When its base tables change, a refresh updates the view, incrementally where possible, instead of recomputing the whole query. Athena and AWS Quick then read the precomputed results, so everyone works from the same numbers.

On each run, the script creates any view that doesn’t exist yet and refreshes the rest. It maintains one view for each leadership question:

View Built from Answers
weekly_spend_by_business_unit fact_cost_daily, dim_workspace, workspace_business_unit Which business units are driving AI spend?
unit_cost fact_cost_daily, dim_workspace, workspace_business_unit, support_outcomes_daily Is the spend paying off?
access_review dim_api_key, dim_user, dim_workspace, fact_usage_daily, hr_directory Are any active API keys owned by employees who have left?

Add your own views

The script is extensible. Each view is one entry in the VIEWS dictionary: the key is the view name, and the value is the view’s SQL query. To answer a new question, add an entry. For example, the following entry adds a view of daily token usage by workspace and model:

VIEWS = {
    # ... the three views in the preceding table ...
    # Which models consume the most tokens in each workspace?
    "tokens_by_model": f"""
        SELECT u.usage_date,
            w.name AS workspace,
            u.model,
            sum(u.uncached_input_tokens) AS uncached_input_tokens,
            sum(u.cache_read_input_tokens) AS cache_read_input_tokens,
            sum(u.output_tokens) AS output_tokens
        FROM {CURATED}.fact_usage_daily u
        LEFT JOIN {CURATED}.dim_workspace w ON w.workspace_id = u.workspace_id
        GROUP BY 1, 2, 3
    """,
}

The next run of the job creates the view, and later runs refresh it. To change the definition of an existing view, set the optional --recreate job parameter to the view name, for example tokens_by_model, for one run. The job drops the view and creates it again with the new definition.

Follow two rules when you write a view definition:

  • Make definitions deterministic. Functions such as current_date() aren’t allowed, so calculate those values at query time.
  • Use inline subqueries instead of a WITH clause. In our testing, views that used a WITH clause could be created but failed to refresh.

Create the AWS Glue jobs

Create one AWS Glue job for each script. Both jobs connect to the table bucket with the same job parameter, so prepare its value first.

Prepare the table bucket configuration

The scripts read and write the table bucket through an Apache Spark catalog named s3tables. You configure the catalog with one job parameter, --conf. Copy the following value as a single line, and replace <account-id>, <region>, and amzn-s3-demo-table-bucket with your own values:

spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions --conf spark.sql.catalog.s3tables=org.apache.iceberg.spark.SparkCatalog --conf spark.sql.catalog.s3tables.type=glue --conf spark.sql.catalog.s3tables.glue.id=<account-id>:s3tablescatalog/amzn-s3-demo-table-bucket --conf spark.sql.catalog.s3tables.glue.account-id=<account-id> --conf spark.sql.catalog.s3tables.glue.region=<region> --conf spark.sql.catalog.s3tables.client.region=<region> --conf spark.sql.catalog.s3tables.warehouse=s3://amzn-s3-demo-table-bucket/warehouse/

The value contains several Spark settings. AWS Glue accepts only one --conf parameter, so the settings are separated by --conf inside the value. With this configuration, the scripts refer to tables as s3tables.<namespace>.<table>, for example s3tables.curated.fact_cost_daily. For details about these settings, see Running ETL jobs on Amazon S3 tables with AWS Glue.

Create the ETL job

  1. On the AWS Glue console, choose ETL jobs, and then choose Script editor.
  2. For Engine, choose Spark. Choose Upload script, select anthropic_usage_etl.py, and choose Create script.
  3. On the Job details tab, for Name, enter anthropic-usage-etl. For IAM Role, choose the role from the prerequisites. For Glue version, choose Glue 6.0.
  4. Expand Advanced properties. Under Connections, choose the Admin connection and each workspace connection that you created in Part 1.
  5. Under Job parameters, choose Add new parameter and add each of the following keys and values:
Key Value Purpose
--datalake-formats iceberg Adds Apache Iceberg support to the job
--conf The value that you prepared Connects the job to the table bucket
--admin_connection anthropic-admin Name of the Admin connection
--workspace_connections {"anthropic-workspace": "Customer Service"} Optional. Maps each workspace connection to its workspace name. Without it, the job skips message_batches and files.
--reference_data_path s3://<your-bucket>/<prefix>/ Location of your business data
--start_date 2026-10-01 First day to load on the first run
  1. Choose Save.

Create the materialized view job

  1. On the AWS Glue console, choose ETL jobs, and then choose Script editor.
  2. For Engine, choose Spark. Choose Upload script, select anthropic_usage_mvs.py, and choose Create script.
  3. On the Job details tab, for Name, enter anthropic-usage-mvs. For IAM Role, choose the same role. For Glue version, choose Glue 6.0 (AWS Glue materialized views require AWS Glue 5.1 or later).
  4. Expand Advanced properties. Under Job parameters, add --datalake-formats with the value iceberg, and --conf with the same value as the ETL job. This job reads only from the table bucket, so it doesn’t need connections or other parameters.
  5. Choose Save.

For more information about job parameters, see Using job parameters in AWS Glue jobs.

Run and schedule the pipeline

On the ETL jobs page, run anthropic-usage-etl. After it succeeds, run anthropic-usage-mvs, which creates the views on its first run and refreshes them on later runs.

To keep the views current, create an AWS Glue workflow that runs the ETL job daily at 06:30 UTC, after Anthropic’s daily buckets close, and then runs the materialized view job. Alternatively, add SCHEDULE REFRESH EVERY 24 HOURS to each CREATE MATERIALIZED VIEW statement so that AWS Glue refreshes the views on a schedule, and schedule only the ETL job.

Answer the business questions with Amazon Athena

After you execute the following Glue scripts, in the Athena query editor, choose the catalog s3tablescatalog/amzn-s3-demo-table-bucket and the database mart. The results in this section come from the demo organization. The business datasets are samples.

Which business units are driving AI spend?

SELECT week_start, business_unit, spend_usd, prev_week_spend_usd
FROM weekly_spend_by_business_unit
WHERE week_start = (SELECT max(week_start) FROM weekly_spend_by_business_unit)
ORDER BY spend_usd DESC;

Is the spend paying off?

SELECT outcome_date, spend_usd, completed_resolutions, qa_score_pct, cost_per_resolution_usd
FROM unit_cost
WHERE business_unit = 'Customer Service'
ORDER BY outcome_date;
Athena query results for the unit_cost view showing daily spend and cost per resolution for Customer Service

Figure 8: Cost per resolution over time for Customer Service

Are any active API keys owned by employees who have left?

SELECT key_name, key_type, workspace, creator_status, last_used, output_tokens
FROM access_review
WHERE review_candidate
ORDER BY output_tokens DESC;
Athena query results for the access_review view listing active API keys whose creators have left the company

Figure 9: Active API keys owned by employees who have left

The query returns two keys, support-legacy in Customer Service and docproc-batch-legacy in Document Processing. Both are legacy keys, created by an employee who has since left, and both were used the previous day. A departed creator doesn’t mean that a key is misused. It identifies keys whose service ownership should be confirmed, for example by moving the workload to a service-account key, before the old key is disabled.

Part 3: Visualize AI spend and governance in AWS Quick

AWS Quick is a generative AI assistant for work. It helps employees find insights, conduct deep research, automate tasks, and take action across their business applications, bringing chat agents, research, workflow automation, and business intelligence (BI) together in one place. Its BI capability, AWS Quick Sight, turns data into interactive dashboards. With generative BI, you can build a multi-sheet dashboard from a natural language prompt or ask questions of your data in plain language.

Allow AWS Quick to access the table bucket

AWS Quick reads materialized views directly from the table bucket. Before you create a dataset, an AWS Quick administrator allows Quick to access the bucket:

  1. In AWS Quick, open Manage account.
  2. Under Permissions, choose AWS resources.
  3. Select Amazon S3 Tables, choose Select S3 table buckets, select the amzn-s3-demo-table-bucket table bucket, and choose Finish.

    AWS Quick Manage account permissions page granting access to the Amazon S3 table bucket

    Figure 10: Granting AWS Quick access to the table bucket

Without this step, creating the data source fails with a message that AWS Quick doesn’t have permission to access the database.

Create datasets from the materialized views

Create one dataset for each view that the dashboard uses:

  1. Choose Data, then Create dataset, and then Create data source.
  2. Choose Amazon S3 Tables. Enter a data source name, such as anthropic-usage, and the table bucket ARN, for example arn:aws:s3tables:<region>:<account-id>:bucket/amzn-s3-demo-table-bucket. Choose Create data source.
  3. For Namespace, choose mart. Select weekly_spend_by_business_unit and choose Select.
  4. Choose Directly query your data, and then Edit/Preview data. Check the preview and choose Save & publish.
  5. Repeat these steps for unit_cost, and select the anthropic-usage data source that you created instead of creating a new one.
AWS Quick dataset creation using the Amazon S3 Tables data source and the mart namespace views

Figure 11: Creating datasets from the materialized views in AWS Quick

Because the datasets query the views directly, the dashboard shows the latest results after each refresh of the materialized views. You don’t need a separate refresh schedule in AWS Quick.

Generate the analysis from a prompt

Instead of building each visual by hand, describe the review that leadership wants and let AWS Quick generate the analysis. On the Analyses page, choose Generate analysis. Choose Add data, select both datasets, and enter a prompt such as the following:

Create a simple weekly AI spend review for retail leadership, titled "Weekly AI Spend Review", with two sheets and no more than four visuals per sheet.

Spend sheet: each row of weekly_spend_by_business_unit is one business unit in one week. Filter the whole sheet to the most recent week_start only, never sum across weeks. Show a KPI of total spend_usd for that week compared with total prev_week_spend_usd, a horizontal bar chart of spend_usd by business_unit sorted from highest to lowest, and a bar chart of change_usd by business_unit. Add a business unit filter control.

Value sheet: Customer Service only, by outcome_date. Show cost_per_resolution_usd as US dollars with 4 decimal places in a KPI (average) and a line chart, a line chart of qa_score_pct, and a combo chart with spend_usd as bars and completed_resolutions as a line.

Keep sheet descriptions to one short plain sentence.
AWS Quick Generate analysis page with the weekly AI spend review prompt entered

Figure 12: Generating the analysis from a natural language prompt

Choose Preview analysis outline. AWS Quick reviews the columns and statistics of each dataset and proposes a plan with filter controls, sheets, and the visuals on each sheet. Review the plan, choose Edit if you want to change it, and then choose Generate.

AWS Quick analysis outline proposing sheets, filter controls, and visuals before generation

Figure 13: Previewing the proposed analysis outline

Describe the shape of your data in the prompt. The weekly_spend_by_business_unit view has one row per business unit per week. When our first prompt only asked to compare spend with the previous week, the generated analysis added all weeks together. Asking for the most recent week only fixed it.

Review the dashboard

The Spend sheet shows which business units are driving AI spend.

AWS Quick Spend sheet showing weekly AI spend by business unit with a KPI and bar charts

Figure 14: The Spend sheet showing AI spend by business unit

The Value sheet shows whether the spend is paying off.

AWS Quick Value sheet showing cost per resolution, QA score, and spend against completed resolutions for Customer Service

Figure 15: The Value sheet showing whether the spend is paying off

Publish and share the dashboard

Choose Publish to create a dashboard from the analysis, and share it with leadership. Viewers can filter and explore the dashboard without access to the analysis or the datasets behind it. To have the review arrive before the weekly meeting, schedule an email report from the dashboard.

Go further

This dashboard answers leadership’s questions with two datasets and a short prompt, but the same connector data supports much more. For advanced use cases, use the Agent Toolkit for AWS with your preferred AI coding agent to build a richer version of this solution through natural language. The following dashboard compares the price per million tokens across models, shows how much prompt caching saves, and lists the API keys to revoke. We generated the entire data pipeline and this dashboard with Kiro and the Agent Toolkit for AWS.

Advanced AWS Quick dashboard comparing price per million tokens across models, prompt caching savings, and API keys to revoke

Figure 16: A richer dashboard built with the Agent Toolkit for AWS

Considerations

  • Report time windows: Set starting_at for every usage and cost read. Daily buckets include only completed days. Use bucket_width = '1h' for the current day.
  • API key scope: An Admin API key reads organization data but not workspace data such as models, message batches, or files, and a workspace API key reads only its workspace. Use one connection per key, and one set of connections per Anthropic organization.
  • Rate limits: The Anthropic Admin API limits request rates. Use bounded time windows and scheduled incremental reads rather than large historical reads.
  • AWS Glue materialized views: AWS Glue materialized views require AWS Glue 5.1 or later and iam:PassRole for the role that refreshes them. Definitions must be deterministic, and in our testing views with a WITH clause failed to refresh, so use inline subqueries.
  • Security: Grant the AWS Glue role read access only to the secrets it needs, rotate Anthropic API keys regularly, and restrict access to curated tables.

Clean up

To avoid ongoing charges, delete the resources you created: the AWS Glue jobs, workflow, and connections. The Secrets Manager secrets. The materialized views, tables, namespaces, and table bucket in Amazon S3 Tables. The reference data and scripts in Amazon S3. You can also remove the dashboards and datasets that you created in AWS Quick. Consider revoking any Anthropic API keys you created for this walkthrough.

Conclusion

In this post, we showed how to use the AWS Glue connector for Anthropic to bring Anthropic usage, cost, and access data into AWS, store it as Apache Iceberg tables in Amazon S3 Tables, and keep business-ready results current with materialized views. With Amazon Athena, the retailer can see which business units drive AI spend, whether that spend pays off, and which API keys need an ownership review. Using AWS Quick, we used natural language to create dashboards.

To get started, see Anthropic connection options in the AWS Glue Developer Guide. To browse the other connection types that AWS Glue supports, including the new native connectors for SaaS applications, see Available connections.


About the authors

Daniyal Alam

Daniyal Alam

Daniyal is a Software Development Engineer at AWS. He is passionate about the data foundation behind generative AI, building data integration services that connect customers’ SaaS applications, databases, and data warehouses to their analytics and AI workloads on AWS. Outside of work, Daniyal enjoys cooking, driving, weightlifting, and getting outdoors to snowboard and hike.

David Zhang

David Zhang

David is a Senior Specialist Solutions Architect specializing in Data & AI at AWS. He focuses on designing and implementing open lakehouse architectures and agentic AI solutions. He is an active speaker at AWS events and contributes to technical publications and open-source initiatives. He is also the co-author of Apache Iceberg on AWS book. Outside of work, David enjoys staying active through volleyball, tennis, and basketball.

Kamen Sharlandjiev

Kamen Sharlandjiev

Kamen is a Pr. Big Data and ETL Solutions Architect, MWAA and AWS Glue ETL expert. He’s on a mission to make life easier for customers who are facing complex data integration and orchestration challenges. His secret weapon? Fully managed AWS services that can get the job done with minimal effort.

Shrey Malpani

Shrey Malpani

Shrey is a Senior Product Manager Technical at Amazon Web Services (AWS), where he works at the intersection of distributed data processing and data integration. He is focused on building and scaling data integration and data management capabilities across services like AWS Glue, Amazon EMR, and Amazon Redshift that help customers build AI-ready data platforms for their analytics and machine learning workflows.

Joju Eruppanal

Joju Eruppanal

Joju leads engineering teams at AWS, building foundational capabilities for agentic data processing. He helps customers and their agents process and work with data in the cloud. Outside of work, Joju enjoys spending time with his family.

A governed AI-driven development lifecycle for financial services with Kiro and AWS Frontier Agents

Post Syndicated from Qingwei Li original https://aws.amazon.com/blogs/devops/a-governed-ai-driven-development-lifecycle-for-financial-services-with-kiro-and-aws-frontier-agents/

The FSI challenge: Faster delivery with stronger controls

Financial institutions face a difficult asymmetry. Frontier models can help defenders find and remediate weaknesses faster, but regulators are also warning that the same capabilities might accelerate vulnerability discovery and exploitation. The supervisory response is raising expectations for prioritized vulnerability management, continuous monitoring, operational resilience, supply-chain assurance, and the use of AI-based defensive tools under safeguards, human oversight, and robust risk management.

Traditional software delivery makes that harder. Build, security, risk, and operations often work in separate tools and review cycles, with context passed through tickets and manual handoffs. Security checks might occur late, evidence is assembled after the fact, and incident responders must reconstruct what changed across multiple systems. For regulated teams, this creates more than delay: it makes controls harder to apply consistently and decisions harder to evidence.

Under the Digital Operational Resilience Act (DORA), accountability for Information and Communication Technology (ICT) risk remains with the financial institution, including its use of cloud and other third-party providers. Fast development speed alone isn’t enough. Teams need a delivery model that shortens the cycle from discovery to remediation while retaining approval points, traceable evidence, and human accountability.

A governed AI-DLC with three Frontier Agents

The AI-Driven Development Lifecycle (AI-DLC) provides a practical pattern: an AI agent drafts or analyzes, a human evaluates, and the cycle repeats in short iterations. Applied across the lifecycle, agents can help author code, assess release readiness, identify security weaknesses, and investigate production failures. Humans continue to set policy, evaluate findings, authorize material changes, and own the production decision.

In this hands-on walkthrough, Kiro, AWS Security Agent, and AWS DevOps Agent work across a shared GitHub-based workflow. Kiro authors and revises code. AWS DevOps Agent reviews release readiness before and during the pull request. AWS Security Agent performs a deeper security review. A human approves the merge, and AWS DevOps Agent investigates production failures.

Under DORA, accountability for ICT risk stays with the financial institution regardless of which cloud or tooling it uses. Showing that every change was scanned, reviewed, and approved before it reached production, with evidence captured in the delivery toolchain itself, is what turns a good engineering practice into a defensible compliance posture. The institution moves faster without weakening the governance chain, because the agents handle the analysis while humans retain the authority over what gets deployed. This reference implementation doesn’t provide compliance by itself. Each institution must map it to its policies, segregation-of-duties requirements, model risk controls, risk appetite, and DORA obligations.

The three agents — role mapping across the SDLC

SDLC Phase Agent What it does
Plan → Build → Test Kiro (autonomous agent) Virtual developer. Maintains persistent context across sessions, learns from PRs and feedback. Handles multi-repo tasks: bug triage, code coverage, feature implementation. Connects to Jira, GitHub, Slack.
Security AWS Security Agent Virtual security engineer. Reviews design docs, scans PRs against org-specific security requirements, runs autonomous penetration testing. Returns validated findings with remediation code.
Review → Operate → Improve AWS DevOps Agent Virtual site reliability engineer (SRE), and now code reviewer. Release readiness code reviews on every change (cross-repo dependency risks, standards compliance, access control, automated verification testing), plus always-on incident triage, root cause identification and proactive reliability recommendations. Works with Amazon CloudWatch, Datadog, Dynatrace, Splunk, New Relic, Grafana, ServiceNow, Jenkins, GitHub.

Integration model: Workflow-level orchestration

The three agents operate as complementary autonomous systems that share the same software development lifecycle (SDLC) context through common tooling (repos, continuous integration and continuous delivery (CI/CD) pipelines, ticketing systems). The AWS DevOps Agent pulls double duty in this pipeline. Its release readiness code reviews capability makes it the first reviewer on every change: inside Kiro while the code is being written, and again on the PR, before it switches hats to incident response in production.

Agent workflow from Kiro code authoring through AWS DevOps Agent and AWS Security Agent reviews to AWS Lambda deploy and production monitoring

Figure 1: End-to-end workflow across Kiro, AWS DevOps Agent, and AWS Security Agent in a shared GitHub-based pipeline

  • Developer prompts Kiro on what to build. Kiro authors the code.
  • With the AWS DevOps Agent Kiro Power installed in Kiro, you can request a code release readiness review from AWS DevOps Agent right in the Kiro IDE. The release readiness review covers cross-repo dependency risks, standards compliance, access-control correctness, and automated verification testing.
  • After we pass the AWS DevOps Agent code readiness review, we push the code to GitHub from Kiro. The GitHub workflow is designed in a way that a Pull Request (PR) is automatically created.
  • AWS Security Agent runs the deeper OWASP / AWS Identity and Access Management (IAM) / secrets pass on the PR.
  • The developer might incorporate the output from AWS Security Agent and further revise the code. If all looks good, the developer merges the PR.
  • On merge, GitHub Actions deploys.
  • AWS DevOps Agent watches production and, the moment something breaks, opens an investigation, finds the root cause and ties back to the same GitHub repo Kiro is working in.

The rest of this post is the hands-on version of that loop: the exact wiring you need to make it run against a real repo.

Step-by-step setup

This section walks through the setup end to end, from a quick primer on GitHub Actions through the prerequisites and the six steps that wire the agents together.

A quick primer on GitHub Actions

GitHub Actions is GitHub’s built-in automation system. You drop YAML files into .github/workflows/ in your repo, and GitHub runs them on events you care about, such as a push, a PR being opened, a label being added, or a merge to main. Each workflow spins up a fresh Linux VM (“runner”), checks out your code, and executes a series of steps. Steps can be shell commands or reusable packages called actions. We use GitHub Actions as our CI/CD pipeline manager for demonstration purposes.

Prerequisite 1 — What you’ll need

  • A GitHub repo. In this demo example, we deploy a Python application to AWS Lambda using GitHub Actions.
  • An AWS account with permission to create IAM roles, Lambda functions, and an OpenID Connect (OIDC) identity provider.
  • Kiro installed locally.
  • A Slack workspace (for AWS DevOps Agent notifications).

Prerequisite 2 — Install the GitHub Apps and connect the agents

GitHub Apps are the modern way to give automation identity and scoped permissions. For the general model, see About using GitHub Apps. For this demo, install the following on your repo:

Step 1 — Author code in Kiro and push to GitHub

Kiro is an agentic IDE: you describe what you want to build, it writes and edits files, and you commit the result. Open your repo in Kiro, iterate until the feature works, then push a feature branch.

For demonstration purposes, we intentionally started with a flawed .py file with a hard-coded credential and a SQL injection vulnerability so the AWS DevOps Agent and AWS Security Agent have something to catch downstream. This is only to exercise the review agents end-to-end.

Because we installed the AWS DevOps Agent Kiro Power in Prerequisite 2, the review actually starts here, before anything is pushed. The Power includes Skills that tell Kiro to invoke a release readiness review after significant code changes and before creating a PR. Findings surface directly in the IDE, and Kiro offers to fix them on the spot. For this demo, we let the flawed file through so you can see the PR-side review catch it too.

Step 2 — Let the AWS DevOps Agent review the code

This is where the AWS DevOps Agent takes the first review pass. In this post, we use Kiro’s AWS DevOps Agent Power and chat directly with Kiro to kick off the review. This is convenient because you can download the review report and incorporate it into your code. Note that the AWS DevOps Agent can be configured to automatically run a release readiness code review every time a PR is opened or updated.

Prompt: Starting a release readiness review on DevOps-agent-demo @ update-lambda-import. Run it as static analysis.

AWS DevOps Agent release readiness review results shown in the Kiro IDE

Figure 2: AWS DevOps Agent release readiness review results in the Kiro IDE

Each review evaluates the change for cross-repository dependency risks, internal standards compliance, and access-control correctness. With automated verification testing enabled, the agent goes further than static analysis. It clones the change into an AWS-managed verification environment, figures out the build tools from your project files, builds the code, generates a test plan, and runs it. This surfaces functional risks like edge cases that would fail at runtime.

Step 3 — Auto-create the PR

We don’t want to context-switch to the GitHub UI only to open a PR. A tiny workflow does it for us. On every push to a non-main branch, it opens a PR against main if one doesn’t already exist. Put this in .github/workflows/auto-create-pr.yml:

# .github/workflows/auto-create-pr.yml (gist)
on: push to any non-main branch
steps:
- checkout repo
- mint a GitHub App token (APP_ID + APP_PRIVATE_KEY)
- if no PR exists for this branch:
gh pr create --base main --head <branch>

The workflow runs on push to any non-main branch and opens a PR against main if one doesn’t already exist.

Step 4 — Wire up the AWS Security Agent review

The AWS Security Agent was also connected to the repo in Prerequisite 2. This workflow is narrower and stricter than the AWS DevOps Agent’s release readiness pass: OWASP Top 10, hardcoded secrets, IAM misuse, and dependency risk. It gates on the needs-security-review label, so it only runs after the AWS DevOps Agent has cleared the PR.

Create .github/workflows/security-review.yml:

# .github/workflows/security-review.yml (gist)
on: pull_request [opened, labeled]
if: label 'needs-security-review' is present
steps:
- checkout repo
- assume AWS_ROLE_TO_ASSUME via OIDC
- run the Security Agent with:
prompt: "Security review: injection, secrets,
dependencies, IAM, input validation, OWASP Top 10.
Approve if secure; request changes if not."

Two agents now gate every merge. If either requests changes, you fix the code in Kiro and push again, and the whole review cycle restarts automatically.

Here’s what the output looks like in practice:

AWS DevOps Agent release readiness finding posted as a PR comment

AWS Security Agent finding posted as a comment on a GitHub pull request

Figure 3: AWS Security Agent finding posted as a pull request comment

Step 5 — Deploy to Lambda on merge

This demo keeps a human approval before production. After both agents have completed their reviews, an authorized reviewer evaluates the findings and chooses Merge. Financial institutions can add the approvals, separation of duties, change records, and policy checks required by their control framework. The moment the merge lands on main, the deploy workflow takes over.

Create .github/workflows/deploy.yml:

# .github/workflows/deploy.yml (gist)
on: pull_request closed against main
if: PR was merged (not just closed)
steps:
- checkout repo
- assume AWS_ROLE_TO_ASSUME via OIDC
- zip the repo into function.zip
- aws-lambda-deploy --function-name <LAMBDA_FUNCTION_NAME> --zip function.zip

At this point the PR has gone from Kiro push to auto-created PR, AWS DevOps Agent release readiness review, AWS Security Agent review, human approval, and Lambda update. The agents automate analysis and workflow steps, while the authorized reviewer remains accountable for the production decision.

Step 6 — Let the AWS DevOps Agent handle incidents

Deployments fail. Functions throw. Latency spikes. This is where the AWS DevOps Agent earns its keep. It’s an incident-response teammate that investigates on its own, finds root causes, and reports to Slack.

The AWS DevOps Agent is already wired up from Prerequisite 2. It’s connected to this repo (so it can read workflow runs, commits, and IAM policy references) and to Slack (so investigations post to your channel). The only thing left is to point an alert source at it. Follow the webhook configuration guide to grab a webhook URL, then aim your alerts at it, whether GitHub Actions failure notifications, Amazon CloudWatch alarms, or both. An event that hits the webhook kicks off a new investigation.

What an investigation looks like:

Here’s a real run from this demo. A Lambda deploy failed because the OIDC role was missing one IAM permission. The agent walks through it as a timeline:

4:22 PM — Investigation started: Lambda deployment failed. [Symptom] Deploy to Lambda workflow failed on main. [Observation] Workflow assumed the github-action-lambda role, then got AccessDenied calling GetFunctionConfiguration. [Finding] IAM policy frontier-agent-deploy-lambda is missing lambda:GetFunctionConfiguration. Investigation complete — root cause: that one missing IAM permission.

In the AWS DevOps Agent console you see the full timeline and the identified root cause, and you can ask the agent to generate a mitigation plan from there. It proposes the IAM policy change and the steps to apply it.

You’ll also get a Slack ping the moment the investigation kicks off, because we connected the Slack integration in Prerequisite 2:

Slack notification of an AWS DevOps Agent investigation for a failed Lambda deployment

Figure 4: AWS DevOps Agent investigation notification in Slack

Conclusion

In this post we walked end-to-end through an AI-DLC pipeline. Kiro authors the code, with the AWS DevOps Agent Kiro Power reviewing changes in the IDE as they’re written, and opens the PR. The AWS DevOps Agent runs a release readiness review and the AWS Security Agent runs a security review, both posting their findings as PR comments. A human merges, GitHub Actions deploys to Lambda, and the AWS DevOps Agent watches production, investigating failures, surfacing root causes in its console, and pinging Slack the moment something goes wrong.

The value isn’t in any single agent. It’s in what happens when you put them together. Kiro gives you a virtual developer that carries context across sessions. The AWS Security Agent gives you a security engineer on every PR instead of once a quarter. The AWS DevOps Agent gives you a release readiness reviewer on every change, from the IDE to the PR, and an always-on SRE that triages before a human is even paged. Each phase of the SDLC (build, review, secure, operate) gets its own frontier agent, and the handoffs between them are automatic. They pass the baton through GitHub, AWS, and Slack, and the feature moves forward.

Financial services institutions adopt development tooling to deliver better software while meeting their security, resilience, and governance obligations. The workflow demonstrated here brings build, security, and operations into a shared delivery loop, helping teams identify issues earlier and reduce the time from development to production. It also retains review findings and human approvals within the delivery workflow, providing evidence that controls were applied before code reached customers. For financial services industry (FSI) teams, this combination can make software delivery faster, safer, and more straightforward to defend during governance and regulatory reviews.

Ready to explore this approach? You can start with a low-risk workload in a non-production environment. Connect Kiro, AWS DevOps Agent, and AWS Security Agent, then map each automated step to your organization’s approval, segregation-of-duties, and evidence requirements.


About the authors

Qingwei Li

Qingwei Li

Qingwei is a Machine Learning Specialist at Amazon Web Services. He received his Ph.D. in Operations Research after he broke his advisor’s research grant account and failed to deliver the Nobel Prize he promised. Currently he helps customers in the financial service and insurance industry build machine learning solutions on AWS. In his spare time, he likes reading and teaching.

Suheel Farooq

Suheel Farooq

Suheel is a Principal GenAI/ML Specialist Solutions Architect at AWS, specializing in artificial intelligence, machine learning, and generative AI. He helps Foundation Model Provider customers design, build, modernize, and scale their AI/ML and generative AI workloads on AWS — from bringing foundation models to Amazon Bedrock to optimizing training and inference and building Agentic AI solutions. His experience spans the AWS AI/ML and generative AI portfolio, particularly Amazon Bedrock, Amazon Bedrock AgentCore, and Amazon SageMaker AI. In his free time, Suheel enjoys working out and hiking.

Aastha Bhardwaj

Aastha Bhardwaj

Aastha is a Security Specialist at AWS who works with Global Financial Services customers. She helps leading financial institutions prepare for the agentic era so they can adopt AI and autonomous agents safely and at scale. She partners with CISOs and security leaders to build security into migrations and modernizations from day one, protect the AI applications and agents their teams build and use, and defend against AI-powered threats. Outside of work, Aastha loves to travel, dance, and spend time with friends.

Upgrading and troubleshooting Amazon MWAA with AWS agent skills

Post Syndicated from Kamen Sharlandjiev original https://aws.amazon.com/blogs/big-data/upgrading-and-troubleshooting-amazon-mwaa-with-aws-agent-skills/

Amazon Managed Workflows for Apache Airflow (Amazon MWAA) is a managed service for Apache Airflow that you can use to set up and run data pipelines in the cloud at scale, without managing the underlying infrastructure. Amazon MWAA also helps simplify upgrading the Airflow version your environment runs on, with the managed offering including built-in upgrade functionality. Keeping your DAGs current is the harder part. As Airflow innovates, teams struggle to upgrade their DAGs at the same pace, and the work demands deep Airflow expertise and constant switching between tools. The result is a familiar cycle: upgrade efforts often yield broken code and bugs, and debugging them takes time to find and fix. Teams then postpone upgrades and fall further behind. The 2.x-to-3.x jump makes this especially painful, with breaking changes, a Python transition, and a required stepping-stone version.

Apache Airflow version upgrade lifecycle, moving from Airflow 2.x through the required 2.11.x stepping-stone to Airflow 3.x

Figure 1: Apache Airflow version upgrade lifecycle

Automated tools promise to speed this up. But Airflow users quickly find that standard automation approaches often aren’t trained on the latest Airflow syntax or mix concepts between Airflow versions, producing code that fails in exactly the ways you’re trying to avoid.

AWS now publishes a set of MWAA agent skills as part of the open source AWS agent toolkit: skills authored by AWS that your coding assistant uses to better plan, execute, and debug MWAA version upgrades. In this post, you’ll learn what each MWAA skill does, how to install the skills, and how to start using them with sample prompts for upgrades, troubleshooting, and authoring. By the end, you’ll have a complete picture of what the MWAA agent skills are, how to install them in your Airflow project, and how to put them to work on real upgrade and troubleshooting tasks.

What are AWS agent skills?

An agent skill is an instruction package that guides a coding assistant through a specific task. The MWAA skills follow the open Agent Skills standard, so they work across assistants that support it, including Kiro, Claude Code, Cursor, and Codex. The assistant loads a skill authored by AWS and follows its steps, which keeps it current with Airflow and MWAA behavior.

The skills run AWS Command Line Interface (AWS CLI) commands to interact with your resources. The Agent Toolkit for AWS also provides the AWS Model Context Protocol (MCP) Server, and the plugin install bundles its configuration with the skills. The skills use it to fetch current AWS documentation at runtime and to run AWS CLI commands with sandboxed execution and audit logging.

The MWAA skills

The aws-data-analytics plugin ships four Amazon MWAA skills:

  • authoring-mwaa-workflow: Authors and deploys Airflow DAGs for provisioned environments and YAML workflows for MWAA Serverless.
  • testing-mwaa-workflow: Triggers a deployed DAG or workflow, monitors it to completion, and retests after fixes. It can also call the debugging and authoring skills when a run fails.
  • debugging-mwaa-workflow: Finds the root cause of failed runs and tasks, DAGs that don’t appear, import errors, worker out-of-memory errors, and AWS Identity and Access Management (IAM) permission errors.
  • upgrading-mwaa-environments: Upgrades a provisioned environment to a newer Airflow version, including 2.x to 3.x, using a blue/green or in-place strategy. It also updates and tests your DAG code so it runs on the new version. When the source is older than 2.11.x, it plans the route through the latest 2.11.x version on 2.x, which is a bridge for an in-place upgrade to Airflow 3 for provisioned environments.

Provisioned environments use Python DAGs and MWAA Serverless uses YAML files. All four skills work with provisioned environments, and the authoring, testing, and debugging skills also work with MWAA Serverless.

Note: agents using these skills make changes, not only recommendations. Depending on the task, they can edit and deploy DAG files. Try the skills on a development environment first, keep your DAGs under version control, and verify each proposed change.

Prerequisites

  • An AWS account with an existing MWAA provisioned environment. This post starts from Airflow 2.11.x (see the following setup section).
  • An AI coding assistant that supports the Agent Skills standard (for example, Kiro or Claude Code).
  • IAM permissions for the MWAA action namespaces you use, scoped to your resources: the airflow namespace for provisioned environments and the Apache Airflow REST API, and the airflow-serverless namespace for MWAA Serverless workflows and runs.
  • Least-privilege credentials for investigation steps. Grant write access only for the confirmed change steps.

Installing the MWAA skills

The MWAA skills are part of the aws-data-analytics plugin in the Agent Toolkit for AWS. How you install them depends on your assistant. There are two common paths.

Option A: Install the plugin (Claude Code, Codex)

Install the aws-data-analytics plugin from the claude-plugins-official marketplace. First update the marketplace so the latest plugin version is available, then install it. For example, in Claude Code:

/plugin marketplace update claude-plugins-official
/plugin install aws-data-analytics@claude-plugins-official

If you install without updating the marketplace first, you may see an error such as “Plugin ‘aws-data-analytics’ not found in marketplace ‘claude-plugins-official’”. Running the preceding marketplace update command resolves it. The Anthropic plugin directory may still list an older version, so install from claude-plugins-official to get the MWAA skills. Codex and other plugin-based assistants follow the equivalent plugin install in Getting started.

Option B: AWS MCP Server, then add the skills (Kiro)

For Kiro, add the AWS MCP Server to your configuration (~/.kiro/settings/mcp.json). Copy the current configuration from the Kiro section of Getting started in the Agent Toolkit for AWS User Guide, and set AWS_REGION to the Region of your MWAA environment. Then add the skills from the repository:

npx skills add aws/agent-toolkit-for-aws/skills

Alternatively with AWS CLI, run aws configure agent-toolkit. It detects the AI coding assistants you have installed, installs default AWS skills and configures the AWS MCP Server.

After installation, the skills are selected automatically based on your prompt, so you don’t need to name a skill. For step by step setup instructions for each assistant, follow Getting started in the Agent Toolkit for AWS User Guide and Using agent skills in MWAA in the Amazon MWAA User Guide.

Sample prompts to check the setup

  • What AWS Regions are available? – A list of regions means the AWS MCP Server is connected.
  • What can MWAA Skills help me with? – This confirms your assistant can see the skills.

Setting up an example environment

To demonstrate the steps the skills take, we provide two walkthroughs with sample prompts to help you get started. Walkthrough 1 discusses the upgrade process from 2.x to 3.x and Walkthrough 2 shows how to troubleshoot a failed DAG.

Walkthrough 1: Upgrading a provisioned environment from Airflow 2.x to 3.x

Prompt the assistant in natural language, the upgrading-mwaa-environments skill then drives a structured, confirmation-gated process:

  1. Plan the version path. The skill computes an ordered list of version jumps from source to target, inserting the required 2.11.x stepping-stone and the Python-transition step when the path crosses the 2.x-to-3.x boundary.
  2. Choose a strategy. Based on whether run history and the same environment URL/ARN must be kept, the skill selects a new-environment (blue/green) upgrade, a rehearsed in-place upgrade validated on a test copy, or a direct in-place upgrade.
  3. Validate the DAGs. For 3.x moves, the skill runs Ruff scanning and deprecation-warning log scans, plus Docker validation, surfacing breaking changes.
  4. Deploy and switch over, saving a resumable plan so a multi-session upgrade can be paused and continued.

Safety is built in: the skill never creates an environment, changes an Airflow version, or modifies your current environment without per-action confirmation, and every version jump is confirmed individually.

Sample prompts that you can use

  • Upgrade <environment_name> from Airflow 2.7.2 to the latest 3.x. We don’t need the run history.
  • Upgrade <environment_name> from 2.10.3 to 2.11.x. We must keep run history and the same URL. It has a large number of DAGs.
  • Upgrade <environment_name> from 2.11.0 to 3.2.1 in place. Skip the test copy, we don’t have budget. Some DAGs import airflow.datasets and one runs ‘airflow db clean’ in a BashOperator.

Walkthrough 2: Troubleshooting a failed DAG

Upgrades surface failures, a DAG that no longer imports, or one that stops appearing in the Airflow UI. The debugging-mwaa-workflow skill walks through the common MWAA failure modes and identifies the root cause. Next, you can either manually fix the problem or ask the authoring skill to update your DAG.

Sample prompts that you can use

  • DAG <dag_name> on <environment_name> started failing this morning with ModuleNotFoundError: No module named ‘snowflake’. Nobody changed the DAG code.
  • My serverless workflow arn:aws:airflow-serverless:<region>:<accountid>:workflow/<workflowname> failed on its last run. Why?
  • Task <taskname> in DAG <dag_name> on <environment_name> fails with AccessDenied on s3://<s3_bucket>/inbound/. Fix the permissions.

Authoring and testing workflows

The MWAA skills cover both flavors of MWAA. While the upgrade skill applies to provisioned environments only, the authoring, testing, and debugging skills all work with MWAA Serverless, where you define workflows in YAML rather than Python DAGs. To show this, we use authoring-mwaa-workflow to build a YAML workflow, testing-mwaa-workflow to run it to completion, and the debugging skill if a run fails.

Sample prompts you can use

  • Write a Python DAG for my MWAA environment <environment_name> that runs an Athena query against <db>.<table>, writes results to s3://<s3bucket>/orders/, and sends an SNS alert on failure. Then deploy and test it.
  • Create an MWAA Serverless workflow that runs Glue job orders-clean, then a Python step that uses pyarrow to validate the Parquet output row count. Run it nightly. Deploy only, don’t run it yet.
  • Smoke-test DAG <dagname> on <environment_name> (Airflow 3.0.6). It was just uploaded and is still paused.
  • Run arn:aws:airflow-serverless:<region>:<accountid>:workflow/<workflow_name> and confirm it succeeds. If it fails, fix it and retry up to 5 times.

Best practices

  • Test in a development environment first. Before an in-place production upgrade, rehearse on a test copy, and prefer a new-environment (blue/green) upgrade when you don’t need to keep run history.
  • Keep the assistant in a confirm-before-act posture for any environment-changing operation, and review each version jump.
  • Use read-only credentials for investigation and troubleshooting; scope write access to the confirmed change steps, and scope IAM to the airflow / airflow-serverless namespaces you use.
  • Install the AWS MCP Server alongside the skills so the assistant fetches current AWS docs at runtime and runs CLI commands with sandboxed execution and audit logging.
  • Keep DAGs and requirements under version control so you can review and roll back any changes these skills makes.

Conclusion and next steps

The MWAA agent skills give your AI coding assistant AWS-authored procedures for the operational work that slows Airflow teams down: upgrading Airflow versions, debugging failed runs, and authoring and testing workflows. You describe the goal, and the assistant plans the work, asks before it changes your environment, and tests the result.
To get started:
  1. Install the skills from the Agent Toolkit for AWS and connect the AWS MCP Server, as described in Getting started.
  2. Try the sample prompts in this post against a development environment.
  3. For more example prompts, see Using agent skills with Amazon MWAA in the Amazon MWAA User Guide. If you’re planning a move to Airflow 3, also read Best practices for migrating from Apache Airflow 2.x to Apache Airflow 3.x on Amazon MWAA.

Cleanup

If the walkthrough created a new environment (blue/green), a rehearsal copy, or a Serverless workflow, delete those resources when you’re done to avoid ongoing charges.


About the authors

Kamen Sharlandjiev

Kamen Sharlandjiev

Kamen is Principal Big Data and ETL SA. He’s on a mission to make life easier for customers who are facing complex data integration and orchestration challenges. His secret weapon? Fully managed AWS services that can get the job done with minimal effort. Follow Kamen on LinkedIn to keep up to date with the latest MWAA and AWS Glue features and news!

Harshawardhan Kulkarni

Harshawardhan Kulkarni

Harsh is a Partner Technical Account Manager at AWS, Amazon MWAA Subject Matter Expert. Based in Dublin Ireland, he partners with Enterprise Customers across EMEA to help navigate complex workflows and orchestration challenges while ensuring best practice implementation. Outside of work, he enjoys traveling and spending time with his family.

Boyko Radulov

Boyko Radulov

Boyko is a Senior Cloud Support Engineer at Amazon Web Services (AWS), Amazon MWAA and AWS Glue Subject Matter Expert. He works closely with customers to build and optimize their workloads on AWS while reducing the overall cost. Beyond work, he is passionate about sports and travelling.

Aritra Ghosh

Aritra Ghosh

Aritra is a Senior Product Manager at Amazon Web Services (AWS), where he leads product development for Amazon Managed Workflows for Apache Airflow (Amazon MWAA) and Amazon SageMaker Unified Studio. Outside of work, Aritra enjoys playing squash and hitting the gym.

Ashish Goel

Ashish Goel

Ashish Goel is a Principal Engineer at AWS who has supported Amazon Managed Workflows for Apache Airflow (Amazon MWAA) since its inception in 2019, guiding the Amazon development teams and the Open-Source team that contributes directly to Apache Airflow. Outside of work, Ashish enjoys tennis and nature.

PHP2Shell: Using AWS Transform to move legacy PHP onto a patched runtime

Post Syndicated from Armando Barrales original https://aws.amazon.com/blogs/devops/php2shell-using-aws-transform-to-move-legacy-php-onto-a-patched-runtime/

On October 21, 2026, the PHP project fixed two critical vulnerabilities in the PHP engine, CVE-2026-109618 and CVE-2026-109619, which are known together as PHP2Shell. Both vulnerabilities have a Common Vulnerability Scoring System (CVSS) v4.0 score of 9.2 because either one can let an unauthenticated caller run code on any server that handles PHP requests. The U.S. Cybersecurity and Infrastructure Security Agency (CISA) has since added both of them to its Known Exploited Vulnerabilities catalog.

These vulnerabilities don’t affect AWS services, but they can affect workloads running on AWS that serve PHP. The potential exposure is significant because PHP remains widely used across websites, with many sites still running PHP 8.1 or older versions.

If you run PHP 8.1 or older, you cannot patch PHP2Shell in place because no PHP release fixes those branches. Moving to a supported version isn’t always straightforward either, because legacy code often breaks on newer PHP releases. As a result, upgrading the code becomes the real blocker to patching the runtime.

With AWS Transform continuous modernization, you can remove that blocker by finding legacy PHP across your repositories and upgrading to PHP 8.4 or 8.5. AWS Transform analyzes your repositories on a schedule and flags end-of-life runtimes and other technical debt before they become urgent.

In this post, you learn how to use AWS Transform to find and upgrade legacy PHP, confirm that the upgrade was validated on a patched PHP runtime, and then patch and restart the runtime to remediate the vulnerabilities.

This post focuses on moving your code onto a patched runtime. For detection and mitigation guidance, refer to the AWS WAF post and the community checklist Find It, Patch It, Watch It. Compromise assessment is out of scope, so if a system was exposed while it was unpatched, investigate it separately and rotate any credentials the application could read.

Understand the PHP2Shell vulnerabilities

Before you start the upgrade, review which PHP releases are affected and which releases contain the fix, because this determines whether you only need to patch the runtime or whether you must also upgrade your code. The GHSA-w8hw-w9fx-j79w and GHSA-6wmf-4rv5-p3rp advisories describe the two vulnerabilities, and the following table summarizes the affected and fixed releases.

PHP branch Affected First fixed
8.5 8.5.0 to 8.5.11 8.5.12
8.4 8.4.0 to 8.4.26 8.4.27
8.3 8.3.0 to 8.3.35 8.3.36
8.2 8.2.0 to 8.2.34 8.2.35
5.4 to 8.1 all No release fixes these branches. Migrate to 8.4 or 8.5

Source: AWS Security Bulletin 2026-143-AWS. The bulletin recommends that you migrate to a supported branch, and this post recommends PHP 8.4 or 8.5 based on their support dates on the PHP supported versions page. Amazon Threat Intelligence identified an exploitation attempt on October 17, 2026, four days before the fixes were released. It has reported broad exploitation attempts since then. The disclosure date isn’t necessarily the earliest date of exploitation. The report advises you to start your investigation no later than October 17, 2026.

Your next action depends on the PHP branch that you run. The following table shows what to do for each branch.

You run What to do
PHP 8.2, 8.3, 8.4, or 8.5 These versions are vulnerable until you patch to 8.2.35, 8.3.36, 8.4.27, or 8.5.12. Your code doesn’t need to change. Patch the runtime and restart all running workers.
PHP 8.1 or older No release fixes these branches. PHP published minimal source backports for 7.4 to 8.1 as a stopgap for people who build from source. First, check whether your distribution or LTS vendor ships backported fixes. Otherwise, migrate to 8.4 or 8.5. PHP 8.2 reaches end of life on December 31, 2026, and PHP 8.3 reaches end of life on December 31, 2027. Until you migrate, apply the interim controls in the bulletin and the AWS WAF post. Your code might need changes first. The rest of this post covers those changes.
PHP you cannot find Build the inventory first. Use Amazon Inspector, AWS Systems Manager Inventory, and your container registries.

For PHP 8.1 or older, upgrading the code doesn’t fix the CVEs by itself. Instead, the upgrade removes the blocker that prevents you from updating the runtime, which is an application that breaks on a supported PHP version.

Solution overview

The solution works in three steps. Continuous modernization first analyzes your repositories and returns findings. A managed transformation then upgrades the code from those findings and validates the result on a patched PHP runtime. Finally, you patch and restart the runtime itself, which is the step that remediates the CVEs. The following diagram shows the flow.

Diagram showing repositories analyzed by AWS Transform continuous modernization, findings remediated by a managed PHP upgrade transformation, the upgraded branch validated on a patched PHP release, and the runtime patched and restarted.

Figure 1: Analysis, upgrade, and patch flow with AWS Transform continuous modernization

The walkthrough covers the following steps:

  1. Analyze your repositories for end-of-life PHP.
  2. Upgrade the code from the findings.
  3. Patch and restart the runtime.

Explore the sample application

This walkthrough uses a sample application so that you can follow along. Later, you can apply the same three steps to your own code. The sample is a PHP 7.4 application that represents common pre-8.0 codebases, with five small classes and seven PHPUnit tests. It includes the three kinds of breakage that you find in real code. The following table shows these kinds of breakage.

Kind Example in the sample What PHP 8 does
Removed or stricter, fails to parse or run $text{0}, create_function(), each(), count(null) Parse error, fatal error or TypeError
Silent behavior change 0 == "abc" in Matcher::isZeroLike No error, a different result. Only a test notices
Deprecated Implicit nullable parameter, dynamic properties, "${var}" Deprecation notices on 8.2 to 8.4

Silent behavior changes are the hardest to detect. The code runs without errors, but it returns a different result.

Prerequisites

To follow this walkthrough, you need the following:

  • An AWS account and the AWS Transform CLI 3.20.0 or later (check with atx --version) in a supported AWS Region. For setup and authentication, refer to Getting started with continuous modernization.
  • AWS credentials with the AWSTransformCustomFullAccess managed policy.
  • Node.js 22 or later, Git, and jq. You also need Docker, or a patched PHP on your target branch, on the machine that runs step 2: the transformation validates its work on one of them.
  • The transformation installs nothing on the host. If the machine has no PHP and no Docker, or its only PHP is on a branch older than your target, the preflight stops the run before any migration work and names what is missing. If its only PHP is an unpatched release of your target branch and there is no Docker, it validates on that PHP instead, writes NOT a patched … interpreter and reports Success with warnings. Install Docker or a patched PHP to avoid both cases.
  • Throwaway clones of your repositories. You also need a disposable machine for step 2 because the agent runs commands there unattended. AWS/php-version-upgrade is in public early access, so test it in a non-production environment first.
  • A target branch of 8.4 or 8.5. Export it as TARGET because every command in this post uses it.

The sample application lives in the guide folder, so clone it once:

git clone https://github.com/aws-samples/aws-transform-custom-samples
export GUIDE="$PWD/aws-transform-custom-samples/community-sourced-transformations/php2shell-patch-and-verify"
export TARGET=8.5 # or 8.4; see "Check the upgraded branch before you ship"

A local continuous modernization source is a folder of Git repositories. Create that folder first. The following commands set it up with the sample application. To use your own code instead, point REPO at your own repository folder.

mkdir -p ~/repos
cp -R "$GUIDE/samples/legacy-php-app" ~/repos/
export REPO=legacy-php-app # your repository folder name under ~/repos
git -C ~/repos/$REPO init -q
git -C ~/repos/$REPO add -A
git -C ~/repos/$REPO commit -qm "baseline before the upgrade"

If you use a host PHP instead of Docker, install the patched release on Amazon Linux 2023:

sudo dnf install -y --releasever=2023.12.20261021 php$TARGET-cli php$TARGET-xml php$TARGET-mbstring composer
php -v # 8.5.12 or later (8.4.27 or later for 8.4)

Step 1: Analyze your repositories for end-of-life PHP

In this step, you connect your repositories to continuous modernization and run two analyses. You use the atx ct command group, which runs continuous modernization.

To run the analysis

Add the folder as a source and scan it. Then run the rapid and comprehensive analyses and list the open findings:

atx ct source add --name my-php --provider local --path ~/repos
atx ct discovery scan --source my-php
atx ct analysis run --type rapid-techdebt-analysis --source my-php --wait # 1 to 2 minutes
atx ct analysis run --type tech-debt-comprehensive --source my-php --wait # 5 to 10+ minutes
atx ct findings list --source my-php --status open --json

Run both analyses because they answer different questions. The rapid scan reads only composer.json and takes 1 to 2 minutes per repository, which makes it a good first sweep to find the repositories in your estate that run an end-of-life PHP version. The comprehensive analysis reads the code itself and takes 5 to 10 minutes or more, but it’s the analysis that finds the silent behavior changes.

On the sample, the rapid scan returned one high-severity finding named “PHP Version Upgrade” with AWS/php-version-upgrade as its fix. The comprehensive analysis returned between 6 and 11 findings, depending on the run, including removed constructs such as create_function() and each(), silent behavior changes, and the end-of-life php >=7.4 constraint in composer.json.

Most findings name a transformation in their fix field, although some recommend a manual change instead, and step 2 acts on the findings that name AWS/php-version-upgrade.

The analysis leaves each repository on its own branch and writes an ATXDocumentation/ folder into it. Step 2 doesn’t run on a repository with uncommitted changes. Switch back to your branch, remove that folder, and confirm that the working tree is clean before you continue:

cd ~/repos/$REPO
git checkout <your-branch> # switch back from the analysis branch
rm -rf ATXDocumentation # remove the folder the analysis wrote
git status --short # commit, stash or delete anything listed
git status --porcelain # must print nothing before you continue

Step 2: Upgrade the code from the findings

In this step, you start the upgrade from the step 1 findings by using AWS/php-version-upgrade, an AWS managed transformation that is in public early access. A continuous modernization remediation passes the findings to the transformation, so the run plans around the findings and not only around the target version.

To create a remediation from the findings

Confirm the account has version 2026-11-02 or later, then collect the IDs of open findings whose fix is AWS/php-version-upgrade and create a remediation:

atx custom def list | grep -i php # AWS/php-version-upgrade, version 2026-11-02 or later
IDS=$(atx ct findings list --source my-php --status open --fix-transform AWS/php-version-upgrade --json | jq -r '[.[].id] | join(",")')
if [ -z "$IDS" ]; then echo "No open findings name AWS/php-version-upgrade: rerun step 1"; else
atx ct remediation create --ids "$IDS" --name php-upgrade \
  --transformation-name AWS/php-version-upgrade \
  -g "{\"additionalPlanContext\":\"The target PHP version is $TARGET\"}"
fi

The -g flag is accepted only together with --transformation-name. Without both, the remediation migrates to PHP 8.5 regardless of TARGET.

The command returns when the run ends, which took about 8 minutes on the sample. The atx ct remediation status --id <id> command then shows the repository as pr_open and the findings as change_ready. Do not interrupt the run, because an interrupted run stays in the running state until you cancel it. On a local source, the job runs on your machine and trusts every tool. Use the disposable machine from the prerequisites, with Docker or a patched PHP and no production credentials.

A remediation has no cost cap and no opt-out of knowledge-item extraction. If you need either, run the transformation directly:

atx custom def exec -n AWS/php-version-upgrade -p ~/repos/$REPO -x -t -d --limit 300 \
  -g "{\"additionalPlanContext\":\"The target PHP version is $TARGET\"}"

The -d flag opts the run out of knowledge-item extraction, and the --limit flag caps the agent minutes (300 is a ceiling of $10.50, not the expected cost). On the 13-file sample the direct runs used 64 to 79 agent minutes, so budget at least 100 even for a small project and raise it for a real application. A run that reaches the cap stops with exit code 2. The CLI help says it can be resumed with a higher limit, but the resume command it prints (atx --conversation-id <id> -t --limit <n> ) has to be run attended, because it cannot be combined with -x (seen on CLI 3.21.0). Otherwise rerun on a fresh clone with a higher limit, and do not merge the branch a stopped run leaves. This direct run doesn’t read the findings.

Either way, the result is a new branch. Two of its edits follow. The first replaces a construct that PHP 8 removed:

--- a/src/Initials.php
+++ b/src/Initials.php
class Initials {
    public function first($text) {
-        return $text{0};
+        return $text[0];
    }
}

The second changes the test instead of the production code, because PHP 8 returns a different result here:

--- a/tests/MatcherTest.php
+++ b/tests/MatcherTest.php
public function testZeroLikeValues() {
    $m = new Matcher();
    $this->assertTrue($m->isZeroLike(0));
-    $this->assertTrue($m->isZeroLike('abc'));
+    $this->assertFalse($m->isZeroLike('abc'));
}

Review the full diff before you merge it. The first edit is mechanical. The second is a behavior change that the upgrade made deliberately: PHP 8 changed loose comparisons on purpose, to close a class of bug that causes authentication bypasses, so ‘abc’ == 0 is now false. Version 2026-11-02 kept the PHP 8 result in all five test runs and listed the changed assertion under Behaviour changes in its run summary. Read that item, because a caller that relied on the old result changes behavior too. If the upgrade ever keeps a pre-PHP-8 result on purpose, it records the site under Security review required. Either way, check every ==, switch statement, and non-strict in_array call that handles user input.

Check the upgraded branch before you ship

Version 2026-11-02 of the managed transformation validates the upgrade for you. Confirm three things on the branch before you ship it.

The transformation validates its own work on a patched runtime. Version 2026-11-02 selects the interpreter it validates on: a host PHP on your target branch at or above that branch’s patched release, or else the official Docker image of the patched release. It installs nothing on the host. Across five test runs on November 6, 2026, every run validated on 8.4.27 or 8.5.12, and a host PHP of 8.5.3 was rejected. After the run has finished (a direct run exits with code 0, or a remediation shows the repository as pr_open), check out the upgraded branch and find the Validated on PHP line in the commit message. Set BASE to the branch you started the run from:

git branch --show-current # must be the upgraded branch, not BASE
BASE=main
git log --format=%B "$BASE..HEAD" | grep -oE 'Validated on PHP.{0,120}|NOT a patched.{0,40}'

The output must name a patched release of your target version, for example Validated on PHP 8.4.27 (security floor 8.4.27). If it prints nothing, names an unpatched release, or prints NOT a patched …, do not ship yet: run the independent verify check in the sample folder (step 3 of its README). Empty output also happens when BASE doesn’t exist or when you are still on BASE, so treat it as not verified, never as fine. The line tells you which PHP the run tested on, not which PHP you deploy on.

The transformation also writes a constraint that excludes unpatched releases. Version 2026-11-02 wrote ^8.5.12 for target 8.5 and ~8.4.27 || ^8.5.12 for target 8.4 in all five runs, and added no config.platform.php pin. Earlier versions wrote branch-level constraints such as “>=8.5”, which still admit the vulnerable releases, so check the value if you ran an older version. Confirm that your branch uses one of these constraints. Details are in the GitHub README.

Set require.php to ^8.5.12 for target 8.5, or to ~8.4.27 || ^8.5.12 for target 8.4. If composer.json sets config.platform.php, set that value to 8.5.12 (or 8.4.27), and then run composer update --lock. Composer’s generated platform_check.php file checks only the lowest version in require.php. With ^8.5.12, the application refused to start on both 8.5.11 and 8.4.27. With ~8.4.27 || ^8.5.12 it refused to start on 8.4.26 but still started on 8.5.11. In both cases, the manifest prevents an install on older PHP, although it doesn’t replace the runtime patch.

Step 3 is required whatever the run summary says, and the run summary file might not exist at all. The constraint is enforced when Composer installs, but at run time Composer’s platform_check.php checks only the lowest bound. The 8.4 outputs of the test runs booted on PHP 8.5.11, which is vulnerable (the 8.5 outputs refused it). Only step 3 closes that gap.

Step 3: Patch and restart the runtime

The previous steps prepare your code, but this step is the one that remediates the CVEs. The following table shows the action to take for each place where PHP runs.

Where PHP runs Action
Amazon Linux 2023 Upgrade every PHP package of your branch to the release in the advisory (command that follows)
Containers Rebuild on a base image with a fixed release (for example php:8.4.27-fpm) and redeploy
AWS Elastic Beanstalk Updated PHP platform versions exist for 8.2 to 8.5. Managed platform updates apply them in the next maintenance window. Otherwise update the platform version yourself
Amazon Lightsail No in-place update: create new instances from the updated blueprint and migrate
Debian, Ubuntu, RHEL, LTS builds Use your vendor’s package. The version string might not change: trust the vendor advisory
AWS Lambda No managed PHP runtime. If the runtime is yours (a custom runtime or a container image), rebuild it with a patched release and redeploy

On Amazon Linux 2023, upgrade every installed package for your branch with a quoted wildcard such as ’php8.5*’. The advisories are ALAS2023-2026-3301 for 8.2, -3302 for 8.3, -3303 for 8.4, and -3304 for 8.5. Use the quoted wildcard because dnf upgrades only installed packages, so a bare name such as php8.4 can match nothing and leave the host unpatched.

To upgrade PHP on Amazon Linux 2023

Set your branch and advisory from the table, and upgrade:

B=8.5; A=ALAS2023-2026-3304 # 8.5 shown; set your branch and advisory. Keep this shell open: later checks reuse $A
sudo dnf upgrade -y --releasever=2023.12.20261021 "php$B*"

Set session.upload_progress.enabled=0, and keep it set after patching. A separate vulnerability, CVE-2026-115560, affects session upload progress in an uncommon configuration and was still unpatched as of October 26, 2026. Because the setting is on by default, PHP recommends that you keep it disabled until its next regular release. The following paths are for Amazon Linux, and you can find yours by running php --ini and checking “Scan for additional .ini files”. A pool setting overrides php.ini, so check the pools too:

echo 'session.upload_progress.enabled=0' | sudo tee /etc/php.d/99-php2shell.ini
grep -rn 'upload_progress' /etc/php-fpm.d/ /etc/php-fpm.conf # remove any line that turns it back on
Restart every PHP-FPM pool, every web server that loads PHP, and every queue, consumer or long-running cron PHP worker, because a package upgrade does nothing for processes already in memory. Then confirm the patch. On Amazon Linux 2023, the package changelog doesn’t list the CVE IDs, so check the advisory instead. With Apache mod_php, check the version of the package that provides the Apache module and restart httpd. If the updateinfo command prints nothing on a host you believe is patched, run it again with the
--releasever value you used for the upgrade, and rely on the rpm and php-fpm -v checks.
sudo systemctl restart php-fpm httpd # use your web server's unit (nginx, for example) instead of httpd
/usr/sbin/php-fpm -v # the binary that serves requests
dnf updateinfo list --installed | grep "$A" # the advisory for your branch is installed
rpm -qf --qf '%{NAME}-%{VERSION} installed %{INSTALLTIME:date}\n' /usr/sbin/php-fpm
ps -o lstart= -p "$(pgrep -o -f 'php-fpm: master')" # must be later than the install time from the rpm command
/usr/sbin/php-fpm -i | grep session.upload_progress.enabled # Off

We ran these steps in Amazon Linux 2023 containers that started on php8.4-fpm 8.4.26 (B=8.4) and on php8.5-fpm 8.5.11 (B=8.5). Containers have no systemd, so we restarted php-fpm by starting it again directly. The workers came back on 8.4.27 and 8.5.12, with the matching advisory installed and upload progress set to Off.

Clean up

To avoid unneeded resources and charges, remove what this walkthrough created:

# The branch that the step 1 analysis wrote into each repository
cd ~/repos/$REPO && git branch # find the analysis branch, then: git branch -D <branch>
# Container images the upgrade pulled to validate on a patched PHP
docker image ls | grep -E '^(php|composer) ' # then: docker image rm <image>

If you no longer need the my-php source in continuous modernization, remove it in this order. Deleting a finding on its own requires it to be dismissed or obsolete, so --cascade-findings is simpler, and the source cannot be removed while any repository still references it:

atx ct analysis list --json | grep my-php # note each analysis id
atx ct analysis delete --id <analysis-id> --cascade-findings
atx ct repository delete --repo "my-php::<repo>" --source my-php
atx ct source remove --name my-php

Then delete the throwaway clones. Terminate the disposable machine from step 2 because it ran an agent with -t, which trusts its tools. Keep the upgraded branch until it’s reviewed and merged.

Cost

AWS Transform bills per agent minute ($0.035 as of November 6, 2026). For current rates, refer to AWS Transform pricing.

On the 13-file sample, as measured in the project’s BENCHMARKS.md on GitHub, version 2026-11-02 used about 64–79 agent minutes ($2.24–2.76) per upgrade. That’s more than earlier versions used with a host PHP (21 to 38 agent minutes). The transformation’s own instructions say its Docker path takes about three times as long as a host PHP. A larger application costs more, so start from --limit 300 and raise it for larger code. A remediation started from findings has no cost cap. Measured results per run are in the GitHub README.

Limitations

  • This solution doesn’t patch your servers or detect a compromise. Step 3 is yours. If a system was exposed while unpatched, investigate separately and rotate credentials the application could read.
  • The upgrade doesn’t prove identical behavior. Its validation runs your tests and a lint pass on a patched PHP, so it catches what your tests cover. Review the diff, and the Behaviour changes item in the run summary or commit message. Treat a missing item as unknown, not as none, before you merge.
  • The upgrade runs an AI agent with your tools trusted. Use throwaway clones and a disposable machine, review every diff, and use the inventory step to find PHP outside your connected repositories.

Conclusion

In this post, you learned how to use AWS Transform continuous modernization to find legacy PHP across your repositories, upgrade it with a managed transformation that validates the result on a patched PHP runtime, and then patch and restart the runtime. Because the analysis keeps running on a schedule, the same setup flags the next end-of-life runtime before it becomes urgent.

Of the three steps, the runtime patch and restart is the one that remediates the CVEs. The analysis and the managed upgrade are what make that patch possible for legacy code.

To get started, clone the sample from the GitHub repo and run it end to end. Then connect your own repositories to AWS Transform continuous modernization. If you have questions about applying this pattern in your organization, contact your AWS account team.

For more information, refer to the following resources:

Related posts:


About the authors

Armando Barrales

Armando Barrales

Armando is a Senior Migration and Modernization Solutions Architect at AWS, based in Mexico. Over more than 20 years in IT, he has helped organizations across Latin America and worldwide move legacy systems to the cloud. Today he focuses on application modernization and generative AI, helping customers go from idea to working solution.

Nishant Agarwal

Nishant Agarwal

Nishant is a Principal Go-to-Market Lead for AWS Transform. He helps customers use agentic AI to modernize their applications, reduce tech debt and keep their software secure and current.

Venugopalan Vasudevan

Venugopalan Vasudevan

Venugopalan is a Principal Specialist Solutions Architect at AWS. He leads generative AI initiatives that focus on Kiro, and AWS Transform. He helps customers adopt and scale AI-powered developer and modernization solutions to accelerate innovation.