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
53 changes: 53 additions & 0 deletions .github/scripts/ensure_ecr_promotion_access.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Restore the production pull grant after CDK bootstrap updates its ECR policy."""

import argparse
import json
import re
import subprocess

SID = "AllowProductionImagePromotion"


def ensure_access(repository, role_arn):
if not re.fullmatch(r"arn:aws:iam::\d{12}:role/[\w+=,.@/-]+", role_arn):
raise ValueError("Expected a specific production IAM role ARN")

# Bootstrap owns the other statements. Never replace them with a blank policy
# if reading the current policy fails (including a missing repository policy).
result = subprocess.run(
["aws", "ecr", "get-repository-policy", "--repository-name", repository,
"--query", "policyText", "--output", "text"],
check=True, capture_output=True, text=True,
)
current = json.loads(result.stdout)
statements = current["Statement"]
if not isinstance(statements, list):
raise ValueError("Expected a list of repository policy statements")

desired = dict(current)
desired["Statement"] = [s for s in statements if s.get("Sid") != SID] + [{
"Sid": SID,
"Effect": "Allow",
"Principal": {"AWS": role_arn},
"Action": ["ecr:BatchCheckLayerAvailability", "ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer"],
}]
if desired == current:
print("Production image promotion access is already configured.")
return

# Only our named statement is replaced, so role changes do not accumulate grants.
subprocess.run(
["aws", "ecr", "set-repository-policy", "--repository-name", repository,
"--policy-text", json.dumps(desired)],
check=True, stdout=subprocess.DEVNULL,
)
print("Restored production image promotion access.")


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("repository")
parser.add_argument("role_arn")
args = parser.parse_args()
ensure_access(args.repository, args.role_arn)
84 changes: 84 additions & 0 deletions .github/scripts/test_ecr_promotion_access.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import copy
import json
import subprocess
import unittest
from unittest.mock import patch

from ensure_ecr_promotion_access import SID, ensure_access

ROLE = "arn:aws:iam::359590772493:role/github-oidc-provider-Role-F6vlRCdf8Hkx"
REPOSITORY = "cdk-hnb659fds-container-assets-751533618173-us-east-1"
BOOTSTRAP_POLICY = {
"Version": "2012-10-17",
"Statement": [{
"Sid": service + "ECRImageRetrievalPolicy",
"Effect": "Allow",
"Principal": {"Service": service.lower() + ".amazonaws.com"},
"Action": ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"],
"Condition": {"StringLike": {"aws:sourceArn": "arn:aws:lambda:us-east-1:751533618173:*"}},
} for service in ["Lambda", "EmrServerless"]],
}


class PromotionPolicyTest(unittest.TestCase):
def apply(self, policy):
with patch("ensure_ecr_promotion_access.subprocess.run") as run:
run.return_value.stdout = json.dumps(policy)
ensure_access(REPOSITORY, ROLE)
if run.call_count == 1:
return policy, False
args = run.call_args.args[0]
self.assertEqual(args[:5], ["aws", "ecr", "set-repository-policy", "--repository-name", REPOSITORY])
return json.loads(args[args.index("--policy-text") + 1]), True

def test_preserves_bootstrap_and_unrelated_statements(self):
original = copy.deepcopy(BOOTSTRAP_POLICY)
original["Statement"].append({"Effect": "Deny", "Principal": "*", "Action": "ecr:DeleteRepository"})
updated, changed = self.apply(original)
self.assertTrue(changed)
self.assertEqual(updated["Version"], original["Version"])
self.assertEqual(updated["Statement"][:-1], original["Statement"])
grant = updated["Statement"][-1]
self.assertEqual(grant["Principal"], {"AWS": ROLE})
self.assertEqual(set(grant["Action"]), {"ecr:BatchCheckLayerAvailability", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"})

def test_rerun_does_not_write(self):
updated, _ = self.apply(BOOTSTRAP_POLICY)
self.assertFalse(self.apply(updated)[1])

def test_replaces_stale_role_grant(self):
original = copy.deepcopy(BOOTSTRAP_POLICY)
original["Statement"].append({"Sid": SID, "Principal": {"AWS": "old-role"}, "Action": "ecr:*"})
updated, _ = self.apply(original)
self.assertEqual(len(updated["Statement"]), len(original["Statement"]))
self.assertNotIn("old-role", json.dumps(updated))

def test_read_failure_never_writes(self):
with patch("ensure_ecr_promotion_access.subprocess.run", side_effect=subprocess.CalledProcessError(1, "aws")) as run:
with self.assertRaises(subprocess.CalledProcessError):
ensure_access(REPOSITORY, ROLE)
self.assertEqual(run.call_count, 1)

def test_malformed_policy_never_writes(self):
with patch("ensure_ecr_promotion_access.subprocess.run") as run:
run.return_value.stdout = "not-json"
with self.assertRaises(json.JSONDecodeError):
ensure_access(REPOSITORY, ROLE)
self.assertEqual(run.call_count, 1)

def test_rejects_account_or_wildcard_principal(self):
for role in ["arn:aws:iam::359590772493:root", "*", ROLE + "*"]:
with self.subTest(role=role), patch("ensure_ecr_promotion_access.subprocess.run") as run:
with self.assertRaises(ValueError):
ensure_access(REPOSITORY, role)
run.assert_not_called()

def test_write_failure_propagates(self):
with patch("ensure_ecr_promotion_access.subprocess.run") as run:
run.side_effect = [subprocess.CompletedProcess([], 0, json.dumps(BOOTSTRAP_POLICY)), subprocess.CalledProcessError(1, "aws")]
with self.assertRaises(subprocess.CalledProcessError):
ensure_access(REPOSITORY, ROLE)


if __name__ == "__main__":
unittest.main()
3 changes: 3 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ jobs:
steps:
- name: Checkout Code
uses: actions/checkout@v7

- name: Test ECR promotion policy reconciliation
run: python3 -m unittest discover -s .github/scripts -p 'test_*.py' -v

# Use AWS Java to build
- name: Set up JDK 25
Expand Down
11 changes: 11 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ jobs:
working-directory: ./cdk
run: cdk bootstrap --ci=true aws://${AWS_ACCOUNT_ID}/${{ vars.AWS_REGION || 'us-east-1' }}

# Bootstrap upgrades can replace the asset repository policy. Restore the
# narrowly scoped cross-account pull grant before production promotion.
- name: Ensure Production Can Pull Tested Images
env:
PROD_PROMOTION_ROLE_ARN: ${{ vars.PROD_PROMOTION_ROLE_ARN || 'arn:aws:iam::359590772493:role/github-oidc-provider-Role-F6vlRCdf8Hkx' }}
ECR_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
run: >
python3 .github/scripts/ensure_ecr_promotion_access.py
"cdk-hnb659fds-container-assets-${AWS_ACCOUNT_ID}-${ECR_REGION}"
"$PROD_PROMOTION_ROLE_ARN"

- name: Deploy CDK Stack
working-directory: ./cdk
env:
Expand Down
Loading