From 9897863be3aeec434773bd86e3746f40f845db05 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 13 Oct 2026 22:32:57 -0400 Subject: [PATCH 1/2] feat(github): configurable build-deploy roles and separate MSBuild output paths Part of the v11 migration (released as v11.1). Fix #45: build-deploy exported its publish folder as an `outputPath` environment variable (job env and $GITHUB_ENV). MSBuild reads environment variables as properties, so every project in a multi-project solution built into that folder. The variable is now TEMPLATE_OUTPUT_PATH, matching pr-build (#44); the publish location is unchanged. A self-test guard fails if any workflow exports an MSBuild output-path property again. Implement #46: build-deploy no longer hard-codes the management-account role and region. Callers pass roleArn (development, non-tag runs) and productionRoleArn (production, tag runs), plus awsRegion (default us-east-1). A composite action validates them and selects the role before the build and before any credentials are requested; tag runs require productionRoleArn and never fall back to roleArn. configure-aws-credentials is pinned to a commit and masks the account ID. No IAM, trust, or permission changes. Callers moving build-deploy from v10 with runCdk: true pass roleArn and, for tag runs, productionRoleArn; to keep the v10 behavior, pass arn:aws:iam::403542860824:role/github-deploy-role for both and awsRegion: us-east-1. Callers pinned to v10.x are unaffected. Co-Authored-By: Claude Opus 5.5 --- .../resolve-aws-deploy-role/action.yml | 68 ++++++++++ .github/scripts/check-msbuild-env.py | 52 ++++++++ .github/workflows/build-deploy.yaml | 49 +++++-- .github/workflows/self-test-build-deploy.yml | 123 ++++++++++++++++++ README.md | 76 ++++++++++- 5 files changed, 355 insertions(+), 13 deletions(-) create mode 100644 .github/actions/resolve-aws-deploy-role/action.yml create mode 100644 .github/scripts/check-msbuild-env.py create mode 100644 .github/workflows/self-test-build-deploy.yml diff --git a/.github/actions/resolve-aws-deploy-role/action.yml b/.github/actions/resolve-aws-deploy-role/action.yml new file mode 100644 index 0000000..e3e89a9 --- /dev/null +++ b/.github/actions/resolve-aws-deploy-role/action.yml @@ -0,0 +1,68 @@ +name: Resolve AWS Deployment Role +description: > + Validates the deployment role and region inputs and selects the role for this run, before any + AWS credentials are requested. Tag runs deploy production and require productionRoleArn; all other + runs deploy development and use roleArn. There is no fallback between the two. +inputs: + roleArn: + description: Development deployment role ARN (non-tag runs). + required: false + default: "" + productionRoleArn: + description: Production deployment role ARN (tag runs). + required: false + default: "" + awsRegion: + description: AWS region. + required: true + ref: + description: The run's git ref (github.ref); refs/tags/* selects production. + required: true +outputs: + role-arn: + description: The role ARN to assume. + value: ${{ steps.resolve.outputs.role-arn }} + environment: + description: "`production` for tag runs, otherwise `development`." + value: ${{ steps.resolve.outputs.environment }} +runs: + using: composite + steps: + - id: resolve + shell: bash + env: + ROLE_ARN: ${{ inputs.roleArn }} + PRODUCTION_ROLE_ARN: ${{ inputs.productionRoleArn }} + AWS_REGION_INPUT: ${{ inputs.awsRegion }} + RUN_REF: ${{ inputs.ref }} + run: | + set -euo pipefail + role_pattern='^arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]{1,64}$' + + [[ "$AWS_REGION_INPUT" =~ ^[a-z]{2}(-[a-z]+)+-[0-9]$ ]] \ + || { echo "::error::awsRegion '$AWS_REGION_INPUT' is not an AWS region (for example us-east-1)."; exit 1; } + + if [[ "$RUN_REF" == refs/tags/* ]]; then + environment=production + input=productionRoleArn + selected="$PRODUCTION_ROLE_ARN" + if [[ -z "$selected" ]]; then + echo "::error::This tag run deploys production, but productionRoleArn is not set. build-deploy never falls back to roleArn for production. Set productionRoleArn (to keep the previous single-role behavior, pass the same ARN as roleArn)." + exit 1 + fi + else + environment=development + input=roleArn + selected="$ROLE_ARN" + if [[ -z "$selected" ]]; then + echo "::error::runCdk is true, but roleArn is not set. Set roleArn to the development deployment role, or set runCdk: false." + exit 1 + fi + fi + + [[ "$selected" =~ $role_pattern ]] \ + || { echo "::error::$input is not an IAM role ARN (arn:aws:iam::<12-digit account>:role/)."; exit 1; } + + echo "Deploying $environment with the role from $input." + echo "role-arn=$selected" >> "$GITHUB_OUTPUT" + echo "environment=$environment" >> "$GITHUB_OUTPUT" diff --git a/.github/scripts/check-msbuild-env.py b/.github/scripts/check-msbuild-env.py new file mode 100644 index 0000000..5e69d82 --- /dev/null +++ b/.github/scripts/check-msbuild-env.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Fails when a workflow or composite action exports an MSBuild output-path property as an env var. + +MSBuild reads environment variables as properties (case-insensitively), so an environment variable +such as `outputPath` silently becomes `OutputPath` for every project built in that job and redirects +all build output into one folder (#45). Checks every `env:` mapping and every `NAME=... >> $GITHUB_ENV` +write under .github/workflows and .github/actions. +""" +import pathlib +import re +import sys + +import yaml + +RESERVED = { + "outputpath", "outdir", "baseoutputpath", "intermediateoutputpath", + "baseintermediateoutputpath", "publishdir", "packageoutputpath", +} +GITHUB_ENV_WRITE = re.compile(r'''^\s*echo\s+["']?([A-Za-z_][A-Za-z0-9_]*)=.*>>\s*"?\$\{?GITHUB_ENV''', re.MULTILINE) + + +def walk(node, path, problems, source): + if isinstance(node, dict): + for key, value in node.items(): + if key == "env" and isinstance(value, dict): + for name in value: + if str(name).lower() in RESERVED: + problems.append(f"{source}: {'/'.join(path)}/env/{name}") + if key == "run" and isinstance(value, str): + for name in GITHUB_ENV_WRITE.findall(value): + if name.lower() in RESERVED: + problems.append(f"{source}: {'/'.join(path)} writes {name} to $GITHUB_ENV") + walk(value, path + [str(key)], problems, source) + elif isinstance(node, list): + for index, item in enumerate(node): + walk(item, path + [str(index)], problems, source) + + +def main(root: str) -> int: + base = pathlib.Path(root) + files = sorted(base.glob(".github/workflows/*.y*ml")) + sorted(base.glob(".github/actions/**/action.y*ml")) + problems: list[str] = [] + for file in files: + walk(yaml.safe_load(file.read_text()), [], problems, str(file.relative_to(base))) + for problem in problems: + print(f"::error::MSBuild reads environment variables as properties; rename this variable: {problem}") + print(f"Checked {len(files)} files; {len(problems)} MSBuild property collision(s).") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else ".")) diff --git a/.github/workflows/build-deploy.yaml b/.github/workflows/build-deploy.yaml index 8731e02..d94db3d 100644 --- a/.github/workflows/build-deploy.yaml +++ b/.github/workflows/build-deploy.yaml @@ -81,6 +81,21 @@ on: description: "Name of the AWS CDK stack" required: false type: string + roleArn: + description: "IAM role ARN assumed through GitHub OIDC for development (non-tag) CDK deployments. Required when runCdk is true." + required: false + default: "" + type: string + productionRoleArn: + description: "IAM role ARN assumed through GitHub OIDC for production (tag) CDK deployments. Required for tag runs when runCdk is true; there is no fallback to roleArn." + required: false + default: "" + type: string + awsRegion: + description: "AWS region for CDK deployments" + required: false + default: "us-east-1" + type: string functions: description: "JSON array of Lambda functions to build" required: false @@ -100,15 +115,28 @@ jobs: if: github.event_name != 'pull_request' || github.event.pull_request.draft == false runs-on: ${{ inputs.lambdaRuntimeVersion == 'net11.0' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} env: - outputPath: ${{ github.workspace }}/${{ inputs.outputPath }} + # Not named outputPath: MSBuild reads environment variables as properties, and an `outputPath` + # variable would redirect every project's OutputPath into this one folder (#45). + TEMPLATE_OUTPUT_PATH: ${{ github.workspace }}/${{ inputs.outputPath }} steps: + # Validate the deployment role before building anything, and before requesting credentials. + - name: Resolve AWS deployment role + id: aws-role + if: inputs.runCdk == true + uses: $/.github/actions/resolve-aws-deploy-role + with: + roleArn: ${{ inputs.roleArn }} + productionRoleArn: ${{ inputs.productionRoleArn }} + awsRegion: ${{ inputs.awsRegion }} + ref: ${{ github.ref }} + - name: Set Default Output Path If Not Provided run: | if [ -z "${{ inputs.outputPath }}" ]; then - echo "outputPath=${{ github.workspace }}/publish" >> $GITHUB_ENV + echo "TEMPLATE_OUTPUT_PATH=${{ github.workspace }}/publish" >> $GITHUB_ENV else - echo "outputPath=${{ github.workspace}}/${{ inputs.outputPath }}" >> $GITHUB_ENV + echo "TEMPLATE_OUTPUT_PATH=${{ github.workspace}}/${{ inputs.outputPath }}" >> $GITHUB_ENV fi - name: Compute Build Flags @@ -171,7 +199,7 @@ jobs: if [[ "${{ github.ref }}" == refs/tags/* ]]; then WASM_ENV="Production" fi - dotnet publish ${{ inputs.webPath }} --configuration ${{ inputs.buildConfiguration }} --no-restore --output ${{ env.outputPath }} -p:WasmApplicationEnvironmentName=$WASM_ENV + dotnet publish ${{ inputs.webPath }} --configuration ${{ inputs.buildConfiguration }} --no-restore --output ${{ env.TEMPLATE_OUTPUT_PATH }} -p:WasmApplicationEnvironmentName=$WASM_ENV - name: Detect Lambda custom build images id: lambda-custom-container @@ -197,7 +225,7 @@ jobs: functions: ${{ inputs.functions }} configuration: ${{ inputs.buildConfiguration }} lambdaRuntimeVersion: ${{ inputs.lambdaRuntimeVersion }} - outputPath: ${{ env.outputPath }} + outputPath: ${{ env.TEMPLATE_OUTPUT_PATH }} # Functions whose own aws-lambda-tools-defaults.json declares `container-image-for-build` were # already built and packaged by the step above, from an isolated checkout copy - see that @@ -216,7 +244,7 @@ jobs: echo "Skipping $NAME - already packaged by the Native AOT isolated-build step" continue fi - ZIP_PATH="${{ env.outputPath }}/${NAME}.zip" + ZIP_PATH="${{ env.TEMPLATE_OUTPUT_PATH }}/${NAME}.zip" dotnet tool run dotnet-lambda package -pl "$FUNC_PATH" --configuration ${{ inputs.buildConfiguration }} --no-restore --framework ${{ inputs.lambdaRuntimeVersion }} --output-package "$ZIP_PATH" done @@ -369,7 +397,7 @@ jobs: exit 1 fi - SITE_OUT="${{ env.outputPath }}/$OUTPUT_SUBDIR" + SITE_OUT="${{ env.TEMPLATE_OUTPUT_PATH }}/$OUTPUT_SUBDIR" rm -rf "$SITE_OUT" mkdir -p "$SITE_OUT" cp -a "$BUILD_OUT/." "$SITE_OUT/" @@ -421,11 +449,12 @@ jobs: - name: Configure AWS Credentials via OIDC if: inputs.runCdk == true - uses: aws-actions/configure-aws-credentials@v6 + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 with: audience: sts.amazonaws.com - aws-region: us-east-1 - role-to-assume: arn:aws:iam::403542860824:role/github-deploy-role + aws-region: ${{ inputs.awsRegion }} + role-to-assume: ${{ steps.aws-role.outputs.role-arn }} + mask-aws-account-id: true - name: Run AWS CDK Deploy if: inputs.runCdk == true diff --git a/.github/workflows/self-test-build-deploy.yml b/.github/workflows/self-test-build-deploy.yml new file mode 100644 index 0000000..e219b0e --- /dev/null +++ b/.github/workflows/self-test-build-deploy.yml @@ -0,0 +1,123 @@ +name: Self-test Build Deploy +# Validates this revision of build-deploy's deployment-role resolution and the MSBuild environment +# guard without AWS credentials. build-deploy itself is not run here: it deploys and pushes tags. +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - .github/workflows/** + - .github/actions/** + - .github/scripts/check-msbuild-env.py + workflow_dispatch: + +permissions: + contents: read + +jobs: + msbuild-env: + name: msbuild env guard + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - name: Install PyYAML + run: python3 -m pip install --quiet pyyaml==6.0.2 + - name: No workflow exports an MSBuild output-path property + run: python3 .github/scripts/check-msbuild-env.py . + + aws-role: + name: aws role (${{ matrix.case.name }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + case: + - name: development uses roleArn + ref: refs/heads/main + roleArn: arn:aws:iam::111111111111:role/dev-deploy + productionRoleArn: arn:aws:iam::222222222222:role/prod-deploy + awsRegion: us-east-1 + expect: success + expectRole: arn:aws:iam::111111111111:role/dev-deploy + expectEnvironment: development + - name: development without productionRoleArn + ref: refs/heads/main + roleArn: arn:aws:iam::111111111111:role/dev-deploy + productionRoleArn: "" + awsRegion: eu-west-2 + expect: success + expectRole: arn:aws:iam::111111111111:role/dev-deploy + expectEnvironment: development + - name: production uses productionRoleArn + ref: refs/tags/v1.2.3 + roleArn: arn:aws:iam::111111111111:role/dev-deploy + productionRoleArn: arn:aws:iam::222222222222:role/prod-deploy + awsRegion: us-east-1 + expect: success + expectRole: arn:aws:iam::222222222222:role/prod-deploy + expectEnvironment: production + - name: production never falls back to roleArn + ref: refs/tags/v1.2.3 + roleArn: arn:aws:iam::111111111111:role/dev-deploy + productionRoleArn: "" + awsRegion: us-east-1 + expect: failure + - name: missing roleArn + ref: refs/heads/main + roleArn: "" + productionRoleArn: arn:aws:iam::222222222222:role/prod-deploy + awsRegion: us-east-1 + expect: failure + - name: malformed roleArn + ref: refs/heads/main + roleArn: "arn:aws:iam::1111:role/dev; curl evil" + productionRoleArn: "" + awsRegion: us-east-1 + expect: failure + - name: malformed productionRoleArn + ref: refs/tags/v1.2.3 + roleArn: arn:aws:iam::111111111111:role/dev-deploy + productionRoleArn: arn:aws:iam::222222222222:user/prod-deploy + awsRegion: us-east-1 + expect: failure + - name: malformed region + ref: refs/heads/main + roleArn: arn:aws:iam::111111111111:role/dev-deploy + productionRoleArn: "" + awsRegion: "us-east-1 && id" + expect: failure + + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Resolve + id: resolve + continue-on-error: true + uses: ./.github/actions/resolve-aws-deploy-role + with: + roleArn: ${{ matrix.case.roleArn }} + productionRoleArn: ${{ matrix.case.productionRoleArn }} + awsRegion: ${{ matrix.case.awsRegion }} + ref: ${{ matrix.case.ref }} + + - name: Assert + env: + OUTCOME: ${{ steps.resolve.outcome }} + EXPECT: ${{ matrix.case.expect }} + ROLE: ${{ steps.resolve.outputs.role-arn }} + ENVIRONMENT: ${{ steps.resolve.outputs.environment }} + EXPECT_ROLE: ${{ matrix.case.expectRole }} + EXPECT_ENVIRONMENT: ${{ matrix.case.expectEnvironment }} + run: | + set -euo pipefail + echo "outcome=$OUTCOME role=${ROLE:-} environment=${ENVIRONMENT:-}" + [[ "$OUTCOME" == "$EXPECT" ]] || { echo "::error::Expected $EXPECT, got $OUTCOME."; exit 1; } + if [[ "$EXPECT" == success ]]; then + [[ "$ROLE" == "$EXPECT_ROLE" ]] || { echo "::error::Expected role $EXPECT_ROLE, got $ROLE."; exit 1; } + [[ "$ENVIRONMENT" == "$EXPECT_ENVIRONMENT" ]] || { echo "::error::Expected $EXPECT_ENVIRONMENT, got $ENVIRONMENT."; exit 1; } + else + [[ -z "$ROLE" ]] || { echo "::error::A failed resolution must not output a role."; exit 1; } + fi diff --git a/README.md b/README.md index c05566b..5b28815 100644 --- a/README.md +++ b/README.md @@ -18,13 +18,15 @@ on: jobs: build-deploy: - uses: your-org/devops-templates/.github/workflows/build-deploy.yaml@main + uses: LayeredCraft/devops-templates/.github/workflows/build-deploy.yaml@ with: - nodeVersion: '18.x' - dotnetVersion: '9.0.x' + nodeVersion: '22.x' + dotnetVersion: '10.0.x' outputPath: 'publish' hasTests: true runCdk: true + roleArn: arn:aws:iam::123456789012:role/my-app-dev-deploy + productionRoleArn: arn:aws:iam::123456789012:role/my-app-prod-deploy ``` ## PR Build (`pr-build.yaml`, v11) @@ -80,6 +82,9 @@ workflow definition; never put secrets there. values to keep previous behavior. - **Node.js validation.** Use `nodeProjects` to run lint/type-check/test/build scripts; `spaSites` remains for build-output packaging. +- **`build-deploy.yaml`.** From v11.1, CDK deployments take `roleArn` / `productionRoleArn` / + `awsRegion` instead of the hard-coded role, and projects keep their own build output folders. See + [Build and Deploy](#build-and-deploy-build-deployyaml). ## CDK Preview (`cdk-preview.yaml`) @@ -118,6 +123,71 @@ Reference it by **commit SHA**: the role should trust exactly this workflow revi `job_workflow_ref` claim (plus `aud`, `sub`, and `repository_id`) and allow only `cloudformation:GetTemplate` on the listed stacks. IAM is the authoritative stack allowlist. +## Build and Deploy (`build-deploy.yaml`) + +Builds, tests, and packages the application, then (with `runCdk: true`) deploys the CDK stack: +`-dev` on non-tag runs and `-prod` on tag runs. + +### AWS deployment roles + +The workflow assumes a role through GitHub OIDC. The caller chooses the role; the template does not +hard-code an account. + +| Input | Required | Used for | +|---|---|---| +| `roleArn` | when `runCdk: true` and the run is not a tag | development deployments (`-dev`) and the post-deploy integration tests | +| `productionRoleArn` | when `runCdk: true` and the run is a tag | production deployments (`-prod`) | +| `awsRegion` | no (default `us-east-1`) | the deployment region | + +- **Role selection.** A run whose `github.ref` is `refs/tags/*` deploys production and assumes + `productionRoleArn`. Every other run deploys development and assumes `roleArn`. +- **No fallback.** A tag run without `productionRoleArn` fails; it never uses `roleArn` for + production. +- **Validation happens first.** The ARNs and region are checked before anything is built and before + any credentials are requested. Missing or malformed values fail with an error that names the input + to fix. +- **Trust stays in IAM.** The template does not change any IAM role, trust policy, or permission. + Recommended trust for deployment roles: exact `aud` (`sts.amazonaws.com`), the immutable + `repository_id`, and a `sub` limited to `ref:refs/heads/main` (development) or tag refs / a + protected `environment` (production). Never trust `pull_request`. Do not pin `job_workflow_ref`, + so template updates never require IAM changes. +- **Integration tests use the development role.** `integrationTestSolution` runs after a development + deployment with the `roleArn` credentials (never on tag runs). Running them with a narrower role is + tracked in #47. + +### Output folder + +Publish and package steps (Blazor, Lambda ZIPs, SPAs) write to `outputPath` (default `publish`). The +folder is exposed to steps as `TEMPLATE_OUTPUT_PATH`, never `outputPath`, because MSBuild reads +environment variables as properties and an `outputPath` variable would redirect every project's build +output into one folder (#45). Projects build to their normal `bin//`. +`.github/scripts/check-msbuild-env.py` (run by the self-test) fails if any workflow reintroduces such a +variable. + +### Migrating from v10 (part of the v11 migration) + +Configurable deployment roles are part of the v11 migration and ship in **v11.1**. v11.0 left +`build-deploy.yaml` unchanged from v10, so when moving `build-deploy` from v10 to v11, use v11.1 or +later. Callers pinned to v10.x tags are unaffected until they change their reference. + +v10 always assumed `arn:aws:iam::403542860824:role/github-deploy-role` in `us-east-1` for both +environments. From v11.1, callers that use `runCdk: true` pass their roles. To keep exactly the v10 +behavior, pass the same role for both: + +```yaml + uses: LayeredCraft/devops-templates/.github/workflows/build-deploy.yaml@v11.1 + with: + runCdk: true + roleArn: arn:aws:iam::403542860824:role/github-deploy-role + productionRoleArn: arn:aws:iam::403542860824:role/github-deploy-role + awsRegion: us-east-1 +``` + +Prefer separate, narrowly trusted development and production roles when you can. Callers with +`runCdk: false` need no change. If a required role is missing, the run stops at its first step with +an error naming the input. A tag run without `productionRoleArn` is refused; it never deploys +production with `roleArn`. + ## Draft Pull Requests Draft pull requests run only lightweight feedback workflows. `pr-title-check.yml` can still run on draft PRs, but workflows that build, deploy, publish packages, tag commits, or update release metadata skip draft PRs. From 37b64308812633b992c4a24125a72ebcafbccb20 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 13 Oct 2026 22:47:39 -0400 Subject: [PATCH 2/2] fix(github): accept IAM role paths when validating role ARNs The role-ARN check limited everything after `role/` to 64 characters, which rejected valid roles with a path (IAM allows a path of up to 512 characters plus a 64-character name) and path punctuation. Validate the partition, account, path, and name separately in resolve-aws-deploy-role and cdk-preview, and add self-test cases for path roles and the limits. Addresses Codex review feedback on #48. Co-Authored-By: Claude Opus 5.5 --- .../resolve-aws-deploy-role/action.yml | 19 +++++++++-- .github/workflows/cdk-preview.yaml | 16 ++++++++- .github/workflows/self-test-build-deploy.yml | 34 +++++++++++++++++++ README.md | 4 ++- 4 files changed, 68 insertions(+), 5 deletions(-) diff --git a/.github/actions/resolve-aws-deploy-role/action.yml b/.github/actions/resolve-aws-deploy-role/action.yml index e3e89a9..e7f2a40 100644 --- a/.github/actions/resolve-aws-deploy-role/action.yml +++ b/.github/actions/resolve-aws-deploy-role/action.yml @@ -37,7 +37,20 @@ runs: RUN_REF: ${{ inputs.ref }} run: | set -euo pipefail - role_pattern='^arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]{1,64}$' + # IAM role ARN: arn::iam:::role/. The path + # (with its leading and trailing slash) is at most 512 printable non-space ASCII characters; + # the name is 1-64 characters of [A-Za-z0-9+=,.@_-]. + is_role_arn() { + local LC_ALL=C rest name path + [[ "$1" =~ ^arn:aws(-cn|-us-gov)?:iam::[0-9]{12}:role/(.+)$ ]] || return 1 + rest="${BASH_REMATCH[2]}" + name="${rest##*/}" + path="/" + [[ "$rest" == */* ]] && path="/${rest%/*}/" + [[ "$name" =~ ^[A-Za-z0-9+=,.@_-]{1,64}$ ]] || return 1 + (( ${#path} <= 512 )) || return 1 + [[ "$path" =~ ^[[:graph:]]+$ ]] + } [[ "$AWS_REGION_INPUT" =~ ^[a-z]{2}(-[a-z]+)+-[0-9]$ ]] \ || { echo "::error::awsRegion '$AWS_REGION_INPUT' is not an AWS region (for example us-east-1)."; exit 1; } @@ -60,8 +73,8 @@ runs: fi fi - [[ "$selected" =~ $role_pattern ]] \ - || { echo "::error::$input is not an IAM role ARN (arn:aws:iam::<12-digit account>:role/)."; exit 1; } + is_role_arn "$selected" \ + || { echo "::error::$input is not an IAM role ARN (arn:aws:iam::<12-digit account>:role/[/])."; exit 1; } echo "Deploying $environment with the role from $input." echo "role-arn=$selected" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/cdk-preview.yaml b/.github/workflows/cdk-preview.yaml index c26941f..6a81067 100644 --- a/.github/workflows/cdk-preview.yaml +++ b/.github/workflows/cdk-preview.yaml @@ -83,7 +83,21 @@ jobs: STACKS: ${{ inputs.stacks }} run: | set -euo pipefail - [[ "$ROLE_ARN" =~ ^arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]{1,64}$ ]] || { echo "::error::roleArn is not an IAM role ARN."; exit 1; } + # IAM role ARN: arn::iam:::role/. The path + # (with its leading and trailing slash) is at most 512 printable non-space ASCII characters; + # the name is 1-64 characters of [A-Za-z0-9+=,.@_-]. + is_role_arn() { + local LC_ALL=C rest name path + [[ "$1" =~ ^arn:aws(-cn|-us-gov)?:iam::[0-9]{12}:role/(.+)$ ]] || return 1 + rest="${BASH_REMATCH[2]}" + name="${rest##*/}" + path="/" + [[ "$rest" == */* ]] && path="/${rest%/*}/" + [[ "$name" =~ ^[A-Za-z0-9+=,.@_-]{1,64}$ ]] || return 1 + (( ${#path} <= 512 )) || return 1 + [[ "$path" =~ ^[[:graph:]]+$ ]] + } + is_role_arn "$ROLE_ARN" || { echo "::error::roleArn is not an IAM role ARN (arn:aws:iam::<12-digit account>:role/[/])."; exit 1; } [[ "$AWS_REGION_INPUT" =~ ^[a-z]{2}(-[a-z]+)+-[0-9]$ ]] || { echo "::error::awsRegion is not an AWS region."; exit 1; } jq -e 'type == "array" and length >= 1 and length <= 20 and (map(type == "object" and (.stack | type) == "string") | all) and (map(.stack) | unique | length) == length' <<<"$STACKS" >/dev/null \ || { echo "::error::stacks must be a JSON array of 1-20 objects with distinct \"stack\" names."; exit 1; } diff --git a/.github/workflows/self-test-build-deploy.yml b/.github/workflows/self-test-build-deploy.yml index e219b0e..a02a8ed 100644 --- a/.github/workflows/self-test-build-deploy.yml +++ b/.github/workflows/self-test-build-deploy.yml @@ -81,6 +81,40 @@ jobs: productionRoleArn: arn:aws:iam::222222222222:user/prod-deploy awsRegion: us-east-1 expect: failure + - name: role with a path + ref: refs/heads/main + roleArn: arn:aws:iam::111111111111:role/platform/ci/dev-deploy + productionRoleArn: "" + awsRegion: us-east-1 + expect: success + expectRole: arn:aws:iam::111111111111:role/platform/ci/dev-deploy + expectEnvironment: development + - name: long path with a 64-character name + ref: refs/tags/v1.2.3 + roleArn: "" + productionRoleArn: arn:aws-us-gov:iam::222222222222:role/division-1/division-2/division-3/division-4/division-5/division-6/division-7/division-8/team_a+b=c,d.e@f/dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd + awsRegion: us-gov-west-1 + expect: success + expectRole: arn:aws-us-gov:iam::222222222222:role/division-1/division-2/division-3/division-4/division-5/division-6/division-7/division-8/team_a+b=c,d.e@f/dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd + expectEnvironment: production + - name: role name over 64 characters + ref: refs/heads/main + roleArn: arn:aws:iam::111111111111:role/ci/ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddx + productionRoleArn: "" + awsRegion: us-east-1 + expect: failure + - name: space in role path + ref: refs/heads/main + roleArn: arn:aws:iam::111111111111:role/ci team/dev-deploy + productionRoleArn: "" + awsRegion: us-east-1 + expect: failure + - name: path over 512 characters + ref: refs/heads/main + roleArn: arn:aws:iam::111111111111:role/ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp/dev-deploy + productionRoleArn: "" + awsRegion: us-east-1 + expect: failure - name: malformed region ref: refs/heads/main roleArn: arn:aws:iam::111111111111:role/dev-deploy diff --git a/README.md b/README.md index 5b28815..988e791 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,9 @@ hard-code an account. production. - **Validation happens first.** The ARNs and region are checked before anything is built and before any credentials are requested. Missing or malformed values fail with an error that names the input - to fix. + to fix. Role ARNs follow IAM's rules: the `aws`, `aws-cn`, or `aws-us-gov` partition, an optional + role path of up to 512 characters, and a role name of up to 64 characters. `cdk-preview.yaml` + applies the same check to its `roleArn`. - **Trust stays in IAM.** The template does not change any IAM role, trust policy, or permission. Recommended trust for deployment roles: exact `aud` (`sts.amazonaws.com`), the immutable `repository_id`, and a `sub` limited to `ref:refs/heads/main` (development) or tag refs / a