Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
225 changes: 225 additions & 0 deletions .github/SETUP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
# GitHub Actions Docker Push Setup

This guide gives the setup that CI must have to push Docker images to ECR. It also gives the security rules for that setup.

## How pushes are gated

Only maintainers can cause CI to push an image through the pybot role. The workflow file does not enforce this, because a writer can change the file on a branch. GitHub Environments and the AWS trust policy enforce it.

```
pull_request (any author) --> docker-build build only, no AWS credentials
push to master, first attempt --> docker-build-push environment ecr-main no wait
workflow_dispatch (any ref) --> docker-build-push environment ecr-approval maintainer approves
re-run of any push run --> docker-build-push environment ecr-approval maintainer approves
|
v
role GitHubActions-ECR-Push-pybot trusts ONLY the ecr-main and ecr-approval subjects
```

- `ecr-main` can skip the wait because the org ruleset on `master` requires a pull request with code-owner review.
- Image tags: `:prod` and `:latest` when the ref is `master`, and `:staging` for all other refs. All tags are in the same ECR repository, `pybot`.
- Pull requests, Dependabot and forks included, never get AWS credentials. Branch and PR pushes do not publish `:staging`. A maintainer pushes `:staging` with a dispatch (see [Push a Staging Image](#push-a-staging-image-maintainers)).
- The gate is not complete until the old shared role is deleted. See [The Old Shared Role](#the-old-shared-role).

## Required Secret

- **`AWS_ROLE_ARN`** (repository secret): the ARN of the IAM role that the push job assumes.

```bash
gh secret set AWS_ROLE_ARN --repo OperationCode/operationcode-pybot --body "arn:aws:iam::633607774026:role/GitHubActions-ECR-Push-pybot"
```

## Required Environments

Create the two environments in Settings > Environments. Create them **before** a workflow uses them. If a workflow uses an environment that does not exist, GitHub creates it with no protection rules.

| Environment | Required reviewers | Deployment branches and tags |
|---|---|---|
| `ecr-main` | None | "Selected branches and tags", with one **branch** rule: `master`. Do not add a tag rule. Do not use "Protected branches only". |
| `ecr-approval` | `irvingpop` and `kylemh` | No restriction |

- The owner chose the `ecr-approval` reviewers. The owner can change them later in Settings > Environments > `ecr-approval`. GitHub allows at most 6 users or teams. Add only maintainers. Do not add a team that has only write access (for example `contributors` or `core-contributors`).
- One approval from a reviewer is sufficient.

Check the environments after you create them:

```bash
gh api repos/OperationCode/operationcode-pybot/environments \
--jq '.environments[] | {name, protection_rules, deployment_branch_policy}'
gh api repos/OperationCode/operationcode-pybot/environments/ecr-main/deployment-branch-policies \
--jq '.branch_policies[] | {name, type}'
# Expect exactly one policy: {"name":"master","type":"branch"}
```

The old environments `oc-pybot-production` and `oc-pybot-staging` are not used by any workflow, and no role trusts them.

## AWS Role

The pybot repository has its own role, `GitHubActions-ECR-Push-pybot`. No other repository uses it.

### Trust policy

The repository uses immutable OIDC subjects. To get the prefix, run this command:

```bash
gh api repos/OperationCode/operationcode-pybot/actions/oidc/customization/sub --jq .sub_claim_prefix
# repo:OperationCode@10479364/operationcode-pybot@146210805
```

Save this as `pybot-trust.json`:

```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::633607774026:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": [
"repo:OperationCode@10479364/operationcode-pybot@146210805:environment:ecr-main",
"repo:OperationCode@10479364/operationcode-pybot@146210805:environment:ecr-approval"
]
}
}
}
]
}
```

Rules:
- Use `StringEquals` and these two subjects only. Do not use `StringLike` or `*`.
- Do not add `:pull_request` or `:ref:refs/heads/...` subjects. A writer can get those subjects without approval.
- Do not add subjects of another repository. Each repository gets its own role.
- The role must have only this one `Allow` statement. Examine all statements with this command:
`aws iam get-role --role-name GitHubActions-ECR-Push-pybot --query Role.AssumeRolePolicyDocument`

### Permissions policy (inline)

Save this as `pybot-ecr-push.json`. The first statement has the ECR actions of the push job, on the `pybot` repository only. `ecr:GetAuthorizationToken` (used by `amazon-ecr-login`) cannot be limited to a repository, so it has its own statement on `*`.

```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
"ecr:PutImage"
],
"Resource": "arn:aws:ecr:us-east-2:633607774026:repository/pybot"
},
{
"Effect": "Allow",
"Action": "ecr:GetAuthorizationToken",
"Resource": "*"
}
]
}
```

### Create the role

The role is defined in [operationcode_infra](https://github.com/OperationCode/operationcode_infra), file `terraform/github_actions_ecr.tf`. Apply it with Terraform. Do not create the role by hand, and do not edit it by hand.

The trust policy and permissions policy above are a reference only. The Terraform file is the source of truth.

To examine the result after the apply:

```bash
aws iam get-role --role-name GitHubActions-ECR-Push-pybot \
--query 'Role.[Arn,MaxSessionDuration,AssumeRolePolicyDocument]'
aws iam list-role-policies --role-name GitHubActions-ECR-Push-pybot # only ecr-push-pybot
aws iam list-attached-role-policies --role-name GitHubActions-ECR-Push-pybot # empty
```

## The Old Shared Role

Before this change, pybot used `arn:aws:iam::633607774026:role/GitHubActions-ECR-Push`. That role is shared with `OperationCode/back-end`:
- Its trust uses `StringLike` with `repo:...:*` subjects for back-end and pybot. Any branch or pull request of either repository can assume it.
- Its policy allows push to `repository/back-end` and to `repository/pybot`. Thus a session of either repository can overwrite the images of the other.

**The old role is not gated.** It stays open to branch workflows of both repositories until it is deleted. A writer can edit a workflow on a branch, put the old role ARN in it, and get credentials without an approval. These credentials can push `pybot:prod` and `back-end:prod`. The environments do not stop this.

**Do not change the old role during the move.** Do not edit its trust, do not edit its permissions, and do not use "Revoke active sessions" on it. The other repository uses it until its own move is done.

The old role is deleted one time, after both repositories have done step 6 of their move. The back-end guide owns the deletion and the CloudTrail check of ECR writes to both repositories: see "The Old Shared Role" and the steps after it in [back-end `.github/SETUP.md`](https://github.com/OperationCode/back-end/blob/main/.github/SETUP.md). Do not do those steps from this guide.

## Safe Change to the New Role

Use this procedure to move pybot from the old shared role to its own role. Do not change the old role during this procedure (see above).

1. Create the two environments, as given in [Required Environments](#required-environments). Write down the time when you start this step (S). The back-end CloudTrail check uses the earlier S of the two repositories.
2. Create the new role, as given in [Create the role](#create-the-role). Get the pull request that adds the environments to `ci.yml` approved and green. Do not merge it yet.
3. Set the secret to the new role ARN, as given in [Required Secret](#required-secret).
- Between step 3 and step 5, every push run of the old workflow fails at "Configure AWS credentials", because the new role does not trust its subject. Nobody must push to `master` during this time.
4. Cancel every pybot CI run that is in progress or queued. These runs can hold the old ARN or credentials of the old role.
```bash
# List the runs, then cancel each one.
for s in in_progress queued; do
gh run list --repo OperationCode/operationcode-pybot --status $s --limit 100 --json databaseId --jq '.[].databaseId'
done | xargs -n 1 gh run cancel --repo OperationCode/operationcode-pybot
```
To cancel one run: `gh run cancel <id> --repo OperationCode/operationcode-pybot`. Run the list again until it is empty.
5. Immediately merge the pull request. The push to `master` that the merge causes uses `ecr-main` and the new role, and pushes `:prod` and `:latest`.
- If the first push fails, correct the new role (see the rules above). Then re-run the job. The re-run uses `ecr-approval`, so a maintainer must approve it.
- When the push run is complete, write down the image digest of `:prod`. Give it to the person who does the back-end CloudTrail check:
`aws ecr describe-images --region us-east-2 --repository-name pybot --image-ids imageTag=prod --query 'imageDetails[0].imageDigest' --output text`
6. Confirm one successful push to `master` through the new role. Use one of these:
- CloudTrail: find the `AssumeRoleWithWebIdentity` event for the new role ARN, at the time of the push run from step 5.
```bash
aws cloudtrail lookup-events --region us-east-2 \
--lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
--start-time <merge time> --output json |
jq -r '.Events[] | (.CloudTrailEvent | fromjson) as $c
| select($c.requestParameters.roleArn == "arn:aws:iam::633607774026:role/GitHubActions-ECR-Push-pybot")
| [.EventTime, $c.requestParameters.roleArn, ($c.userIdentity.userName // "-"), ($c.errorCode // "ok")] | @tsv'
```
Expect a line with `ok` and the subject `...:environment:ecr-main`.
- Run log: the push run from step 5 shows environment `ecr-main`, and the "Output image URI" step prints `Successfully pushed Production images`.

The pybot move is done after this step. Tell the back-end owner, because the old role is deleted only after both repositories finish step 6.

## Push a Staging Image (maintainers)

Pull requests do not push images. To push `:staging` from a branch:

1. Go to Actions > CI > "Run workflow". Select the branch. You can also run `gh workflow run ci.yml --repo OperationCode/operationcode-pybot --ref <branch>`.
2. The `Build and Push Docker Image` job waits for the `ecr-approval` review.
3. Before you approve, read the commit **and** `.github/workflows/ci.yml` on that branch. The approved job runs with the branch's workflow file. Its credentials can also write `:prod` and `:latest`.
4. Approve the deployment. The job pushes `pybot:staging`.

A dispatch on `master` pushes `:prod` and `:latest`, and it also needs approval.

## Troubleshooting

### Build fails with "Error assuming role"
- Make sure that the `AWS_ROLE_ARN` secret is the ARN of `GitHubActions-ECR-Push-pybot`.
- Make sure that the job ran in `ecr-main` or `ecr-approval` (the job page shows the environment).
- Compare the trust subjects with the prefix from `gh api .../actions/oidc/customization/sub`. The subject is `<prefix>:environment:<environment name>`. Never add an old subject back.

### Build fails with "AccessDenied" to ECR
- Make sure that the role has the inline policy `ecr-push-pybot`.
- Make sure that the repository is `633607774026.dkr.ecr.us-east-2.amazonaws.com/pybot`.

### Production build runs even when tests fail
- This must not occur. The push job depends on the `ci-success` job.
- Make sure that `ci-success` fails when lint or tests fail.

## Additional Resources

- [GitHub Actions secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets)
- [GitHub deployment environments](https://docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments)
- [GitHub OIDC reference](https://docs.github.com/en/actions/reference/security/oidc)
- [AWS OIDC with GitHub](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)
56 changes: 37 additions & 19 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -141,36 +141,57 @@ jobs:
- name: Display Bandit results
run: poetry run bandit -r pybot -x pybot/_vendor --skip B101 -f txt || true

# Every PR (same-repo, fork, Dependabot): build only, no AWS credentials
docker-build:
name: Build Docker Image
runs-on: ubuntu-24.04-arm
if: github.event_name == 'pull_request'
needs: [ci-success]
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v7

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
platforms: linux/arm64

- name: Build Docker image
uses: docker/build-push-action@v7
with:
context: .
file: docker/Dockerfile
target: prod
platforms: linux/arm64
push: false
provenance: false
cache-from: type=gha,scope=arm64
cache-to: type=gha,mode=max,scope=arm64

# Push to master and manual dispatch only. The environment's protection rules,
# not this file, are the gate: the AWS role must trust only these environments.
docker-build-push:
name: Build and Push Docker Image
runs-on: ubuntu-24.04-arm
# Run on push to master (build+push), manual dispatch (build+push) and on PRs (build only)
if: github.event_name == 'push' || github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
# Wait for CI checks to pass
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
needs: [ci-success]
# First attempt of a push to master: reviewed by a code owner before merge, so no wait.
# Dispatch and re-runs (any ref, any writer): a maintainer must approve.
environment: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master' && github.run_attempt == '1') && 'ecr-main' || 'ecr-approval' }}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium security, confidence medium, pass security

Approval-free ecr-main depends on external branch-policy config

The no-approval path depends on the ecr-main environment being restricted to the master branch and on the AWS trust policy. The workflow file cannot enforce this, because a writer can edit it on a branch. If the environment is missing or lacks the master-only branch rule, GitHub auto-creates it with no protection. A branch workflow could then claim ecr-main and obtain AWS credentials without approval. The SETUP.md documents the requirement, but the PR does not verify it.

Model output from untrusted input. Check it before you act on it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium bug, confidence medium, pass review

Environment expression compares run_attempt to string; may fall to ecr-approval

github.run_attempt is a number in expression contexts. GitHub's loose equality coerces '1' to a number so it likely works. However, the `ecr-main` environment is restricted to the master branch, and this expression is the only selector. If the comparison ever fails, every master push would silently require approval and hang. This is a low-likelihood fragility.

Model output from untrusted input. Check it before you act on it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium security, confidence medium, pass security

ecr-main push path has no approval and depends on external settings

Any push to master gets AWS credentials with no reviewer wait. Safety rests on the branch-only rule for master in the ecr-main environment and on the org ruleset requiring code-owner review. None of this is verifiable in the PR. If the environment is misconfigured, or a writer or admin bypasses the ruleset, a push to master can push :prod. The old shared role also remains assumable from any branch workflow until it is deleted, which the docs acknowledge, so the gate is not effective until then.

Model output from untrusted input. Check it before you act on it.

permissions:
id-token: write # Required for OIDC authentication
contents: read # Required to checkout code
steps:
- name: Checkout code
uses: actions/checkout@v7

- name: Determine push eligibility
id: can-push
run: |
if [ "${{ github.event_name }}" == "push" ] || [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
echo "push=true" >> "$GITHUB_OUTPUT"
elif [ "${{ github.event.pull_request.head.repo.full_name }}" == "${{ github.repository }}" ]; then
echo "push=true" >> "$GITHUB_OUTPUT"
else
echo "push=false" >> "$GITHUB_OUTPUT"
fi

- name: Determine Docker tags
id: docker-tag
run: |
ECR=633607774026.dkr.ecr.us-east-2.amazonaws.com/pybot
if [ "${{ github.ref }}" == "refs/heads/master" ]; then
if [ "$GITHUB_REF" == "refs/heads/master" ]; then
echo "images=${ECR}:prod,${ECR}:latest" >> "$GITHUB_OUTPUT"
echo "environment=Production" >> "$GITHUB_OUTPUT"
else
Expand All @@ -184,7 +205,6 @@ jobs:
platforms: linux/arm64

- name: Configure AWS credentials
if: steps.can-push.outputs.push == 'true'
uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
Expand All @@ -193,7 +213,6 @@ jobs:

- name: Login to Amazon ECR
id: login-ecr
if: steps.can-push.outputs.push == 'true'
uses: aws-actions/amazon-ecr-login@v2

- name: Build and push Docker image
Expand All @@ -203,7 +222,7 @@ jobs:
file: docker/Dockerfile
target: prod
platforms: linux/arm64
push: ${{ steps.can-push.outputs.push == 'true' }}
push: true
tags: ${{ steps.docker-tag.outputs.images }}
provenance: false
no-cache: ${{ inputs.no_cache == true }}
Expand All @@ -212,7 +231,6 @@ jobs:
cache-to: type=gha,mode=max,scope=arm64

- name: Output image URI
if: steps.can-push.outputs.push == 'true'
run: |
echo "Successfully pushed ${{ steps.docker-tag.outputs.environment }} images:"
echo "${{ steps.docker-tag.outputs.images }}"
Expand Down