

# Backend identity and access management

 AWS Amplify backends use two distinct authorization systems, and understanding the split is the single most important thing in this section:


| Your task | You authenticate with | Authorization is by | 
| --- | --- | --- | 
|  **Managing** backends and branches (CLI, SDK, CI/CD) |  **AWS Signature Version 4** (IAM) | IAM policies using `amplifygen3:` actions | 
|  **Reading or writing data** in a backend (your application) | A branch-issued **API key**, optionally with an end-user token, or SigV4 | The **PostgreSQL role** the credential maps to, and your **row-level security policies**  | 

IAM governs the control plane. Your own database policies govern your data. An IAM policy cannot grant or restrict access to individual rows, and a row-level security policy cannot grant permission to create a backend.

**Topics**
+ [How an Amplify backend works with IAM](#security_iam_backend_how_it_works)
+ [Backend identity-based policy examples](#security_iam_backend_policy_examples)
+ [Backend resource-based policy examples](#security_iam_backend_resource_policy_examples)
+ [AWS managed policies for backend access](#security_iam_backend_managed_policies)
+ [The backend data-plane credentials, and what each one grants](#security_iam_backend_credentials)
+ [Calling a backend’s data API with an AWS Sign-In access token](#security_iam_backend_signin_token)
+ [What a backend’s data API reveals beyond your rows](#security_iam_backend_data_api_reveals)
+ [Connecting directly to your backend database](#security_iam_backend_direct_db)
+ [Connecting to your backend database with your AWS identity](#security_iam_backend_pg_endpoint)
+ [Logging PostgreSQL endpoint connections with AWS CloudTrail](#security_iam_backend_pg_cloudtrail)
+ [Troubleshooting backend identity and access](#security_iam_backend_troubleshoot)
+ [Using service-linked roles for Amplify backends](#security_iam_backend_slr)
+ [End-user sessions](#security_iam_backend_end_user_sessions)
+ [Responding to a backend security incident](#security_iam_backend_incident_response)
+ [Backend configuration and vulnerability analysis](#security_iam_backend_config_vuln)
+ [Backend security best practices](#security_iam_backend_best_practices)

## How an Amplify backend works with IAM
<a name="security_iam_backend_how_it_works"></a>

Every backend control-plane operation maps to an IAM action in the `amplifygen3` namespace. Requests must be signed with SigV4, and IAM evaluates the caller’s identity-based policies before Amplify executes the operation. SigV4-signed requests to a backend’s data API, and requests that carry an AWS Sign-In OAuth access token instead, are authorized with the `amplifygen3:Connect` action, on the ARN of the branch they address. Scope that grant to the branches a role needs, and give it only to roles you would trust with those branches' data.

 **A principal that holds `amplifygen3:Connect` acts as `service_role` on every backend and branch your grant reaches, bypassing row-level security** (see the credential table below), so grant it only to trusted server-side roles, and name the branches it covers rather than `*`.

 **Amplify determines your tenancy from the calling AWS account ** – The account that signs the request owns the backends it creates and can see only its own backends. There is no cross-account sharing of a backend. The same holds on a backend’s data API: a SigV4-signed data request is accepted only when a principal in the account that owns the backend signed it. A request signed from any other account is refused with HTTP 403, even if that account has granted its own principals `amplifygen3:Connect`.

**Note**  
 **Most backend control-plane actions support resource-level permissions.** Which resource an action authorizes against depends on the action:  
 **Branch actions** authorize against the branch ARN, `arn:aws:amplifygen3:_region_:_account-id_:app/app-name/environment/environment-name/branch/branch-name `. These actions are `GetBranch`, `DeleteBranch`, `ListApiKeys`, `GetApiKey`, `RevokeApiKey`, `GetRestoreWindow`, and `RestoreBranch`.
 **Environment actions** authorize against the environment ARN, `arn:aws:amplifygen3:_region_:_account-id_:app/app-name/environment/environment-name `. These actions are `ListBranches` and `CreateDeployment`.
 **Deployment actions** authorize against the deployment ARN. `GetDeployment` is one of them.
 **App actions** such as `DeleteBackendFromApp` and `ResumeBackend` authorize against the app.
Scope a grant to the resources that a principal needs, and separate environments that need different trust levels into different AWS accounts.

Amplify backends do not currently support:
+  **Resource-based policies.** You cannot attach a policy to a backend or branch, so cross-account access cannot be granted that way.
+  **Service-linked roles.** Amplify backends create no service-linked role in your account.

You do not supply an IAM role when you create or update a backend. Amplify does assume your environment’s role, to run your app and to write a deployment’s migration output to that app’s deployment log. You give that role to Amplify when you create or update the environment, and you need `iam:PassRole` on it. For more information, see [Cross-service confused deputy prevention](cross-service-confused-deputy-prevention.md).

## Backend identity-based policy examples
<a name="security_iam_backend_policy_examples"></a>

All examples name each action explicitly, with no `Action` wildcards. Least privilege means naming exactly the actions that a principal needs, and scoping `Resource` to the environment or branch that the principal works with, as the note above describes.

The `Resource` element takes one of two forms, and which one depends on the action:
+  **Backend control-plane actions** take the ARN of the environment, branch, or deployment that they act on, as the note above lists.
+  ** `amplifygen3:Connect` ** takes a branch ARN, `arn:aws:amplifygen3:_region_:_account-id_:app/app-name/environment/environment-name/branch/branch-name `. Amplify authorizes the action on the ARN of the branch a request or connection addresses, so naming one branch limits the grant to that branch. Use a wildcard in the ARN, for example `…​/environment/production/branch/*`, to cover several branches.

In each example, replace the following values with your own:
+  `111122223333` – your 12-digit AWS account ID
+  `us-east-1` – your AWS Region
+  `my-app`, `production` and `main` – your app, environment and branch names

 **Allow an application’s CI/CD role to deploy migrations, and nothing else.** This authorizes deployment only to the `production` environment of `my-app`:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DeployMigrations",
      "Effect": "Allow",
      "Action": [
        "amplifygen3:CreateDeployment",
        "amplifygen3:GetDeployment"
      ],
      "Resource": [
        "arn:aws:amplifygen3:us-east-1:111122223333:app/my-app/environment/production",
        "arn:aws:amplifygen3:us-east-1:111122223333:app/my-app/environment/production/*"
      ]
    }
  ]
}
```

 **Allow a read-only auditor to inspect backend and branch configuration without reading data or issuing credentials.** This is the case where action-level scoping is genuinely sufficient, because no action here can read a row or mint a credential:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AuditBackendConfigurationOnly",
      "Effect": "Allow",
      "Action": [
        "amplifygen3:ListBranches",
        "amplifygen3:GetBranch",
        "amplifygen3:ListApiKeys"
      ],
      "Resource": "arn:aws:amplifygen3:us-east-1:111122223333:*"
    }
  ]
}
```

 `amplifygen3:ListApiKeys` returns key **metadata** only. Retrieving any key’s value, including a secret key, requires `amplifygen3:GetApiKey`, which is deliberately excluded from the auditor policy above. `amplifygen3:GetBranch` and `amplifygen3:GetBackend` return no key value.

 **Allow a server-side role to call a backend’s data API as `service_role`.** A SigV4-signed request from a principal in the backend’s own account that holds `amplifygen3:Connect` is `service_role` on its own, so no key is involved. This bypasses row-level security on the branch the policy names, so attach it to those server-side roles alone:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowServiceRoleDataAccess",
      "Effect": "Allow",
      "Action": "amplifygen3:Connect",
      "Resource": "arn:aws:amplifygen3:us-east-1:111122223333:app/my-app/environment/production/branch/main"
    }
  ]
}
```

Make that request from server code with the Amplify backend client SDK, which signs it as that role. A signed request needs no API key; Amplify ignores one sent with it.

An identity-based policy only grants; it cannot stop a *different* principal that has its own grant. So if you want the organization-wide guarantee that **only** one role may act as `service_role`, the restriction has to live somewhere that applies across identities. Use a **service control policy** (SCP) on the account or organizational unit — this is an SCP, not an identity-based policy, and `aws:PrincipalArn` is meaningful here precisely because the policy is evaluated for every principal in scope:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OnlyTheDesignatedRoleMayActAsServiceRole",
      "Effect": "Deny",
      "Action": "amplifygen3:Connect",
      "Resource": "*",
      "Condition": {
        "ArnNotEquals": {
          "aws:PrincipalArn": "arn:aws:iam::111122223333:role/BackendDataPlaneServiceRole"
        }
      }
    }
  ]
}
```

A permissions boundary attached to the other roles achieves the same end if you would rather not use an SCP.

## Backend resource-based policy examples
<a name="security_iam_backend_resource_policy_examples"></a>

 **Not applicable.** Amplify backends do not support resource-based policies, so there is no policy you can attach to a backend or a branch. Control access to a backend with the identity-based policies shown above, and use separate AWS accounts to separate environments that need different trust levels.

## AWS managed policies for backend access
<a name="security_iam_backend_managed_policies"></a>

Amplify publishes no AWS managed policy specific to backend access. Write your own identity-based policies, as shown above. For the AWS managed policies Amplify does publish, see [AWS managed policies for AWS Amplify](security-iam-awsmanpol.md).

## The backend data-plane credentials, and what each one grants
<a name="security_iam_backend_credentials"></a>

A backend’s data API accepts four kinds of caller, which map to three PostgreSQL roles. **The difference matters more than any other security detail in this section.** 


| Credential | PostgreSQL role | Row-level security | Safe in a browser or mobile app? | 
| --- | --- | --- | --- | 
|  **Publishable key**  |  `anon`  |  **Enforced**  |  **Yes** — it is designed to be public | 
|  **Publishable key \+ end-user token**  |  `authenticated`  |  **Enforced**  | Yes | 
|  **SigV4-signed request** from a principal in the owning account with `amplifygen3:Connect`  |  `service_role`  |  **BYPASSED**  |  **No** — server-side only | 
|  **AWS Sign-In access token** (an `Authorization: Bearer` header carrying a token whose value begins `ASOA`) minted by a principal in the owning account with `amplifygen3:Connect`  |  `service_role`  |  **BYPASSED**  |  **No** — server-side only | 
+ A **publishable key** is safe to embed in client-side code. It grants only the `anon` role, and every query it makes is still subject to your row-level security policies. Its safety depends entirely on your policies being correct.
+ A **SigV4-signed request** is `service_role`, which **bypasses row-level security completely** and can read and write every row in every table, including the auth server’s administrative endpoints. Treat `amplifygen3:Connect` exactly as you would a database superuser grant: give it only to server-side roles, and use an explicit `Deny` on `amplifygen3:Connect` for any role that should not reach backend data. End users never sign requests; they use a publishable key plus their token.
+ An **AWS Sign-In access token** stands for the IAM principal that minted it, and Amplify authorizes it exactly like a signed request (`amplifygen3:Connect` in the account that owns the backend). Unlike a signature, which covers one request, a token is a bearer credential: anyone who holds it can replay it on any request that principal may make until it expires. It is `service_role` too, so keep it on servers. Use it where a client cannot sign each request; see [Calling a backend’s data API with an AWS Sign-In access token](#security_iam_backend_signin_token) below.
+ An `apikey` sent on a signed request is ignored, and the request needs none: the signature decides. A **secret key** therefore adds nothing, and on an unsigned request it is rejected. No backend operation mints one.

 **Key lifetime and revocation** 
+ API keys you create do not expire on a schedule. They remain valid until you revoke them with `amplifygen3:RevokeApiKey`.
+  **Revocation takes effect within five minutes.** Treat a compromised key as exposed for up to five minutes after you revoke it. To stop a principal’s `service_role` access, remove its `amplifygen3:Connect` permission; that takes effect typically within seconds as the IAM change propagates, for every backend and branch the removed grant covered. Revoking an API key does not affect signed requests.
+  **The same removal stops that principal’s Sign-In access tokens.** Amplify checks `amplifygen3:Connect` on every request a token makes, as it does for a signed request. A token cannot be revoked on its own; it stops working when it expires, at most one hour after it was minted.
+  **A deployment creates the branch’s publishable key.** A deployment creates a key when the branch has none, or when its key was revoked. To make a new key, run `aws amplifygen3 deploy --create-publishable-key`. The old key stays active until you revoke it with `aws amplifygen3 backend publishable-key revoke`.
+  **Revoking a branch’s only publishable key breaks anonymous access** until you create and deploy a replacement. To rotate, run `aws amplifygen3 deploy --create-publishable-key` first, move every client that holds the old key to the new one, then revoke the old key.
+  **A key’s value remains retrievable** through `amplifygen3:GetApiKey` after creation. Restrict that action accordingly — the auditor policy above shows how.

## Calling a backend’s data API with an AWS Sign-In access token
<a name="security_iam_backend_signin_token"></a>

AWS Sign-In issues these tokens for `amplifygen3.amazonaws.com` in all AWS Regions.

A server that cannot sign each request with SigV4 can present an AWS Sign-In access token instead. The principal that mints it needs `signin:CreateOAuth2Token`, and Amplify accepts the token only if that principal also has `amplifygen3:Connect`.

```bash
TOKEN="$(aws signin create-oauth2-token-with-iam \
    --grant-type client_credentials --resource amplifygen3.amazonaws.com \
    --query accessToken --output text)"
curl -H "Authorization: Bearer $TOKEN" "https://my-branch-endpoint/rest/my-table"
```
+ Send exactly one `Authorization` header, and do not also sign the request.
+ An `apikey` header is ignored, as it is on a signed request.
+ The token works only on backends owned by the AWS account of the principal that minted it, and only when minted for the resource `amplifygen3.amazonaws.com`.
+ Mint a new token before the old one expires (`expiresIn`, at most one hour). Never log it, put it in a URL, or send it to a browser.

A backend’s access logs record each request a token makes with `auth_method` set to `signin_token`. A request a backend served, or refused after confirming the caller is in your account, also carries the calling principal’s ARN in `auth_aws_principal`; a token that is expired, invalid, or from another account is logged without one.

## What a backend’s data API reveals beyond your rows
<a name="security_iam_backend_data_api_reveals"></a>

Row-level security decides which rows a caller reads. It does not hide everything about the rows it filters out, and a backend’s data API passes database errors through as PostgreSQL raises them:
+  **Counts are exact.** The data API refuses `Prefer: count=planned` and `Prefer: count=estimated` with `400` and the code `COUNT_NOT_SUPPORTED`. PostgreSQL computes those estimates from statistics over the whole table, including rows the caller cannot read, so they could show how many hidden rows match a filter. `Prefer: count=exact` counts only the rows the caller may read.
+  **Key conflicts.** A unique key is checked against every row in the table. An insert or an upsert with an explicit key that a hidden row already holds answers `409` with the code `WRITE_CONFLICT`, except for `service_role`. Give each table a key a caller cannot guess (for example `id uuid DEFAULT gen_random_uuid()`), and do not grant `INSERT` or `UPDATE` on the key column to `anon` or `authenticated`.
+  **Names.** An error names the table, column or type a request referred to, including a table the caller may not read. Do not put secrets in table, column or function names.

The `auth` schema is not on the data API’s search path. A function you write that calls `auth.uid()`, `auth.jwt()` or an `auth` table names the schema.

The data API serves only the `public` schema: a function there that a caller may execute can be called at `/rest/rpc/function-name `, a `SECURITY DEFINER` one included. Put a `SECURITY DEFINER` helper that a row-level security policy calls in a schema of your own (`CREATE SCHEMA private`, in a migration), and grant `USAGE` on that schema to the roles whose policies call it. The data API does not serve that schema. Amplify reserves the schema names `auth`, `extensions`, `realtime` and `storage`.

## Connecting directly to your backend database
<a name="security_iam_backend_direct_db"></a>

You can open a direct `psql` or driver connection to a branch’s database through Amplify’s PostgreSQL endpoint, signed in with your AWS identity; see [Connecting to your backend database with your AWS identity](#security_iam_backend_pg_endpoint). A connection authenticates as a database user dedicated to that one branch, and that user can connect only to that branch’s database.

 **A direct connection is owner-level access to the branch’s database** – The database user owns the tables your deployments create and bypasses row-level security, even on a table that sets `FORCE ROW LEVEL SECURITY`, so do not rely on a policy to limit what a direct connection reads or writes. Treat a direct connection like a `service_role` request:
+  **Use it only from server-side code or your own machine.** The credential you connect with is a database password. Never send it to a browser or mobile app.
+  **Verify the server certificate.** Connect with TLS and certificate verification (`sslmode=verify-full`, or `ssl: { rejectUnauthorized: true }` in `node-postgres`). The `aws amplifygen3 db` commands do this by default; if you build a connection yourself, do not turn it off.
+  **Change your schema through deployments, not over a direct connection.** Amplify applies your schema from a backend’s deployments. Use an ORM on a direct connection for queries only, and do not run its migration or schema-sync commands against a branch.

## Connecting to your backend database with your AWS identity
<a name="security_iam_backend_pg_endpoint"></a>

You connect to a branch’s database through Amplify’s PostgreSQL endpoint, ` branch-id.db.amplify.app` on port 5432, with your own AWS identity. The endpoint checks an AWS Sign-In access token minted with your AWS credentials, then authorizes `amplifygen3:Connect`, so you can grant access by AWS identity. Minting the token needs `signin:CreateOAuth2Token`. Log in as the branch’s database user and database, which `aws amplifygen3 db token` reports.

 **Connect with `sslmode=verify-full sslrootcert=system` ** – This is what the `aws amplifygen3 db` commands use, and it is the setting to give any other client:
+ The endpoint refuses a connection that does not start TLS, before it asks for a password, so no `sslmode` sends your token in plaintext. `sslmode=disable` fails. `prefer` and `allow` end up on TLS, but without verifying the certificate, the same as `require`.
+  `sslmode=require`, `prefer` and `allow` are not enough. They encrypt the connection but do not check who is on the other end, so anyone who can intercept your network traffic can present their own certificate, receive your token as the password, and use it to open every branch your identity may open until it expires. `verify-full` checks that the certificate is valid for the host name you connected to, so the token is only sent to the endpoint.
+  `sslrootcert=system` verifies the endpoint against your operating system’s trust store and needs libpq 16 or later. Drivers that are not built on libpq verify against the system roots when verification is on (in `node-postgres`, `ssl: { rejectUnauthorized: true }`). On Windows, some PostgreSQL client builds have no default trust store, so `system` fails there; set `sslrootcert` to a file holding the Amazon Trust Services root certificates (https://www.amazontrust.com/repository/) instead.

The endpoint limits failed logins from one network address: after repeated refused tokens, logins for another account’s branch, or logins to a branch that does not exist, it closes new connections from that address for a short time before TLS. A client that keeps retrying a bad or expired credential can lock out other clients behind the same address (a NAT) until it stops; fix the credential rather than retrying in a loop.

The endpoint cannot tell whether your client verified its certificate, so this setting is your responsibility.
+  **With the AWS CLI.** `aws amplifygen3 db connect` opens `psql` on the branch signed in with your AWS identity, passing a token it mints as the password. Name the branch with `--app` and `--env`, or with `--branch-arn branch-arn `. `--print` shows the connection command instead of running it, and `--service service-name ` saves the connection as a `pg_service.conf` entry for any libpq tool; neither prints or saves a token, and both carry `sslmode=verify-full sslrootcert=system`.
+  **With any PostgreSQL client, passing the token as the password.** Mint a token for Amplify and use it as the password:

  ```bash
  export PGPASSWORD="$(aws signin create-oauth2-token-with-iam \
      --grant-type client_credentials --resource amplifygen3.amazonaws.com \
      --query accessToken --output text)"
  psql "host=my-branch-id.db.amplify.app port=5432 user=my-db-user dbname=my-database \
      sslmode=verify-full sslrootcert=system"
  ```

  The token opens new connections until it expires; mint another for connections after that. A connection already open stays open, up to the endpoint’s session limit.

A Sign-In access token is a bearer credential: anyone who holds it can open every branch your identity may open, until it expires. Mint it where you use it, and never send it to a browser or a server you do not trust.

## Logging PostgreSQL endpoint connections with AWS CloudTrail
<a name="security_iam_backend_pg_cloudtrail"></a>

Amplify’s PostgreSQL endpoint records connections to your branches as AWS CloudTrail **data events**. CloudTrail does not log data events by default. To receive them, add an advanced event selector for the resource type `AWS::AmplifyGen3::Branch` to a trail or an event data store in the AWS account that owns the branch.

Each event has the event source `amplifygen3.amazonaws.com` and the event name `DbConnect`, names the branch’s ARN as its resource, and records the following:
+  `userIdentity` – the AWS identity the access token was minted for.
+  `sourceIPAddress` – the address your client connected from.
+  `requestParameters` – the `database` and `user` the client asked to log in as. The event never records the token or any other credential.
+  `additionalEventData` – the kind of credential the client presented and how it connected.

The endpoint records one event per connection, when it decides the connection’s outcome, and none when a session ends.


| Outcome |  `errorCode`  | 
| --- | --- | 
| The login was admitted. The event is recorded once the database accepts it. | None | 
| The identity may not connect to the branch: it lacks `amplifygen3:Connect` on the branch’s ARN, or it belongs to another AWS account. |  `AccessDenied`  | 
| The client asked for a database other than the branch’s. |  `ValidationException`  | 

 **What is not recorded** – An event needs an AWS identity to attribute, so a connection whose credential does not authenticate (a malformed, expired, or wrong token) gets **no** event, even though it named your branch. Neither does a connection the endpoint refuses for rate limiting, a connection to a branch with no running database (for example, a paused backend), or a connection that fails on Amplify’s side. Do not read the absence of `DbConnect` events as the absence of connection attempts.

## Troubleshooting backend identity and access
<a name="security_iam_backend_troubleshoot"></a>


| Symptom | Likely cause | 
| --- | --- | 
|  `AccessDeniedException` from a backend control-plane call | The calling principal lacks the `amplifygen3:` action. | 
|  `ResourceNotFoundException` for a backend you know exists | The backend belongs to a different AWS account from the one that signed the request. | 
| HTTP 403 before Amplify responds | The request was not SigV4-signed, or the AWS credentials used to sign it have expired. | 
| HTTP 403 on a SigV4-signed request to a backend’s data API | The request was signed by a principal in an AWS account other than the one that owns the backend. Sign with credentials from the owning account. | 
| HTTP 401 from a backend’s data API, "No apikey was sent." | The request carried no API key, or an empty one. Send the backend’s publishable key in the `apikey` header, or sign the request with SigV4. | 
| HTTP 401 from a backend’s data API, "The apikey is not a valid key for this backend." | The API key is for a different branch, has been revoked, or has been superseded. | 
| A secret key returns 401 on the data API | The request was not SigV4-signed. A secret key grants nothing on its own; sign the request instead (it then needs no key). | 
| HTTP 401 with more than one `Authorization` header | Send exactly one: either a SigV4 signature or a `Bearer` token. | 
| HTTP 401 or 403 with a `Bearer` token whose value begins `ASOA`  | The token has expired, was minted for a resource other than `amplifygen3.amazonaws.com`, or is not one AWS Sign-In issued. Mint a new one with `--resource amplifygen3.amazonaws.com`. | 
| HTTP 403 with a freshly minted `amplifygen3.amazonaws.com` token | The minting principal lacks `amplifygen3:Connect`, belongs to an AWS account other than the one that owns the backend, or the branch is not ready to serve yet. | 
|  `ValidationException` (`invalid_target`) from `create-oauth2-token-with-iam`  | AWS Sign-In does not issue tokens for that `--resource` to your account. Use `amplifygen3.amazonaws.com`, which Sign-In issues tokens for in all AWS Regions. | 
| Queries fail or return no rows with a publishable key, but work with a SigV4-signed request | Working as designed. A new table is reachable through a backend’s data API only after you `GRANT` it to the role, and Amplify enables RLS on it with **no policy**, which denies all rows until you add one. You need both the grant and a policy. | 

## Using service-linked roles for Amplify backends
<a name="security_iam_backend_slr"></a>

 **Not applicable.** Amplify does not create or use a service-linked role in your account for backend management.

## End-user sessions
<a name="security_iam_backend_end_user_sessions"></a>
+ A session created with "remember me" off lasts one day, and an impersonation session started through the auth admin API lasts one hour. Neither is extended by use, whatever cookies the request carries. A remembered session lasts `session.expiresIn` (seven days by default) and is extended while it is used.
+  `POST /auth/revoke-session` and `POST /auth/admin/revoke-session` accept the session’s token or its `id` (both are in the session list). They answer HTTP 404 when the value names no session, or, on `/auth/revoke-session`, a session of another user. Check for the 404: a 404 means nothing was signed out.
+ Signing a user out everywhere, banning them or removing them also ends every session they started as another user.

## Responding to a backend security incident
<a name="security_iam_backend_incident_response"></a>

 **Detection** – Connections through Amplify’s PostgreSQL endpoint are recorded as `DbConnect` data events (see [Logging PostgreSQL endpoint connections with AWS CloudTrail](#security_iam_backend_pg_cloudtrail)). Watch them for an identity or source address you do not expect, and for a run of `AccessDenied` events against a branch.

If you believe a backend credential is compromised:

1. Revoke the affected API keys with `amplifygen3:RevokeApiKey`, remembering that revocation takes effect within five minutes.

1. If AWS credentials for a principal with `amplifygen3:Connect` were exposed, **remove its `amplifygen3:Connect` permission** (and rotate the credentials), because a signed request from it is `service_role`. This takes effect as the IAM change propagates, typically within seconds. The removal covers every branch the grant names; to cut off one branch only, add an explicit `Deny` of `amplifygen3:Connect` on that branch’s ARN instead.

1. If a credential for a direct database connection may have been exposed, note that a connection already opened with it stays open after the credential expires. Remove the principal’s `amplifygen3:Connect` permission to stop new connections through the PostgreSQL endpoint, and terminate any unexpected sessions from inside the database (for example with `pg_terminate_backend`).

1. Review your row-level security policies — a compromised `anon` key is only as damaging as your policies allow.

## Backend configuration and vulnerability analysis
<a name="security_iam_backend_config_vuln"></a>

Configuration and IT controls are a shared responsibility between AWS and you.

 ** AWS is responsible for:** 
+ Patching and updating the managed runtime that serves a backend — the REST layer, the authentication server, and the underlying operating system and virtual-machine image. You do not manage a guest operating system, and there is nothing for you to patch in an Amplify managed runtime.
+ Patching the managed database engine. Amazon Aurora maintenance is applied by AWS.
+ Scanning Amplify’s own code and dependencies for vulnerabilities.

 **You are responsible for:** 
+ The SQL you deploy — your schema, functions, triggers, and especially your **row-level security policies**. Amplify cannot tell whether your policies express your intent. A missing policy denies access, but an overly broad one grants it.
+ Any application code and dependencies you run against a backend.
+ The client libraries you use to call a backend, and keeping them current.
+ How you store and distribute the credentials Amplify issues you.
+  **Your local development environment.** The local Amplify backend stack (`aws amplifygen3 local run`) is published to `127.0.0.1` only and treats any SigV4-signed request as `service_role` without verifying the signature — any process that can reach the local port gets full administrative access to the local database. The local stack refuses a SigV4-signed request that a web page on another origin sends to it, but that does not stop every page: a page served from the local stack’s own address, or one whose requests your development server proxies to the local stack, may still get `service_role`. Sign requests only from server-side code, never in browser code. The local GUI that `aws amplifygen3 local run` starts (at the URL it prints, usually `http://localhost:54323`) is the same: anyone who can reach it can run any SQL against your local database and read your local database password, and, when your auth config references any `${env:NAME}`, the values in `.secrets/client_secrets.env`. **Never expose a local backend gateway or the local GUI on a routable network address**, and keep real user data and production secrets out of a local stack. If you run the local image yourself rather than through `aws amplifygen3 local run`, publish every port only to `127.0.0.1` (for example `-p 127.0.0.1:8443:8443`), since a port published without an address is reachable from your network. The local GUI listens only inside the container unless you set `LOCAL_GUI_BIND=0.0.0.0`; set it only together with a `127.0.0.1` publish (`-e LOCAL_GUI_BIND=0.0.0.0 -p 127.0.0.1:54323:54323`).
+  **Verifying the local image.** `aws amplifygen3 local run` checks the local image’s signature only when the `notation` CLI and its AWS Signer plugin are installed; without them it warns and runs the image unverified. Install both to have every run checked, and do not pass `--no-verify-image-signature` or name another image with `AWS_AMPLIFY_LOCAL_IMAGE` unless you trust where it comes from.
+  **The origins you trust locally.** The local stack admits browser requests, with credentials, from every origin in your `backend.auth` `trustedOrigins`, including on its management endpoints. List only origins you control, never a wildcard such as `https://*` (it admits every HTTPS site), and review the `trustedOrigins` of any project you clone before running `aws amplifygen3 local run`.
+  **Web pages you open while the local stack runs.** A malicious page can point a DNS name it controls at `127.0.0.1` (DNS rebinding) and reach the local gateway from your browser; the local GUI refuses such requests, but not pages served from another port on `localhost`. Stop the local stack (`aws amplifygen3 local stop`) when you are not using it.

 **Updates** – Amplify applies runtime updates to a backend without requiring action from you; there is no maintenance window for you to set and no opt-out. Updates are applied progressively, and a branch picks up a new runtime version when its virtual machine is next started.

 **Penetration testing** – If you want to conduct security testing against your own backend, follow the [AWS Customer Support Policy for Penetration Testing](https://aws.amazon.com/security/penetration-testing/).

## Backend security best practices
<a name="security_iam_backend_best_practices"></a>

The following best practices are general guidelines and don’t represent a complete security solution. Because these best practices might not be appropriate or sufficient for your environment, treat them as helpful considerations rather than prescriptions.

### Backend production checklist
<a name="security_iam_backend_best_practices_checklist"></a>

Before real users sign in to your app, check each of the following items for the `production` environment. Each item links to the page that explains it.
+  **Keep row level security on for every table.** Amplify turns on row level security (RLS) for each new table, and a table with no policy returns no rows. Write each table’s grants and policies in the migration that creates it, and never turn RLS off or write `USING (true)` on users' data. To find a `public` table that `anon` or `authenticated` can reach with RLS off, run `aws amplifygen3 db lint --env production --fail-on error`. Test each policy through the Data API, signed in and signed out. See [Secure your data](backend-rls.md).
+  **Trust only origins that you control.** Your backend already trusts its environment’s URL, custom domains, and recent preview URLs, so list in `trustedOrigins` only the origins that Amplify doesn’t host. Keep any wildcard inside a domain that you own, such as `https://*.example.com`, because a deployment refuses a wildcard over hosts that others own. See [Auth configuration](backend-auth-config.md).
+  **Send auth email through your own SMTP server.** By default, a deployed backend sends auth email from a shared no-reply address, with a daily limit for each AWS account and Region. Set `platform.customEmail.smtp` in `backend.auth` to send from your own address with your own templates, without that limit. Store the SMTP user name and password as backend secrets. See [Auth emails](backend-auth-email.md).
+  **Decide whether users must verify their email address.** Verification is off by default, so sign-up accepts any address and signs the user in at once. If your app relies on a user’s address, set `requireEmailVerification` to `true` in `emailAndPassword`. In a policy, trust `auth.email()` only together with the token’s `email_verified` claim. See [Email and password](backend-auth-password.md).
+  **Keep `service_role` on your servers.** Give `amplifygen3:Connect` only to server-side roles, and never put AWS credentials in browser code, a mobile app, or a commit. If a principal’s credentials leak, remove its `amplifygen3:Connect` permission and rotate the credentials. See [Permissions for your app](add-IAM-roles.md).
+  **Know how to replace and revoke your publishable key.** To replace the key, deploy with `aws amplifygen3 deploy --env production --create-publishable-key`. Then give the new key to every client that you ship separately, and revoke the old key. Revoking the key that your live deployment uses breaks your app until the next deployment. See [API keys and roles](backend-keys.md).
+  **Set how long production keeps backups.** A new backend keeps 1 day of backups. Set `backupRetentionDays` to the days that you need, from 1 to 35 and within your plan’s limit. Set it for `production` in the `env.production.backend.database` block of `amplify.jsonc`, or with `aws amplifygen3 env edit --env production --backup-retention-days 7`. The next deployment applies it. Before a risky migration, save a copy with `aws amplifygen3 db dump`. See [Backups and restore](backend-backups.md).

### Preventative
<a name="security_iam_backend_best_practices_preventative"></a>

 **Write a row-level security policy for every table, and test it with the `anon` role** *Why:* your publishable key is public by design, so RLS is the only thing standing between an anonymous caller and your data. A new table is not exposed through a backend’s data API until you `GRANT` it, and Amplify enables RLS on it with no policy, which denies every row — so the dangerous moments are the grant and your first permissive policy. Test every policy as `anon` and as `authenticated`, not as `service_role`.

 **Never give `amplifygen3:Connect` to a role an end user or client-side code can use, and never put AWS credentials that hold it in client-side code, a mobile app, or a source repository.** *Why:* a signed request is `service_role`, which bypasses row-level security entirely and can read and write every row in your database. Prefer a publishable key plus an end-user token, and sign requests only from trusted server-side work.

 **Restrict `amplifygen3:Connect` and `amplifygen3:GetApiKey` to a single dedicated role** *Why:* these actions grant or retrieve credentials that bypass your data-access controls. Grant them separately from ordinary deployment permissions.

 **Rotate a publishable key that leaks** *Why:* you can revoke any publishable key, but revoke it only after you deploy a new one, or the running app loses anonymous access.

 **Scope `amplifygen3:Connect` to the branches a principal needs** *Why:* the PostgreSQL endpoint and the data API authorize it on the branch’s ARN, and a grant on `*` opens every branch in your account as `service_role`.

 **If your app must not reveal which email addresses have an account, require email verification (`emailAndPassword.requireEmailVerification`) or turn off `emailAndPassword.autoSignIn`.** *Why:* by default a sign-up signs the new user in, so a sign-up for an address that already has an account is refused with `USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL`. With either setting, that sign-up gets the same answer as a new one. Sign-in and password reset give the same answer for any address, and Amplify sends their email after it answers. So does the verification resend, so it answers the same for any address even while sending fails. A resend whose email could not be sent still answers as a sent one, so tell a user who gets no email to ask again after a minute or two, and to try later if it still does not arrive.

 **Tell users to check for an earlier email before asking for another** *Why:* Amplify emails a password reset, or a verification link from a resend or a refused sign-in, to one address at most about once a minute, so nobody can flood a user’s inbox or spend your daily email quota with repeat requests. A repeat inside that window gets the same answer as a sent one, and the link in the earlier email still works.

Amplify also limits the auth emails that any caller can request for one address. When `rateLimit` is on, which is the default on a deployed backend, the backend accepts at most 5 requests for auth emails to one address in a one-minute window. The window starts at its first request, and until it ends the backend refuses any more with a `429` error. A request counts even when no email goes out, such as one for an address that has no account. The verification emails that sign-up and password sign-in send and the account deletion email don’t count toward it, and two-factor codes have a count of their own. The refusal carries the code `over_request_rate_limit` and an `X-Retry-After` header, and nothing is sent. The code or link that was already sent stays valid. Setting `rateLimit.enabled` to `false` turns this limit off together with the limits on requests from each client address, but leaves the one-minute wait on. For this and the other auth limits, see [Quotas](quotas-chapter.md).

 **Use a separate backend, not just a separate branch, to isolate environments with different trust levels.** *Why:* branches within a backend each have their own database cluster, but they share a credential surface. A separate backend is the stronger boundary.

 **Never log the auth session, an access token, or the user record, including to the browser console.** *Why:* the session’s `access_token` is a bearer credential for a backend’s data API until it expires, and the user record carries the user’s email. Browser extensions, error-reporting tools and client-side telemetry often keep what the console prints. To trace sign-in, log the auth event name and, if you need it, the user id.

 **Keep third-party script off your app’s root page.** *Why:* a sign-in that leaves your page, such as the managed sign-in page, returns to your app’s root with a single-use code in its address. Script on that page can read the code until the client SDK spends it. For more information, see [User sessions](backend-auth-sessions.md).

 **Set `advanced.crossSubDomainCookies.domain` only to your branch’s own host or to a domain you own above a custom domain.** *Why:* every branch host sits under a domain other customers' branches share, so a cookie scoped there would reach their branches too. A deployed branch whose `domain` is above its host, is a public suffix (such as `amplifyapp.com`), or names no host it answers on, does not start its auth server; the error names the domain.

 **Encrypt sensitive fields client-side before storing them** *Why:* Amplify supports no customer-managed key for backend data, so client-side encryption is the only way to hold the key to your most sensitive data yourself.

 **Never expose a local development gateway or the local GUI on a routable address** *Why:* the local stack treats a SigV4-signed request as `service_role` without verifying the signature (it refuses one only when a web page on another origin sends it), so reaching the gateway port is equivalent to holding `service_role`, and reaching the local GUI’s port lets a caller run any SQL against the local database.

### Detective
<a name="security_iam_backend_best_practices_detective"></a>

 **Log and alarm on credential-retrieving API calls** — `amplifygen3:GetApiKey`. *Why:* these are the calls that precede data exfiltration, and they are rare in normal operation, so they alarm cleanly.

 **Alarm on destructive control-plane calls** — `amplifygen3:DeleteBackendFromApp`, `amplifygen3:DeleteBranch`, `amplifygen3:RevokeApiKey`. *Why:* an unexpected delete is either a mistake or an attack, and both need immediate attention.

 **Log `DbConnect` data events for your branches, and alarm on unexpected identities and on runs of `AccessDenied` ** — see [Logging PostgreSQL endpoint connections with AWS CloudTrail](#security_iam_backend_pg_cloudtrail). *Why:* a connection through the PostgreSQL endpoint is direct database access, and these events are the record of who opened one and from where.

 **Review who holds backend `amplifygen3:` permissions on a schedule**, using IAM Access Analyzer to remove unused grants. *Why:* backend credentials are long-lived, so accumulated permissions are accumulated risk.

 **Monitor a backend’s query and error telemetry** for unexpected access patterns — a spike in `anon`-role queries, or queries against tables your application does not use, can indicate a leaked publishable key being explored.

 **Use AWS Security Hub** to check your environment against security industry standards and best practices.