From a2d98cc7cd9aac732aab92b00eded3a69773245c Mon Sep 17 00:00:00 2001 From: Frank Date: Wed, 25 Nov 2026 16:11:20 -0500 Subject: [PATCH 1/2] Add lambda-microvms-github-actions-runner pattern (Go, Terraform) --- .../go/terraform/.gitignore | 28 + .../go/terraform/README.md | 219 ++++++++ .../go/terraform/events/ping.json | 4 + .../terraform/events/workflow_job_queued.json | 18 + .../go/terraform/example-pattern.json | 74 +++ .../example-workflows/buildah-build.yml | 31 ++ .../example-workflows/micro-vm-smoke.yml | 31 ++ .../go/terraform/main.tf | 496 ++++++++++++++++++ .../go/terraform/outputs.tf | 39 ++ .../terraform/src/microvm-runner/Dockerfile | 69 +++ .../go/terraform/src/microvm-runner/build.sh | 32 ++ .../microvm-runner/supervisor/githubrunner.go | 80 +++ .../src/microvm-runner/supervisor/go.mod | 24 + .../src/microvm-runner/supervisor/go.sum | 30 ++ .../src/microvm-runner/supervisor/main.go | 26 + .../microvm-runner/supervisor/supervisor.go | 143 +++++ .../src/microvm-runner/supervisor/types.go | 6 + .../go/terraform/src/webhook/handler.py | 209 ++++++++ .../go/terraform/src/webhook/requirements.txt | 5 + .../go/terraform/src/webhook/test_handler.py | 142 +++++ .../go/terraform/terraform.tfvars.example | 16 + .../go/terraform/variables.tf | 59 +++ .../go/terraform/versions.tf | 21 + 23 files changed, 1802 insertions(+) create mode 100644 lambda-microvms-github-actions-runner/go/terraform/.gitignore create mode 100644 lambda-microvms-github-actions-runner/go/terraform/README.md create mode 100644 lambda-microvms-github-actions-runner/go/terraform/events/ping.json create mode 100644 lambda-microvms-github-actions-runner/go/terraform/events/workflow_job_queued.json create mode 100644 lambda-microvms-github-actions-runner/go/terraform/example-pattern.json create mode 100644 lambda-microvms-github-actions-runner/go/terraform/example-workflows/buildah-build.yml create mode 100644 lambda-microvms-github-actions-runner/go/terraform/example-workflows/micro-vm-smoke.yml create mode 100644 lambda-microvms-github-actions-runner/go/terraform/main.tf create mode 100644 lambda-microvms-github-actions-runner/go/terraform/outputs.tf create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile create mode 100755 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/build.sh create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/githubrunner.go create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.mod create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.sum create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/main.go create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/supervisor.go create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/types.go create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/webhook/handler.py create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/webhook/requirements.txt create mode 100644 lambda-microvms-github-actions-runner/go/terraform/src/webhook/test_handler.py create mode 100644 lambda-microvms-github-actions-runner/go/terraform/terraform.tfvars.example create mode 100644 lambda-microvms-github-actions-runner/go/terraform/variables.tf create mode 100644 lambda-microvms-github-actions-runner/go/terraform/versions.tf diff --git a/lambda-microvms-github-actions-runner/go/terraform/.gitignore b/lambda-microvms-github-actions-runner/go/terraform/.gitignore new file mode 100644 index 000000000..e5916b093 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/.gitignore @@ -0,0 +1,28 @@ +# Terraform +.terraform/ +.terraform.lock.hcl +*.tfstate +*.tfstate.* +*.tfvars +*.tfvars.json +*.tfplan +tfplan +crash.log +.terraform.tfstate.lock.info +override.tf +*_override.tf + +# Build artifacts +.build/ +dist/ +*.zip +src/microvm-runner/supervisor/supervisor + +# Python +__pycache__/ +*.pyc +.pytest_cache/ +.venv/ + +# OS +.DS_Store diff --git a/lambda-microvms-github-actions-runner/go/terraform/README.md b/lambda-microvms-github-actions-runner/go/terraform/README.md new file mode 100644 index 000000000..9c387a141 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/README.md @@ -0,0 +1,219 @@ +# Ephemeral GitHub Actions runners on AWS Lambda MicroVMs + +This pattern runs every GitHub Actions job on its own single-use AWS Lambda MicroVM. A GitHub `workflow_job` webhook reaches an Amazon API Gateway REST API, and an AWS Lambda function verifies it, mints a just-in-time (JIT) runner configuration, and launches a MicroVM from a pre-built snapshot. A small Go supervisor inside the MicroVM runs exactly one job and then terminates its own MicroVM. Nothing runs between jobs, and container images are built with buildah instead of a Docker daemon. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-microvms-github-actions-runner-terraform + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +## Requirements + +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) v2 installed and configured, with `lambda-microvms` support (AWS CLI v2 2.35.10 or later) +* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +* [Terraform](https://developer.hashicorp.com/terraform/install) installed +* [Go](https://go.dev/doc/install) and `zip`, used by `build.sh` to compile the supervisor +* `pip3` with internet access. Terraform vendors a current boto3 into the webhook package, because the Lambda runtime's bundled boto3 has no `lambda-microvms` client. +* An AWS Region where Lambda MicroVMs is available +* A **private** GitHub repository +* A GitHub [fine-grained personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT): + * Repository access → **Only select repositories** → the target repository + * Repository permissions → **Administration: Read and write** + * For organization-level runners (`runner_scope = "org"`), grant Organization permissions → **Self-hosted runners: Read and write** instead. + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ``` + git clone https://github.com/aws-samples/serverless-patterns + ``` +1. Change directory to the pattern directory: + ``` + cd serverless-patterns/lambda-microvms-github-actions-runner/go/terraform + ``` +1. Copy the example variables file and set your target repository (`terraform.tfvars` is gitignored): + ``` + cp terraform.tfvars.example terraform.tfvars + ``` + Then replace `` and ``. For organization-level runners, set `runner_scope = "org"` and `github_org = ""` instead (both are in the file, commented out). See [Variables](#variables) for the other settings. +1. Build the MicroVM code artifact. This cross-compiles the supervisor for linux/arm64 and zips it with the Dockerfile into `src/microvm-runner/dist/supervisor.zip`. It does not call AWS: + ``` + ./src/microvm-runner/build.sh + ``` +1. Deploy. The apply waits a few minutes for the MicroVM image build: + ``` + terraform init + terraform apply + ``` +1. Store the GitHub PAT and a webhook secret (any random string, for example from `openssl rand -hex 32`). Each value is read from a prompt and piped in, so it doesn't appear in shell history or the process list: + ```bash + read -rsp 'GitHub PAT: ' PAT; echo + printf %s "$PAT" | aws secretsmanager put-secret-value --secret-string file:///dev/stdin \ + --secret-id "$(terraform output -raw pat_secret_arn)" \ + --region "$(terraform output -raw region)" + + read -rsp 'Webhook secret: ' WEBHOOK_SECRET; echo + printf %s "$WEBHOOK_SECRET" | aws secretsmanager put-secret-value --secret-string file:///dev/stdin \ + --secret-id "$(terraform output -raw webhook_secret_arn)" \ + --region "$(terraform output -raw region)" + + unset PAT WEBHOOK_SECRET + ``` +1. In the **private** GitHub repository, go to Settings → Webhooks → Add webhook: + * Payload URL: the output of `terraform output -raw webhook_url` (it ends in `/v1/webhook`) + * Content type: `application/json` + * Secret: the webhook secret from the previous step + * Which events: "Let me select individual events" → **Workflow jobs** only +1. Copy a workflow from this pattern's `example-workflows/` folder into the repository's `.github/workflows/` folder and commit it to the default branch. GitHub only offers `workflow_dispatch` for workflows on the default branch. The workflows target `runs-on: [self-hosted, lambda]`, the default `runner_labels`; change both together. + +## How it works + +``` + GitHub (workflow_job "queued") + │ POST, X-Hub-Signature-256 + ▼ + Amazon API Gateway REST API, stage v1, POST /webhook + │ Lambda proxy integration + ▼ + AWS Lambda webhook function (src/webhook/handler.py) + │ 1. verify the HMAC signature with the webhook secret (AWS Secrets Manager) + │ 2. act only on queued jobs whose labels include all runner_labels + │ 3. call GitHub generate-jitconfig with the PAT (AWS Secrets Manager) + │ 4. write the JIT config to Amazon S3 (jit/ prefix), presign a 60 s GET URL + │ 5. RunMicrovm: runner image, execution role, NO_INGRESS + INTERNET_EGRESS, + │ maximumDurationInSeconds, run-hook payload = presigned URL + ▼ + Lambda MicroVM restored from the image snapshot, single use + │ 6. Lambda calls the supervisor's /run hook with the MicroVM ID + payload + │ 7. the supervisor fetches the JIT config over HTTPS from the presigned URL + │ 8. ./run.sh --jitconfig: the runner connects to GitHub and runs ONE job + │ (output streams to Amazon CloudWatch Logs) + │ 9. TerminateMicrovm on its own MicroVM + ▼ + nothing left running +``` + +The runner image is built once by `terraform apply`, and again whenever its zip changes: + +1. `build.sh` cross-compiles the Go supervisor (`src/microvm-runner/supervisor/`) and zips it with `src/microvm-runner/Dockerfile`. +1. Terraform uploads the zip to the S3 bucket under a content-addressed key (`supervisor-runner-.zip`). +1. Terraform creates a one-resource AWS CloudFormation stack holding an `AWS::Lambda::MicrovmImage`, because the Terraform AWS provider's image resource can't configure lifecycle hooks. The image uses the AL2023 managed base image, `ARM_64`, the standard OS capabilities (`AdditionalOsCapabilities: []`), the `INTERNET_EGRESS` connector, and the `/ready` and `/run` hooks on port 8080. Lambda runs the Dockerfile on the base image, starts the supervisor, waits for `/ready`, and snapshots the MicroVM. The Dockerfile bakes in the GitHub Actions runner (checked against a pinned SHA-256) and buildah, preconfigured with the `vfs` storage driver and chroot isolation. +1. A changed zip builds a new image version under the same ARN. `RunMicrovm` always launches the latest active version, so the webhook needs no change. If a build fails, CloudFormation rolls back and the previous version stays active. + +The stack has three IAM roles. The **webhook role** can read the two secrets, write and presign objects under `jit/`, call `RunMicrovm` on the runner image, pass the execution role and the two network connectors, and write its own logs. The **execution role** (attached to each MicroVM) can call `TerminateMicrovm` on the runner image and write runtime logs. The **build role** can read the `supervisor-runner-*` zip and write the image build logs. + +### Security + +* **Private repositories only.** On a public repository anyone who opens a pull request could run code on your runners. +* **The PAT never enters the MicroVM.** The VM receives only the single-use JIT config, through a presigned URL that expires after 60 seconds. The execution role has no S3 or Secrets Manager access. +* **Use a GitHub App in production.** A GitHub App lets the webhook mint short-lived installation tokens instead of holding a long-lived PAT. +* **The API Gateway endpoint is public; the HMAC signature is the authentication.** The webhook function rejects every request without a valid `X-Hub-Signature-256`. In production, attach AWS WAF to the API stage for an IP allowlist of GitHub's webhook ranges and rate limiting. +* **CI job code can use the execution role.** Jobs run as root in the MicroVM, so they can call `TerminateMicrovm` on MicroVMs launched from the runner image and write to the runtime log group, and nothing else. +* The webhook never logs secrets, headers, request bodies, or the presigned URL. Secrets are cached for 5 minutes so a rotated value takes effect without a redeploy. + +### Limitations + +* **ARM64 (AWS Graviton) only.** The supervisor, the runner package and the image are built for `ARM_64`. +* **No Docker daemon.** `dockerd` can't run in the MicroVM with the standard OS capabilities. Use buildah, which the image presets for `vfs` storage and chroot isolation (see `example-workflows/buildah-build.yml`). Running real Docker would require `AdditionalOsCapabilities = ["ALL"]`, which this pattern does not use. +* **Job duration.** A job still running after `microvm_max_duration_seconds` is killed with its MicroVM. +* **Failed webhook deliveries are not retried.** If a delivery fails (for example, before the secrets are stored), redeliver it manually from the repository's webhook settings in GitHub. + +### Optional extensions + +* Push built images: add a registry login step and `buildah push`, for example to Amazon Elastic Container Registry, with push permissions on the execution role. +* Encrypt the secrets and the S3 bucket with a customer managed AWS KMS key. + +### Updating the runner image + +After editing `src/microvm-runner/Dockerfile` (for example, to add tools or bump the runner version together with its SHA-256) or the supervisor, rebuild and apply: + +``` +./src/microvm-runner/build.sh +terraform apply +``` + +The changed zip gets a new S3 key, so CloudFormation builds a new version of the same image (the ARN does not change) and jobs queued after the build use it. To roll back, check out the previous files and run the same two commands. + +### Variables + +| Variable | Default | Purpose | +|----------|---------|---------| +| `region` | `"us-east-1"` | Deployment Region | +| `name_prefix` | `"gha-microvm-runner"` | Prefix for every resource name | +| `runner_scope` | `"repo"` | `repo` or `org` | +| `github_owner`, `github_repo` | `""` | Target repository (required for `repo` scope) | +| `github_org` | `""` | Target organization (required for `org` scope) | +| `runner_labels` | `["self-hosted", "lambda"]` | Labels the runner registers with; jobs must request all of them | +| `microvm_max_duration_seconds` | `900` | Maximum MicroVM lifetime in seconds (1–28800) | + +## Testing + +1. Run the smoke workflow from the Actions tab, or with the GitHub CLI: + ``` + gh workflow run micro-vm-smoke.yml --repo / + ``` +1. Follow the MicroVM output: + ``` + aws logs tail "$(terraform output -raw microvm_runtime_log_group)" --follow --region "$(terraform output -raw region)" + ``` +1. Expected result: the three matrix jobs succeed, each on its own runner named `lambda-jit-`, and each MicroVM terminates itself when its job ends. Afterwards this returns an empty list: + ``` + aws lambda-microvms list-microvms --region "$(terraform output -raw region)" \ + --image-identifier "$(terraform output -raw microvm_image_arn)" \ + --query "items[?state=='RUNNING']" + ``` +1. Run `buildah-build.yml` the same way. The `buildah images` step lists `localhost/hello`. + +To test the webhook endpoint from the CLI with the sample events in `events/`, sign each payload with your webhook secret the way GitHub does (HMAC-SHA256 over the exact request body). The sample `workflow_job` event requests the `ubuntu-latest` label, so it passes the signature check but launches nothing: + +```bash +cd # the folder with main.tf and events/ +URL="$(terraform output -raw webhook_url)" +read -rsp 'Webhook secret: ' WEBHOOK_SECRET; echo + +# Sends a signed payload and prints the HTTP status code. +send() { # usage: send + SIG="sha256=$(openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" "$2" | awk '{print $NF}')" + curl -s -o /dev/null -w '%{http_code}\n' -X POST "$URL" \ + -H "Content-Type: application/json" -H "X-GitHub-Event: $1" \ + -H "X-Hub-Signature-256: $SIG" --data-binary @"$2" +} + +send ping events/ping.json # expect 200 (pong) +send workflow_job events/workflow_job_queued.json # expect 204 (labels do not match, nothing launched) + +# Without a valid signature the webhook rejects the request: +curl -s -o /dev/null -w '%{http_code}\n' -X POST "$URL" \ + -H "Content-Type: application/json" -H "X-GitHub-Event: workflow_job" \ + --data-binary @events/workflow_job_queued.json # expect 401 +unset WEBHOOK_SECRET +``` + +If you added AWS WAF with an IP allowlist in front of the API, these requests from your machine return `403`. Run them from an allowed address, or test through GitHub (Settings → Webhooks → Recent Deliveries → Redeliver). + +To launch a MicroVM from the CLI instead, change the labels in a copy of the event to your `runner_labels` (for example `["self-hosted", "lambda"]`). The webhook then answers `202`, but GitHub has no matching queued job, so the runner idles until `microvm_max_duration_seconds`. Use a real workflow run for end-to-end tests. + +To run the webhook unit tests offline (no AWS or network calls): +``` +cd src/webhook +python3 -m venv .venv && .venv/bin/pip install -r requirements.txt pytest +.venv/bin/python -m pytest -v +``` + +## Cleanup + +1. Remove the webhook in the GitHub repository's Settings → Webhooks. +1. Delete the stack. This deletes the MicroVM image stack, the S3 bucket and its objects, and the secrets (immediately, with no recovery window): + ``` + terraform destroy + ``` +1. Delete the image build log group, which Lambda created outside Terraform: + ``` + aws logs delete-log-group --log-group-name /aws/lambda-microvms/-runner-image --region + ``` +1. Optionally, delete the example workflows from the repository's `.github/workflows/`. + +---- +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/lambda-microvms-github-actions-runner/go/terraform/events/ping.json b/lambda-microvms-github-actions-runner/go/terraform/events/ping.json new file mode 100644 index 000000000..c4b1c2025 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/events/ping.json @@ -0,0 +1,4 @@ +{ + "zen": "Keep it logically awesome.", + "hook_id": 1000000002 +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/events/workflow_job_queued.json b/lambda-microvms-github-actions-runner/go/terraform/events/workflow_job_queued.json new file mode 100644 index 000000000..79f320884 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/events/workflow_job_queued.json @@ -0,0 +1,18 @@ +{ + "action": "queued", + "workflow_job": { + "id": 1000000001, + "run_id": 2000000001, + "name": "example-job", + "status": "queued", + "labels": ["ubuntu-latest"] + }, + "repository": { + "name": "", + "full_name": "/", + "private": true + }, + "sender": { + "login": "" + } +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/example-pattern.json b/lambda-microvms-github-actions-runner/go/terraform/example-pattern.json new file mode 100644 index 000000000..d0f15ca16 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/example-pattern.json @@ -0,0 +1,74 @@ +{ + "title": "Ephemeral GitHub Actions runners on AWS Lambda MicroVMs with Amazon API Gateway", + "description": "Run each GitHub Actions job on its own single-use AWS Lambda MicroVM, launched by a webhook through Amazon API Gateway and AWS Lambda.", + "language": "Go", + "level": "300", + "framework": "Terraform", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern runs every GitHub Actions job on its own single-use AWS Lambda MicroVM. When a job is queued, GitHub sends a workflow_job webhook to an Amazon API Gateway REST API. An AWS Lambda function verifies the webhook's HMAC signature with a secret stored in AWS Secrets Manager and checks that the job requests all of the configured runner labels. It then calls the GitHub API with a personal access token, also stored in Secrets Manager, to mint a just-in-time (JIT) runner configuration that can register exactly one runner for exactly one job. Finally it calls RunMicrovm to launch a MicroVM from a pre-built snapshot, attaching an outbound-only network configuration and a maximum duration.", + "The JIT configuration is larger than the 4096-character run-hook payload limit, so the function writes it to Amazon S3 and passes the MicroVM a presigned GET URL that expires after 60 seconds. Lambda delivers that URL to a small Go supervisor inside the MicroVM through the /run lifecycle hook. The supervisor fetches the configuration over HTTPS, starts the GitHub Actions runner with run.sh --jitconfig, and calls TerminateMicrovm on its own MicroVM as soon as the job ends, whether it passed or failed. The personal access token never enters the MicroVM, and the MicroVM's execution role has no access to S3 or Secrets Manager. It can only terminate runner MicroVMs and write its own logs. Nothing runs between jobs, so the runners scale to zero.", + "The runner image is built once by terraform apply. A build script cross-compiles the supervisor for ARM64 and zips it with a Dockerfile. Terraform uploads the zip to S3 and creates the AWS::Lambda::MicrovmImage resource in a one-resource AWS CloudFormation stack, on the Amazon Linux 2023 managed base image with the /ready and /run hooks enabled on port 8080. Lambda runs the Dockerfile, waits for the /ready hook and snapshots the MicroVM, so every job starts from a fully initialized environment. The image bakes in the GitHub Actions runner, verified against a pinned SHA-256 checksum, and buildah configured for the vfs storage driver and chroot isolation, so jobs can build container images without a Docker daemon.", + "This pattern deploys Amazon API Gateway, an AWS Lambda function, a Lambda MicroVM image, an Amazon S3 bucket and two AWS Secrets Manager secrets, plus three least-privilege IAM roles and Amazon CloudWatch Logs log groups with a retention period. Two example workflows are included: a three-job smoke test and a buildah image build." + ] + }, + "gitHub": { + "template": { + "templateFile": "main.tf", + "patternPath": "lambda-microvms-github-actions-runner/go/terraform" + } + }, + "resources": { + "bullets": [ + { + "text": "AWS Lambda MicroVMs developer guide", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/lambda-microvms-guide.html" + }, + { + "text": "MicroVM images", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/microvms-images.html" + }, + { + "text": "Actions, resources, and condition keys for AWS Lambda", + "link": "https://docs.aws.amazon.com/service-authorization/latest/reference/list_awslambda.html" + }, + { + "text": "GitHub REST API: create configuration for a just-in-time runner", + "link": "https://docs.github.com/en/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-a-repository" + }, + { + "text": "Lambda proxy integrations in Amazon API Gateway", + "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html" + } + ] + }, + "deploy": { + "text": [ + "Build the MicroVM code artifact: ./src/microvm-runner/build.sh", + "Deploy: terraform init && terraform apply", + "Store the GitHub token and webhook secret, add the GitHub webhook and copy an example workflow, as described in steps 6 to 8 of the README." + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Remove the webhook from the GitHub repository settings.", + "Delete the stack: terraform destroy.", + "Delete the image build log group created by Lambda: aws logs delete-log-group --log-group-name /aws/lambda-microvms/<name_prefix>-runner-image." + ] + }, + "authors": [ + { + "name": "Frank Peraza", + "bio": "Associate Solutions Architect at AWS", + "image": "https://avatars.githubusercontent.com/u/213654438?v=4", + "github": "frperaza", + "linkedin": "frank-peraza" + } + ] +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/example-workflows/buildah-build.yml b/lambda-microvms-github-actions-runner/go/terraform/example-workflows/buildah-build.yml new file mode 100644 index 000000000..274adb8ff --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/example-workflows/buildah-build.yml @@ -0,0 +1,31 @@ +name: buildah-build +# There is no Docker daemon in the MicroVM; the runner image presets buildah, +# so a plain `buildah bud` needs no extra flags. +# runs-on must list every label in var.runner_labels. + +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: [self-hosted, lambda] + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + + - name: Write a tiny Containerfile + run: | + mkdir -p "$RUNNER_TEMP/hello" + cat > "$RUNNER_TEMP/hello/Containerfile" <<'CONTAINERFILE' + FROM docker.io/library/alpine:3.20 + RUN echo "built on a Lambda MicroVM" > /hello.txt + CMD ["cat", "/hello.txt"] + CONTAINERFILE + + - name: Build with buildah + run: | + buildah --version + buildah bud -t "localhost/hello:${GITHUB_SHA::7}" "$RUNNER_TEMP/hello" + buildah images diff --git a/lambda-microvms-github-actions-runner/go/terraform/example-workflows/micro-vm-smoke.yml b/lambda-microvms-github-actions-runner/go/terraform/example-workflows/micro-vm-smoke.yml new file mode 100644 index 000000000..071e3e419 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/example-workflows/micro-vm-smoke.yml @@ -0,0 +1,31 @@ +name: micro-vm-smoke + +# runs-on must list every label in var.runner_labels; the webhook only +# launches a MicroVM for jobs that request all of them. +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + smoke: + # Each matrix job lands on its own MicroVM. + strategy: + fail-fast: false + matrix: + n: [1, 2, 3] + runs-on: [self-hosted, lambda] + steps: + - name: Identify this ephemeral runner + run: | + echo "matrix job #${{ matrix.n }}" + echo "host: $(hostname)" + echo "arch: $(uname -m)" + echo "runner: $RUNNER_NAME" + echo "started: $(date -u +%H:%M:%S.%3N)" + + - name: Prove isolation + ephemerality + run: | + echo "Each matrix job runs on a separate single-use MicroVM." + echo "This runner terminates itself when this job finishes." diff --git a/lambda-microvms-github-actions-runner/go/terraform/main.tf b/lambda-microvms-github-actions-runner/go/terraform/main.tf new file mode 100644 index 000000000..01d2bee7e --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/main.tf @@ -0,0 +1,496 @@ +# Ephemeral GitHub Actions runners on AWS Lambda MicroVMs. +# Run ./src/microvm-runner/build.sh before terraform plan/apply. + +data "aws_caller_identity" "current" {} + +locals { + account_id = data.aws_caller_identity.current.account_id + + tags = { + Project = "lambda-microvms-github-actions-runner" + } + + # CloudFormation requires a base image version. Bump it to pick up base-image + # patches (aws lambda-microvms list-managed-microvm-image-versions). + microvm_base_image_arn = "arn:aws:lambda:${var.region}:aws:microvm-image:al2023-1" + microvm_base_image_version = "4" + + # No leading or trailing slash. Scopes the webhook's S3 grant and the lifecycle rule. + jit_key_prefix = "jit" + + webhook_function_name = "${var.name_prefix}-webhook" + + runner_image_name = "${var.name_prefix}-runner-image" + runner_image_arn_pattern = "arn:aws:lambda:${var.region}:${local.account_id}:microvm-image:${var.name_prefix}-runner-*" + build_log_group_arn_pattern = "arn:aws:logs:${var.region}:${local.account_id}:log-group:/aws/lambda-microvms/${var.name_prefix}-runner-*" + + supervisor_zip = "${path.module}/src/microvm-runner/dist/supervisor.zip" + supervisor_zip_md5 = fileexists(local.supervisor_zip) ? filemd5(local.supervisor_zip) : "" +} + +# --- S3: image code artifact + per-job JIT configs --- +# A JIT config (~4.1 KB) exceeds the 4096-char run-hook-payload limit, so the VM +# gets a presigned GET URL for it instead. S3 rather than SSM: Standard +# parameters are also capped at 4 KB. + +resource "aws_s3_bucket" "artifacts" { + bucket = "${var.name_prefix}-artifacts-${local.account_id}" + force_destroy = true + tags = local.tags +} + +resource "aws_s3_bucket_public_access_block" "artifacts" { + bucket = aws_s3_bucket.artifacts.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_policy" "artifacts" { + bucket = aws_s3_bucket.artifacts.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Sid = "DenyInsecureTransport" + Effect = "Deny" + Principal = "*" + Action = "s3:*" + Resource = [aws_s3_bucket.artifacts.arn, "${aws_s3_bucket.artifacts.arn}/*"] + Condition = { Bool = { "aws:SecureTransport" = "false" } } + }] + }) + + # Avoid concurrent bucket-policy / public-access-block writes (OperationAborted). + depends_on = [aws_s3_bucket_public_access_block.artifacts] +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "artifacts" { + bucket = aws_s3_bucket.artifacts.id + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +# The VM has no S3 permissions, so nothing else deletes used JIT configs. +resource "aws_s3_bucket_lifecycle_configuration" "artifacts" { + bucket = aws_s3_bucket.artifacts.id + + rule { + id = "expire-jit-configs" + status = "Enabled" + + filter { + prefix = "${local.jit_key_prefix}/" + } + + expiration { + days = 1 + } + } +} + +# --- Secrets Manager --- +# Values are set out of band so secret material never lands in Terraform state. + +resource "aws_secretsmanager_secret" "pat" { + name = "${var.name_prefix}-github-pat" + # Delete immediately on destroy, so a redeploy with the same name_prefix + # doesn't collide with a secret pending deletion. + recovery_window_in_days = 0 + tags = local.tags +} + +resource "aws_secretsmanager_secret" "webhook" { + name = "${var.name_prefix}-webhook-secret" + recovery_window_in_days = 0 + tags = local.tags +} + +# --- CloudWatch Logs --- +# Lambda creates the image build log group itself; Terraform doesn't manage it. + +resource "aws_cloudwatch_log_group" "microvm_runtime" { + name = "/${var.name_prefix}/microvm-runtime" + retention_in_days = 14 + tags = local.tags +} + +resource "aws_cloudwatch_log_group" "webhook" { + name = "/aws/lambda/${local.webhook_function_name}" + retention_in_days = aws_cloudwatch_log_group.microvm_runtime.retention_in_days + tags = local.tags +} + +# --- IAM --- +# RunMicrovm and TerminateMicrovm authorize against the microvm-image resource. + +# Assumed by Lambda during image builds; the build-time /ready hook runs under it. +resource "aws_iam_role" "microvm_build" { + name = "${var.name_prefix}-microvm-build-role" + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = ["sts:AssumeRole", "sts:TagSession"] + }] + }) + tags = local.tags +} + +resource "aws_iam_role_policy" "microvm_build" { + name = "${var.name_prefix}-microvm-build-policy" + role = aws_iam_role.microvm_build.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "ReadArtifact" + Effect = "Allow" + Action = ["s3:GetObject"] + Resource = ["${aws_s3_bucket.artifacts.arn}/supervisor-runner-*"] + }, + { + Sid = "BuildLogs" + Effect = "Allow" + Action = ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"] + Resource = [local.build_log_group_arn_pattern] + } + ] + }) +} + +# TRUST BOUNDARY: these credentials are reachable by arbitrary CI job code +# running in the VM, not just the supervisor (see README Security). +resource "aws_iam_role" "microvm_execution" { + name = "${var.name_prefix}-microvm-exec-role" + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Action = ["sts:AssumeRole", "sts:TagSession"] + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + }] + }) + tags = local.tags +} + +resource "aws_iam_role_policy" "microvm_execution" { + name = "${var.name_prefix}-microvm-exec-policy" + role = aws_iam_role.microvm_execution.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + # There is no MicroVM-ID resource or condition key, so this is scoped to + # the image the MicroVM was launched from. + Sid = "SelfTerminate" + Effect = "Allow" + Action = ["lambda:TerminateMicrovm"] + Resource = [local.runner_image_arn_pattern] + }, + { + Sid = "RuntimeLogs" + Effect = "Allow" + Action = ["logs:CreateLogStream", "logs:PutLogEvents"] + Resource = ["${aws_cloudwatch_log_group.microvm_runtime.arn}:*"] + } + # No S3 access: the VM reads its JIT config through a presigned URL. + ] + }) +} + +resource "aws_iam_role" "webhook" { + name = "${var.name_prefix}-webhook-role" + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Action = "sts:AssumeRole" + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + }] + }) + tags = local.tags +} + +# Inline policy instead of AWSLambdaBasicExecutionRole, which grants logs on "*". +resource "aws_iam_role_policy" "webhook" { + name = "${var.name_prefix}-webhook-policy" + role = aws_iam_role.webhook.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "FunctionLogs" + Effect = "Allow" + Action = ["logs:CreateLogStream", "logs:PutLogEvents"] + Resource = ["${aws_cloudwatch_log_group.webhook.arn}:*"] + }, + { + Sid = "ReadSecrets" + Effect = "Allow" + Action = ["secretsmanager:GetSecretValue"] + Resource = [aws_secretsmanager_secret.pat.arn, aws_secretsmanager_secret.webhook.arn] + }, + { + Sid = "RunMicrovm" + Effect = "Allow" + Action = ["lambda:RunMicrovm"] + Resource = [local.runner_image_arn_pattern] + }, + { + Sid = "PassMicrovmExecutionRole" + Effect = "Allow" + Action = ["iam:PassRole"] + Resource = [aws_iam_role.microvm_execution.arn] + Condition = { + StringEquals = { "iam:PassedToService" = "lambda.amazonaws.com" } + } + }, + { + # The AWS-managed connectors live in the "aws" account. + Sid = "PassNetworkConnectors" + Effect = "Allow" + Action = ["lambda:PassNetworkConnector"] + Resource = [ + "arn:aws:lambda:${var.region}:aws:network-connector:aws-network-connector:NO_INGRESS", + "arn:aws:lambda:${var.region}:aws:network-connector:aws-network-connector:INTERNET_EGRESS", + ] + }, + { + # Presigning a GET URL requires the signer to hold s3:GetObject. + Sid = "WriteSignJitConfig" + Effect = "Allow" + Action = ["s3:PutObject", "s3:GetObject"] + Resource = ["${aws_s3_bucket.artifacts.arn}/${local.jit_key_prefix}/*"] + } + ] + }) +} + +# --- MicroVM runner image --- +# A one-resource CloudFormation stack: the hashicorp/aws image resource can't +# configure hooks, and hashicorp/awscc drops the empty AdditionalOsCapabilities +# list CloudFormation requires. A new zip changes the template, and the stack +# update builds a new image version under the same ARN; a failed build rolls +# back to the previous version. + +# Content-addressed key: a changed zip is a new object, so a new image version. +resource "aws_s3_object" "supervisor_zip" { + bucket = aws_s3_bucket.artifacts.id + key = "supervisor-runner-${local.supervisor_zip_md5}.zip" + source = local.supervisor_zip + source_hash = local.supervisor_zip_md5 + tags = local.tags + + lifecycle { + # Delete the old zip only after the stack update succeeds. If the new build + # fails, the CloudFormation rollback rebuilds from the old zip's URI. + create_before_destroy = true + + precondition { + condition = local.supervisor_zip_md5 != "" + error_message = "src/microvm-runner/dist/supervisor.zip not found: run ./src/microvm-runner/build.sh first." + } + } +} + +resource "aws_cloudformation_stack" "microvm_image" { + name = "${var.name_prefix}-microvm-image" + # Only applies to a failed first create; a failed update rolls back. + on_failure = "DELETE" + tags = local.tags + + template_body = jsonencode({ + AWSTemplateFormatVersion = "2010-09-09" + Description = "Lambda MicroVM image for the ${var.name_prefix} GitHub Actions runner (managed by Terraform)." + Resources = { + RunnerImage = { + Type = "AWS::Lambda::MicrovmImage" + Properties = { + Name = local.runner_image_name + Description = "GitHub Actions runner supervisor for ${var.name_prefix} (built by Terraform)" + BaseImageArn = local.microvm_base_image_arn + BaseImageVersion = local.microvm_base_image_version + BuildRoleArn = aws_iam_role.microvm_build.arn + CodeArtifact = { Uri = "s3://${aws_s3_object.supervisor_zip.bucket}/${aws_s3_object.supervisor_zip.key}" } + # Must match ARCH in src/microvm-runner/build.sh. + CpuConfigurations = [{ Architecture = "ARM_64" }] + Resources = [{ MinimumMemoryInMiB = 2048 }] + # Required by CloudFormation even when empty. + AdditionalOsCapabilities = [] + # Required by CloudFormation even when empty. + EnvironmentVariables = [] + # The build needs internet (apt, runner download). + EgressNetworkConnectors = ["arn:aws:lambda:${var.region}:aws:network-connector:aws-network-connector:INTERNET_EGRESS"] + # The supervisor needs /run to start the job; /run requires /ready. + Hooks = { + Port = 8080 + MicrovmHooks = { Run = "ENABLED", RunTimeoutInSeconds = 30 } + MicrovmImageHooks = { Ready = "ENABLED", ReadyTimeoutInSeconds = 30 } + } + Logging = { CloudWatch = { LogGroup = "/aws/lambda-microvms/${local.runner_image_name}" } } + Tags = [for k, v in local.tags : { Key = k, Value = v }] + } + } + } + Outputs = { + ImageArn = { Value = { "Fn::GetAtt" = ["RunnerImage", "ImageArn"] } } + } + }) + + # Create and update wait for the image build. + timeouts { + create = "60m" + update = "60m" + delete = "30m" + } + + depends_on = [aws_iam_role_policy.microvm_build, aws_s3_bucket_policy.artifacts] +} + +# --- Webhook Lambda --- + +# Vendors boto3: the runtime's built-in boto3 predates the lambda-microvms client. +resource "null_resource" "webhook_build" { + triggers = { + handler = filemd5("${path.module}/src/webhook/handler.py") + reqs = filemd5("${path.module}/src/webhook/requirements.txt") + } + + provisioner "local-exec" { + command = <<-EOT + set -e + PKG="${path.module}/.build/webhook_pkg" + rm -rf "$PKG" && mkdir -p "$PKG" + cp "${path.module}/src/webhook/handler.py" "$PKG/" + pip3 install -r "${path.module}/src/webhook/requirements.txt" \ + --target "$PKG" --only-binary=:all: --platform manylinux2014_x86_64 \ + --python-version 3.12 --quiet + EOT + } +} + +data "archive_file" "webhook" { + type = "zip" + source_dir = "${path.module}/.build/webhook_pkg" + output_path = "${path.module}/.build/webhook.zip" + depends_on = [null_resource.webhook_build] +} + +resource "aws_lambda_function" "webhook" { + function_name = local.webhook_function_name + role = aws_iam_role.webhook.arn + runtime = "python3.12" + handler = "handler.handler" + filename = data.archive_file.webhook.output_path + source_code_hash = data.archive_file.webhook.output_base64sha256 + timeout = 15 + + environment { + variables = { + RUNNER_SCOPE = var.runner_scope + GITHUB_OWNER = var.github_owner + GITHUB_REPO = var.github_repo + GITHUB_ORG = var.github_org + RUNNER_LABELS = join(",", var.runner_labels) + RUNNER_GROUP_ID = "1" + # RunMicrovm launches the image's latest active version, so an image + # update doesn't change this value. + MICROVM_IMAGE_ARN = aws_cloudformation_stack.microvm_image.outputs["ImageArn"] + MICROVM_EXECUTION_ROLE_ARN = aws_iam_role.microvm_execution.arn + MICROVM_MAX_DURATION_SECONDS = tostring(var.microvm_max_duration_seconds) + JIT_BUCKET = aws_s3_bucket.artifacts.id + JIT_KEY_PREFIX = local.jit_key_prefix + MICROVM_LOG_GROUP = aws_cloudwatch_log_group.microvm_runtime.name + PAT_SECRET_ARN = aws_secretsmanager_secret.pat.arn + WEBHOOK_SECRET_ARN = aws_secretsmanager_secret.webhook.arn + } + } + + lifecycle { + # Variable validation can't reference other variables on Terraform < 1.9. + precondition { + condition = var.runner_scope != "repo" || (var.github_owner != "" && var.github_repo != "") + error_message = "runner_scope = \"repo\" requires github_owner and github_repo." + } + precondition { + condition = var.runner_scope != "org" || var.github_org != "" + error_message = "runner_scope = \"org\" requires github_org." + } + } + + depends_on = [aws_cloudwatch_log_group.webhook] + + tags = local.tags +} + +# --- API Gateway --- +# REST API (v1) so AWS WAF can be attached to the stage. + +resource "aws_api_gateway_rest_api" "webhook" { + name = "${var.name_prefix}-webhook-api" + + endpoint_configuration { + types = ["REGIONAL"] + } + + tags = local.tags +} + +resource "aws_api_gateway_resource" "webhook" { + rest_api_id = aws_api_gateway_rest_api.webhook.id + parent_id = aws_api_gateway_rest_api.webhook.root_resource_id + path_part = "webhook" +} + +resource "aws_api_gateway_method" "webhook_post" { + rest_api_id = aws_api_gateway_rest_api.webhook.id + resource_id = aws_api_gateway_resource.webhook.id + http_method = "POST" + authorization = "NONE" # public; the handler's HMAC check is the authentication +} + +resource "aws_api_gateway_integration" "webhook" { + rest_api_id = aws_api_gateway_rest_api.webhook.id + resource_id = aws_api_gateway_resource.webhook.id + http_method = aws_api_gateway_method.webhook_post.http_method + integration_http_method = "POST" + type = "AWS_PROXY" + uri = aws_lambda_function.webhook.invoke_arn +} + +resource "aws_api_gateway_deployment" "webhook" { + rest_api_id = aws_api_gateway_rest_api.webhook.id + + triggers = { + redeploy = sha1(jsonencode([ + aws_api_gateway_resource.webhook.id, + aws_api_gateway_method.webhook_post.id, + aws_api_gateway_integration.webhook.id, + ])) + } + + lifecycle { + create_before_destroy = true + } +} + +resource "aws_api_gateway_stage" "webhook" { + rest_api_id = aws_api_gateway_rest_api.webhook.id + deployment_id = aws_api_gateway_deployment.webhook.id + stage_name = "v1" + tags = local.tags +} + +resource "aws_lambda_permission" "apigw_invoke" { + statement_id = "AllowAPIGatewayInvoke" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.webhook.function_name + principal = "apigateway.amazonaws.com" + source_arn = "${aws_api_gateway_rest_api.webhook.execution_arn}/*/*" +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/outputs.tf b/lambda-microvms-github-actions-runner/go/terraform/outputs.tf new file mode 100644 index 000000000..8364f7788 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/outputs.tf @@ -0,0 +1,39 @@ +output "webhook_url" { + description = "GitHub webhook Payload URL. Content type: application/json." + value = "${aws_api_gateway_stage.webhook.invoke_url}/webhook" +} + +output "pat_secret_arn" { + description = "Secret to store the GitHub PAT in (aws secretsmanager put-secret-value)." + value = aws_secretsmanager_secret.pat.arn +} + +output "webhook_secret_arn" { + description = "Secret to store the webhook HMAC secret in; use the same value in the GitHub webhook." + value = aws_secretsmanager_secret.webhook.arn +} + +output "microvm_image_arn" { + description = "MicroVM runner image the webhook launches. RunMicrovm uses its latest active version." + value = aws_cloudformation_stack.microvm_image.outputs["ImageArn"] +} + +output "artifacts_bucket_name" { + description = "S3 bucket holding the MicroVM image zip and the per-job JIT configs." + value = aws_s3_bucket.artifacts.id +} + +output "microvm_runtime_log_group" { + description = "CloudWatch log group with the supervisor and runner output of each MicroVM." + value = aws_cloudwatch_log_group.microvm_runtime.name +} + +output "region" { + description = "Region the stack is deployed in." + value = var.region +} + +output "name_prefix" { + description = "Resource name prefix; the runner image is -runner-image." + value = var.name_prefix +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile new file mode 100644 index 000000000..4b4d1496e --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile @@ -0,0 +1,69 @@ +# Lambda builds this on top of the managed AL2023 MicroVM base image +# (--base-image-arn); FROM only selects the container for the app layers. +# The runner is pre-extracted so it is baked into the snapshot. +# arm64: must match CpuConfigurations (ARM_64) in main.tf and ARCH in build.sh. +FROM arm64v8/debian:13-slim + +# Bump RUNNER_SHA256 with RUNNER_VERSION (checksum from the release notes at +# https://github.com/actions/runner/releases), or `sha256sum -c` fails the build. +ARG RUNNER_VERSION=2.337.0 +ARG RUNNER_ARCH=arm64 +ARG RUNNER_SHA256=9b1dc70626422526e3c94767cf024896beb15da5342a3f4819bf2feac13e0393 +# Upstream minor only, so Debian security rebuilds still match. Must be the +# minor shipped by the Debian suite in FROM. +ARG BUILDAH_VERSION=1.39 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + ca-certificates git curl tar gzip \ + && rm -rf /var/lib/apt/lists/* + +# --- GitHub Actions runner --- +# Runs as root: buildah's chroot isolation needs it. Acceptable because each +# MicroVM is single-use and terminates after one job. +WORKDIR /opt/actions-runner +RUN curl -fsSL -o runner.tar.gz \ + "https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-${RUNNER_ARCH}-${RUNNER_VERSION}.tar.gz" \ + && echo "${RUNNER_SHA256} runner.tar.gz" | sha256sum -c - \ + && tar xzf runner.tar.gz \ + && rm runner.tar.gz \ + && ./bin/installdependencies.sh \ + && rm -rf /var/lib/apt/lists/* + +# --- buildah --- +# dockerd can't run in the MicroVM (no mount/PID namespaces, no cgroup v2), so +# CI jobs use buildah with chroot isolation and the vfs driver. +# netavark: buildah refuses to build without a network backend. +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + "buildah=${BUILDAH_VERSION}.*" \ + netavark \ + && rm -rf /var/lib/apt/lists/* \ + && buildah --version \ + && buildah --version | grep -qF "buildah version ${BUILDAH_VERSION}." + +# Defaults so CI jobs can run plain `buildah bud`. Short image names resolve +# to Docker Hub, as with docker. +RUN mkdir -p /etc/containers/registries.conf.d \ + && printf '%s\n' \ + '[storage]' \ + 'driver = "vfs"' \ + 'runroot = "/run/containers/storage"' \ + 'graphroot = "/var/lib/containers/storage"' \ + > /etc/containers/storage.conf \ + && printf '%s\n' \ + 'unqualified-search-registries = ["docker.io"]' \ + > /etc/containers/registries.conf.d/50-microvm-runner.conf +ENV BUILDAH_ISOLATION=chroot + +# --- Supervisor: answers the hooks, runs the job, self-terminates --- +COPY supervisor /usr/local/bin/supervisor + +# The runner refuses to run as root without this flag. +ENV RUNNER_DIR=/opt/actions-runner +ENV RUNNER_ALLOW_RUNASROOT=1 + +# Lifecycle hooks port; must match Hooks.Port in main.tf. +EXPOSE 8080 + +ENTRYPOINT ["/usr/local/bin/supervisor"] diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/build.sh b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/build.sh new file mode 100755 index 000000000..9a9ca45ea --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/build.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Builds dist/supervisor.zip (Dockerfile + linux/arm64 supervisor binary). +# Local only; terraform apply uploads it and builds the image. +set -euo pipefail + +cd "$(dirname "$0")" + +ARCH="${ARCH:-arm64}" # must match CpuConfigurations in main.tf (ARM_64) +DIST="dist" +STAGE="$DIST/stage" + +echo ">> cleaning" +rm -rf "$DIST" +mkdir -p "$STAGE" + +echo ">> cross-compiling supervisor for linux/$ARCH" +( cd supervisor && CGO_ENABLED=0 GOOS=linux GOARCH="$ARCH" \ + go build -trimpath -ldflags="-s -w" -o "../$STAGE/supervisor" . ) + +echo ">> staging Dockerfile" +cp Dockerfile "$STAGE/Dockerfile" + +echo ">> packaging $DIST/supervisor.zip" +# Fixed timestamps and -X make the zip deterministic, so terraform only +# rebuilds the image on a real change. +touch -t 8001010000 "$STAGE/supervisor" "$STAGE/Dockerfile" +# -j: both files at the zip root, where Lambda and the Dockerfile COPY expect them. +( cd "$STAGE" && zip -X -j -q "../supervisor.zip" supervisor Dockerfile ) + +echo ">> done:" +ls -la "$DIST/supervisor.zip" +unzip -l "$DIST/supervisor.zip" diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/githubrunner.go b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/githubrunner.go new file mode 100644 index 000000000..ccc07cf4a --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/githubrunner.go @@ -0,0 +1,80 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "time" +) + +const runnerDirEnv = "RUNNER_DIR" + +// The timeout bounds a stalled S3 GET so the VM still self-terminates +// (http.DefaultClient has no timeout). +var jitHTTPClient = &http.Client{Timeout: 30 * time.Second} + +// resolveJitConfig fetches the JIT config from the presigned S3 URL in the /run +// hook payload, so the MicroVM needs no S3 permissions. +func (s *Supervisor) resolveJitConfig(ctx context.Context, url string) (string, error) { + if url == "" { + return "", errors.New("empty pre-signed URL in run hook payload") + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return "", fmt.Errorf("build JIT request: %w", err) + } + + resp, err := jitHTTPClient.Do(req) + if err != nil { + return "", fmt.Errorf("fetch JIT config: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("read JIT config body: %w", err) + } + if resp.StatusCode != http.StatusOK { + // Never log the URL or body: the URL is a bearer credential. + return "", fmt.Errorf("JIT fetch returned HTTP %d", resp.StatusCode) + } + + return string(body), nil +} + +// runGitHubRunner runs the single-use JIT runner and blocks until its one job +// completes. +func runGitHubRunner(ctx context.Context, jitConfig string) error { + if jitConfig == "" { + return errors.New("empty JIT config: nothing to run") + } + + runnerDir := os.Getenv(runnerDirEnv) + if runnerDir == "" { + return fmt.Errorf("%s not set; cannot locate the Actions runner", runnerDirEnv) + } + + runScript := filepath.Join(runnerDir, "run.sh") + if _, err := os.Stat(runScript); err != nil { + return fmt.Errorf("runner entrypoint %s not found: %w", runScript, err) + } + + cmd := exec.CommandContext(ctx, runScript, "--jitconfig", jitConfig) + cmd.Dir = runnerDir + + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + cmd.Env = os.Environ() + + if err := cmd.Run(); err != nil { + return fmt.Errorf("runner exited with error: %w", err) + } + return nil +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.mod b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.mod new file mode 100644 index 000000000..787f90ce4 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.mod @@ -0,0 +1,24 @@ +module supervisor + +go 1.27.4 + +require ( + github.com/aws/aws-sdk-go-v2/config v1.33.20 + github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.12.2 +) + +require ( + github.com/aws/aws-sdk-go-v2 v1.48.0 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.21.2 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.52.0 // indirect + github.com/aws/smithy-go v1.28.9 // indirect +) diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.sum b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.sum new file mode 100644 index 000000000..21656ddc6 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/go.sum @@ -0,0 +1,30 @@ +github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc= +github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0= +github.com/aws/aws-sdk-go-v2/config v1.33.20 h1:tcppf3ihhY8KsiVN5NJAN4uMlHc9NZrPRhkSuBTkqag= +github.com/aws/aws-sdk-go-v2/config v1.33.20/go.mod h1:WErTFkC327Fgt5x4SZHD2t1L64HTRb2kW42SqzEWxnA= +github.com/aws/aws-sdk-go-v2/credentials v1.21.2 h1:PWB8NaorQv2OzyNjXMy6RjBh+HzneyxY2ECC58jV600= +github.com/aws/aws-sdk-go-v2/credentials v1.21.2/go.mod h1:N/A5a+8LDrdI9pcr4ZjuHuQIHU5km3rtDuVzt+xW2C4= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 h1:oH1E0tjN0g+ZRusbX1dsuat4FJ0z05l8hWaycSbDuNc= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9/go.mod h1:3ZaQGigIoaS45x9HgnLZ4sP475Fs7QoxU3IsZX/J3h4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI= +github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.12.2 h1:J+l0t2GLReRzIAUxledyRaG+IbfzQ7v6+n+FSw21SYE= +github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.12.2/go.mod h1:GEnG9FBOraRH3j7GPz/wQmuBLI7d+yjDje4IriTgQ7o= +github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 h1:bIEk1HfTd3MGzvDa5YOQUodGr96D9+UTnmBLBB8ZJ10= +github.com/aws/aws-sdk-go-v2/service/signin v1.14.0/go.mod h1:LdwHjKqPE9VCC7sTlWcOAizZx3ZJYjmfwC/EW2tIIAE= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 h1:ANAoa+qt3/9kXnvQVgUyxcTzhzZf4DqaBS+M2DQrELU= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.5/go.mod h1:vsMi+SSR7xGQXtV430LVi49qbv/R+U+upHHSp1W/+QI= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy9etdz+RKTeqzchXErAI= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY= +github.com/aws/aws-sdk-go-v2/service/sts v1.52.0 h1:IaBLmJWiIEtKkjXMgMbYGZk7WKXbYA8148wCMCXq9hU= +github.com/aws/aws-sdk-go-v2/service/sts v1.52.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA= +github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY= +github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/main.go b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/main.go new file mode 100644 index 000000000..660e5b9aa --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" +) + +func main() { + ctx := context.Background() + + s, err := NewSupervisor(ctx) + if err != nil { + log.Fatalf("failed to create supervisor: %v", err) + } + + log.Printf("supervisor starting on %s", s.port) + + // The shutdown after self-termination returns http.ErrServerClosed. + if err := s.Run(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("supervisor exited with error: %v", err) + } + + log.Printf("supervisor stopped") +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/supervisor.go b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/supervisor.go new file mode 100644 index 000000000..aea8ce008 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/supervisor.go @@ -0,0 +1,143 @@ +package main + +import ( + "context" + "encoding/json" + "log" + "net/http" + "sync" + "time" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" +) + +type Supervisor struct { + mvmClient *lambdamicrovms.Client + port string + + microvmID string + runHookPayload string // presigned S3 GET URL for the JIT config + + done chan struct{} + once sync.Once +} + +func NewSupervisor(ctx context.Context) (*Supervisor, error) { + cfg, err := config.LoadDefaultConfig(ctx) + if err != nil { + return nil, err + } + + s := &Supervisor{ + mvmClient: lambdamicrovms.NewFromConfig(cfg), + port: ":8080", + done: make(chan struct{}), + } + return s, nil +} + +func (s *Supervisor) Run(ctx context.Context) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + mux := http.NewServeMux() + mux.HandleFunc("/aws/lambda-microvms/runtime/v1/run", s.handleRun) + mux.HandleFunc("/aws/lambda-microvms/runtime/v1/ready", s.handleReady) + // Both handlers reply immediately (the job runs in a goroutine), so these + // fit inside the 30s hook timeouts in main.tf. + server := &http.Server{ + Addr: s.port, + Handler: mux, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 60 * time.Second, + } + + go func() { + <-s.done + server.Shutdown(ctx) + }() + + return server.ListenAndServe() + +} + +func (s *Supervisor) handleRun(w http.ResponseWriter, r *http.Request) { + + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + var req RunHookRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "failed to decode request body", http.StatusBadRequest) + return + } + + if req.MicrovmID == "" { + http.Error(w, "missing microvmId", http.StatusBadRequest) + return + } + + s.once.Do(func() { + s.microvmID = req.MicrovmID + s.runHookPayload = req.RunHookPayload + go s.runJobAndTerminate(context.Background()) + }) + w.WriteHeader(http.StatusOK) + +} + +// handleReady answers the build-time /ready hook. The supervisor is ready once +// its server accepts connections, so Lambda can snapshot right away. +func (s *Supervisor) handleReady(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) +} + +// runJobAndTerminate runs one job, then self-terminates on every exit path. +// The /run hook fires on an already-resumed snapshot, so boot time is not +// included in these timings. +func (s *Supervisor) runJobAndTerminate(ctx context.Context) { + t0 := time.Now() + log.Printf("timing: job start microvmID=%s", s.microvmID) + + tResolve := time.Now() + jitConfig, err := s.resolveJitConfig(ctx, s.runHookPayload) + log.Printf("timing: jit resolve took %s", time.Since(tResolve).Round(time.Millisecond)) + + if err != nil { + log.Printf("could not resolve JIT config: %v (terminating anyway)", err) + } else { + tRun := time.Now() + rerr := runGitHubRunner(ctx, jitConfig) + log.Printf("timing: runner (job) took %s", time.Since(tRun).Round(time.Millisecond)) + if rerr != nil { + log.Printf("runner failed: %v (terminating anyway)", rerr) + } else { + log.Printf("job done, terminating self") + } + } + + tTerm := time.Now() + if err := s.terminateSelf(ctx); err != nil { + log.Printf("terminate failed: %v", err) + } + log.Printf("timing: terminate call took %s", time.Since(tTerm).Round(time.Millisecond)) + log.Printf("timing: total /run -> terminate %s", time.Since(t0).Round(time.Millisecond)) + + close(s.done) + +} + +func (s *Supervisor) terminateSelf(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + + _, err := s.mvmClient.TerminateMicrovm(ctx, &lambdamicrovms.TerminateMicrovmInput{ + MicrovmIdentifier: &s.microvmID, + }) + return err +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/types.go b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/types.go new file mode 100644 index 000000000..d16d8bf4b --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/supervisor/types.go @@ -0,0 +1,6 @@ +package main + +type RunHookRequest struct { + MicrovmID string `json:"microvmId"` + RunHookPayload string `json:"runHookPayload"` +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/webhook/handler.py b/lambda-microvms-github-actions-runner/go/terraform/src/webhook/handler.py new file mode 100644 index 000000000..4ea7c9880 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/webhook/handler.py @@ -0,0 +1,209 @@ +"""GitHub webhook handler: verifies the HMAC signature, mints a JIT runner config +for each queued workflow_job that requests all runner labels, and launches one +MicroVM for it. +""" + +import hashlib +import hmac +import json +import os +import time +import urllib.error +import urllib.request + +import boto3 + +RUNNER_SCOPE = os.environ.get("RUNNER_SCOPE", "repo") +GITHUB_OWNER = os.environ["GITHUB_OWNER"] +GITHUB_REPO = os.environ.get("GITHUB_REPO", "") +GITHUB_ORG = os.environ.get("GITHUB_ORG", "") +RUNNER_LABELS = os.environ.get("RUNNER_LABELS", "self-hosted,lambda").split(",") +RUNNER_GROUP_ID = int(os.environ.get("RUNNER_GROUP_ID", "1")) +PAT_SECRET_ARN = os.environ["PAT_SECRET_ARN"] +WEBHOOK_SECRET_ARN = os.environ["WEBHOOK_SECRET_ARN"] +# Lets a rotated PAT or webhook secret take effect without recycling the function. +SECRET_CACHE_TTL = int(os.environ.get("SECRET_CACHE_TTL_SECONDS", "300")) + +# No imageVersion is passed to RunMicrovm, so it uses the latest active version. +MICROVM_IMAGE_ARN = os.environ["MICROVM_IMAGE_ARN"] +MICROVM_EXECUTION_ROLE_ARN = os.environ["MICROVM_EXECUTION_ROLE_ARN"] +MICROVM_MAX_DURATION_SECONDS = int(os.environ.get("MICROVM_MAX_DURATION_SECONDS", "900")) +JIT_BUCKET = os.environ["JIT_BUCKET"] +JIT_KEY_PREFIX = os.environ.get("JIT_KEY_PREFIX", "jit") +JIT_URL_TTL = int(os.environ.get("JIT_URL_TTL", "60")) # presigned URL lifetime (s) +LOG_GROUP = os.environ.get("MICROVM_LOG_GROUP", "") +REGION = os.environ.get("AWS_REGION", "us-east-1") + +# The runner only dials out, so it needs no ingress. +_NO_INGRESS = f"arn:aws:lambda:{REGION}:aws:network-connector:aws-network-connector:NO_INGRESS" +_INTERNET_EGRESS = f"arn:aws:lambda:{REGION}:aws:network-connector:aws-network-connector:INTERNET_EGRESS" + +_secrets = boto3.client("secretsmanager") +_s3 = boto3.client("s3") +_microvms = boto3.client("lambda-microvms") + +# arn -> (value, monotonic time fetched) +_cache: dict[str, tuple[str, float]] = {} + + +class SafeError(Exception): + """A failure whose message is safe to log: never secrets, headers or bodies.""" + + +def _err(e: Exception) -> str: + """Exception type + AWS error code only (str(e) can echo request data).""" + code = getattr(e, "response", {}).get("Error", {}).get("Code", "") + return f"{type(e).__name__} {code}".strip() + + +def _secret(arn: str) -> str: + """Secret value, whitespace-stripped (a stored trailing newline breaks the + Authorization header). Raises SafeError if it can't be read or is empty.""" + now = time.monotonic() + cached = _cache.get(arn) + if cached is not None and now - cached[1] < SECRET_CACHE_TTL: + return cached[0] + try: + value = _secrets.get_secret_value(SecretId=arn)["SecretString"].strip() + except Exception as e: # noqa: BLE001 — log type/code only, never the value + if cached is not None: + print(f"[webhook] WARN: reading secret {arn} failed ({_err(e)}); using cached value") + return cached[0] + raise SafeError(f"reading secret {arn} failed ({_err(e)})") from None + if not value: + raise SafeError(f"secret {arn} is empty; store a value (see README.md)") + _cache[arn] = (value, now) + return value + + +def _verify_signature(body: bytes, signature_header: str) -> bool: + if not signature_header: + return False + secret = _secret(WEBHOOK_SECRET_ARN).encode() + expected = "sha256=" + hmac.new(secret, body, hashlib.sha256).hexdigest() + return hmac.compare_digest(expected, signature_header) + + +def _generate_jitconfig(runner_name: str) -> str: + """Return the base64 JIT config from GitHub generate-jitconfig. + + Raises SafeError without chaining: urllib errors can embed the PAT header. + """ + if RUNNER_SCOPE == "org": + path = f"/orgs/{GITHUB_ORG}/actions/runners/generate-jitconfig" + else: + path = f"/repos/{GITHUB_OWNER}/{GITHUB_REPO}/actions/runners/generate-jitconfig" + url = f"https://api.github.com{path}" + + payload = json.dumps( + { + "name": runner_name, + "runner_group_id": RUNNER_GROUP_ID, + "labels": RUNNER_LABELS, + "work_folder": "/tmp/_work", + } + ).encode() + + req = urllib.request.Request(url, data=payload, method="POST") + req.add_header("Accept", "application/vnd.github+json") + req.add_header("Authorization", f"Bearer {_secret(PAT_SECRET_ARN)}") + req.add_header("X-GitHub-Api-Version", "2022-11-28") + req.add_header("Content-Type", "application/json") + + try: + with urllib.request.urlopen(req, timeout=10) as resp: + data = json.loads(resp.read()) + return data["encoded_jit_config"] + except urllib.error.HTTPError as e: + # The response body is never read or logged. + if e.code in (401, 403): + # Bad or rotated PAT: refetch it on the next invocation. + _cache.pop(PAT_SECRET_ARN, None) + raise SafeError(f"POST {path} failed: HTTP {e.code} {e.reason}") from None + except Exception as e: # noqa: BLE001 — type only; str(e) may hold the header + raise SafeError(f"POST {path} failed ({type(e).__name__})") from None + + +def _labels_match(requested: list[str]) -> bool: + """True only if the job requested all of our runner labels.""" + return all(label in requested for label in RUNNER_LABELS) + + +def handler(event, _context): + body = event.get("body", "") + if event.get("isBase64Encoded"): + import base64 + + raw = base64.b64decode(body) + else: + raw = body.encode() if isinstance(body, str) else body + + headers = {k.lower(): v for k, v in (event.get("headers") or {}).items()} + + try: + signature_ok = _verify_signature(raw, headers.get("x-hub-signature-256", "")) + except SafeError as e: + print(f"[webhook] ERROR: {e}") + return {"statusCode": 500, "body": "internal error"} + if not signature_ok: + return {"statusCode": 401, "body": "invalid signature"} + + gh_event = headers.get("x-github-event", "") + if gh_event == "ping": + return {"statusCode": 200, "body": "pong"} + if gh_event != "workflow_job": + return {"statusCode": 204, "body": "ignored event"} + + parsed = json.loads(raw) + if parsed.get("action") != "queued": + return {"statusCode": 204, "body": "ignored action"} + + requested = parsed.get("workflow_job", {}).get("labels", []) + if not _labels_match(requested): + return {"statusCode": 204, "body": "labels do not match"} + + job_id = parsed.get("workflow_job", {}).get("id", "unknown") + runner_name = f"lambda-jit-{job_id}" + + try: + jitconfig = _generate_jitconfig(runner_name) + except SafeError as e: + print(f"[webhook] ERROR: job {job_id}: {e}") + return {"statusCode": 500, "body": "internal error"} + + # The JIT config exceeds the 4096-char run-hook-payload limit, so pass a + # short-lived presigned URL instead. The URL is a bearer credential for it. + jit_key = f"{JIT_KEY_PREFIX}/{job_id}-{int(time.time())}" + try: + _s3.put_object(Bucket=JIT_BUCKET, Key=jit_key, Body=jitconfig.encode()) + presigned_url = _s3.generate_presigned_url( + "get_object", + Params={"Bucket": JIT_BUCKET, "Key": jit_key}, + ExpiresIn=JIT_URL_TTL, + ) + except Exception as e: # noqa: BLE001 — type/code only, never the JIT config + print(f"[webhook] ERROR: job {job_id}: storing JIT config failed ({_err(e)})") + return {"statusCode": 500, "body": "internal error"} + + run_kwargs = { + "imageIdentifier": MICROVM_IMAGE_ARN, + "executionRoleArn": MICROVM_EXECUTION_ROLE_ARN, + "ingressNetworkConnectors": [_NO_INGRESS], + "egressNetworkConnectors": [_INTERNET_EGRESS], + "maximumDurationInSeconds": MICROVM_MAX_DURATION_SECONDS, + "runHookPayload": presigned_url, + } + if LOG_GROUP: + run_kwargs["logging"] = { + "cloudWatch": {"logGroup": LOG_GROUP, "logStream": f"job-{job_id}-{int(time.time())}"} + } + try: + resp = _microvms.run_microvm(**run_kwargs) + except Exception as e: # noqa: BLE001 — type/code only; str(e) may echo the pre-signed URL + print(f"[webhook] ERROR: job {job_id}: RunMicrovm failed ({_err(e)})") + return {"statusCode": 500, "body": "internal error"} + microvm_id = resp.get("microvmId", "unknown") + + # Never log the presigned URL; log the key only. + print(f"[webhook] launched {microvm_id} for job {job_id} (runner {runner_name}, jit s3 key {jit_key})") + return {"statusCode": 202, "body": f"launched {microvm_id}"} diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/webhook/requirements.txt b/lambda-microvms-github-actions-runner/go/terraform/src/webhook/requirements.txt new file mode 100644 index 000000000..9b3abafbf --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/webhook/requirements.txt @@ -0,0 +1,5 @@ +# Bundled because the Lambda python3.12 runtime's built-in boto3 lags behind +# and does not include the (new) lambda-microvms service client. Pinned exactly +# (reproducible package) to a version that includes it (service added by +# 1.43.108). See terraform packaging (pip install -t). +boto3==1.44.2 diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/webhook/test_handler.py b/lambda-microvms-github-actions-runner/go/terraform/src/webhook/test_handler.py new file mode 100644 index 000000000..c11d48019 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/src/webhook/test_handler.py @@ -0,0 +1,142 @@ +"""Unit tests for handler.py's MicroVM launch and secret handling (Secrets +Manager stubbed, GitHub and AWS calls mocked, no AWS or network calls). + +Run from src/webhook/: pip install -r requirements.txt pytest && python3 -m pytest -v +""" +import email.message +import hashlib +import hmac +import json +import os +import urllib.error + +import pytest +from botocore.stub import Stubber + +# handler.py reads its config from the environment at import time. +os.environ.update( + { + "AWS_DEFAULT_REGION": "us-east-1", + "AWS_ACCESS_KEY_ID": "testing", + "AWS_SECRET_ACCESS_KEY": "testing", + "GITHUB_OWNER": "example-owner", + "GITHUB_REPO": "example-repo", + "PAT_SECRET_ARN": "arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:pat", + "WEBHOOK_SECRET_ARN": "arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:webhook", + "MICROVM_IMAGE_ARN": "arn:aws:lambda:us-east-1:ACCOUNT:microvm-image:example-runner-image", + "MICROVM_EXECUTION_ROLE_ARN": "arn:aws:iam::ACCOUNT:role/example-exec", + "JIT_BUCKET": "example-jit", + } +) + +import handler + +# --- Secret handling ------------------------------------------------------- + +PAT_ARN = os.environ["PAT_SECRET_ARN"] +WEBHOOK_ARN = os.environ["WEBHOOK_SECRET_ARN"] +FAKE_PAT = "github_pat_FAKE0123456789abcdefTOKEN" +WEBHOOK_SECRET = "test-webhook-secret" + + +@pytest.fixture +def secrets(monkeypatch): + monkeypatch.setattr(handler, "_cache", {}) + clock = {"now": 1000.0} + monkeypatch.setattr(handler.time, "monotonic", lambda: clock["now"]) + with Stubber(handler._secrets) as stub: + stub.clock = clock + yield stub + stub.assert_no_pending_responses() + + +def _add_secret(stub, arn, value): + stub.add_response("get_secret_value", {"SecretString": value}, {"SecretId": arn}) + + +def _queued_event(secret=WEBHOOK_SECRET): + body = json.dumps( + {"action": "queued", "workflow_job": {"id": 7, "labels": ["self-hosted", "lambda"]}} + ) + sig = "sha256=" + hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest() + return {"body": body, "headers": {"X-GitHub-Event": "workflow_job", "X-Hub-Signature-256": sig}} + + +def _logged(capsys, caplog): + out, err = capsys.readouterr() + return out + err + caplog.text + + +def test_secret_whitespace_is_stripped(secrets): + _add_secret(secrets, PAT_ARN, f" {FAKE_PAT}\n") + assert handler._secret(PAT_ARN) == FAKE_PAT + + +def test_empty_secret_returns_500_without_leaking(secrets, capsys, caplog): + _add_secret(secrets, WEBHOOK_ARN, " \n\t") + resp = handler.handler(_queued_event(), None) + assert resp == {"statusCode": 500, "body": "internal error"} + assert WEBHOOK_ARN not in handler._cache # an empty value is never cached + logged = _logged(capsys, caplog) + assert "is empty" in logged + assert WEBHOOK_SECRET not in logged + + +def test_github_error_embedding_token_is_not_logged(secrets, monkeypatch, capsys, caplog): + _add_secret(secrets, WEBHOOK_ARN, WEBHOOK_SECRET) + _add_secret(secrets, PAT_ARN, FAKE_PAT) + + def urlopen(req, timeout): + # What http.client raised in the live run (token with a trailing newline). + raise ValueError(f"Invalid header value b'Bearer {FAKE_PAT}\\n'") + + monkeypatch.setattr(handler.urllib.request, "urlopen", urlopen) + resp = handler.handler(_queued_event(), None) + assert resp == {"statusCode": 500, "body": "internal error"} + logged = _logged(capsys, caplog) + assert "generate-jitconfig failed (ValueError)" in logged + assert FAKE_PAT not in logged + assert "Bearer" not in logged + + +def test_github_401_drops_cached_pat(secrets, monkeypatch, capsys, caplog): + _add_secret(secrets, PAT_ARN, FAKE_PAT) + _add_secret(secrets, PAT_ARN, "github_pat_ROTATED") + + def urlopen(req, timeout): + raise urllib.error.HTTPError(req.full_url, 401, "Unauthorized", email.message.Message(), None) + + monkeypatch.setattr(handler.urllib.request, "urlopen", urlopen) + with pytest.raises(handler.SafeError, match="HTTP 401 Unauthorized"): + handler._generate_jitconfig("lambda-jit-7") + assert PAT_ARN not in handler._cache + assert handler._secret(PAT_ARN) == "github_pat_ROTATED" # refetched, within TTL + assert FAKE_PAT not in _logged(capsys, caplog) + + +def test_secret_refetched_after_ttl(secrets): + _add_secret(secrets, PAT_ARN, FAKE_PAT) + _add_secret(secrets, PAT_ARN, "github_pat_ROTATED") + assert handler._secret(PAT_ARN) == FAKE_PAT + secrets.clock["now"] += handler.SECRET_CACHE_TTL - 1 + assert handler._secret(PAT_ARN) == FAKE_PAT # no second Secrets Manager call + secrets.clock["now"] += 1 + assert handler._secret(PAT_ARN) == "github_pat_ROTATED" + + +def test_handler_launches_configured_image(monkeypatch): + monkeypatch.setattr(handler, "_secret", lambda _arn: WEBHOOK_SECRET) + monkeypatch.setattr(handler, "_generate_jitconfig", lambda _name: "jit") + monkeypatch.setattr(handler._s3, "put_object", lambda **_kw: None) + monkeypatch.setattr(handler._s3, "generate_presigned_url", lambda *_a, **_kw: "https://example/presigned") + calls = [] + + def run_microvm(**kwargs): + calls.append(kwargs) + return {"microvmId": "mvm-1"} + + monkeypatch.setattr(handler._microvms, "run_microvm", run_microvm) + resp = handler.handler(_queued_event(), None) + assert resp["statusCode"] == 202 + assert calls[0]["imageIdentifier"] == os.environ["MICROVM_IMAGE_ARN"] + assert "imageVersion" not in calls[0] diff --git a/lambda-microvms-github-actions-runner/go/terraform/terraform.tfvars.example b/lambda-microvms-github-actions-runner/go/terraform/terraform.tfvars.example new file mode 100644 index 000000000..abed86017 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/terraform.tfvars.example @@ -0,0 +1,16 @@ +# Copy to terraform.tfvars (gitignored) and fill in: +# cp terraform.tfvars.example terraform.tfvars + +# Repository-level runners (default): the private repo the runners serve. +github_owner = "" +github_repo = "" + +# Organization-level runners instead: uncomment, and remove the two lines above. +# runner_scope = "org" +# github_org = "" + +# Optional (defaults shown): +# region = "us-east-1" +# name_prefix = "gha-microvm-runner" +# runner_labels = ["self-hosted", "lambda"] +# microvm_max_duration_seconds = 900 diff --git a/lambda-microvms-github-actions-runner/go/terraform/variables.tf b/lambda-microvms-github-actions-runner/go/terraform/variables.tf new file mode 100644 index 000000000..94fe19944 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/variables.tf @@ -0,0 +1,59 @@ +variable "region" { + description = "AWS Region to deploy into. Lambda MicroVMs must be available in it." + type = string + default = "us-east-1" +} + +variable "name_prefix" { + description = "Prefix for all resource names." + type = string + default = "gha-microvm-runner" +} + +# The webhook function's preconditions (main.tf) enforce the required +# GitHub variables for each runner_scope. + +variable "runner_scope" { + description = "Register runners at 'repo' or 'org' level." + type = string + default = "repo" + + validation { + condition = contains(["repo", "org"], var.runner_scope) + error_message = "runner_scope must be 'repo' or 'org'." + } +} + +variable "github_owner" { + description = "GitHub user or org that owns the repo. Required when runner_scope = \"repo\"." + type = string + default = "" +} + +variable "github_repo" { + description = "GitHub repo name. Required when runner_scope = \"repo\"." + type = string + default = "" +} + +variable "github_org" { + description = "GitHub org. Required when runner_scope = \"org\"; leave empty for repo scope." + type = string + default = "" +} + +variable "runner_labels" { + description = "Labels the runner registers with. Jobs target them with runs-on and must request all of them." + type = list(string) + default = ["self-hosted", "lambda"] +} + +variable "microvm_max_duration_seconds" { + description = <<-EOT + Maximum MicroVM lifespan in seconds, passed to RunMicrovm + (maximumDurationInSeconds, 1-28800). The platform kills the VM at this + limit, so a job that runs longer is cut off. Default 900 (15 minutes). + EOT + type = number + default = 900 +} diff --git a/lambda-microvms-github-actions-runner/go/terraform/versions.tf b/lambda-microvms-github-actions-runner/go/terraform/versions.tf new file mode 100644 index 000000000..332605d06 --- /dev/null +++ b/lambda-microvms-github-actions-runner/go/terraform/versions.tf @@ -0,0 +1,21 @@ +terraform { + required_version = ">= 1.5" + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.0" + } + archive = { + source = "hashicorp/archive" + version = ">= 2.0" + } + null = { + source = "hashicorp/null" + version = ">= 3.0" + } + } +} + +provider "aws" { + region = var.region +} From df6a6225610e731617f54010e436114687ac2db0 Mon Sep 17 00:00:00 2001 From: Frank Date: Fri, 4 Dec 2026 13:17:51 -0600 Subject: [PATCH 2/2] lambda-microvms-github-actions-runner: use overlay storage driver for buildah --- .../go/terraform/README.md | 5 +++-- .../go/terraform/example-pattern.json | 2 +- .../go/terraform/src/microvm-runner/Dockerfile | 7 +++++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/lambda-microvms-github-actions-runner/go/terraform/README.md b/lambda-microvms-github-actions-runner/go/terraform/README.md index 9c387a141..39ed63365 100644 --- a/lambda-microvms-github-actions-runner/go/terraform/README.md +++ b/lambda-microvms-github-actions-runner/go/terraform/README.md @@ -97,7 +97,7 @@ The runner image is built once by `terraform apply`, and again whenever its zip 1. `build.sh` cross-compiles the Go supervisor (`src/microvm-runner/supervisor/`) and zips it with `src/microvm-runner/Dockerfile`. 1. Terraform uploads the zip to the S3 bucket under a content-addressed key (`supervisor-runner-.zip`). -1. Terraform creates a one-resource AWS CloudFormation stack holding an `AWS::Lambda::MicrovmImage`, because the Terraform AWS provider's image resource can't configure lifecycle hooks. The image uses the AL2023 managed base image, `ARM_64`, the standard OS capabilities (`AdditionalOsCapabilities: []`), the `INTERNET_EGRESS` connector, and the `/ready` and `/run` hooks on port 8080. Lambda runs the Dockerfile on the base image, starts the supervisor, waits for `/ready`, and snapshots the MicroVM. The Dockerfile bakes in the GitHub Actions runner (checked against a pinned SHA-256) and buildah, preconfigured with the `vfs` storage driver and chroot isolation. +1. Terraform creates a one-resource AWS CloudFormation stack holding an `AWS::Lambda::MicrovmImage`, because the Terraform AWS provider's image resource can't configure lifecycle hooks. The image uses the AL2023 managed base image, `ARM_64`, the standard OS capabilities (`AdditionalOsCapabilities: []`), the `INTERNET_EGRESS` connector, and the `/ready` and `/run` hooks on port 8080. Lambda runs the Dockerfile on the base image, starts the supervisor, waits for `/ready`, and snapshots the MicroVM. The Dockerfile bakes in the GitHub Actions runner (checked against a pinned SHA-256) and buildah, preconfigured with the `overlay` storage driver and chroot isolation. 1. A changed zip builds a new image version under the same ARN. `RunMicrovm` always launches the latest active version, so the webhook needs no change. If a build fails, CloudFormation rolls back and the previous version stays active. The stack has three IAM roles. The **webhook role** can read the two secrets, write and presign objects under `jit/`, call `RunMicrovm` on the runner image, pass the execution role and the two network connectors, and write its own logs. The **execution role** (attached to each MicroVM) can call `TerminateMicrovm` on the runner image and write runtime logs. The **build role** can read the `supervisor-runner-*` zip and write the image build logs. @@ -114,7 +114,8 @@ The stack has three IAM roles. The **webhook role** can read the two secrets, wr ### Limitations * **ARM64 (AWS Graviton) only.** The supervisor, the runner package and the image are built for `ARM_64`. -* **No Docker daemon.** `dockerd` can't run in the MicroVM with the standard OS capabilities. Use buildah, which the image presets for `vfs` storage and chroot isolation (see `example-workflows/buildah-build.yml`). Running real Docker would require `AdditionalOsCapabilities = ["ALL"]`, which this pattern does not use. +* **No Docker daemon.** `dockerd` can't run in the MicroVM with the standard OS capabilities. Use buildah, which the image presets for `overlay` storage and chroot isolation (see `example-workflows/buildah-build.yml`). Running real Docker would require `AdditionalOsCapabilities = ["ALL"]`, which this pattern does not use. +* **Overlay storage depends on the MicroVM kernel.** AWS doesn't document which kernel features the guest allows. Overlay mounts were verified on the AL2023 managed base image, arm64. If a future base image blocks them, buildah fails with a mount error. Change `driver = "overlay"` to `"vfs"` in the Dockerfile's `storage.conf`, which works anywhere but copies every layer in full, so it is slower and heavy builds can fill the MicroVM's disk. * **Job duration.** A job still running after `microvm_max_duration_seconds` is killed with its MicroVM. * **Failed webhook deliveries are not retried.** If a delivery fails (for example, before the secrets are stored), redeliver it manually from the repository's webhook settings in GitHub. diff --git a/lambda-microvms-github-actions-runner/go/terraform/example-pattern.json b/lambda-microvms-github-actions-runner/go/terraform/example-pattern.json index d0f15ca16..780a2d7b5 100644 --- a/lambda-microvms-github-actions-runner/go/terraform/example-pattern.json +++ b/lambda-microvms-github-actions-runner/go/terraform/example-pattern.json @@ -9,7 +9,7 @@ "text": [ "This pattern runs every GitHub Actions job on its own single-use AWS Lambda MicroVM. When a job is queued, GitHub sends a workflow_job webhook to an Amazon API Gateway REST API. An AWS Lambda function verifies the webhook's HMAC signature with a secret stored in AWS Secrets Manager and checks that the job requests all of the configured runner labels. It then calls the GitHub API with a personal access token, also stored in Secrets Manager, to mint a just-in-time (JIT) runner configuration that can register exactly one runner for exactly one job. Finally it calls RunMicrovm to launch a MicroVM from a pre-built snapshot, attaching an outbound-only network configuration and a maximum duration.", "The JIT configuration is larger than the 4096-character run-hook payload limit, so the function writes it to Amazon S3 and passes the MicroVM a presigned GET URL that expires after 60 seconds. Lambda delivers that URL to a small Go supervisor inside the MicroVM through the /run lifecycle hook. The supervisor fetches the configuration over HTTPS, starts the GitHub Actions runner with run.sh --jitconfig, and calls TerminateMicrovm on its own MicroVM as soon as the job ends, whether it passed or failed. The personal access token never enters the MicroVM, and the MicroVM's execution role has no access to S3 or Secrets Manager. It can only terminate runner MicroVMs and write its own logs. Nothing runs between jobs, so the runners scale to zero.", - "The runner image is built once by terraform apply. A build script cross-compiles the supervisor for ARM64 and zips it with a Dockerfile. Terraform uploads the zip to S3 and creates the AWS::Lambda::MicrovmImage resource in a one-resource AWS CloudFormation stack, on the Amazon Linux 2023 managed base image with the /ready and /run hooks enabled on port 8080. Lambda runs the Dockerfile, waits for the /ready hook and snapshots the MicroVM, so every job starts from a fully initialized environment. The image bakes in the GitHub Actions runner, verified against a pinned SHA-256 checksum, and buildah configured for the vfs storage driver and chroot isolation, so jobs can build container images without a Docker daemon.", + "The runner image is built once by terraform apply. A build script cross-compiles the supervisor for ARM64 and zips it with a Dockerfile. Terraform uploads the zip to S3 and creates the AWS::Lambda::MicrovmImage resource in a one-resource AWS CloudFormation stack, on the Amazon Linux 2023 managed base image with the /ready and /run hooks enabled on port 8080. Lambda runs the Dockerfile, waits for the /ready hook and snapshots the MicroVM, so every job starts from a fully initialized environment. The image bakes in the GitHub Actions runner, verified against a pinned SHA-256 checksum, and buildah configured for the overlay storage driver and chroot isolation, so jobs can build container images without a Docker daemon.", "This pattern deploys Amazon API Gateway, an AWS Lambda function, a Lambda MicroVM image, an Amazon S3 bucket and two AWS Secrets Manager secrets, plus three least-privilege IAM roles and Amazon CloudWatch Logs log groups with a retention period. Two example workflows are included: a three-job smoke test and a buildah image build." ] }, diff --git a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile index 4b4d1496e..5c242c948 100644 --- a/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile +++ b/lambda-microvms-github-actions-runner/go/terraform/src/microvm-runner/Dockerfile @@ -32,7 +32,10 @@ RUN curl -fsSL -o runner.tar.gz \ # --- buildah --- # dockerd can't run in the MicroVM (no mount/PID namespaces, no cgroup v2), so -# CI jobs use buildah with chroot isolation and the vfs driver. +# CI jobs use buildah with chroot isolation and the overlay storage driver. +# overlay needs a kernel that allows mounts, which this MicroVM does. If a future +# base image blocks that, builds fail with a mount error: set driver = "vfs" +# below (it works anywhere but copies every layer in full and can fill the disk). # netavark: buildah refuses to build without a network backend. RUN apt-get update \ && apt-get install -y --no-install-recommends \ @@ -47,7 +50,7 @@ RUN apt-get update \ RUN mkdir -p /etc/containers/registries.conf.d \ && printf '%s\n' \ '[storage]' \ - 'driver = "vfs"' \ + 'driver = "overlay"' \ 'runroot = "/run/containers/storage"' \ 'graphroot = "/var/lib/containers/storage"' \ > /etc/containers/storage.conf \