> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tenetlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy on ECS with CloudFormation

> One CloudFormation template deploys the image into an existing no-NAT VPC: KMS key, Aurora vault, Object Lock audit bucket, VPC endpoints, VPC Lattice services with per-route IAM auth policies, and detect and rehydrate on ECS (Graviton).

**The CloudFormation template** (`tenet-pii-enterprise.yaml`): one stack → a customer-managed KMS key, an Aurora PostgreSQL Serverless v2 vault, the VPC endpoints, an ECS cluster on `c9g.xlarge`, and the detect and rehydrate services, each behind its own Amazon VPC Lattice service whose IAM auth policy names your caller roles per route.

## When to use it

You want ECS rather than EKS, and you want everything created and wired for you. It deploys into an **existing** VPC with private subnets and no NAT. Use the [Terraform module](https://docs.tenetlabs.com/pii-engine/deploy/terraform.md) for the same shape in Terraform.

Deploy the CloudFormation stack — collects parameters, runs preflight checks, and stops for approval before creating anything.

Deploy Tenet PII Engine (Enterprise) on ECS with its CloudFormation template, following [https://docs.tenetlabs.com/pii-engine/deploy/ecs-cloudformation](https://docs.tenetlabs.com/pii-engine/deploy/ecs-cloudformation.md).

Ask me for: stack name; Region; whether this is production or a trial; VpcId and VpcCidr; one private subnet per AZ (≥ 2) and their route table ids; KeyAdminRoleArn (the role that runs the stack), or KmsKeyArn if I bring my own key; ImageUri (the Marketplace image by digest, from the verified release record, in every Region — never a copy); DeploymentId (3–63 chars, lowercase letters/digits/hyphens, never changes); the IAM role ARNs of the applications that call detect (DetectInvokerRoleArns), that may re-identify (RehydrateInvokerRoleArns) and that may erase sessions (ErasureInvokerRoleArns, optional); other caller VPCs (AllowedSourceVpcIds, optional); whether rehydration needs an approval tag; optional AuditReaderRoleArn, BreakGlassTrustedPrincipalArn, AlarmTopicArn; whether the VPC already has private-DNS endpoints (then CreateVpcEndpoints=false) or is already associated with a VPC Lattice service network (then ExistingServiceNetworkArn); an S3 bucket I own in the Region for the template upload; whether to enable rehydration.

Download the template with `curl -sO https://platform.tenetlabs.com/enterprise/current/tenet-pii-enterprise.yaml`. Preflight (read-only): outside us-east-1, the role that runs the stack may create cross-Region VPC endpoints (`vpce:AllowMultiRegion`; Administrator and PowerUser roles can); the VPC has DNS hostnames and DNS support enabled (`aws ec2 describe-vpc-attribute`); the account's On-Demand Standard vCPU quota allows at least 8 vCPUs (12 with rehydration); no route table for the subnets routes to a NAT or internet gateway; every subnet's AZ ID supports VPC Lattice (e.g. use1-az3 does not); `c9g.xlarge` is offered in the Region (else InstanceType=c8g.xlarge); `aurora-postgresql` 16.15 is offered (else ask me for AuroraEngineVersion); every invoker ARN is an IAM role ARN (`arn:aws:iam::<account-id>:role/...`), not a user, root or wildcard; I am running as KeyAdminRoleArn (`aws sts get-caller-identity`); with an existing KmsKeyArn, its key policy already has the CloudWatchLogs statement from the page. Look up S3PrefixListId and LatticePrefixListId with `aws ec2 describe-managed-prefix-lists`.

Show me the complete `aws cloudformation deploy` command with `--s3-bucket`, `--capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND` and every parameter. For production use AuditObjectLockMode=COMPLIANCE, AuroraDeletionProtection=true, VaultDeletionPolicy=Snapshot. For a trial use AuroraDeletionProtection=false VaultDeletionPolicy=Delete AuditObjectLockMode=GOVERNANCE. STOP and wait for my explicit approval before deploying; COMPLIANCE mode cannot be undone for the retention period.

After CREATE\_COMPLETE: print the stack outputs; check both ECS services reach their desired count and every target in the detect and rehydrate Lattice target groups is HEALTHY (`aws vpc-lattice list-targets`). Tell me which roles need the DetectCallerPolicy or RehydrateCallerPolicy output attached and which workloads need LatticeClientSecurityGroupId; ask before attaching anything. Then, from a host inside the VPC running as an invoker role, run one signed /deidentify → /reidentify round trip with the tenet-pii-lattice client and read the newest audit object. If the stack fails, read `aws cloudformation describe-stack-events` and match the error against [https://docs.tenetlabs.com/pii-engine/troubleshooting](https://docs.tenetlabs.com/pii-engine/troubleshooting.md) before retrying.

## What it creates

| Area | Resources | Toggle |
| - | - | - |
| Caller auth | A VPC Lattice service network associated with `VpcId`; a detect and a rehydrate service with HTTPS listeners, exact per-route rules and IAM auth policies naming your roles per route; access logs to `/<NamePrefix>/lattice`; a client security group for callers. No secrets. | `ExistingServiceNetworkArn` |
| Keys | Customer-managed KMS key and alias. The key policy names only this account's roles. | `KmsKeyArn` empty = create |
| Vault | Aurora PostgreSQL Serverless v2, writer and reader, storage and master secret encrypted with the CMK | `CreateVaultDatabase` |
| Compute | ECS cluster; ASG of `c9g.xlarge` on the ECS-optimized AL2023 arm64 AMI; capacity provider with managed scaling; IMDSv2 hop limit 1; `ECS_AWSVPC_BLOCK_IMDS=true` | — |
| Detect | Task definition (4096 CPU, 3072→4096 MiB), ≥ 2 tasks spread across AZs, CPU target tracking at 60%, registered in the detect Lattice target group (HTTPS, health-checked on `/readyz`). Erasures audited to the audit bucket. | `EnableDetectAutoScaling` |
| Rehydrate | Task definition, 2 tasks, its own Lattice service and target group | `EnableRehydration` |
| Audit | S3 bucket with Object Lock and SSE-KMS (CMK): reidentify records under `AuditPrefix`, erasure records under `ErasureAuditPrefix` | `ExistingAuditBucketName` |
| IAM | Detect and rehydrate task roles, a separate execution role for each, the ECS Lattice infrastructure role, instance role, optional break-glass role | — |
| Network | Endpoint, instance, task, DB, Lattice association and client security groups. Task SGs admit 19991 only from the Lattice prefix list. Egress is explicit, never `0.0.0.0/0` (except the opt-in telemetry rule). | — |
| Endpoints | S3 gateway; interface `kms`, `logs`, `secretsmanager`, `sts`, `metering-marketplace`, `ecr.api`, `ecr.dkr`, `ecs`, `ecs-agent`, `ecs-telemetry`; optional `ssm`/`ssmmessages`/`ec2messages`. The image comes from AWS Marketplace in `us-east-1`, so `ecr.api` and `ecr.dkr` always point at `us-east-1`; outside `us-east-1` they're cross-Region (PrivateLink) and a `us-east-1` `s3` interface endpoint, limited to the Marketplace layer bucket, carries the image layers. | `CreateVpcEndpoints`, `EnableSsmEndpoints` |
| Logs | `/<NamePrefix>/detect`, `/<NamePrefix>/rehydrate`, `/<NamePrefix>/lattice`, CMK-encrypted, finite retention; an alarm when usage can't be reported to AWS Marketplace | `AlarmTopicArn` |

## Deploy

Download the template:

```bash theme={null}
curl -sO https://platform.tenetlabs.com/enterprise/current/tenet-pii-enterprise.yaml
```

Before you deploy: [subscribe and verify the release](https://docs.tenetlabs.com/pii-engine/get-started/marketplace.md), use a VPC with DNS hostnames and DNS support enabled (the interface endpoints' private DNS needs both), and check your On-Demand Standard vCPU quota — each detect task fills a `c9g.xlarge`, so the default stack needs 8 vCPUs, 12 with rehydration. `ImageUri` is the Marketplace image from the release record, by digest, in every Region — don't copy it. Outside `us-east-1` the stack creates cross-Region endpoints to reach it, so the role that runs the stack needs `vpce:AllowMultiRegion`; Administrator and PowerUser roles already have it ([The image in every Region](https://docs.tenetlabs.com/pii-engine/get-started/marketplace.md#the-image-in-every-region)).

The template is over CloudFormation's inline size limit, so `$TEMPLATE_BUCKET` must be an S3 bucket you own in the deployment Region. Run the deploy **as `KeyAdminRoleArn`** — while the stack builds Aurora and its secret, that role needs `CreateGrant` and data-key access through RDS and Secrets Manager, which the key policy grants only via `kms:ViaService`.

```bash theme={null}
pl() { aws ec2 describe-managed-prefix-lists --filters Name=prefix-list-name,Values=com.amazonaws.$AWS_REGION.$1 \
  --query 'PrefixLists[0].PrefixListId' --output text; }
IMAGE_URI="<repository>@sha256:<digest>"   # the digest from the verified release record

aws cloudformation deploy \
  --stack-name tenet-pii \
  --template-file tenet-pii-enterprise.yaml \
  --s3-bucket "$TEMPLATE_BUCKET" \
  --capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND \
  --parameter-overrides \
    VpcId=vpc-0123 VpcCidr=10.0.0.0/16 \
    PrivateSubnetIds=subnet-a,subnet-b,subnet-c PrivateRouteTableIds=rtb-a,rtb-b,rtb-c \
    S3PrefixListId=$(pl s3) LatticePrefixListId=$(pl vpc-lattice) \
    KeyAdminRoleArn=arn:aws:iam::<account-id>:role/PlatformAdmin \
    ImageUri="$IMAGE_URI" \
    DeploymentId=acme-prod-use1 \
    AuroraEngineVersion=16.15 \
    DetectInvokerRoleArns=arn:aws:iam::<account-id>:role/claims-app \
    RehydrateInvokerRoleArns=arn:aws:iam::<account-id>:role/claims-reviewer \
    ErasureInvokerRoleArns=arn:aws:iam::<account-id>:role/claims-retention-job \
    BreakGlassTrustedPrincipalArn=arn:aws:iam::<account-id>:role/IncidentResponse \
    AuditObjectLockMode=COMPLIANCE
```

* **`CAPABILITY_AUTO_EXPAND` is required.** The template uses the `AWS::LanguageExtensions` transform (so `VaultDeletionPolicy` can set the Aurora cluster's `DeletionPolicy`). Without it the deploy fails before creating anything.
* **Trial stack** you'll delete: add `AuroraDeletionProtection=false VaultDeletionPolicy=Delete AuditObjectLockMode=GOVERNANCE`.
* **Detection only:** `EnableRehydration=false`. No rehydrate service, task or execution role, or Lattice service is created. The audit bucket still is — detect audits erasures.

## Callers

Each workload that calls the services needs four things:

1. **Its IAM role in the right list:** `DetectInvokerRoleArns` (`POST /detect`, `/redact`, `/deidentify`), `ErasureInvokerRoleArns` (`DELETE /sessions/{session_id}`) or `RehydrateInvokerRoleArns` (`POST /reidentify`). The auth policies name exactly these roles, per path and method. Entries must be IAM role ARNs; the runtime refuses users, root and wildcards at startup.
2. **The `DetectCallerPolicy` or `RehydrateCallerPolicy` output attached to that role** as an identity policy (`vpc-lattice-svcs:Invoke` on the service). A same-account caller needs both this and the auth policy; either alone is a `403`.
3. **A network path:** attach the `LatticeClientSecurityGroupId` output to the workload, or allow egress tcp/443 to the `com.amazonaws.<region>.vpc-lattice` prefix list.
4. **Signed requests:** SigV4, service `vpc-lattice-svcs`, the stack's Region, header `x-amz-content-sha256: UNSIGNED-PAYLOAD`, over HTTPS to `DetectEndpoint` or `RehydrateEndpoint`. The `tenet-pii-lattice` client does this (`pip install https://platform.tenetlabs.com/enterprise/current/tenet_pii_lattice.tar.gz`; Python 3.11+, `boto3`); plain botocore `SigV4Auth` works too. Reuse connections — each new connection pays a TLS handshake.

With `RequireRehydrateApprovalTag=true`, a reidentify call must come from a role session tagged `tenet-approval-id`; your approval workflow sets it when it assumes the invoker role, and Lattice checks it on every call. Also put the approval id in the `RoleSessionName`: Lattice access logs record principal tags only on **denied** requests, while every audit record carries the caller's role session ARN. `requestId` in `/<NamePrefix>/lattice` matches `upstream_request_id` in the audit record.

Callers in another VPC need that VPC associated with the service network (`ServiceNetworkArn` output) and listed in `AllowedSourceVpcIds`. Callers in another account need the service network or the services shared with AWS RAM, and their roles listed by ARN. The full model: [Rehydration and audit](https://docs.tenetlabs.com/pii-engine/concepts/rehydration-and-audit.md).

## Outputs

| Output | Use |
| - | - |
| `DetectEndpoint` | `https://<service>.vpc-lattice-svcs.<region>.on.aws` — detect, redact, de-identify, erase. In-VPC only. |
| `RehydrateEndpoint` | The rehydrate service; callers must be in `RehydrateInvokerRoleArns`. Only with rehydration. |
| `LatticeClientSecurityGroupId` | Attach to every caller: its only egress is 443 to VPC Lattice. |
| `DetectCallerPolicy` | Identity policy (JSON) for each role in `DetectInvokerRoleArns` and `ErasureInvokerRoleArns`. |
| `RehydrateCallerPolicy` | Identity policy for each role in `RehydrateInvokerRoleArns`. Only with rehydration. |
| `ServiceNetworkArn` | Associate other caller VPCs with it, or share it with AWS RAM. |
| `DetectServiceArn`, `RehydrateServiceArn` | The Lattice services. |
| `KmsKeyArn`, `AuditBucket`, `VaultEndpoint`, `ClusterName`, `DeploymentId` | For operations and the other pages. |
| `DetectTaskRoleArn`, `RehydrateTaskRoleArn`, `BreakGlassRoleArn` | IAM wiring and key policies. |

## Parameters

> [accordion] Naming
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `NamePrefix` | `tenet-pii` | Lowercase, ≤ 21 chars. |
> | `DeploymentId` | — | Required. `^[a-z0-9][a-z0-9-]{2,62}$` → `TENET_DEPLOYMENT_ID`. Pinned as `tenet:deployment` in every KMS condition. Never change it on an existing vault. |

> [accordion] Caller auth: IAM through VPC Lattice
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `LatticePrefixListId` | — | Required. `com.amazonaws.<region>.vpc-lattice`. Task SGs admit 19991 only from it. |
> | `ExistingServiceNetworkArn` | empty = create | A VPC can join only one service network. If `VpcId` already has one, give its ARN; you then own its VPC associations and auth policy. |
> | `AllowedSourceVpcIds` | empty = `VpcId` | VPCs whose callers may reach the services (`vpc-lattice-svcs:SourceVpc`). Other VPCs must also be associated with the service network. |
> | `DetectInvokerRoleArns` | — | Required. Roles that may call `/detect`, `/redact`, `/deidentify`. |
> | `ErasureInvokerRoleArns` | empty | Roles that may `DELETE /sessions/{session_id}`. Empty = nobody can erase; sessions expire on their TTL. |

> [accordion] Network
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `VpcId`, `VpcCidr` | — | Endpoint SG admits 443 from `VpcCidr`. |
> | `PrivateSubnetIds` | — | One per AZ, ≥ 2 AZs (3 recommended), no NAT/IGW route, in AZs that VPC Lattice supports. |
> | `PrivateRouteTableIds` | — | For the S3 gateway endpoint. |
> | `S3PrefixListId` | — | `com.amazonaws.<region>.s3`; used in egress rules. |
> | `CreateVpcEndpoints` | `true` | `false` if the VPC already has private-DNS endpoints for these services — a second one fails. |
> | `EnableSsmEndpoints` | `false` | Adds `ssm`/`ssmmessages`/`ec2messages` and the SSM instance policy. A host shell can read process memory. |

> [accordion] Keys
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `KmsKeyArn` | empty = create | Bring your own CMK; add the statements [below](#bringing-your-own-kms-key) to its policy. |
> | `KeyAdminRoleArn` | — | Required when the stack creates the key. Administers it and runs the stack; no direct `Encrypt`/`Decrypt`. |
> | `KeyPolicyIncludeAccountRoot` | `false` | `true` delegates key access to IAM in this account. With `false`, only named roles can use the key — and the key is unmanageable if `KeyAdminRoleArn` is deleted. Neither grants Tenet anything. |

> [accordion] Vault
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `CreateVaultDatabase` | `true` | New Aurora PostgreSQL Serverless v2 cluster, CMK-encrypted. |
> | `AuroraEngineVersion` | `16.15` | Confirm it's offered in your Region. |
> | `AuroraDeletionProtection` | `true` | Keep `true` in production. With `true`, a failed create ends in `ROLLBACK_FAILED`. |
> | `VaultDeletionPolicy` | `Snapshot` | `Delete` for trials. Vault rows are TTL-bound (1 h by default). |
> | `AuroraMinCapacity`, `AuroraMaxCapacity` | `0.5`, `8` | ACUs. |
> | `VaultDatabaseName` | `tenet` | |
> | `ExistingVaultEndpoint`, `ExistingVaultPort`, `ExistingVaultSecretArn`, `ExistingVaultSecurityGroupId` | empty, `5432`, empty, empty | Required when `CreateVaultDatabase=false`. Secret is JSON with `username` and `password`; the stack adds 5432 ingress from the task SGs. |

> [accordion] Rehydration and audit
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `EnableRehydration` | `true` | `false` = no rehydrate service, task role or Lattice service. |
> | `RehydrateDesiredCount` | `2` | `2` rolls out without a gap. With `1`, each rollout stops the task before starting its replacement. |
> | `RehydrateInvokerRoleArns` | — | Required with rehydration. Named in the rehydrate auth policy and in the runtime's own allow-list. |
> | `RequireRehydrateApprovalTag` | `false` | `true` = invokers need the session tag `tenet-approval-id`, checked on every call. |
> | `BreakGlassTrustedPrincipalArn` | empty = none | Who may assume the MFA-gated break-glass role, which may rehydrate without the tag. [Break-glass](https://docs.tenetlabs.com/pii-engine/operate/break-glass.md). |
> | `ExistingAuditBucketName` | empty = create | Must have Object Lock and SSE-KMS with the CMK. |
> | `AuditPrefix` | `rehydrate/` | Reidentify records. |
> | `ErasureAuditPrefix` | `erasure/` | Detect's erasure records. |
> | `AuditObjectLockMode` | `GOVERNANCE` | Use `COMPLIANCE` in production; `GOVERNANCE` is the default only so trial stacks can be torn down. |
> | `AuditRetentionDays` | `2190` | Default retention (6 years). |
> | `AuditReaderRoleArn` | empty | Read access to audit records for auditors or your SIEM. |

> [accordion] Compute
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `ImageUri` | — | The AWS Marketplace image, by digest from the release record, in any Region. Outside `us-east-1` the stack's ECR and S3 endpoints reach it across Regions. A copy in your own ECR won't pull. |
> | `InstanceType` | `c9g.xlarge` | `c8g.xlarge` where C9g isn't offered. |
> | `EcsAmiId` | `/aws/service/ecs/optimized-ami/amazon-linux-2023/arm64/recommended/image_id` | Public SSM parameter. |
> | `AsgMinSize`, `AsgMaxSize` | `2`, `12` | |
> | `DetectDesiredCount` | `2` | ≥ 2, spread across AZs. |
> | `EnableDetectAutoScaling`, `DetectMaxCount`, `DetectCpuTargetPercent` | `true`, `10`, `60` | Target tracking on CPU. |
> | `DeploymentMinimumHealthyPercent`, `DeploymentMaximumPercent` | `50`, `100` | Replace in place; see [Upgrades](https://docs.tenetlabs.com/pii-engine/operate/upgrades.md). |

> [accordion] Logs and alarms
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `TelemetryPath` | empty = stdout | `TENET_TELEMETRY_PATH`, under `/tmp/`. Counts-only usage records, kept local. |
> | `LogRetentionDays` | `365` | CloudWatch Logs retention value. |
> | `AlarmTopicArn` | empty | SNS topic for the alarm on usage that can't be reported to AWS Marketplace. Empty = the alarm shows in CloudWatch only. [Billing](https://docs.tenetlabs.com/pii-engine/concepts/billing.md). |

> [accordion] Usage telemetry egress (opt-in)
>
> | Parameter | Default | Notes |
> | - | - | - |
> | `EnableUsageTelemetryEgress` | `false` | `true` sends the hourly counts-only usage records to Tenet. Creates an Elastic IP, a NAT gateway and a tcp/443 egress rule on the detect task SG only (about \$37/month fixed in us-east-1). `false` creates nothing. |
> | `UsageTelemetrySinkUrl` | `https://judge.tenetlabs.com` | `TENET_TELEMETRY_SINK_URL`. https, no credentials, query or fragment. |
> | `UsageTelemetryApiKeySecretArn` | empty | Required with egress. A Secrets Manager secret holding a Tenet Platform API key → `TENET_TELEMETRY_API_KEY`. [Getting the key](https://docs.tenetlabs.com/pii-engine/operate/monitoring.md#sending-usage-records-to-tenet). If it uses a customer-managed key, allow the detect execution role `kms:Decrypt` with it. |
> | `UsageTelemetryNatSubnetId` | empty | Required with egress. An existing **public** subnet for the NAT gateway (one AZ). |
> | `UsageTelemetryCreateDefaultRoute` | `true` | Adds `0.0.0.0/0` → the NAT on every `PrivateRouteTableIds` entry. `false` if those tables already have a default route (else `RouteAlreadyExists`). |
>
> The detect egress rule is tcp/443 to `0.0.0.0/0` through the NAT, not limited to Tenet's endpoint — a compromised detect task could reach any HTTPS host. For tighter control, put AWS Network Firewall with a domain allowlist or an egress proxy on that path. Record contents: [Monitoring](https://docs.tenetlabs.com/pii-engine/operate/monitoring.md).

## Bringing your own KMS key

With `KmsKeyArn` set, the template can't edit that key's policy. Add these statements yourself — the log-group one **before** the first deploy (or the log groups fail to create), the rest once the stack has created the roles (`<prefix>-detect-task`, `<prefix>-rehydrate-task`, `<prefix>-detect-exec`, `<prefix>-rehydrate-exec`):

```json theme={null}
{"Sid":"DetectWrapsVaultKeyPairs","Effect":"Allow","Principal":{"AWS":"<detect-task-role-arn>"},
 "Action":"kms:Encrypt","Resource":"*",
 "Condition":{"StringEquals":{"kms:EncryptionContext:tenet:purpose":["pii-vault-lookup-key","pii-vault-private-key"],
   "kms:EncryptionContext:tenet:deployment":"<DeploymentId>"}}},
{"Sid":"DetectUnwrapsLookupKeys","Effect":"Allow","Principal":{"AWS":"<detect-task-role-arn>"},
 "Action":"kms:Decrypt","Resource":"*",
 "Condition":{"StringEquals":{"kms:EncryptionContext:tenet:purpose":"pii-vault-lookup-key",
   "kms:EncryptionContext:tenet:deployment":"<DeploymentId>"}}},
{"Sid":"DenyDetectPrivateKeys","Effect":"Deny","Principal":{"AWS":"<detect-task-role-arn>"},
 "Action":"kms:Decrypt","Resource":"*",
 "Condition":{"StringEquals":{"kms:EncryptionContext:tenet:purpose":"pii-vault-private-key"}}},
{"Sid":"DenyDetectReEncryptAndGrants","Effect":"Deny","Principal":{"AWS":"<detect-task-role-arn>"},
 "Action":["kms:ReEncrypt*","kms:CreateGrant"],"Resource":"*"},
{"Sid":"RehydrateVaultKeysDecryptOnly","Effect":"Allow","Principal":{"AWS":"<rehydrate-task-role-arn>"},
 "Action":"kms:Decrypt","Resource":"*",
 "Condition":{"StringEquals":{"kms:EncryptionContext:tenet:purpose":["pii-vault-lookup-key","pii-vault-private-key"],
   "kms:EncryptionContext:tenet:deployment":"<DeploymentId>"}}},
{"Sid":"RehydrateAuditWritesViaS3","Effect":"Allow","Principal":{"AWS":"<rehydrate-task-role-arn>"},
 "Action":"kms:GenerateDataKey","Resource":"*",
 "Condition":{"StringEquals":{"kms:ViaService":"s3.<region>.amazonaws.com"}}},
{"Sid":"DetectErasureAuditWritesViaS3","Effect":"Allow","Principal":{"AWS":"<detect-task-role-arn>"},
 "Action":"kms:GenerateDataKey","Resource":"*",
 "Condition":{"StringEquals":{"kms:ViaService":"s3.<region>.amazonaws.com"}}},
{"Sid":"ExecutionRolesReadSecrets","Effect":"Allow","Principal":{"AWS":["<detect-exec-role-arn>","<rehydrate-exec-role-arn>"]},
 "Action":"kms:Decrypt","Resource":"*",
 "Condition":{"StringEquals":{"kms:ViaService":"secretsmanager.<region>.amazonaws.com"}}},
{"Sid":"CloudWatchLogs","Effect":"Allow","Principal":{"Service":"logs.<region>.amazonaws.com"},
 "Action":["kms:Encrypt*","kms:Decrypt*","kms:ReEncrypt*","kms:GenerateDataKey*","kms:Describe*"],"Resource":"*",
 "Condition":{"ArnLike":{"kms:EncryptionContext:aws:logs:arn":"arn:aws:logs:<region>:<account-id>:log-group:/<prefix>/*"}}}
```

* **The two `Deny` statements keep detect out of the vault.** Detect creates each vault key pair and wraps its private half, but can never unwrap it, so it can't read back any value it stored. The stack's detect role policy repeats both Denies, so they hold before you edit the key policy; keep them in the key policy anyway, so no IAM policy attached to the role later can lift them. [Architecture — KMS design](https://docs.tenetlabs.com/pii-engine/concepts/architecture.md#kms-design).
* **`DetectErasureAuditWritesViaS3`** lets detect write erasure records to the SSE-KMS audit bucket.
* **If your key policy delegates to IAM** (the `root` statement), add the log-group statement before the first deploy.

## Gotchas

* **The Aurora master secret rotates every 7 days.** ECS injects `PGUSER`/`PGPASSWORD` at task start, so running tasks keep the old password and fail on their next reconnect. After each rotation, `aws ecs update-service --force-new-deployment` both services — or create a dedicated least-privilege database user for the engine with its own rotation schedule (recommended).
* **Stack updates reset the detect count.** With autoscaling on, every update sets the service back to `DetectDesiredCount`, then autoscaling scales it up again. Update off-peak or raise `DetectDesiredCount` first.
* **Health checks.** Detect's container check runs `tenet-pii-enterprise healthcheck` against `/healthz`; its Lattice target group checks `/readyz`. Rehydrate's container check uses `--ready` (`/readyz`), so a task that can't reach the vault is replaced; its target group checks `/readyz` too. The probes aren't routed through Lattice — callers get `404` on them.
* **VPC Lattice isn't in every AZ** (for example `use1-az3` in us-east-1). Keep `PrivateSubnetIds` in supported AZs, or target registration fails for tasks placed there.
* **One service network per VPC.** If `VpcId` is already associated with one, pass `ExistingServiceNetworkArn`. The stack then only adds its services; you own that network's VPC associations and auth policy. The services' own auth policies still apply.
* **Rollouts replace tasks in place.** `50`/`100` stops half the tasks, starts the new revision on the freed instances, then does the other half — during a rollout, 1 of 2 detect tasks serves. Deploy off-peak or raise `DetectDesiredCount` first; or set `100`/`200` and leave `AsgMaxSize` headroom for one surge instance per service.
* **Failed first create.** The KMS key and audit bucket use `DeletionPolicy: RetainExceptOnCreate`, so a rollback deletes them (the key enters a 30-day pending deletion). With `AuroraDeletionProtection=true`, a failed create ends in `ROLLBACK_FAILED` — disable protection on the cluster and continue the rollback.
* **"Invalid principals" on `VaultKey`.** IAM propagation can lag a role created seconds earlier. Retry the stack operation.
* **Tear-down.** Stack delete keeps the KMS key and the audit bucket (in `COMPLIANCE` mode nobody can delete audit objects before retention ends). Set `AuroraDeletionProtection=false` and update before deleting; `VaultDeletionPolicy=Snapshot` leaves a final snapshot for you to delete. A delete can end `DELETE_FAILED` on a Lattice target group with "Exceeded attempts to wait", because ECS is still deregistering tasks — delete the stack again. If a delete sticks with services in `DRAINING`, see [Troubleshooting](https://docs.tenetlabs.com/pii-engine/troubleshooting.md#stack-delete-hangs).
* **One private subnet per AZ.** Interface endpoints take at most one subnet per AZ.
* **Tasks stop at startup with a metering error.** `AWS Marketplace metering refused this deployment` means the account isn't subscribed or the task role lacks `aws-marketplace:MeterUsage`; `AWS Marketplace metering is unreachable` means the `metering-marketplace` endpoint is missing or unreachable. With `CreateVpcEndpoints=false`, your existing endpoints must include `metering-marketplace`. [Troubleshooting](https://docs.tenetlabs.com/pii-engine/troubleshooting.md#entitlement-check-refuses-startup).

## Links

* [Prerequisites](https://docs.tenetlabs.com/pii-engine/deploy/prerequisites.md)
* [Rehydration and audit — the caller model](https://docs.tenetlabs.com/pii-engine/concepts/rehydration-and-audit.md)
* [Quickstart — a signed round trip against this stack](https://docs.tenetlabs.com/pii-engine/quickstart.md)
* [Upgrades](https://docs.tenetlabs.com/pii-engine/operate/upgrades.md)
* [Troubleshooting](https://docs.tenetlabs.com/pii-engine/troubleshooting.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.