carlos / platform Public

infra: media-engine module, one Fargate task per conversion

Plan 3 Task 11. The module creates the image repository, a VPC with no
route out, four named endpoints, a DNS firewall, the execution and
conversion roles, the console's grants, one task definition per preset
and class, and the reaper.

The drill input reaches only the four endpoint policies and the
repository policy, and stays null outside the endpoint drill on dev.

internal/mediaaws tests feed the module's rendered task definitions and
output to the real gate and config parser. The render is checked in, so
CI covers that side without OpenTofu.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ea2048d0049e18219c6b1e3a7c1380c40ce3c21f parent e8736b3
16 files changed, +2,557 −0
  • docs/superpowers/notes/media-conversion-copy-deck.md +17 −0
  • infra/modules/README.md +6 −0
  • infra/modules/media-engine/README.md +95 −0
  • infra/modules/media-engine/ecs.tf +86 −0
  • infra/modules/media-engine/iam.tf +157 −0
  • infra/modules/media-engine/main.tf +65 −0
  • infra/modules/media-engine/network.tf +267 −0
  • infra/modules/media-engine/outputs.tf +35 −0
  • infra/modules/media-engine/reaper.tf +92 −0
  • infra/modules/media-engine/reaper/reaper.py +72 −0
  • infra/modules/media-engine/reaper/reaper_test.py +160 −0
  • infra/modules/media-engine/tests/media_engine.tftest.hcl +765 −0
  • infra/modules/media-engine/variables.tf +179 −0
  • infra/modules/media-engine/versions.tf +13 −0
  • internal/mediaaws/module_test.go +511 −0
  • internal/mediaaws/testdata/media-engine-rendered.json +37 −0
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index ec3655d39..df71c34ed 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -691,3 +691,20 @@ for whoever deploys the console and are not listed here.
| `engine.aws.grant.presign` | `the presigned transfers do not share one credential`, `an output's URL is not under the output prefix`, `a presigned URL does not have the expected shape`, `a presigned URL does not sign the expected headers` (pending Luna pass; plan 3 Task 9) |
| `engine.aws.rejected` | The reason in `engine rejected the launch: %s`: an AWS error code, `HTTP 429`, the reason ECS gave, `no task definition for this class`, `no task and no failure reported`, `no reason reported`, `a reason that cannot be shown`, or `the API refused the request` (pending Luna pass; plan 3 Task 9) |
| `console.media.off_at_boot` | `console: media conversion is off until the next start: %v`, logged once at boot when the cloud account cannot be read or a client cannot be built. `%v` is `the cloud account could not be reached: <step>: <cause>`. The step is `sts GetCallerIdentity`, `build the S3 client` or `build the conversion engine`; the cause is one of the `engine.aws.cause.*` texts, never the error's own message (pending Luna pass; plan 3 Task 10 fix 2) |
+
+### The media-engine module (plan 3 Task 11)
+
+The module's README and its plan-time refusals, for whoever deploys it. The
+reaper's lines reach only the task's stop reason and the function's own log.
+
+| Key | Text |
+|---|---|
+| `infra.media_engine.readme` | The whole of `infra/modules/media-engine/README.md` (pending Luna pass; plan 3 Task 11) |
+| `infra.modules_readme.media_engine` | The `media-engine` section of `infra/modules/README.md` (pending Luna pass; plan 3 Task 11) |
+| `infra.media_engine.descriptions` | Every variable and output `description` in `infra/modules/media-engine/variables.tf` and `outputs.tf` (pending Luna pass; plan 3 Task 11) |
+| `infra.media_engine.refused.variables` | Every `error_message` in `infra/modules/media-engine/variables.tf` (pending Luna pass; plan 3 Task 11) |
+| `infra.media_engine.refused.region` | `The media engine must run in the store region: region and store_region differ.` (pending Luna pass; plan 3 Task 11) |
+| `infra.media_engine.refused.drill_account` | `The drill's foreign principal must be in another account.` (pending Luna pass; plan 3 Task 11) |
+| `engine.reaper.stop_reason` | `carlos media reaper: older than %d minutes`, the stop reason ECS records. `%d` is `MAX_AGE_MINUTES` (pending Luna pass; plan 3 Task 11) |
+| `engine.reaper.undescribed` | `carlos media reaper: a task could not be described` (pending Luna pass; plan 3 Task 11) |
+| `engine.reaper.not_stopped` | `carlos media reaper: %d of %d tasks were not stopped` (pending Luna pass; plan 3 Task 11) |
diff --git a/infra/modules/README.md b/infra/modules/README.md
index bf2ca851c..dc87d4629 100644
--- a/infra/modules/README.md
+++ b/infra/modules/README.md
@@ -137,6 +137,12 @@ Port 3310 is open only while a self-test has passed against the clamd process ru
Outputs: `clamd_addr` (set as the console's `CARLOS_CLAMD_ADDR`), `stream_max_bytes` (set as `CARLOS_CLAMD_MAX_BYTES`), `instance_id`, `security_group_id`.
+## media-engine
+
+Media conversion: one Fargate task per conversion, in a private VPC with no route to the internet. The module creates the image repository, the network and its endpoints, a DNS firewall, the IAM roles, a task definition for each preset and class, and a reaper for tasks left running too long. Apply it once to create the repository, push the image, then apply again with the image's digest. The module's `README.md` has the steps and the checks to pass before turning conversion on.
+
+Outputs: `carlos_media_engine` (set as the console's `CARLOS_MEDIA_ENGINE`), `repository_url`, `cluster_arn`, `conversion_role_arn`.
+
## region-remote-host
What an off-cloud CARLOS host needs from AWS when there is no EC2
diff --git a/infra/modules/media-engine/README.md b/infra/modules/media-engine/README.md
new file mode 100644
index 000000000..49058b63c
--- /dev/null
+++ b/infra/modules/media-engine/README.md
@@ -0,0 +1,95 @@
+# media-engine: one Fargate task per conversion
+
+This module runs CARLOS media conversion. Each conversion gets its own Fargate
+task, which downloads one source, converts it, uploads the results and exits.
+The module creates the image repository, a private network, the IAM roles, one
+task definition per preset and class, and a reaper that stops any task left
+running too long.
+
+A task holds no AWS credentials. It has no task role, and the console hands it
+presigned requests for that one conversion.
+
+```hcl
+module "media_engine" {
+ source = "git::https://github.com/carlosframework/platform.git//infra/modules/media-engine?ref=<release-tag>"
+ name = "carlos-example-media"
+ region = "eu-west-1"
+ store_region = "eu-west-1"
+ store_bucket_prefix = "carlos-example-store-"
+ deployment_bucket_name = module.buckets.deployment_bucket
+ console_role_name = module.host_ie.role_name
+ console_role_arn = module.host_ie.role_arn
+
+ image_digest = ""
+ image_built_at = ""
+ image_ffmpeg = ""
+
+ drill = var.media_engine_drill
+}
+
+variable "media_engine_drill" {
+ type = object({
+ endpoints_open = bool
+ foreign_principal_arn = string
+ })
+ default = null
+}
+```
+
+Keep the module’s name `media_engine` and leave the variable’s default at
+`null`. The endpoint drill relies on both.
+
+## Region
+
+The engine must run in the same region as the deployment’s stores. If `region`
+and `store_region` differ, the plan fails.
+
+## Apply it in two steps
+
+The image has to be pushed to a repository that the first apply creates.
+
+1. Apply with `image_digest` empty. This creates everything except the task
+ definitions, and `carlos_media_engine` stays empty. The `repository_url`
+ output says where to push.
+2. Build and push the image as `deploy/media-image/README.md` describes. Copy
+ `digest`, `built_at` and `ffmpeg` from its `image.json` into `image_digest`,
+ `image_built_at` and `image_ffmpeg`, then apply again.
+
+## Connect the console
+
+Set the console’s `CARLOS_MEDIA_ENGINE` to the `carlos_media_engine` output and
+restart the console. The console also needs `CARLOS_STORE_CONVERSION=1` and a
+store backend in the engine’s region, account and bucket prefix. While
+`CARLOS_MEDIA_ENGINE` is unset, the media API answers 503.
+
+The other outputs are `repository_url`, `cluster_arn` and `conversion_role_arn`.
+
+## Before you turn it on
+
+Keep conversion off in a deployment until all of these have been shown on that
+deployment:
+
+- Requests signed with an unrelated account’s credentials are refused at all
+ four endpoints. `scripts/media-endpoint-drill.sh` runs this check.
+- `codec` does not start before `deadline` is running, and does not start at
+ all when `deadline` fails to start.
+- The `deadline` container ends a task whose `codec` ignores every signal and
+ tries to kill the timer, with the console stopped.
+
+## Roll back
+
+Set `image_digest`, `image_built_at` and `image_ffmpeg` back to the previous
+image’s values, apply, and update the console’s `CARLOS_MEDIA_ENGINE` from the
+output. Do the console straight after the apply: the apply retires the revisions
+the console is still using, so new conversions fail until it restarts.
+
+## The endpoint drill
+
+`drill` stays `null` everywhere except on dev while the drill script runs. The
+script sets it, changes only the four endpoint policies and the repository
+policy, and sets it back to `null` when it finishes.
+
+## Removing the module
+
+The DNS firewall’s association with the VPC has mutation protection on, so
+`tofu destroy` cannot remove it. Turn that protection off first.
diff --git a/infra/modules/media-engine/ecs.tf b/infra/modules/media-engine/ecs.tf
new file mode 100644
index 000000000..f750a026f
--- /dev/null
+++ b/infra/modules/media-engine/ecs.tf
@@ -0,0 +1,86 @@
+resource "aws_ecs_cluster" "engine" {
+ name = var.name
+
+ setting {
+ name = "containerInsights"
+ value = "disabled"
+ }
+}
+
+resource "aws_ecs_cluster_capacity_providers" "engine" {
+ cluster_name = aws_ecs_cluster.engine.name
+ capacity_providers = ["FARGATE"]
+}
+
+locals {
+ engine_image = "${aws_ecr_repository.engine.repository_url}@${var.image_digest}"
+
+ # What both containers share. internal/media/gate.go refuses a revision that
+ # differs from this, so a change here must satisfy CheckTaskDefinition.
+ engine_container = {
+ image = local.engine_image
+ essential = true
+ entryPoint = ["/usr/local/bin/carlos-media"]
+ user = "65534:65534"
+ readonlyRootFilesystem = true
+ stopTimeout = 30
+ linuxParameters = { capabilities = { drop = ["ALL"] } }
+ }
+
+ codec_logs = var.logs ? {
+ logConfiguration = {
+ logDriver = "awslogs"
+ options = {
+ awslogs-group = aws_cloudwatch_log_group.engine.name
+ awslogs-region = var.region
+ awslogs-stream-prefix = "media"
+ }
+ }
+ } : {}
+}
+
+# One definition per class, and only once there is an image to run.
+resource "aws_ecs_task_definition" "engine" {
+ for_each = var.image_digest == "" ? {} : local.classes
+
+ family = "${var.name}-${each.value.preset}-${each.value.class}"
+ requires_compatibilities = ["FARGATE"]
+ network_mode = "awsvpc"
+ cpu = each.value.cpu
+ memory = each.value.memory
+ execution_role_arn = aws_iam_role.execution.arn
+
+ runtime_platform {
+ operating_system_family = "LINUX"
+ cpu_architecture = "ARM64"
+ }
+
+ volume {
+ name = "scratch"
+ }
+
+ dynamic "ephemeral_storage" {
+ for_each = each.value.ephemeral_gib == null ? [] : [each.value.ephemeral_gib]
+ content {
+ size_in_gib = ephemeral_storage.value
+ }
+ }
+
+ container_definitions = jsonencode([
+ merge(local.engine_container, {
+ name = "deadline"
+ command = ["deadline"]
+ cpu = 64
+ memory = 64
+ }),
+ merge(local.engine_container, local.codec_logs, {
+ name = "codec"
+ command = ["codec"]
+ cpu = each.value.cpu - 64
+ memory = each.value.memory - 64
+ dependsOn = [{ containerName = "deadline", condition = "START" }]
+ environment = [{ name = "TMPDIR", value = "/scratch/tmp" }]
+ mountPoints = [{ sourceVolume = "scratch", containerPath = "/scratch", readOnly = false }]
+ }),
+ ])
+}
diff --git a/infra/modules/media-engine/iam.tf b/infra/modules/media-engine/iam.tf
new file mode 100644
index 000000000..284681caf
--- /dev/null
+++ b/infra/modules/media-engine/iam.tf
@@ -0,0 +1,157 @@
+# The execution role is the Fargate agent's: it pulls the image and writes
+# logs. No container is offered its credentials, because no task has a role.
+resource "aws_iam_role" "execution" {
+ name = "${var.name}-execution"
+ assume_role_policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Effect = "Allow"
+ Principal = { Service = "ecs-tasks.amazonaws.com" }
+ Action = "sts:AssumeRole"
+ Condition = { StringEquals = { "aws:SourceAccount" = local.account_id } }
+ }]
+ })
+}
+
+resource "aws_iam_role_policy" "execution" {
+ name = "${var.name}-execution"
+ role = aws_iam_role.execution.id
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Effect = "Allow"
+ Action = "ecr:GetAuthorizationToken"
+ Resource = "*"
+ },
+ {
+ Effect = "Allow"
+ Action = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
+ Resource = aws_ecr_repository.engine.arn
+ },
+ {
+ Effect = "Allow"
+ Action = ["logs:CreateLogStream", "logs:PutLogEvents"]
+ Resource = "${aws_cloudwatch_log_group.engine.arn}:*"
+ },
+ ]
+ })
+}
+
+# The console assumes the conversion role, narrowed by a session policy to one
+# execution, and signs that execution's transfers with the session. Tasks never
+# hold these credentials: only the presigned requests reach them.
+resource "aws_iam_role" "conversion" {
+ name = "${var.name}-conversion"
+ max_session_duration = 3600
+ assume_role_policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Effect = "Allow"
+ Principal = { AWS = var.console_role_arn }
+ Action = "sts:AssumeRole"
+ }]
+ })
+}
+
+resource "aws_iam_role_policy" "conversion" {
+ name = "${var.name}-conversion"
+ role = aws_iam_role.conversion.id
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Sid = "ReadSources"
+ Effect = "Allow"
+ Action = "s3:GetObject"
+ Resource = local.store_objects
+ },
+ {
+ Sid = "WriteOutputs"
+ Effect = "Allow"
+ Action = "s3:PutObject"
+ Resource = local.store_derived
+ },
+ {
+ Sid = "WriteResults"
+ Effect = "Allow"
+ Action = "s3:PutObject"
+ Resource = local.results_objects
+ },
+ {
+ Sid = "NeverReadInfected"
+ Effect = "Deny"
+ Action = "s3:GetObject"
+ Resource = local.store_objects
+ Condition = { StringEquals = { "s3:ExistingObjectTag/carlos-scan" = "infected" } }
+ },
+ {
+ Sid = "NeverWriteScanTags"
+ Effect = "Deny"
+ Action = "s3:PutObject"
+ Resource = "*"
+ Condition = {
+ "ForAnyValue:StringEquals" = {
+ "s3:RequestObjectTagKeys" = ["carlos-scan", "carlos-scan-version", "carlos-scan-at", "carlos-scan-sig"]
+ }
+ }
+ },
+ ]
+ })
+}
+
+resource "aws_iam_role_policy" "console" {
+ name = "${var.name}-console"
+ role = var.console_role_name
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Sid = "AssumeConversion"
+ Effect = "Allow"
+ Action = "sts:AssumeRole"
+ Resource = aws_iam_role.conversion.arn
+ },
+ {
+ Sid = "RunTasks"
+ Effect = "Allow"
+ Action = "ecs:RunTask"
+ Resource = "arn:aws:ecs:${var.region}:${local.account_id}:task-definition/${var.name}-*:*"
+ Condition = { ArnEquals = { "ecs:cluster" = aws_ecs_cluster.engine.arn } }
+ },
+ {
+ Sid = "WatchTasks"
+ Effect = "Allow"
+ Action = ["ecs:DescribeTasks", "ecs:StopTask"]
+ Resource = local.cluster_tasks
+ },
+ {
+ Sid = "ListTasks"
+ Effect = "Allow"
+ Action = "ecs:ListTasks"
+ Resource = "*"
+ Condition = { ArnEquals = { "ecs:cluster" = aws_ecs_cluster.engine.arn } }
+ },
+ {
+ Sid = "ReadTaskDefinitions"
+ Effect = "Allow"
+ Action = "ecs:DescribeTaskDefinition"
+ Resource = "*"
+ },
+ {
+ Sid = "PassExecutionRole"
+ Effect = "Allow"
+ Action = "iam:PassRole"
+ Resource = aws_iam_role.execution.arn
+ Condition = { StringEquals = { "iam:PassedToService" = "ecs-tasks.amazonaws.com" } }
+ },
+ {
+ Sid = "ListResults"
+ Effect = "Allow"
+ Action = "s3:ListBucket"
+ Resource = "arn:aws:s3:::${var.deployment_bucket_name}"
+ Condition = { StringLike = { "s3:prefix" = "media-results/*" } }
+ },
+ ]
+ })
+}
diff --git a/infra/modules/media-engine/main.tf b/infra/modules/media-engine/main.tf
new file mode 100644
index 000000000..3fd0327f2
--- /dev/null
+++ b/infra/modules/media-engine/main.tf
@@ -0,0 +1,65 @@
+data "aws_caller_identity" "current" {}
+
+data "aws_availability_zones" "available" {
+ state = "available"
+ filter {
+ name = "opt-in-status"
+ values = ["opt-in-not-required"]
+ }
+}
+
+locals {
+ account_id = data.aws_caller_identity.current.account_id
+
+ classes = { for c in var.classes : "${c.preset}/${c.class}" => c }
+
+ # The bucket patterns every policy in this module shares.
+ store_objects = "arn:aws:s3:::${var.store_bucket_prefix}*/*"
+ store_derived = "arn:aws:s3:::${var.store_bucket_prefix}*/derived/*"
+ results_objects = "arn:aws:s3:::${var.deployment_bucket_name}/media-results/*"
+
+ cluster_tasks = "arn:aws:ecs:${var.region}:${local.account_id}:task/${aws_ecs_cluster.engine.name}/*"
+}
+
+resource "aws_ecr_repository" "engine" {
+ name = var.name
+ image_tag_mutability = "IMMUTABLE"
+
+ image_scanning_configuration {
+ scan_on_push = true
+ }
+
+ lifecycle {
+ precondition {
+ condition = var.region == var.store_region
+ error_message = "The media engine must run in the store region: region and store_region differ."
+ }
+ }
+}
+
+# Exists only while the endpoint drill runs. See the drill variable.
+resource "aws_ecr_repository_policy" "engine" {
+ count = var.drill == null ? 0 : 1
+ repository = aws_ecr_repository.engine.name
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Sid = "CarlosMediaEndpointDrill"
+ Effect = "Allow"
+ Principal = { AWS = var.drill.foreign_principal_arn }
+ Action = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
+ }]
+ })
+
+ lifecycle {
+ precondition {
+ condition = split(":", var.drill.foreign_principal_arn)[4] != local.account_id
+ error_message = "The drill's foreign principal must be in another account."
+ }
+ }
+}
+
+resource "aws_cloudwatch_log_group" "engine" {
+ name = "/carlos/${var.name}/engine"
+ retention_in_days = var.log_retention_days
+}
diff --git a/infra/modules/media-engine/network.tf b/infra/modules/media-engine/network.tf
new file mode 100644
index 000000000..eb0296996
--- /dev/null
+++ b/infra/modules/media-engine/network.tf
@@ -0,0 +1,267 @@
+# A VPC of its own with no way out: no internet gateway, no NAT, no default
+# route. A task reaches S3 and three AWS APIs through endpoints, and each
+# endpoint's policy names who may use it.
+
+resource "aws_vpc" "engine" {
+ cidr_block = var.vpc_cidr
+ enable_dns_support = true
+ enable_dns_hostnames = true
+ tags = { Name = var.name }
+}
+
+resource "aws_subnet" "private" {
+ count = 2
+ vpc_id = aws_vpc.engine.id
+ cidr_block = cidrsubnet(var.vpc_cidr, 1, count.index)
+ availability_zone = data.aws_availability_zones.available.names[count.index]
+
+ map_public_ip_on_launch = false
+
+ tags = { Name = "${var.name}-${count.index}" }
+}
+
+resource "aws_route_table" "private" {
+ vpc_id = aws_vpc.engine.id
+ # Empty on purpose. The S3 gateway endpoint adds its own route.
+ route = []
+ tags = { Name = var.name }
+}
+
+resource "aws_route_table_association" "private" {
+ count = 2
+ subnet_id = aws_subnet.private[count.index].id
+ route_table_id = aws_route_table.private.id
+}
+
+resource "aws_security_group" "endpoints" {
+ name = "${var.name}-endpoints"
+ description = "media-engine interface endpoints"
+ vpc_id = aws_vpc.engine.id
+ egress = []
+ tags = { Name = "${var.name}-endpoints" }
+}
+
+resource "aws_security_group" "tasks" {
+ name = "${var.name}-tasks"
+ description = "media-engine tasks"
+ vpc_id = aws_vpc.engine.id
+ ingress = []
+ egress = [
+ {
+ description = "S3 through the gateway endpoint"
+ from_port = 443
+ to_port = 443
+ protocol = "tcp"
+ prefix_list_ids = [aws_vpc_endpoint.s3.prefix_list_id]
+ cidr_blocks = []
+ ipv6_cidr_blocks = []
+ security_groups = []
+ self = false
+ },
+ {
+ description = "The interface endpoints"
+ from_port = 443
+ to_port = 443
+ protocol = "tcp"
+ security_groups = [aws_security_group.endpoints.id]
+ prefix_list_ids = []
+ cidr_blocks = []
+ ipv6_cidr_blocks = []
+ self = false
+ },
+ ]
+ tags = { Name = "${var.name}-tasks" }
+}
+
+resource "aws_vpc_security_group_ingress_rule" "endpoints_from_tasks" {
+ security_group_id = aws_security_group.endpoints.id
+ description = "HTTPS from the media tasks"
+ ip_protocol = "tcp"
+ from_port = 443
+ to_port = 443
+ referenced_security_group_id = aws_security_group.tasks.id
+}
+
+resource "aws_vpc_endpoint" "s3" {
+ vpc_id = aws_vpc.engine.id
+ service_name = "com.amazonaws.${var.region}.s3"
+ vpc_endpoint_type = "Gateway"
+ route_table_ids = [aws_route_table.private.id]
+ tags = { Name = "${var.name}-s3" }
+}
+
+resource "aws_vpc_endpoint" "ecr_api" {
+ vpc_id = aws_vpc.engine.id
+ service_name = "com.amazonaws.${var.region}.ecr.api"
+ vpc_endpoint_type = "Interface"
+ subnet_ids = aws_subnet.private[*].id
+ security_group_ids = [aws_security_group.endpoints.id]
+ private_dns_enabled = true
+ tags = { Name = "${var.name}-ecr-api" }
+}
+
+resource "aws_vpc_endpoint" "ecr_dkr" {
+ vpc_id = aws_vpc.engine.id
+ service_name = "com.amazonaws.${var.region}.ecr.dkr"
+ vpc_endpoint_type = "Interface"
+ subnet_ids = aws_subnet.private[*].id
+ security_group_ids = [aws_security_group.endpoints.id]
+ private_dns_enabled = true
+ tags = { Name = "${var.name}-ecr-dkr" }
+}
+
+resource "aws_vpc_endpoint" "logs" {
+ count = var.logs ? 1 : 0
+ vpc_id = aws_vpc.engine.id
+ service_name = "com.amazonaws.${var.region}.logs"
+ vpc_endpoint_type = "Interface"
+ subnet_ids = aws_subnet.private[*].id
+ security_group_ids = [aws_security_group.endpoints.id]
+ private_dns_enabled = true
+ tags = { Name = "${var.name}-logs" }
+}
+
+locals {
+ # AWS's default endpoint policy, written out. Only the endpoint drill uses it.
+ endpoint_open_policy = "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"*\",\"Resource\":\"*\"}]}"
+
+ execution_role_only = { StringEquals = { "aws:PrincipalArn" = aws_iam_role.execution.arn } }
+
+ s3_endpoint_policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Sid = "ConversionTransfers"
+ Effect = "Allow"
+ Principal = "*"
+ Action = ["s3:GetObject", "s3:PutObject"]
+ Resource = [local.store_objects, local.results_objects]
+ Condition = { StringEquals = { "aws:PrincipalArn" = aws_iam_role.conversion.arn } }
+ },
+ {
+ # ECR signs these requests itself, so no principal of ours can be named.
+ Sid = "ImageLayers"
+ Effect = "Allow"
+ Principal = "*"
+ Action = "s3:GetObject"
+ Resource = "arn:aws:s3:::prod-${var.region}-starport-layer-bucket/*"
+ },
+ ]
+ })
+
+ ecr_endpoint_policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Sid = "PullTheEngineImage"
+ Effect = "Allow"
+ Principal = "*"
+ Action = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
+ Resource = aws_ecr_repository.engine.arn
+ Condition = local.execution_role_only
+ },
+ {
+ Sid = "RegistryToken"
+ Effect = "Allow"
+ Principal = "*"
+ Action = "ecr:GetAuthorizationToken"
+ Resource = "*"
+ Condition = local.execution_role_only
+ },
+ ]
+ })
+
+ logs_endpoint_policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Sid = "EngineLogs"
+ Effect = "Allow"
+ Principal = "*"
+ Action = ["logs:CreateLogStream", "logs:PutLogEvents"]
+ Resource = "${aws_cloudwatch_log_group.engine.arn}:*"
+ Condition = local.execution_role_only
+ }]
+ })
+}
+
+# The endpoints set no inline policy: these four resources own them, so the
+# endpoint drill can change the policies and nothing else.
+resource "aws_vpc_endpoint_policy" "s3" {
+ vpc_endpoint_id = aws_vpc_endpoint.s3.id
+ policy = try(var.drill.endpoints_open, false) ? local.endpoint_open_policy : local.s3_endpoint_policy
+}
+
+resource "aws_vpc_endpoint_policy" "ecr_api" {
+ vpc_endpoint_id = aws_vpc_endpoint.ecr_api.id
+ policy = try(var.drill.endpoints_open, false) ? local.endpoint_open_policy : local.ecr_endpoint_policy
+}
+
+resource "aws_vpc_endpoint_policy" "ecr_dkr" {
+ vpc_endpoint_id = aws_vpc_endpoint.ecr_dkr.id
+ policy = try(var.drill.endpoints_open, false) ? local.endpoint_open_policy : local.ecr_endpoint_policy
+}
+
+resource "aws_vpc_endpoint_policy" "logs" {
+ count = var.logs ? 1 : 0
+ vpc_endpoint_id = aws_vpc_endpoint.logs[0].id
+ policy = try(var.drill.endpoints_open, false) ? local.endpoint_open_policy : local.logs_endpoint_policy
+}
+
+# A security group cannot stop queries to the VPC resolver, so this does:
+# the services' names resolve and every other name does not exist.
+resource "aws_route53_resolver_firewall_domain_list" "allowed" {
+ name = "${var.name}-allowed"
+ domains = [
+ "s3.${var.region}.amazonaws.com",
+ "*.s3.${var.region}.amazonaws.com",
+ "api.ecr.${var.region}.amazonaws.com",
+ "*.dkr.ecr.${var.region}.amazonaws.com",
+ "logs.${var.region}.amazonaws.com",
+ ]
+}
+
+resource "aws_route53_resolver_firewall_domain_list" "everything" {
+ name = "${var.name}-everything"
+ domains = ["*"]
+}
+
+resource "aws_route53_resolver_firewall_rule_group" "engine" {
+ name = var.name
+}
+
+resource "aws_route53_resolver_firewall_rule" "allow" {
+ name = "${var.name}-allow"
+ firewall_rule_group_id = aws_route53_resolver_firewall_rule_group.engine.id
+ firewall_domain_list_id = aws_route53_resolver_firewall_domain_list.allowed.id
+ priority = 100
+ action = "ALLOW"
+}
+
+resource "aws_route53_resolver_firewall_rule" "block" {
+ name = "${var.name}-block"
+ firewall_rule_group_id = aws_route53_resolver_firewall_rule_group.engine.id
+ firewall_domain_list_id = aws_route53_resolver_firewall_domain_list.everything.id
+ priority = 200
+ action = "BLOCK"
+ block_response = "NXDOMAIN"
+}
+
+resource "aws_route53_resolver_firewall_rule_group_association" "engine" {
+ name = var.name
+ firewall_rule_group_id = aws_route53_resolver_firewall_rule_group.engine.id
+ vpc_id = aws_vpc.engine.id
+ priority = 1000
+ mutation_protection = "ENABLED"
+
+ # Rules first, so the VPC is never associated with a half-built group.
+ depends_on = [
+ aws_route53_resolver_firewall_rule.allow,
+ aws_route53_resolver_firewall_rule.block,
+ ]
+}
+
+# If DNS Firewall itself fails, queries are refused rather than let through.
+resource "aws_route53_resolver_firewall_config" "engine" {
+ resource_id = aws_vpc.engine.id
+ firewall_fail_open = "DISABLED"
+}
diff --git a/infra/modules/media-engine/outputs.tf b/infra/modules/media-engine/outputs.tf
new file mode 100644
index 000000000..d3a6d177d
--- /dev/null
+++ b/infra/modules/media-engine/outputs.tf
@@ -0,0 +1,35 @@
+output "carlos_media_engine" {
+ description = "The console's CARLOS_MEDIA_ENGINE. Empty until image_digest is set."
+ value = var.image_digest == "" ? "" : jsonencode({
+ v = 1
+ region = var.region
+ cluster = aws_ecs_cluster.engine.arn
+ task_definitions = { for key, td in aws_ecs_task_definition.engine : key => td.arn }
+ subnets = [for s in aws_subnet.private : s.id]
+ security_group = aws_security_group.tasks.id
+ conversion_role = aws_iam_role.conversion.arn
+ results_bucket = var.deployment_bucket_name
+ store_prefix = var.store_bucket_prefix
+ account_id = local.account_id
+ image = {
+ digest = var.image_digest
+ built_at = var.image_built_at
+ ffmpeg = var.image_ffmpeg
+ }
+ })
+}
+
+output "repository_url" {
+ description = "Where the engine image is pushed."
+ value = aws_ecr_repository.engine.repository_url
+}
+
+output "cluster_arn" {
+ description = "The engine's ECS cluster."
+ value = aws_ecs_cluster.engine.arn
+}
+
+output "conversion_role_arn" {
+ description = "The role the console assumes to sign one conversion's transfers."
+ value = aws_iam_role.conversion.arn
+}
diff --git a/infra/modules/media-engine/reaper.tf b/infra/modules/media-engine/reaper.tf
new file mode 100644
index 000000000..f82cc4529
--- /dev/null
+++ b/infra/modules/media-engine/reaper.tf
@@ -0,0 +1,92 @@
+# A backstop on a one-minute schedule: it stops any task of this cluster older
+# than reaper_max_age_minutes. No bound in the design rests on its timing.
+
+data "archive_file" "reaper" {
+ type = "zip"
+ source_file = "${path.module}/reaper/reaper.py"
+ output_path = "${path.root}/.terraform/media-engine/${var.name}-reaper.zip"
+}
+
+resource "aws_cloudwatch_log_group" "reaper" {
+ name = "/aws/lambda/${var.name}-reaper"
+ retention_in_days = var.log_retention_days
+}
+
+resource "aws_iam_role" "reaper" {
+ name = "${var.name}-reaper"
+ assume_role_policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Effect = "Allow"
+ Principal = { Service = "lambda.amazonaws.com" }
+ Action = "sts:AssumeRole"
+ }]
+ })
+}
+
+resource "aws_iam_role_policy" "reaper" {
+ name = "${var.name}-reaper"
+ role = aws_iam_role.reaper.id
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Sid = "ListTasks"
+ Effect = "Allow"
+ Action = "ecs:ListTasks"
+ Resource = "*"
+ Condition = { ArnEquals = { "ecs:cluster" = aws_ecs_cluster.engine.arn } }
+ },
+ {
+ Sid = "StopOldTasks"
+ Effect = "Allow"
+ Action = ["ecs:DescribeTasks", "ecs:StopTask"]
+ Resource = local.cluster_tasks
+ },
+ {
+ Sid = "OwnLogs"
+ Effect = "Allow"
+ Action = ["logs:CreateLogStream", "logs:PutLogEvents"]
+ Resource = "${aws_cloudwatch_log_group.reaper.arn}:*"
+ },
+ ]
+ })
+}
+
+resource "aws_lambda_function" "reaper" {
+ function_name = "${var.name}-reaper"
+ role = aws_iam_role.reaper.arn
+ runtime = "python3.13"
+ architectures = ["arm64"]
+ handler = "reaper.handler"
+ filename = data.archive_file.reaper.output_path
+ source_code_hash = data.archive_file.reaper.output_base64sha256
+ timeout = 50
+
+ environment {
+ variables = {
+ CLUSTER = aws_ecs_cluster.engine.arn
+ MAX_AGE_MINUTES = tostring(var.reaper_max_age_minutes)
+ }
+ }
+
+ depends_on = [aws_cloudwatch_log_group.reaper, aws_iam_role_policy.reaper]
+}
+
+resource "aws_cloudwatch_event_rule" "reaper" {
+ name = "${var.name}-reaper"
+ schedule_expression = "rate(1 minute)"
+}
+
+resource "aws_cloudwatch_event_target" "reaper" {
+ rule = aws_cloudwatch_event_rule.reaper.name
+ arn = aws_lambda_function.reaper.arn
+}
+
+resource "aws_lambda_permission" "reaper" {
+ statement_id = "AllowEventBridge"
+ action = "lambda:InvokeFunction"
+ function_name = aws_lambda_function.reaper.function_name
+ principal = "events.amazonaws.com"
+ source_arn = aws_cloudwatch_event_rule.reaper.arn
+}
diff --git a/infra/modules/media-engine/reaper/reaper.py b/infra/modules/media-engine/reaper/reaper.py
new file mode 100644
index 000000000..fc04fb408
--- /dev/null
+++ b/infra/modules/media-engine/reaper/reaper.py
@@ -0,0 +1,72 @@
+"""The media engine's reaper: a backstop that stops tasks past their age.
+
+Every minute it stops each running task of one cluster that is older than
+MAX_AGE_MINUTES. It reads the cluster and the age from its environment and
+nothing from the event, so it handles no tenant input. No bound in the design
+rests on its timing.
+"""
+
+import os
+from datetime import datetime, timedelta, timezone
+
+DESCRIBE_BATCH = 100
+
+
+def _client():
+ import boto3
+
+ return boto3.client("ecs")
+
+
+def _now():
+ return datetime.now(timezone.utc)
+
+
+def _running(ecs, cluster):
+ arns = []
+ args = {"cluster": cluster, "desiredStatus": "RUNNING"}
+ while True:
+ page = ecs.list_tasks(**args)
+ arns.extend(page.get("taskArns", []))
+ token = page.get("nextToken")
+ if not token:
+ return arns
+ args["nextToken"] = token
+
+
+def _described(ecs, cluster, arns):
+ """Every task in arns, or an exception: a partial answer stops nothing."""
+ tasks = []
+ for start in range(0, len(arns), DESCRIBE_BATCH):
+ answer = ecs.describe_tasks(cluster=cluster, tasks=arns[start:start + DESCRIBE_BATCH])
+ # MISSING is a task that has already gone. Anything else says nothing
+ # about the task, so this run decides nothing.
+ if any(f.get("reason") != "MISSING" for f in answer.get("failures", [])):
+ raise RuntimeError("carlos media reaper: a task could not be described")
+ tasks.extend(answer.get("tasks", []))
+ return tasks
+
+
+def handler(event, context):
+ cluster = os.environ["CLUSTER"]
+ minutes = int(os.environ["MAX_AGE_MINUTES"])
+ ecs = _client()
+ oldest_allowed = _now() - timedelta(minutes=minutes)
+
+ tasks = _described(ecs, cluster, _running(ecs, cluster))
+ old = [t for t in tasks if "createdAt" in t and t["createdAt"] < oldest_allowed]
+
+ refused = 0
+ for t in old:
+ try:
+ ecs.stop_task(
+ cluster=cluster,
+ task=t["taskArn"],
+ reason=f"carlos media reaper: older than {minutes} minutes",
+ )
+ except Exception:
+ # The rest are still stopped; the run is reported failed below.
+ refused += 1
+ if refused:
+ raise RuntimeError(f"carlos media reaper: {refused} of {len(old)} tasks were not stopped")
+ return {"stopped": len(old)}
diff --git a/infra/modules/media-engine/reaper/reaper_test.py b/infra/modules/media-engine/reaper/reaper_test.py
new file mode 100644
index 000000000..e74d00308
--- /dev/null
+++ b/infra/modules/media-engine/reaper/reaper_test.py
@@ -0,0 +1,160 @@
+"""Tests for the media engine's reaper, on a stub ECS client."""
+
+import os
+import unittest
+from datetime import datetime, timedelta, timezone
+from unittest import mock
+
+import reaper
+
+NOW = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
+CLUSTER = "arn:aws:ecs:eu-west-1:123456789012:cluster/media"
+
+
+def task(arn, age_minutes):
+ return {"taskArn": arn, "createdAt": NOW - timedelta(minutes=age_minutes)}
+
+
+class StubECS:
+ def __init__(self, pages, tasks, describe_error=None, failures=None, stop_errors=()):
+ self.pages = pages
+ self.tasks = {t["taskArn"]: t for t in tasks}
+ self.describe_error = describe_error
+ self.failures = failures or []
+ self.stop_errors = set(stop_errors)
+ self.list_calls = []
+ self.describe_calls = []
+ self.stopped = []
+
+ def list_tasks(self, **kwargs):
+ self.list_calls.append(kwargs)
+ return self.pages[len(self.list_calls) - 1]
+
+ def describe_tasks(self, **kwargs):
+ self.describe_calls.append(kwargs)
+ if self.describe_error is not None:
+ raise self.describe_error
+ return {
+ "tasks": [self.tasks[a] for a in kwargs["tasks"] if a in self.tasks],
+ "failures": self.failures,
+ }
+
+ def stop_task(self, **kwargs):
+ if kwargs["task"] in self.stop_errors:
+ raise RuntimeError("refused")
+ self.stopped.append(kwargs)
+ return {}
+
+
+def run(stub, event=None):
+ env = {"CLUSTER": CLUSTER, "MAX_AGE_MINUTES": "70"}
+ with mock.patch.dict(os.environ, env, clear=True), \
+ mock.patch.object(reaper, "_client", return_value=stub), \
+ mock.patch.object(reaper, "_now", return_value=NOW):
+ return reaper.handler(event if event is not None else {}, None)
+
+
+class ReaperTest(unittest.TestCase):
+ def test_an_old_task_is_stopped(self):
+ stub = StubECS([{"taskArns": ["old"]}], [task("old", 71)])
+ run(stub)
+ self.assertEqual(stub.stopped, [{
+ "cluster": CLUSTER,
+ "task": "old",
+ "reason": "carlos media reaper: older than 70 minutes",
+ }])
+
+ def test_a_young_task_is_not_stopped(self):
+ stub = StubECS([{"taskArns": ["young"]}], [task("young", 69)])
+ run(stub)
+ self.assertEqual(stub.stopped, [])
+
+ def test_a_task_exactly_at_the_limit_is_not_stopped(self):
+ stub = StubECS([{"taskArns": ["edge"]}], [task("edge", 70)])
+ run(stub)
+ self.assertEqual(stub.stopped, [])
+
+ def test_a_task_with_no_creation_time_is_not_stopped(self):
+ stub = StubECS([{"taskArns": ["unknown"]}], [{"taskArn": "unknown"}])
+ run(stub)
+ self.assertEqual(stub.stopped, [])
+
+ def test_only_running_tasks_of_the_cluster_are_listed(self):
+ stub = StubECS([{"taskArns": []}], [])
+ run(stub)
+ self.assertEqual(stub.list_calls, [{"cluster": CLUSTER, "desiredStatus": "RUNNING"}])
+ self.assertEqual(stub.describe_calls, [])
+
+ def test_pagination_across_two_pages(self):
+ stub = StubECS(
+ [{"taskArns": ["a"], "nextToken": "more"}, {"taskArns": ["b"]}],
+ [task("a", 80), task("b", 90)],
+ )
+ run(stub)
+ self.assertEqual(stub.list_calls[1], {
+ "cluster": CLUSTER, "desiredStatus": "RUNNING", "nextToken": "more",
+ })
+ self.assertEqual([s["task"] for s in stub.stopped], ["a", "b"])
+
+ def test_describes_in_batches_of_100(self):
+ arns = [f"t{i}" for i in range(250)]
+ stub = StubECS([{"taskArns": arns}], [task(a, 1) for a in arns])
+ run(stub)
+ self.assertEqual([len(c["tasks"]) for c in stub.describe_calls], [100, 100, 50])
+
+ def test_a_describe_failure_stops_nothing(self):
+ stub = StubECS([{"taskArns": ["old"]}], [task("old", 500)], describe_error=RuntimeError("throttled"))
+ with self.assertRaises(RuntimeError):
+ run(stub)
+ self.assertEqual(stub.stopped, [])
+
+ def test_a_failure_in_a_later_batch_stops_nothing(self):
+ arns = [f"t{i}" for i in range(101)]
+ stub = StubECS([{"taskArns": arns}], [task(a, 500) for a in arns])
+ real = stub.describe_tasks
+
+ def second_batch_fails(**kwargs):
+ if stub.describe_calls:
+ raise RuntimeError("throttled")
+ return real(**kwargs)
+
+ stub.describe_tasks = second_batch_fails
+ with self.assertRaises(RuntimeError):
+ run(stub)
+ self.assertEqual(stub.stopped, [])
+
+ def test_a_reported_describe_failure_stops_nothing(self):
+ stub = StubECS(
+ [{"taskArns": ["old", "odd"]}], [task("old", 500)],
+ failures=[{"arn": "odd", "reason": "INTERNAL"}],
+ )
+ with self.assertRaises(RuntimeError):
+ run(stub)
+ self.assertEqual(stub.stopped, [])
+
+ def test_a_missing_task_is_not_a_failure(self):
+ stub = StubECS(
+ [{"taskArns": ["old", "gone"]}], [task("old", 500)],
+ failures=[{"arn": "gone", "reason": "MISSING"}],
+ )
+ run(stub)
+ self.assertEqual([s["task"] for s in stub.stopped], ["old"])
+
+ def test_one_refused_stop_does_not_spare_the_rest(self):
+ stub = StubECS(
+ [{"taskArns": ["a", "b"]}], [task("a", 500), task("b", 500)],
+ stop_errors=["a"],
+ )
+ with self.assertRaises(RuntimeError):
+ run(stub)
+ self.assertEqual([s["task"] for s in stub.stopped], ["b"])
+
+ def test_the_event_is_not_read(self):
+ stub = StubECS([{"taskArns": ["young"]}], [task("young", 1)])
+ run(stub, event={"cluster": "other", "MAX_AGE_MINUTES": "0", "tasks": ["young"]})
+ self.assertEqual(stub.stopped, [])
+ self.assertEqual(stub.list_calls[0]["cluster"], CLUSTER)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/infra/modules/media-engine/tests/media_engine.tftest.hcl b/infra/modules/media-engine/tests/media_engine.tftest.hcl
new file mode 100644
index 000000000..de7902763
--- /dev/null
+++ b/infra/modules/media-engine/tests/media_engine.tftest.hcl
@@ -0,0 +1,765 @@
+# Mock resources only: this suite never contacts an AWS account.
+mock_provider "aws" {
+ mock_data "aws_caller_identity" {
+ defaults = { account_id = "123456789012" }
+ }
+ mock_data "aws_availability_zones" {
+ defaults = { names = ["eu-west-1a", "eu-west-1b", "eu-west-1c"] }
+ }
+}
+
+override_resource {
+ target = aws_iam_role.execution
+ values = { arn = "arn:aws:iam::123456789012:role/carlos-test-media-execution" }
+}
+
+override_resource {
+ target = aws_iam_role.conversion
+ values = { arn = "arn:aws:iam::123456789012:role/carlos-test-media-conversion" }
+}
+
+override_resource {
+ target = aws_iam_role.reaper
+ values = { arn = "arn:aws:iam::123456789012:role/carlos-test-media-reaper" }
+}
+
+override_resource {
+ target = aws_lambda_function.reaper
+ values = { arn = "arn:aws:lambda:eu-west-1:123456789012:function:carlos-test-media-reaper" }
+}
+
+override_resource {
+ target = aws_cloudwatch_event_rule.reaper
+ values = { arn = "arn:aws:events:eu-west-1:123456789012:rule/carlos-test-media-reaper" }
+}
+
+override_resource {
+ target = aws_ecr_repository.engine
+ values = {
+ arn = "arn:aws:ecr:eu-west-1:123456789012:repository/carlos-test-media"
+ repository_url = "123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media"
+ }
+}
+
+override_resource {
+ target = aws_cloudwatch_log_group.engine
+ values = { arn = "arn:aws:logs:eu-west-1:123456789012:log-group:/carlos/carlos-test-media/engine" }
+}
+
+override_resource {
+ target = aws_cloudwatch_log_group.reaper
+ values = { arn = "arn:aws:logs:eu-west-1:123456789012:log-group:/aws/lambda/carlos-test-media-reaper" }
+}
+
+override_resource {
+ target = aws_ecs_cluster.engine
+ values = { arn = "arn:aws:ecs:eu-west-1:123456789012:cluster/carlos-test-media" }
+}
+
+override_resource {
+ target = aws_vpc.engine
+ values = { id = "vpc-0123456789abcdef0" }
+}
+
+override_resource {
+ target = aws_subnet.private
+ values = { id = "subnet-0123456789abcdef0" }
+}
+
+override_resource {
+ target = aws_security_group.tasks
+ values = { id = "sg-0123456789abcdef0" }
+}
+
+override_resource {
+ target = aws_security_group.endpoints
+ values = { id = "sg-0fedcba9876543210" }
+}
+
+override_resource {
+ target = aws_vpc_endpoint.s3
+ values = { id = "vpce-0123456789abcdef0", prefix_list_id = "pl-6da54004" }
+}
+
+override_resource {
+ target = aws_ecs_task_definition.engine
+ values = { arn = "arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7" }
+}
+
+variables {
+ name = "carlos-test-media"
+ region = "eu-west-1"
+ store_region = "eu-west-1"
+ store_bucket_prefix = "carlos-test-store-"
+ deployment_bucket_name = "carlos-test-deployment"
+ console_role_name = "carlos-test-console"
+ console_role_arn = "arn:aws:iam::123456789012:role/carlos-test-console"
+}
+
+run "region_must_be_store_region" {
+ command = plan
+ variables {
+ store_region = "us-east-1"
+ }
+ expect_failures = [aws_ecr_repository.engine]
+}
+
+run "no_digest_creates_only_the_repository" {
+ command = apply
+ assert {
+ condition = length(aws_ecs_task_definition.engine) == 0
+ error_message = "no task definition before there is an image"
+ }
+ assert {
+ condition = output.carlos_media_engine == ""
+ error_message = "the console's variable stays empty until there is an image"
+ }
+ assert {
+ condition = (
+ aws_ecr_repository.engine.image_tag_mutability == "IMMUTABLE"
+ && aws_ecr_repository.engine.image_scanning_configuration[0].scan_on_push
+ )
+ error_message = "immutable tags, scanned on push"
+ }
+ assert {
+ condition = output.repository_url == "123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media"
+ error_message = "the first apply answers where to push"
+ }
+}
+
+run "task_definitions_pass_the_gate" {
+ command = apply
+ variables {
+ image_digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ image_built_at = "2026-11-18T00:00:00Z"
+ image_ffmpeg = "7:7.1.5-0+deb13u1"
+ }
+ assert {
+ condition = jsonencode(sort(keys(aws_ecs_task_definition.engine))) == jsonencode(["audio-aac/long", "audio-aac/short", "video-720p/long", "video-720p/short"])
+ error_message = "one definition per class"
+ }
+ assert {
+ condition = alltrue([for k, td in aws_ecs_task_definition.engine :
+ td.family == "carlos-test-media-${replace(k, "/", "-")}"
+ ])
+ error_message = "family is <name>-<preset>-<class>"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ td.task_role_arn == null && td.pid_mode == null
+ ])
+ error_message = "no task role and no pid mode"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ td.runtime_platform[0].cpu_architecture == "ARM64" && td.runtime_platform[0].operating_system_family == "LINUX"
+ ])
+ error_message = "Linux on ARM64"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ td.network_mode == "awsvpc" && jsonencode(td.requires_compatibilities) == jsonencode(["FARGATE"])
+ ])
+ error_message = "Fargate in awsvpc mode"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ jsonencode([for v in td.volume : v.name]) == jsonencode(["scratch"]) && alltrue([for v in td.volume : v.host_path == null])
+ ])
+ error_message = "one volume, scratch, with no host path"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ jsonencode([for c in jsondecode(td.container_definitions) : c.name]) == jsonencode(["deadline", "codec"])
+ ])
+ error_message = "the deadline and codec containers, nothing else"
+ }
+ assert {
+ condition = alltrue(flatten([for td in aws_ecs_task_definition.engine : [for c in jsondecode(td.container_definitions) :
+ c.essential == true && c.stopTimeout == 30 && c.readonlyRootFilesystem == true && c.user == "65534:65534"
+ ]]))
+ error_message = "both essential, 30 s to stop, read-only root, the numeric non-root user"
+ }
+ assert {
+ condition = alltrue(flatten([for td in aws_ecs_task_definition.engine : [for c in jsondecode(td.container_definitions) :
+ jsonencode(c.linuxParameters.capabilities) == jsonencode({ drop = ["ALL"] })
+ ]]))
+ error_message = "every capability dropped and none added"
+ }
+ assert {
+ condition = alltrue(flatten([for td in aws_ecs_task_definition.engine : [for c in jsondecode(td.container_definitions) :
+ c.image == "123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ ]]))
+ error_message = "both containers run the repository's image, pinned by digest"
+ }
+ assert {
+ condition = alltrue(flatten([for td in aws_ecs_task_definition.engine : [for c in jsondecode(td.container_definitions) :
+ jsonencode(c.entryPoint) == jsonencode(["/usr/local/bin/carlos-media"]) && jsonencode(c.command) == jsonencode([c.name])
+ ]]))
+ error_message = "each container runs exactly its role"
+ }
+ assert {
+ condition = alltrue(flatten([for td in aws_ecs_task_definition.engine : [for c in jsondecode(td.container_definitions) :
+ !can(c.restartPolicy) && !can(c.volumesFrom)
+ ]]))
+ error_message = "no restart policy and no volumesFrom"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ !can(jsondecode(td.container_definitions)[0].dependsOn)
+ && jsonencode(try(jsondecode(td.container_definitions)[1].dependsOn, null)) == jsonencode([{ condition = "START", containerName = "deadline" }])
+ ])
+ error_message = "codec depends on deadline's START, and deadline on nothing"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ !can(jsondecode(td.container_definitions)[0].mountPoints)
+ && jsonencode([for m in jsondecode(td.container_definitions)[1].mountPoints : [m.sourceVolume, m.containerPath]]) == jsonencode([["scratch", "/scratch"]])
+ ])
+ error_message = "scratch is mounted in codec only"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ jsonencode(jsondecode(td.container_definitions)[1].environment) == jsonencode([{ name = "TMPDIR", value = "/scratch/tmp" }])
+ && !can(jsondecode(td.container_definitions)[0].environment)
+ ])
+ error_message = "codec alone gets TMPDIR"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ !can(jsondecode(td.container_definitions)[0].logConfiguration)
+ && jsondecode(td.container_definitions)[1].logConfiguration.logDriver == "awslogs"
+ && jsondecode(td.container_definitions)[1].logConfiguration.options["awslogs-group"] == "/carlos/carlos-test-media/engine"
+ && jsondecode(td.container_definitions)[1].logConfiguration.options["awslogs-region"] == "eu-west-1"
+ ])
+ error_message = "codec alone logs, to the engine's log group"
+ }
+ assert {
+ condition = jsonencode({ for k, td in aws_ecs_task_definition.engine : k => [td.cpu, td.memory] }) == jsonencode({
+ "audio-aac/long" = ["2048", "4096"]
+ "audio-aac/short" = ["1024", "2048"]
+ "video-720p/long" = ["16384", "32768"]
+ "video-720p/short" = ["4096", "8192"]
+ })
+ error_message = "CPU and memory per class"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine :
+ jsondecode(td.container_definitions)[0].cpu == 64
+ && jsondecode(td.container_definitions)[0].memory == 64
+ && jsondecode(td.container_definitions)[1].cpu == tonumber(td.cpu) - 64
+ && jsondecode(td.container_definitions)[1].memory == tonumber(td.memory) - 64
+ ])
+ error_message = "deadline holds 64 units and 64 MiB, codec the rest"
+ }
+ assert {
+ condition = alltrue([for td in aws_ecs_task_definition.engine : length(td.ephemeral_storage) == 0])
+ error_message = "storage is set per run unless a class says otherwise"
+ }
+}
+
+run "a_class_can_fix_its_storage" {
+ command = apply
+ variables {
+ image_digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ image_built_at = "2026-11-18T00:00:00Z"
+ image_ffmpeg = "7:7.1.5-0+deb13u1"
+ classes = [
+ { preset = "video-720p", class = "short", cpu = 4096, memory = 8192 },
+ { preset = "video-720p", class = "long", cpu = 16384, memory = 32768, ephemeral_gib = 48 },
+ { preset = "audio-aac", class = "short", cpu = 1024, memory = 2048 },
+ { preset = "audio-aac", class = "long", cpu = 2048, memory = 4096 },
+ ]
+ }
+ assert {
+ condition = (
+ aws_ecs_task_definition.engine["video-720p/long"].ephemeral_storage[0].size_in_gib == 48
+ && length(aws_ecs_task_definition.engine["video-720p/short"].ephemeral_storage) == 0
+ )
+ error_message = "ephemeral_gib sets that class's storage alone"
+ }
+}
+
+run "logs_off_removes_the_logs_path" {
+ command = apply
+ variables {
+ logs = false
+ image_digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ image_built_at = "2026-11-18T00:00:00Z"
+ image_ffmpeg = "7:7.1.5-0+deb13u1"
+ }
+ assert {
+ condition = length(aws_vpc_endpoint.logs) == 0 && length(aws_vpc_endpoint_policy.logs) == 0
+ error_message = "no logs endpoint when logs are off"
+ }
+ assert {
+ condition = alltrue(flatten([for td in aws_ecs_task_definition.engine : [for c in jsondecode(td.container_definitions) :
+ !can(c.logConfiguration)
+ ]]))
+ error_message = "no container logs when logs are off"
+ }
+}
+
+run "endpoint_policies_name_their_principals" {
+ command = apply
+ assert {
+ condition = jsonencode(jsondecode(aws_vpc_endpoint_policy.s3.policy).Statement) == jsonencode([
+ {
+ Action = ["s3:GetObject", "s3:PutObject"]
+ Condition = { StringEquals = { "aws:PrincipalArn" = "arn:aws:iam::123456789012:role/carlos-test-media-conversion" } }
+ Effect = "Allow"
+ Principal = "*"
+ Resource = ["arn:aws:s3:::carlos-test-store-*/*", "arn:aws:s3:::carlos-test-deployment/media-results/*"]
+ Sid = "ConversionTransfers"
+ },
+ {
+ Action = "s3:GetObject"
+ Effect = "Allow"
+ Principal = "*"
+ Resource = "arn:aws:s3:::prod-eu-west-1-starport-layer-bucket/*"
+ Sid = "ImageLayers"
+ },
+ ])
+ error_message = "the S3 endpoint admits the conversion role's transfers and reads of the layer bucket, nothing else"
+ }
+ assert {
+ condition = alltrue(flatten([for p in [aws_vpc_endpoint_policy.ecr_api.policy, aws_vpc_endpoint_policy.ecr_dkr.policy, aws_vpc_endpoint_policy.logs[0].policy] : [
+ for s in jsondecode(p).Statement :
+ s.Effect == "Allow" && jsonencode(try(s.Condition, null)) == jsonencode({ StringEquals = { "aws:PrincipalArn" = "arn:aws:iam::123456789012:role/carlos-test-media-execution" } })
+ ]]))
+ error_message = "every interface endpoint statement names the execution role"
+ }
+ assert {
+ condition = alltrue([for p in [aws_vpc_endpoint_policy.ecr_api.policy, aws_vpc_endpoint_policy.ecr_dkr.policy] :
+ jsonencode([for s in jsondecode(p).Statement : [s.Action, s.Resource]]) == jsonencode([
+ [["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"], "arn:aws:ecr:eu-west-1:123456789012:repository/carlos-test-media"],
+ ["ecr:GetAuthorizationToken", "*"],
+ ])
+ ])
+ error_message = "both registry endpoints admit pulls of this repository and the token"
+ }
+ assert {
+ condition = jsonencode([for s in jsondecode(aws_vpc_endpoint_policy.logs[0].policy).Statement : [s.Action, s.Resource]]) == jsonencode([
+ [["logs:CreateLogStream", "logs:PutLogEvents"], "arn:aws:logs:eu-west-1:123456789012:log-group:/carlos/carlos-test-media/engine:*"],
+ ])
+ error_message = "the logs endpoint admits writes to the engine's log group only"
+ }
+ assert {
+ condition = (
+ aws_vpc_endpoint.ecr_api.private_dns_enabled && aws_vpc_endpoint.ecr_dkr.private_dns_enabled && aws_vpc_endpoint.logs[0].private_dns_enabled
+ && aws_vpc_endpoint.s3.vpc_endpoint_type == "Gateway"
+ && aws_vpc_endpoint.ecr_api.service_name == "com.amazonaws.eu-west-1.ecr.api"
+ && aws_vpc_endpoint.ecr_dkr.service_name == "com.amazonaws.eu-west-1.ecr.dkr"
+ && aws_vpc_endpoint.logs[0].service_name == "com.amazonaws.eu-west-1.logs"
+ )
+ error_message = "the four endpoints, with private DNS on the interface ones"
+ }
+}
+
+run "tasks_sg_has_no_ingress_and_only_https_egress" {
+ command = apply
+ assert {
+ condition = length(aws_security_group.tasks.ingress) == 0
+ error_message = "nothing connects to a task"
+ }
+ assert {
+ condition = length(aws_security_group.tasks.egress) == 2 && alltrue([for e in aws_security_group.tasks.egress :
+ e.from_port == 443 && e.to_port == 443 && e.protocol == "tcp"
+ && length(e.cidr_blocks) == 0 && length(e.ipv6_cidr_blocks) == 0 && !e.self
+ ])
+ error_message = "egress is TCP 443 and names no address range"
+ }
+ assert {
+ condition = (
+ jsonencode(flatten([for e in aws_security_group.tasks.egress : e.prefix_list_ids])) == jsonencode(["pl-6da54004"])
+ && jsonencode(flatten([for e in aws_security_group.tasks.egress : tolist(e.security_groups)])) == jsonencode(["sg-0fedcba9876543210"])
+ )
+ error_message = "egress reaches the S3 prefix list and the endpoints' group only"
+ }
+ assert {
+ condition = (
+ aws_vpc_security_group_ingress_rule.endpoints_from_tasks.security_group_id == "sg-0fedcba9876543210"
+ && aws_vpc_security_group_ingress_rule.endpoints_from_tasks.referenced_security_group_id == "sg-0123456789abcdef0"
+ && aws_vpc_security_group_ingress_rule.endpoints_from_tasks.ip_protocol == "tcp"
+ && aws_vpc_security_group_ingress_rule.endpoints_from_tasks.from_port == 443
+ && aws_vpc_security_group_ingress_rule.endpoints_from_tasks.to_port == 443
+ && aws_vpc_security_group_ingress_rule.endpoints_from_tasks.cidr_ipv4 == null
+ && length(aws_security_group.endpoints.egress) == 0
+ )
+ error_message = "the endpoints admit TCP 443 from the tasks' group only"
+ }
+}
+
+run "no_default_route" {
+ command = apply
+ assert {
+ condition = length(aws_route_table.private.route) == 0
+ error_message = "the route table holds no route of its own"
+ }
+ assert {
+ condition = !can(regex("aws_internet_gateway|aws_egress_only_internet_gateway|aws_nat_gateway|\"aws_route\"", join("\n", [
+ file("${path.module}/main.tf"), file("${path.module}/network.tf"), file("${path.module}/ecs.tf"),
+ file("${path.module}/iam.tf"), file("${path.module}/reaper.tf"),
+ ])))
+ error_message = "no gateway and no separate route anywhere in the module"
+ }
+ assert {
+ condition = (
+ aws_vpc.engine.enable_dns_support && aws_vpc.engine.enable_dns_hostnames
+ && jsonencode(aws_subnet.private[*].cidr_block) == jsonencode(["10.98.0.0/25", "10.98.0.128/25"])
+ && aws_subnet.private[0].availability_zone != aws_subnet.private[1].availability_zone
+ && alltrue([for s in aws_subnet.private : s.map_public_ip_on_launch == false])
+ && jsonencode(tolist(aws_vpc_endpoint.s3.route_table_ids)) == jsonencode([aws_route_table.private.id])
+ )
+ error_message = "two private /25 subnets in two zones, DNS on, S3 routed by its endpoint"
+ }
+}
+
+run "dns_firewall_allows_three_services_and_blocks_the_rest" {
+ command = apply
+ assert {
+ condition = jsonencode(sort(tolist(aws_route53_resolver_firewall_domain_list.allowed.domains))) == jsonencode(sort([
+ "s3.eu-west-1.amazonaws.com",
+ "*.s3.eu-west-1.amazonaws.com",
+ "api.ecr.eu-west-1.amazonaws.com",
+ "*.dkr.ecr.eu-west-1.amazonaws.com",
+ "logs.eu-west-1.amazonaws.com",
+ ]))
+ error_message = "the allow list is S3, the registry and logs in this region"
+ }
+ assert {
+ condition = (
+ aws_route53_resolver_firewall_rule.allow.priority == 100
+ && aws_route53_resolver_firewall_rule.allow.action == "ALLOW"
+ && aws_route53_resolver_firewall_rule.allow.firewall_domain_list_id == aws_route53_resolver_firewall_domain_list.allowed.id
+ )
+ error_message = "the allow list is allowed first"
+ }
+ assert {
+ condition = (
+ aws_route53_resolver_firewall_rule.block.priority == 200
+ && aws_route53_resolver_firewall_rule.block.action == "BLOCK"
+ && aws_route53_resolver_firewall_rule.block.block_response == "NXDOMAIN"
+ && aws_route53_resolver_firewall_rule.block.firewall_domain_list_id == aws_route53_resolver_firewall_domain_list.everything.id
+ && jsonencode(tolist(aws_route53_resolver_firewall_domain_list.everything.domains)) == jsonencode(["*"])
+ )
+ error_message = "every other name answers NXDOMAIN"
+ }
+ assert {
+ condition = (
+ aws_route53_resolver_firewall_rule_group_association.engine.vpc_id == "vpc-0123456789abcdef0"
+ && aws_route53_resolver_firewall_rule_group_association.engine.mutation_protection == "ENABLED"
+ && aws_route53_resolver_firewall_config.engine.resource_id == "vpc-0123456789abcdef0"
+ && aws_route53_resolver_firewall_config.engine.firewall_fail_open == "DISABLED"
+ )
+ error_message = "associated with the VPC, protected from change, and closed if the firewall fails"
+ }
+}
+
+run "conversion_role_policy_exact" {
+ command = apply
+ assert {
+ condition = jsonencode(jsondecode(aws_iam_role_policy.conversion.policy).Statement) == jsonencode([
+ { Action = "s3:GetObject", Effect = "Allow", Resource = "arn:aws:s3:::carlos-test-store-*/*", Sid = "ReadSources" },
+ { Action = "s3:PutObject", Effect = "Allow", Resource = "arn:aws:s3:::carlos-test-store-*/derived/*", Sid = "WriteOutputs" },
+ { Action = "s3:PutObject", Effect = "Allow", Resource = "arn:aws:s3:::carlos-test-deployment/media-results/*", Sid = "WriteResults" },
+ {
+ Action = "s3:GetObject"
+ Condition = { StringEquals = { "s3:ExistingObjectTag/carlos-scan" = "infected" } }
+ Effect = "Deny"
+ Resource = "arn:aws:s3:::carlos-test-store-*/*"
+ Sid = "NeverReadInfected"
+ },
+ {
+ Action = "s3:PutObject"
+ Condition = { "ForAnyValue:StringEquals" = { "s3:RequestObjectTagKeys" = ["carlos-scan", "carlos-scan-version", "carlos-scan-at", "carlos-scan-sig"] } }
+ Effect = "Deny"
+ Resource = "*"
+ Sid = "NeverWriteScanTags"
+ },
+ ])
+ error_message = "three Allows and two Denies, exactly"
+ }
+ assert {
+ condition = jsonencode(jsondecode(aws_iam_role.conversion.assume_role_policy).Statement) == jsonencode([{
+ Action = "sts:AssumeRole"
+ Effect = "Allow"
+ Principal = { AWS = "arn:aws:iam::123456789012:role/carlos-test-console" }
+ }])
+ error_message = "only the console may assume the conversion role"
+ }
+ assert {
+ condition = aws_iam_role.conversion.max_session_duration == 3600
+ error_message = "sessions last at most an hour"
+ }
+ assert {
+ condition = jsonencode(jsondecode(aws_iam_role.execution.assume_role_policy).Statement) == jsonencode([{
+ Action = "sts:AssumeRole"
+ Condition = { StringEquals = { "aws:SourceAccount" = "123456789012" } }
+ Effect = "Allow"
+ Principal = { Service = "ecs-tasks.amazonaws.com" }
+ }])
+ error_message = "the execution role is for ECS tasks of this account"
+ }
+ assert {
+ condition = jsonencode(jsondecode(aws_iam_role_policy.execution.policy).Statement) == jsonencode([
+ { Action = "ecr:GetAuthorizationToken", Effect = "Allow", Resource = "*" },
+ { Action = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"], Effect = "Allow", Resource = "arn:aws:ecr:eu-west-1:123456789012:repository/carlos-test-media" },
+ { Action = ["logs:CreateLogStream", "logs:PutLogEvents"], Effect = "Allow", Resource = "arn:aws:logs:eu-west-1:123456789012:log-group:/carlos/carlos-test-media/engine:*" },
+ ])
+ error_message = "the execution role pulls this image and writes this log group"
+ }
+}
+
+run "console_policy_exact" {
+ command = apply
+ assert {
+ condition = aws_iam_role_policy.console.role == "carlos-test-console"
+ error_message = "the policy goes on the console's role"
+ }
+ assert {
+ condition = jsonencode(jsondecode(aws_iam_role_policy.console.policy).Statement) == jsonencode([
+ { Action = "sts:AssumeRole", Effect = "Allow", Resource = "arn:aws:iam::123456789012:role/carlos-test-media-conversion", Sid = "AssumeConversion" },
+ {
+ Action = "ecs:RunTask"
+ Condition = { ArnEquals = { "ecs:cluster" = "arn:aws:ecs:eu-west-1:123456789012:cluster/carlos-test-media" } }
+ Effect = "Allow"
+ Resource = "arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-*:*"
+ Sid = "RunTasks"
+ },
+ { Action = ["ecs:DescribeTasks", "ecs:StopTask"], Effect = "Allow", Resource = "arn:aws:ecs:eu-west-1:123456789012:task/carlos-test-media/*", Sid = "WatchTasks" },
+ {
+ Action = "ecs:ListTasks"
+ Condition = { ArnEquals = { "ecs:cluster" = "arn:aws:ecs:eu-west-1:123456789012:cluster/carlos-test-media" } }
+ Effect = "Allow"
+ Resource = "*"
+ Sid = "ListTasks"
+ },
+ { Action = "ecs:DescribeTaskDefinition", Effect = "Allow", Resource = "*", Sid = "ReadTaskDefinitions" },
+ {
+ Action = "iam:PassRole"
+ Condition = { StringEquals = { "iam:PassedToService" = "ecs-tasks.amazonaws.com" } }
+ Effect = "Allow"
+ Resource = "arn:aws:iam::123456789012:role/carlos-test-media-execution"
+ Sid = "PassExecutionRole"
+ },
+ {
+ Action = "s3:ListBucket"
+ Condition = { StringLike = { "s3:prefix" = "media-results/*" } }
+ Effect = "Allow"
+ Resource = "arn:aws:s3:::carlos-test-deployment"
+ Sid = "ListResults"
+ },
+ ])
+ error_message = "the console's grants, exactly"
+ }
+}
+
+run "reaper_role_is_cluster_scoped" {
+ command = apply
+ assert {
+ condition = jsonencode(jsondecode(aws_iam_role_policy.reaper.policy).Statement) == jsonencode([
+ {
+ Action = "ecs:ListTasks"
+ Condition = { ArnEquals = { "ecs:cluster" = "arn:aws:ecs:eu-west-1:123456789012:cluster/carlos-test-media" } }
+ Effect = "Allow"
+ Resource = "*"
+ Sid = "ListTasks"
+ },
+ { Action = ["ecs:DescribeTasks", "ecs:StopTask"], Effect = "Allow", Resource = "arn:aws:ecs:eu-west-1:123456789012:task/carlos-test-media/*", Sid = "StopOldTasks" },
+ { Action = ["logs:CreateLogStream", "logs:PutLogEvents"], Effect = "Allow", Resource = "arn:aws:logs:eu-west-1:123456789012:log-group:/aws/lambda/carlos-test-media-reaper:*", Sid = "OwnLogs" },
+ ])
+ error_message = "the reaper reaches this cluster's tasks and its own logs, nothing else"
+ }
+ assert {
+ condition = (
+ aws_lambda_function.reaper.runtime == "python3.13"
+ && jsonencode(aws_lambda_function.reaper.architectures) == jsonencode(["arm64"])
+ && aws_lambda_function.reaper.timeout == 50
+ && aws_lambda_function.reaper.handler == "reaper.handler"
+ && aws_lambda_function.reaper.environment[0].variables["CLUSTER"] == "arn:aws:ecs:eu-west-1:123456789012:cluster/carlos-test-media"
+ && aws_lambda_function.reaper.environment[0].variables["MAX_AGE_MINUTES"] == "70"
+ && aws_cloudwatch_event_rule.reaper.schedule_expression == "rate(1 minute)"
+ )
+ error_message = "the reaper's runtime, environment and schedule"
+ }
+}
+
+run "output_parses" {
+ command = apply
+ variables {
+ image_digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ image_built_at = "2026-11-18T00:00:00Z"
+ image_ffmpeg = "7:7.1.5-0+deb13u1"
+ }
+ assert {
+ condition = (
+ jsondecode(output.carlos_media_engine).v == 1
+ && jsondecode(output.carlos_media_engine).region == "eu-west-1"
+ && jsondecode(output.carlos_media_engine).account_id == "123456789012"
+ && jsondecode(output.carlos_media_engine).cluster == "arn:aws:ecs:eu-west-1:123456789012:cluster/carlos-test-media"
+ && jsondecode(output.carlos_media_engine).security_group == "sg-0123456789abcdef0"
+ && jsondecode(output.carlos_media_engine).conversion_role == "arn:aws:iam::123456789012:role/carlos-test-media-conversion"
+ && jsondecode(output.carlos_media_engine).results_bucket == "carlos-test-deployment"
+ && jsondecode(output.carlos_media_engine).store_prefix == "carlos-test-store-"
+ && length(jsondecode(output.carlos_media_engine).subnets) == 2
+ )
+ error_message = "the console's configuration"
+ }
+ assert {
+ condition = jsonencode(sort(keys(jsondecode(output.carlos_media_engine).task_definitions))) == jsonencode(["audio-aac/long", "audio-aac/short", "video-720p/long", "video-720p/short"])
+ error_message = "four task definitions, keyed by preset and class"
+ }
+ assert {
+ condition = jsonencode(jsondecode(output.carlos_media_engine).image) == jsonencode({
+ built_at = "2026-11-18T00:00:00Z"
+ digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ ffmpeg = "7:7.1.5-0+deb13u1"
+ })
+ error_message = "the image's three facts"
+ }
+}
+
+run "drill_off_by_default" {
+ command = apply
+ assert {
+ condition = length(aws_ecr_repository_policy.engine) == 0
+ error_message = "no repository policy, so no foreign principal"
+ }
+ assert {
+ condition = alltrue([for p in [aws_vpc_endpoint_policy.s3.policy, aws_vpc_endpoint_policy.ecr_api.policy, aws_vpc_endpoint_policy.ecr_dkr.policy, aws_vpc_endpoint_policy.logs[0].policy] :
+ jsondecode(p).Version == "2012-10-17" && !strcontains(p, "\"Action\":\"*\"")
+ ])
+ error_message = "the endpoints keep their locked policies"
+ }
+}
+
+run "drill_closed_admits_only_the_user" {
+ command = apply
+ variables {
+ drill = {
+ endpoints_open = false
+ foreign_principal_arn = "arn:aws:iam::999999999999:user/carlos-media-drill-0123456789abcdef"
+ }
+ }
+ assert {
+ condition = jsonencode(jsondecode(aws_ecr_repository_policy.engine[0].policy).Statement) == jsonencode([{
+ Action = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
+ Effect = "Allow"
+ Principal = { AWS = "arn:aws:iam::999999999999:user/carlos-media-drill-0123456789abcdef" }
+ Sid = "CarlosMediaEndpointDrill"
+ }])
+ error_message = "one statement, for the drill's user"
+ }
+ assert {
+ condition = (
+ aws_vpc_endpoint_policy.s3.policy == local.s3_endpoint_policy
+ && aws_vpc_endpoint_policy.ecr_api.policy == local.ecr_endpoint_policy
+ && aws_vpc_endpoint_policy.ecr_dkr.policy == local.ecr_endpoint_policy
+ && aws_vpc_endpoint_policy.logs[0].policy == local.logs_endpoint_policy
+ )
+ error_message = "the endpoint policies are unchanged"
+ }
+}
+
+run "drill_open_opens_only_the_endpoints" {
+ command = apply
+ variables {
+ drill = {
+ endpoints_open = true
+ foreign_principal_arn = "arn:aws:iam::999999999999:user/carlos-media-drill-0123456789abcdef"
+ }
+ }
+ assert {
+ condition = alltrue([for p in [aws_vpc_endpoint_policy.s3.policy, aws_vpc_endpoint_policy.ecr_api.policy, aws_vpc_endpoint_policy.ecr_dkr.policy, aws_vpc_endpoint_policy.logs[0].policy] :
+ p == "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"*\",\"Resource\":\"*\"}]}"
+ ])
+ error_message = "all four endpoints hold AWS's default policy"
+ }
+ assert {
+ condition = length(jsondecode(aws_ecr_repository_policy.engine[0].policy).Statement) == 1
+ error_message = "the repository still admits the user alone"
+ }
+ assert {
+ condition = (
+ !strcontains(aws_iam_role_policy.conversion.policy, "999999999999")
+ && !strcontains(aws_iam_role_policy.execution.policy, "999999999999")
+ && !strcontains(aws_iam_role_policy.console.policy, "999999999999")
+ && !strcontains(aws_iam_role.conversion.assume_role_policy, "999999999999")
+ )
+ error_message = "the drill's user reaches no role"
+ }
+}
+
+run "drill_refuses_another_principal" {
+ command = plan
+ variables {
+ drill = {
+ endpoints_open = false
+ foreign_principal_arn = "arn:aws:iam::999999999999:role/carlos-media-drill-0123456789abcdef"
+ }
+ }
+ expect_failures = [var.drill]
+}
+
+run "drill_refuses_a_user_of_another_name" {
+ command = plan
+ variables {
+ drill = {
+ endpoints_open = true
+ foreign_principal_arn = "arn:aws:iam::999999999999:user/admin"
+ }
+ }
+ expect_failures = [var.drill]
+}
+
+run "drill_refuses_the_modules_own_account" {
+ command = plan
+ variables {
+ drill = {
+ endpoints_open = false
+ foreign_principal_arn = "arn:aws:iam::123456789012:user/carlos-media-drill-0123456789abcdef"
+ }
+ }
+ expect_failures = [aws_ecr_repository_policy.engine]
+}
+
+run "store_prefix_refuses_a_wildcard" {
+ command = plan
+ variables {
+ store_bucket_prefix = "carlos-*"
+ }
+ expect_failures = [var.store_bucket_prefix]
+}
+
+run "store_prefix_refuses_empty" {
+ command = plan
+ variables {
+ store_bucket_prefix = ""
+ }
+ expect_failures = [var.store_bucket_prefix]
+}
+
+run "a_digest_needs_its_image_facts" {
+ command = plan
+ variables {
+ image_digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ }
+ expect_failures = [var.image_digest]
+}
+
+run "classes_must_be_the_four" {
+ command = plan
+ variables {
+ classes = [{ preset = "video-720p", class = "short", cpu = 4096, memory = 8192 }]
+ }
+ expect_failures = [var.classes]
+}
+
+run "the_reaper_must_outlive_a_grant" {
+ command = plan
+ variables {
+ reaper_max_age_minutes = 60
+ }
+ expect_failures = [var.reaper_max_age_minutes]
+}
diff --git a/infra/modules/media-engine/variables.tf b/infra/modules/media-engine/variables.tf
new file mode 100644
index 000000000..b1dab13fc
--- /dev/null
+++ b/infra/modules/media-engine/variables.tf
@@ -0,0 +1,179 @@
+variable "name" {
+ description = "Prefix for everything this module creates. Task definition families are <name>-<preset>-<class>."
+ type = string
+ validation {
+ condition = can(regex("^[a-z0-9][a-z0-9-]{0,30}$", var.name))
+ error_message = "name must be 1 to 31 lower-case letters, digits or hyphens, starting with a letter or digit."
+ }
+}
+
+variable "region" {
+ description = "The region the engine runs in. It must be the store region."
+ type = string
+ validation {
+ condition = can(regex("^[a-z]{2}(-[a-z]+)+-[0-9]+$", var.region))
+ error_message = "region must be an AWS region name."
+ }
+}
+
+variable "store_region" {
+ description = "The region of this deployment's stores."
+ type = string
+ validation {
+ condition = can(regex("^[a-z]{2}(-[a-z]+)+-[0-9]+$", var.store_region))
+ error_message = "store_region must be an AWS region name."
+ }
+}
+
+variable "store_bucket_prefix" {
+ description = "The name prefix every store bucket of this deployment shares."
+ type = string
+ validation {
+ # This value is written into IAM and endpoint policies, where * and ? are
+ # wildcards and an empty prefix would mean every bucket.
+ condition = can(regex("^[a-z0-9][a-z0-9.-]{2,}$", var.store_bucket_prefix))
+ error_message = "store_bucket_prefix must be at least 3 characters of a bucket name, with no wildcards."
+ }
+}
+
+variable "deployment_bucket_name" {
+ description = "The deployment bucket. Conversion results are written under media-results/ there."
+ type = string
+ validation {
+ condition = can(regex("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$", var.deployment_bucket_name))
+ error_message = "deployment_bucket_name must be a bucket name."
+ }
+}
+
+variable "console_role_name" {
+ description = "The console's IAM role name. The module adds one inline policy to it."
+ type = string
+ validation {
+ condition = can(regex("^[A-Za-z0-9+=,.@_-]{1,64}$", var.console_role_name))
+ error_message = "console_role_name must be an IAM role name."
+ }
+}
+
+variable "console_role_arn" {
+ description = "The console's IAM role ARN, the only principal that may assume the conversion role."
+ type = string
+ validation {
+ condition = can(regex("^arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]+$", var.console_role_arn))
+ error_message = "console_role_arn must be an IAM role ARN."
+ }
+}
+
+variable "image_digest" {
+ description = "The engine image's digest. Empty on the first apply, which creates the repository to push to."
+ type = string
+ default = ""
+ validation {
+ condition = var.image_digest == "" || can(regex("^sha256:[0-9a-f]{64}$", var.image_digest))
+ error_message = "image_digest must be empty or sha256: and 64 lower-case hex characters."
+ }
+ validation {
+ condition = var.image_digest == "" ? true : var.image_built_at != "" && var.image_ffmpeg != ""
+ error_message = "Set image_built_at and image_ffmpeg with image_digest: all three come from the image's image.json."
+ }
+}
+
+variable "image_built_at" {
+ description = "The built_at value from the image's image.json."
+ type = string
+ default = ""
+ validation {
+ condition = var.image_built_at == "" || can(formatdate("YYYY", var.image_built_at))
+ error_message = "image_built_at must be an RFC 3339 time."
+ }
+}
+
+variable "image_ffmpeg" {
+ description = "The ffmpeg value from the image's image.json: a Debian package version such as 7:7.1.5-0+deb13u1."
+ type = string
+ default = ""
+ validation {
+ condition = var.image_ffmpeg == "" || can(regex("^([0-9]+:)?[0-9][A-Za-z0-9.+~-]*$", var.image_ffmpeg))
+ error_message = "image_ffmpeg must be a Debian package version."
+ }
+}
+
+variable "vpc_cidr" {
+ description = "The engine VPC's address range, a /24 split into two /25 subnets."
+ type = string
+ default = "10.98.0.0/24"
+ validation {
+ condition = can(cidrsubnet(var.vpc_cidr, 1, 1)) && endswith(var.vpc_cidr, "/24")
+ error_message = "vpc_cidr must be an IPv4 /24."
+ }
+}
+
+variable "logs" {
+ description = "Send the codec container's logs to CloudWatch, through a logs endpoint in the VPC."
+ type = bool
+ default = true
+}
+
+variable "log_retention_days" {
+ description = "Days the engine's and the reaper's logs are kept."
+ type = number
+ default = 14
+}
+
+variable "reaper_max_age_minutes" {
+ description = "The reaper stops any task older than this. A grant lasts 60 minutes, so it must be longer."
+ type = number
+ default = 70
+ validation {
+ condition = var.reaper_max_age_minutes > 60 && floor(var.reaper_max_age_minutes) == var.reaper_max_age_minutes
+ error_message = "reaper_max_age_minutes must be a whole number above 60: a grant lasts 60 minutes."
+ }
+}
+
+variable "classes" {
+ description = "One task definition per preset and class. Set ephemeral_gib only if RunTask refuses a per-run storage override."
+ type = list(object({
+ preset = string
+ class = string
+ cpu = number
+ memory = number
+ ephemeral_gib = optional(number)
+ }))
+ default = [
+ { preset = "video-720p", class = "short", cpu = 4096, memory = 8192 },
+ { preset = "video-720p", class = "long", cpu = 16384, memory = 32768 },
+ { preset = "audio-aac", class = "short", cpu = 1024, memory = 2048 },
+ { preset = "audio-aac", class = "long", cpu = 2048, memory = 4096 },
+ ]
+ validation {
+ condition = (
+ join(",", sort([for c in var.classes : "${c.preset}/${c.class}"])) ==
+ "audio-aac/long,audio-aac/short,video-720p/long,video-720p/short"
+ )
+ error_message = "classes must name exactly video-720p and audio-aac, each short and long."
+ }
+ validation {
+ condition = alltrue([for c in var.classes : c.cpu > 64 && c.memory > 64])
+ error_message = "Each class needs more than the 64 CPU units and 64 MiB the deadline container holds."
+ }
+ validation {
+ condition = alltrue([for c in var.classes : c.ephemeral_gib == null ? true : c.ephemeral_gib >= 21 && c.ephemeral_gib <= 200])
+ error_message = "ephemeral_gib must be between 21 and 200, or unset for Fargate's 20 GiB default."
+ }
+}
+
+variable "drill" {
+ description = "The endpoint drill's state. Leave null: only scripts/media-endpoint-drill.sh sets it, on dev."
+ type = object({
+ endpoints_open = bool
+ foreign_principal_arn = string
+ })
+ default = null
+ validation {
+ condition = var.drill == null ? true : var.drill.endpoints_open != null
+ error_message = "drill.endpoints_open must be true or false."
+ }
+ validation {
+ condition = var.drill == null ? true : can(regex("^arn:aws:iam::[0-9]{12}:user/carlos-media-drill-[0-9a-f]{16}$", var.drill.foreign_principal_arn))
+ error_message = "drill.foreign_principal_arn must be the drill's own IAM user, carlos-media-drill-<16 hex characters>."
+ }
+}
diff --git a/infra/modules/media-engine/versions.tf b/infra/modules/media-engine/versions.tf
new file mode 100644
index 000000000..c3761a142
--- /dev/null
+++ b/infra/modules/media-engine/versions.tf
@@ -0,0 +1,13 @@
+terraform {
+ required_version = ">= 1.10"
+ required_providers {
+ aws = {
+ source = "hashicorp/aws"
+ version = ">= 6.0"
+ }
+ archive = {
+ source = "hashicorp/archive"
+ version = ">= 2.4"
+ }
+ }
+}
diff --git a/internal/mediaaws/module_test.go b/internal/mediaaws/module_test.go
new file mode 100644
index 000000000..c7e443bb6
--- /dev/null
+++ b/internal/mediaaws/module_test.go
@@ -0,0 +1,511 @@
+package mediaaws
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "testing"
+ "testing/fstest"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ ecstypes "github.com/aws/aws-sdk-go-v2/service/ecs/types"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// These tests hold infra/modules/media-engine to the code that consumes it.
+// testdata/media-engine-rendered.json is what the module renders under its
+// test suite's mock provider. The gate and the config parser read that file
+// in every run, CI included; TestModuleRenderIsCurrent proves the file is
+// still what the module renders wherever OpenTofu is installed.
+
+const (
+ moduleDir = "../../infra/modules/media-engine"
+ renderedModule = "testdata/media-engine-rendered.json"
+ // updateRender rewrites renderedModule from a fresh render.
+ updateRender = "MEDIA_ENGINE_UPDATE_RENDER"
+)
+
+type renderedTaskDefinition struct {
+ ARN string `json:"arn"`
+ Family string `json:"family"`
+ TaskRoleARN string `json:"task_role_arn"`
+ PIDMode string `json:"pid_mode"`
+ CPUArchitecture string `json:"cpu_architecture"`
+ ContainerDefinitions string `json:"container_definitions"`
+}
+
+type moduleRender struct {
+ Engine string `json:"carlos_media_engine"`
+ TaskDefinitions map[string]renderedTaskDefinition `json:"task_definitions"`
+}
+
+func readModuleRender(t *testing.T) moduleRender {
+ t.Helper()
+ b, err := os.ReadFile(renderedModule)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var r moduleRender
+ if err := json.Unmarshal(b, &r); err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+// ecsTaskDefinition reads a rendered definition the way DescribeTaskDefinition
+// would answer it. A key ECS would not recognise is an error, because ECS
+// would drop it and the gate would never see the setting.
+func ecsTaskDefinition(t *testing.T, r renderedTaskDefinition) *ecstypes.TaskDefinition {
+ t.Helper()
+ dec := json.NewDecoder(strings.NewReader(r.ContainerDefinitions))
+ dec.DisallowUnknownFields()
+ var containers []ecstypes.ContainerDefinition
+ if err := dec.Decode(&containers); err != nil {
+ t.Fatalf("%s: container definitions: %v", r.Family, err)
+ }
+ td := &ecstypes.TaskDefinition{
+ TaskDefinitionArn: aws.String(r.ARN),
+ PidMode: ecstypes.PidMode(r.PIDMode),
+ RuntimePlatform: &ecstypes.RuntimePlatform{CpuArchitecture: ecstypes.CPUArchitecture(r.CPUArchitecture)},
+ ContainerDefinitions: containers,
+ }
+ if r.TaskRoleARN != "" {
+ td.TaskRoleArn = aws.String(r.TaskRoleARN)
+ }
+ return td
+}
+
+func TestModuleTaskDefinitionsPassTheGate(t *testing.T) {
+ r := readModuleRender(t)
+ var classes []string
+ for class, rendered := range r.TaskDefinitions {
+ classes = append(classes, class)
+ if err := media.CheckTaskDefinition(taskDefinition(ecsTaskDefinition(t, rendered))); err != nil {
+ t.Errorf("%s: the gate refuses the module's definition: %v", class, err)
+ }
+ }
+ slices.Sort(classes)
+ if !slices.Equal(classes, configClasses()) {
+ t.Fatalf("rendered classes = %v, want %v", classes, configClasses())
+ }
+}
+
+// The gate must be able to refuse what the render holds, or the test above
+// proves nothing about it.
+func TestModuleGateWitnessRefusesABrokenDefinition(t *testing.T) {
+ rendered := readModuleRender(t).TaskDefinitions["video-720p/short"]
+ for name, breakIt := range map[string]func(*ecstypes.TaskDefinition){
+ "task role": func(td *ecstypes.TaskDefinition) { td.TaskRoleArn = aws.String("arn:aws:iam::123456789012:role/x") },
+ "x86": func(td *ecstypes.TaskDefinition) { td.RuntimePlatform.CpuArchitecture = ecstypes.CPUArchitectureX8664 },
+ "root user": func(td *ecstypes.TaskDefinition) { td.ContainerDefinitions[1].User = aws.String("0:0") },
+ "no stop timeout": func(td *ecstypes.TaskDefinition) { td.ContainerDefinitions[0].StopTimeout = nil },
+ } {
+ td := ecsTaskDefinition(t, rendered)
+ breakIt(td)
+ var refused *media.Misconfigured
+ if err := media.CheckTaskDefinition(taskDefinition(td)); !errors.As(err, &refused) {
+ t.Errorf("%s: gate answered %v, want a refusal", name, err)
+ }
+ }
+}
+
+func TestModuleOutputParses(t *testing.T) {
+ r := readModuleRender(t)
+ c, err := ParseConfig(r.Engine)
+ if err != nil {
+ t.Fatalf("the console refuses the module's output: %v", err)
+ }
+ if c.Image.FFmpeg != "7:7.1.5-0+deb13u1" {
+ t.Errorf("image ffmpeg = %q", c.Image.FFmpeg)
+ }
+ if len(c.TaskDefinitions) != 4 || len(c.Subnets) != 2 {
+ t.Errorf("task definitions = %d, subnets = %d", len(c.TaskDefinitions), len(c.Subnets))
+ }
+}
+
+// renderModule runs the module's test suite and keeps what its output_parses
+// run applied. A failing suite fails the test.
+func renderModule(t *testing.T, tofu string) moduleRender {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Minute)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, tofu, "test", "-json", "-verbose", "-no-color")
+ cmd.Dir = moduleDir
+ // The suite uses a mock provider; no credential is ever needed.
+ for _, kv := range os.Environ() {
+ if !strings.HasPrefix(kv, "AWS_") {
+ cmd.Env = append(cmd.Env, kv)
+ }
+ }
+ output, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("tofu test: %v\n%s", err, tail(output))
+ }
+ render, err := parseModuleRender(output)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return render
+}
+
+func tail(b []byte) []byte {
+ if len(b) > 4000 {
+ return b[len(b)-4000:]
+ }
+ return b
+}
+
+// parseModuleRender finds the state of the output_parses run in tofu's JSON
+// lines.
+func parseModuleRender(output []byte) (moduleRender, error) {
+ lines := bufio.NewScanner(bytes.NewReader(output))
+ lines.Buffer(nil, 64<<20)
+ for lines.Scan() {
+ var line struct {
+ Run string `json:"@testrun"`
+ Type string `json:"type"`
+ State json.RawMessage `json:"test_state"`
+ }
+ if json.Unmarshal(lines.Bytes(), &line) != nil || line.Type != "test_state" || line.Run != "output_parses" {
+ continue
+ }
+ return renderFromState(line.State)
+ }
+ if err := lines.Err(); err != nil {
+ return moduleRender{}, err
+ }
+ return moduleRender{}, errors.New("tofu test reported no state for the output_parses run")
+}
+
+func renderFromState(raw json.RawMessage) (moduleRender, error) {
+ var state struct {
+ Values struct {
+ Outputs map[string]struct {
+ Value string `json:"value"`
+ } `json:"outputs"`
+ Root struct {
+ Resources []struct {
+ Type string `json:"type"`
+ Index json.RawMessage `json:"index"`
+ Values json.RawMessage `json:"values"`
+ } `json:"resources"`
+ } `json:"root_module"`
+ } `json:"values"`
+ }
+ if err := json.Unmarshal(raw, &state); err != nil {
+ return moduleRender{}, err
+ }
+ r := moduleRender{Engine: state.Values.Outputs["carlos_media_engine"].Value, TaskDefinitions: map[string]renderedTaskDefinition{}}
+ for _, res := range state.Values.Root.Resources {
+ if res.Type != "aws_ecs_task_definition" {
+ continue
+ }
+ var class string
+ if err := json.Unmarshal(res.Index, &class); err != nil {
+ return moduleRender{}, err
+ }
+ var values struct {
+ renderedTaskDefinition
+ RuntimePlatform []struct {
+ CPUArchitecture string `json:"cpu_architecture"`
+ } `json:"runtime_platform"`
+ }
+ if err := json.Unmarshal(res.Values, &values); err != nil {
+ return moduleRender{}, err
+ }
+ td := values.renderedTaskDefinition
+ if len(values.RuntimePlatform) == 1 {
+ td.CPUArchitecture = values.RuntimePlatform[0].CPUArchitecture
+ }
+ r.TaskDefinitions[class] = td
+ }
+ return r, nil
+}
+
+// TestModuleRenderIsCurrent runs the module's OpenTofu suite. CI's runner has
+// no OpenTofu, so it skips there and the checked-in render stands in for it.
+func TestModuleRenderIsCurrent(t *testing.T) {
+ tofu, err := exec.LookPath("tofu")
+ if err != nil {
+ t.Skipf("OpenTofu is not installed: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(moduleDir, ".terraform", "providers")); err != nil {
+ t.Skip("the module is not initialised: run tofu init -backend=false in infra/modules/media-engine")
+ }
+ got := renderModule(t, tofu)
+ b, err := json.MarshalIndent(got, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b = append(b, '\n')
+ if os.Getenv(updateRender) != "" {
+ if err := os.WriteFile(renderedModule, b, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want, err := os.ReadFile(renderedModule)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(b, want) {
+ t.Fatalf("%s is stale: rerun this test with %s=1\n%s", renderedModule, updateRender, b)
+ }
+}
+
+// TestReaperPythonGuards runs the reaper's unit tests, so CI runs them too. It
+// skips locally without python3 and fails in CI without it.
+func TestReaperPythonGuards(t *testing.T) {
+ python, err := exec.LookPath("python3")
+ if err != nil {
+ if os.Getenv("CI") != "" || os.Getenv("AMADAN_CI") != "" {
+ t.Fatalf("python3 is required in CI: %v", err)
+ }
+ t.Skipf("python3 is not installed: %v", err)
+ }
+ cmd := exec.Command(python, "-I", "-B", "-m", "unittest", "discover", "-s", filepath.Join(moduleDir, "reaper"), "-p", "*_test.py")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("reaper tests: %v\n%s", err, output)
+ }
+}
+
+// topLevelBlocks splits HCL into its top-level blocks, keyed by header line.
+// Comments are dropped first, so a comment cannot hide or fake a reference.
+func topLevelBlocks(src string) map[string]string {
+ blocks := map[string]string{}
+ var header string
+ var body strings.Builder
+ depth := 0
+ for line := range strings.SplitSeq(src, "\n") {
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, "//") {
+ continue
+ }
+ if depth == 0 {
+ header = trimmed
+ body.Reset()
+ }
+ body.WriteString(line + "\n")
+ depth += strings.Count(line, "{") - strings.Count(line, "}")
+ if depth == 0 && header != "" {
+ blocks[header] += body.String()
+ }
+ }
+ return blocks
+}
+
+func moduleBlocks(t *testing.T) map[string]string {
+ t.Helper()
+ files, err := filepath.Glob(filepath.Join(moduleDir, "*.tf"))
+ if err != nil || len(files) == 0 {
+ t.Fatalf("module files: %v, %v", files, err)
+ }
+ all := map[string]string{}
+ for _, file := range files {
+ b, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for header, body := range topLevelBlocks(string(b)) {
+ all[header] += body
+ }
+ }
+ return all
+}
+
+// drillResources are the five resources the endpoint drill may change.
+var drillResources = []string{
+ `resource "aws_vpc_endpoint_policy" "s3" {`,
+ `resource "aws_vpc_endpoint_policy" "ecr_api" {`,
+ `resource "aws_vpc_endpoint_policy" "ecr_dkr" {`,
+ `resource "aws_vpc_endpoint_policy" "logs" {`,
+ `resource "aws_ecr_repository_policy" "engine" {`,
+}
+
+// Nothing but the drill's five resources may depend on the drill input.
+func TestOnlyTheFivePoliciesReadTheDrillInput(t *testing.T) {
+ blocks := moduleBlocks(t)
+ for _, header := range drillResources {
+ if !strings.Contains(blocks[header], "var.drill") {
+ t.Errorf("%s does not read var.drill", header)
+ }
+ }
+ for header, body := range blocks {
+ if strings.Contains(body, "var.drill") && !slices.Contains(drillResources, header) && header != `variable "drill" {` {
+ t.Errorf("%s reads var.drill", header)
+ }
+ }
+}
+
+// The endpoints set no inline policy, or two resources would own one policy.
+func TestEndpointsSetNoInlinePolicy(t *testing.T) {
+ inline := regexp.MustCompile(`(?m)^\s*policy\s*=`)
+ found := 0
+ for header, body := range moduleBlocks(t) {
+ if strings.HasPrefix(header, `resource "aws_vpc_endpoint" `) {
+ found++
+ if inline.MatchString(body) {
+ t.Errorf("%s sets an inline policy", header)
+ }
+ }
+ }
+ if found != 4 {
+ t.Fatalf("found %d endpoints, want 4", found)
+ }
+}
+
+// The drill script targets these addresses by name.
+func TestDrillScriptTargetsTheFivePolicies(t *testing.T) {
+ b, err := os.ReadFile("../../scripts/media-endpoint-drill.sh")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, m := range regexp.MustCompile(`(?m)^\s*-target=module\.media_engine\.(\S+)$`).FindAllStringSubmatch(string(b), -1) {
+ got = append(got, m[1])
+ }
+ want := []string{
+ "aws_vpc_endpoint_policy.s3", "aws_vpc_endpoint_policy.ecr_api", "aws_vpc_endpoint_policy.ecr_dkr",
+ "aws_vpc_endpoint_policy.logs", "aws_ecr_repository_policy.engine",
+ }
+ if !slices.Equal(got, want) {
+ t.Fatalf("script targets %v, want %v", got, want)
+ }
+}
+
+var (
+ drillAssignment = regexp.MustCompile(`(?m)^\s*media_engine_drill\s*=\s*(.*?)\s*$`)
+ drillArgument = regexp.MustCompile(`(?m)^\s*drill\s*=\s*(.*?)\s*$`)
+ drillDefault = regexp.MustCompile(`(?m)^\s*default\s*=\s*(.*?)\s*$`)
+)
+
+// isDevPath reports whether a path segment, or the file's name without its
+// extensions, is exactly "dev".
+func isDevPath(name string) bool {
+ segments := strings.Split(path.Dir(name), "/")
+ base, _, _ := strings.Cut(path.Base(name), ".")
+ return slices.Contains(append(segments, base), "dev")
+}
+
+// drillViolations answers how one file turns the endpoint drill on.
+func drillViolations(name, src string) []string {
+ var out []string
+ switch {
+ case strings.HasSuffix(name, ".tfvars.json"):
+ var values map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(src), &values); err != nil {
+ return []string{name + ": not JSON"}
+ }
+ if v, ok := values["media_engine_drill"]; ok && string(bytes.TrimSpace(v)) != "null" {
+ out = append(out, name+": sets media_engine_drill")
+ }
+ case strings.HasSuffix(name, ".tfvars"):
+ for _, m := range drillAssignment.FindAllStringSubmatch(src, -1) {
+ if m[1] != "null" {
+ out = append(out, name+": sets media_engine_drill")
+ }
+ }
+ case strings.HasSuffix(name, ".tf"):
+ for header, body := range topLevelBlocks(src) {
+ switch header {
+ case `variable "media_engine_drill" {`:
+ if m := drillDefault.FindStringSubmatch(body); m == nil || m[1] != "null" {
+ out = append(out, name+": media_engine_drill does not default to null")
+ }
+ case `module "media_engine" {`:
+ for _, m := range drillArgument.FindAllStringSubmatch(body, -1) {
+ if m[1] != "var.media_engine_drill" && m[1] != "null" {
+ out = append(out, name+": passes "+m[1]+" as drill")
+ }
+ }
+ }
+ }
+ }
+ return out
+}
+
+// drillSettingsOutsideDev walks a tree of deployment roots.
+func drillSettingsOutsideDev(root fs.FS) ([]string, error) {
+ var out []string
+ err := fs.WalkDir(root, ".", func(name string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ switch d.Name() {
+ case ".git", ".terraform", ".claude", ".superpowers", "node_modules":
+ return fs.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(name, ".tf") && !strings.HasSuffix(name, ".tfvars") && !strings.HasSuffix(name, ".tfvars.json") {
+ return nil
+ }
+ if isDevPath(name) {
+ return nil
+ }
+ b, err := fs.ReadFile(root, name)
+ if err != nil {
+ return err
+ }
+ out = append(out, drillViolations(name, string(b))...)
+ return nil
+ })
+ return out, err
+}
+
+func TestNoDeploymentRootSetsTheDrillOutsideDev(t *testing.T) {
+ root, err := filepath.Abs("../..")
+ if err != nil {
+ t.Fatal(err)
+ }
+ found, err := drillSettingsOutsideDev(os.DirFS(root))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(found) != 0 {
+ t.Fatalf("the endpoint drill is set outside dev:\n%s", strings.Join(found, "\n"))
+ }
+}
+
+func TestDrillSettingsOutsideDevAreFound(t *testing.T) {
+ const on = `{ endpoints_open = true, foreign_principal_arn = "x" }`
+ for _, tc := range []struct {
+ name, file, src string
+ want int
+ }{
+ {"flagship tfvars", "roots/flagship/terraform.tfvars", "media_engine_drill = " + on + "\n", 1},
+ {"flagship tfvars json", "roots/flagship/drill.tfvars.json", `{"media_engine_drill":{"endpoints_open":true}}`, 1},
+ {"flagship default", "roots/flagship/main.tf", "variable \"media_engine_drill\" {\n default = " + on + "\n}\n", 1},
+ {"flagship no default", "roots/flagship/main.tf", "variable \"media_engine_drill\" {\n type = string\n}\n", 1},
+ {"flagship literal argument", "roots/flagship/main.tf", "module \"media_engine\" {\n drill = " + on + "\n}\n", 1},
+ {"flagship off", "roots/flagship/terraform.tfvars", "media_engine_drill = null\n", 0},
+ {"flagship off json", "roots/flagship/drill.tfvars.json", `{"media_engine_drill":null}`, 0},
+ {"flagship wired off", "roots/flagship/main.tf", "variable \"media_engine_drill\" {\n default = null\n}\nmodule \"media_engine\" {\n drill = var.media_engine_drill\n}\n", 0},
+ {"a commented setting", "roots/flagship/terraform.tfvars", "# media_engine_drill = " + on + "\n", 0},
+ {"dev directory", "roots/dev/terraform.tfvars", "media_engine_drill = " + on + "\n", 0},
+ {"dev file", "roots/shared/dev.tfvars", "media_engine_drill = " + on + "\n", 0},
+ {"a name holding dev", "roots/devops/terraform.tfvars", "media_engine_drill = " + on + "\n", 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := drillSettingsOutsideDev(fstest.MapFS{tc.file: {Data: []byte(tc.src)}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != tc.want {
+ t.Fatalf("found %v, want %d", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/mediaaws/testdata/media-engine-rendered.json b/internal/mediaaws/testdata/media-engine-rendered.json
new file mode 100644
index 000000000..8f39f9148
--- /dev/null
+++ b/internal/mediaaws/testdata/media-engine-rendered.json
@@ -0,0 +1,37 @@
+{
+ "carlos_media_engine": "{\"account_id\":\"123456789012\",\"cluster\":\"arn:aws:ecs:eu-west-1:123456789012:cluster/carlos-test-media\",\"conversion_role\":\"arn:aws:iam::123456789012:role/carlos-test-media-conversion\",\"image\":{\"built_at\":\"2026-11-18T00:00:00Z\",\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"ffmpeg\":\"7:7.1.5-0+deb13u1\"},\"region\":\"eu-west-1\",\"results_bucket\":\"carlos-test-deployment\",\"security_group\":\"sg-0123456789abcdef0\",\"store_prefix\":\"carlos-test-store-\",\"subnets\":[\"subnet-0123456789abcdef0\",\"subnet-0123456789abcdef0\"],\"task_definitions\":{\"audio-aac/long\":\"arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7\",\"audio-aac/short\":\"arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7\",\"video-720p/long\":\"arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7\",\"video-720p/short\":\"arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7\"},\"v\":1}",
+ "task_definitions": {
+ "audio-aac/long": {
+ "arn": "arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7",
+ "family": "carlos-test-media-audio-aac-long",
+ "task_role_arn": "",
+ "pid_mode": "",
+ "cpu_architecture": "ARM64",
+ "container_definitions": "[{\"command\":[\"deadline\"],\"cpu\":64,\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"memory\":64,\"name\":\"deadline\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"},{\"command\":[\"codec\"],\"cpu\":1984,\"dependsOn\":[{\"condition\":\"START\",\"containerName\":\"deadline\"}],\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"environment\":[{\"name\":\"TMPDIR\",\"value\":\"/scratch/tmp\"}],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"logConfiguration\":{\"logDriver\":\"awslogs\",\"options\":{\"awslogs-group\":\"/carlos/carlos-test-media/engine\",\"awslogs-region\":\"eu-west-1\",\"awslogs-stream-prefix\":\"media\"}},\"memory\":4032,\"mountPoints\":[{\"containerPath\":\"/scratch\",\"readOnly\":false,\"sourceVolume\":\"scratch\"}],\"name\":\"codec\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"}]"
+ },
+ "audio-aac/short": {
+ "arn": "arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7",
+ "family": "carlos-test-media-audio-aac-short",
+ "task_role_arn": "",
+ "pid_mode": "",
+ "cpu_architecture": "ARM64",
+ "container_definitions": "[{\"command\":[\"deadline\"],\"cpu\":64,\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"memory\":64,\"name\":\"deadline\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"},{\"command\":[\"codec\"],\"cpu\":960,\"dependsOn\":[{\"condition\":\"START\",\"containerName\":\"deadline\"}],\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"environment\":[{\"name\":\"TMPDIR\",\"value\":\"/scratch/tmp\"}],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"logConfiguration\":{\"logDriver\":\"awslogs\",\"options\":{\"awslogs-group\":\"/carlos/carlos-test-media/engine\",\"awslogs-region\":\"eu-west-1\",\"awslogs-stream-prefix\":\"media\"}},\"memory\":1984,\"mountPoints\":[{\"containerPath\":\"/scratch\",\"readOnly\":false,\"sourceVolume\":\"scratch\"}],\"name\":\"codec\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"}]"
+ },
+ "video-720p/long": {
+ "arn": "arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7",
+ "family": "carlos-test-media-video-720p-long",
+ "task_role_arn": "",
+ "pid_mode": "",
+ "cpu_architecture": "ARM64",
+ "container_definitions": "[{\"command\":[\"deadline\"],\"cpu\":64,\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"memory\":64,\"name\":\"deadline\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"},{\"command\":[\"codec\"],\"cpu\":16320,\"dependsOn\":[{\"condition\":\"START\",\"containerName\":\"deadline\"}],\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"environment\":[{\"name\":\"TMPDIR\",\"value\":\"/scratch/tmp\"}],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"logConfiguration\":{\"logDriver\":\"awslogs\",\"options\":{\"awslogs-group\":\"/carlos/carlos-test-media/engine\",\"awslogs-region\":\"eu-west-1\",\"awslogs-stream-prefix\":\"media\"}},\"memory\":32704,\"mountPoints\":[{\"containerPath\":\"/scratch\",\"readOnly\":false,\"sourceVolume\":\"scratch\"}],\"name\":\"codec\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"}]"
+ },
+ "video-720p/short": {
+ "arn": "arn:aws:ecs:eu-west-1:123456789012:task-definition/carlos-test-media-video-720p-short:7",
+ "family": "carlos-test-media-video-720p-short",
+ "task_role_arn": "",
+ "pid_mode": "",
+ "cpu_architecture": "ARM64",
+ "container_definitions": "[{\"command\":[\"deadline\"],\"cpu\":64,\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"memory\":64,\"name\":\"deadline\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"},{\"command\":[\"codec\"],\"cpu\":4032,\"dependsOn\":[{\"condition\":\"START\",\"containerName\":\"deadline\"}],\"entryPoint\":[\"/usr/local/bin/carlos-media\"],\"environment\":[{\"name\":\"TMPDIR\",\"value\":\"/scratch/tmp\"}],\"essential\":true,\"image\":\"123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-test-media@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"linuxParameters\":{\"capabilities\":{\"drop\":[\"ALL\"]}},\"logConfiguration\":{\"logDriver\":\"awslogs\",\"options\":{\"awslogs-group\":\"/carlos/carlos-test-media/engine\",\"awslogs-region\":\"eu-west-1\",\"awslogs-stream-prefix\":\"media\"}},\"memory\":8128,\"mountPoints\":[{\"containerPath\":\"/scratch\",\"readOnly\":false,\"sourceVolume\":\"scratch\"}],\"name\":\"codec\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,\"user\":\"65534:65534\"}]"
+ }
+ }
+}