diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f13a1484e..fe856ae24 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -236,4 +236,4 @@ jobs: GATEWAY_ZIP="$S/gateway" WORKER_ZIP="$S/worker" MCP_PROXY_DIR="$S/mcp" CODERHELM_DASHBOARD_DIR="$S/dash" node dist/lib/native/build.js v0.0.0-ci "$RUNNER_TEMP/native" pip install --quiet cfn-lint==1.58.0 cfn-lint ../infra/cfn/*.yaml - cfn-lint -i W3005 -i W2531 -- "$RUNNER_TEMP/native/coderhelm.json" "$RUNNER_TEMP/native"/stacks/*.json \ No newline at end of file + cfn-lint -i W3005 -i W2531 -- "$RUNNER_TEMP/native/coderhelm.json" "$RUNNER_TEMP/native/access.json" "$RUNNER_TEMP/native"/stacks/*.json \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dec0022ee..c6dba7e28 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -341,9 +341,9 @@ jobs: export CODERHELM_COMMIT CODERHELM_RELEASED_AT CODERHELM_DASHBOARD_DIR="$RUNNER_TEMP/dash" node dist/lib/native/build.js "$TAG" "$RUNNER_TEMP/native" pip install --quiet cfn-lint==1.58.0 - cfn-lint -i W3005 -i W2531 -- "$RUNNER_TEMP/native/coderhelm.json" "$RUNNER_TEMP/native"/stacks/*.json + cfn-lint -i W3005 -i W2531 -- "$RUNNER_TEMP/native/coderhelm.json" "$RUNNER_TEMP/native/access.json" "$RUNNER_TEMP/native"/stacks/*.json cp "$RUNNER_TEMP/native/coderhelm.json" ../dist/coderhelm.json - tar -czf ../dist/coderhelm-native.tar.gz -C "$RUNNER_TEMP/native" stacks assets + tar -czf ../dist/coderhelm-native.tar.gz -C "$RUNNER_TEMP/native" access.json stacks assets - name: Checksums run: | (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh coderhelm.json coderhelm-native.tar.gz models.json coderhelm-log-reader.yaml coderhelm-log-reader-update.yaml > SHA256SUMS) diff --git a/docs/self-host/security.md b/docs/self-host/security.md index 191c40b32..7a5b5ffb9 100644 --- a/docs/self-host/security.md +++ b/docs/self-host/security.md @@ -145,7 +145,7 @@ It can't choose the code: only a published release's template. It does choose th **What waits for a person.** The updater reads every change, with its before and after values, in the parent's change set and each part's. It never executes by itself a change set (or a part's) that would replace or remove a table, bucket, key, user pool or secret, or that changes who may do what: an IAM role or policy added or changed, a function permission or URL, a resource policy (a bucket's, queue's, topic's, secret's, key's or table's), or a principal other than an AWS service anywhere in a property. It waits, and Settings, System lists exactly those changes. It applies once an install admin confirms that list there: the confirmation names this prepared update and exactly those changes, so a confirmation of an older list, or of another update, is refused. The gateway passes it on only from an install admin (`PLATFORM_ADMIN_EMAILS`, who is also a team admin), and the history records who confirmed what. -**What CoderHelm never applies.** A change set that changes the deploy role or either boundary: the boundary forbids the role to change those (that is what keeps it from giving itself more), and nothing else in the install may. Settings, System says so and links to the change set; someone with administrator rights in the account executes it in the CloudFormation console. Letting CoderHelm apply these would need a role that can rewrite the deploy role's boundary, which is a role that can give itself anything: so there is none. +**What CoderHelm never applies.** A change set that changes the deploy role or either boundary: the boundary forbids the role to change those (that is what keeps it from giving itself more), and nothing else in the install may. Executing such a change set in the CloudFormation console doesn't get around it either: the stack's service role is the deploy role, so AWS runs it as that role whoever presses Execute (and its rollback fails the same way). So no update changes them: the parent template carries them exactly as installs have them, every update keeps the install's own copies, and the updater checks every IAM call a prepared update needs against the deploy role before it runs. Newer documents for them ship in each release's signed `access.json`, which someone with administrator rights applies with their own permissions as the stack `coderhelm--access` (Settings, System, Permissions; [Updates](./updates.md#permissions)). Its writer function and role are named `CoderHelmAccess-`, outside the install's names, so no CoderHelm role can invoke, pass or change them, and no CoderHelm role may create, change or delete that stack (`TheAccessStackStays`). Letting CoderHelm apply these would need a role that can rewrite the deploy role's boundary, which is a role that can give itself anything: so there is none. - Only CloudFormation can assume it, only for this account (`aws:SourceAccount`) and only for this stack and its parts (`aws:SourceArn`). - It carries the boundary (its own copy, kept with it). diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index a48a18520..72c39eb82 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -113,7 +113,8 @@ The **Version** section of **Settings, then System** shows one state at a time, | **vX would replace or remove data** | The prepared update would replace or remove data, and waits for you ([Update now](#update-now)). | **Replace the data and apply**, once you've read what it lists. | | **vX is ready to apply** | Prepared and waiting: the maintenance window held it because it changes what CoderHelm's own roles may do, or auto-update was turned off before it ran. | **Apply update**. | | **vX is ready to apply** | The prepared update waits for an admin, for example because automatic updates were turned off before it ran. | **Apply vX**. | -| **vX needs an AWS admin** | The update changes the deploy role or a permissions boundary, which CoderHelm can't apply for itself ([why](#what-an-update-does)). | **Open it in the AWS console**: someone with administrator rights reviews it and chooses **Execute**. | +| **vX needs an AWS admin** | Only on a stack from before the deploy role existed (up to v0.8.26 with **AutoUpdate** off): its first update adds the role ([below](#the-first-update-onto-a-release-with-the-deploy-role-on-every-install)). | **Open it in the AWS console**: someone with administrator rights reviews it and chooses **Execute**. | +| **Couldn't start: it needs permissions CoderHelm's update role doesn't have** | The check before it runs found a call the deploy role would be refused ([Permissions](#permissions)). Nothing ran. | Apply the permission change under **Permissions**, then **Update** again. | | **Applying vX…** / **Updating to vX…** | The update runs (10 to 20 minutes), with who started it and when. When someone executed it in the AWS console, it says so. Coderhelm keeps running your current version until it finishes. | Nothing. The page follows it. | | **The update to vX couldn't start** / **didn't finish** / **stopped partway** | The last try didn't work ([When an update fails](#when-an-update-fails)). | **Try again**, after fixing what **Install health** lists. After **stopped partway**, **Roll back** is offered too. | | **vX is available, but can't install yet** | An install check that stops updates fails. | **See what to fix** opens **Install health**. | @@ -127,6 +128,27 @@ Under the status, **Check for updates** sits next to when GitHub last answered ( There is only ever one update waiting. A newer prepared update replaces an older one that hasn't run, and the history lists the older one as **Replaced**. An update that AWS is still preparing or already applying is never replaced. +## Permissions + +Some releases can do more once your install's permission limit (its boundary) or its deploy role allows a little more, for example reading Airflow, ECS and ECR in your own account. No update can change those: the deploy role that runs updates may never change itself or a boundary. So the update installs without them, the features that need them say so where you use them, and **Settings, then System, then Version** shows a separate, optional item: **Permissions**, with what it adds in plain words (for example "adds read access to Airflow, ECR and ECS"). + +**Open in the AWS console** opens one link: a stack named `coderhelm--access`, from that release's signed `access.json`, with your install's values filled in. Someone with administrator rights in the AWS account checks the box and chooses **Create stack**. It runs with that person's own permissions (the stack has no service role), writes a new version of `coderhelm--boundary-stack` and `coderhelm--deploy-boundary-stack` and the deploy role's policy, only where they differ, and finishes in about a minute. The item then reads **Applied**. Deleting that stack later changes nothing. If the stack exists from an earlier change, delete it first (the item links to it); no CoderHelm role can create, change or delete a stack of that name. + +Updates never wait for this item, and it never waits for an update. + +### An install launched from v0.8.54-beta.20261108 + +v0.8.54-beta.20261108 was the one release whose template carried a newer boundary. An install launched from it (not updated to it) has that boundary, and its updater is the one from before held updates. So the next release, which carries the earlier boundary, shows **vX needs an AWS admin** there once. Don't execute that change set: it runs as the deploy role and can't change the boundary. If someone already did and the stack reads `UPDATE_ROLLBACK_FAILED`, recover it once in the CloudFormation console: + +1. Open the stack `coderhelm-`, then **Stack actions**, then **Continue update rollback**. +2. Under **Resources to skip**, select **Boundary** and **DeployBoundary**. Neither was changed: the update was refused before it changed them. Choose **Continue update rollback**. + +The install is then back on v0.8.54-beta.20261108, working as before, and it stays on it: its updater can't keep its own boundary in a newer release, and the deploy role can't change it. Moving such an install on takes one step by an AWS admin, which CoderHelm doesn't automate yet. No other install is affected: every install launched from any other release updates as usual. + +## A rollback that stopped + +If AWS stops while it puts the previous release back (the stack reads `UPDATE_ROLLBACK_FAILED`), no update can run until the rollback finishes. CoderHelm finishes it by itself: for each resource AWS couldn't put back, it checks that the resource is already exactly as the previous release has it (a policy's document, as IAM has it now), and continues the rollback skipping only those. **Settings, then System** shows it, and the update's history entry ends as rolled back. If a resource isn't as the previous release has it, CoderHelm skips nothing, emails admins once and shows what differs. + ## Install health **Install health**, its own section under **Version**, is the install's own checks: its address, GitHub, email, Claude and its queues. It says **All N checks pass**, or lists each check that fails or needs a look with its fix. A failing check marked **Stops updates** holds an update until it passes (the update's own health check would stop it otherwise); a failing integration such as Slack doesn't. **Re-run checks** runs them again; **See every check** opens **Settings, then Setup**. The same list is `GET /api/system/preflight`; see [Check your install](./check-your-install.md). @@ -165,7 +187,8 @@ On an install made with Launch Stack, an update is a stack update of `coderhelm- 4. **Applies it, through the deploy role.** **Settings, then System** shows the change set's summary while it runs: how many resources are added, changed and removed, which ones are replaced, which parts it touches, and a link to it in the CloudFormation console if you want to look. - **You pressed Update:** it applies as soon as it is prepared. The card says next to the button that one press includes any change to what CoderHelm's own roles may do; those always stay inside the install's permissions boundary, and the deploy role can't change itself or the boundary. When it would replace or remove data, it stops: the card lists what it replaces or removes, in words, and **Replace the data and apply** applies exactly those changes (if they changed since the page showed them, it asks again). The raw CloudFormation list is under **Technical details**. - **The maintenance window started it (auto-update on):** it applies by itself, except when it would replace or remove data or change permissions: then it waits, admins get an email, and you confirm it on the page the same way. If auto-update was turned off before it ran, it waits for you to press **Apply**. - - **It changes the deploy role or a permissions boundary:** the deploy role can't change those (that is what keeps it from giving itself more), so CoderHelm can't apply it for you. The page says so and links to the change set: someone with administrator rights in the AWS account reviews it and chooses **Execute**. Releases do this rarely, and their notes say so. + - **The deploy role and the permissions boundaries never change in an update.** The deploy role can't change itself or a boundary (that is what keeps it from giving itself more), and executing the change set in the AWS console doesn't get around it: the stack's service role is the deploy role, so AWS runs it as that role whoever presses **Execute**. So every update keeps your install's own deploy role and boundaries exactly as they are, and the rest of the release installs. A release that needs newer ones lists them under [Permissions](#permissions), as a separate step. + - **Before it runs**, the updater checks every IAM call the change set needs against the deploy role's own policy and boundary, as IAM has them now. If one would be refused, the update stops before anything changes and says which call and which rule refused it. 5. **Follows it.** The updater reads the change set and the stack every 5 minutes until the update ends, and again each time **Settings, then System** asks, so the page never shows an older state than CloudFormation's. An update executed outside the app (in the AWS console or the AWS CLI) is followed the same way, and the history records it as applied in the AWS console. Before it calls the update a success, it checks that the stack reports the new release. When the stack update starts, the install's own copy step checks every file of the release against the sha256 that `coderhelm.json` lists before any part changes. If a part fails, CloudFormation rolls the whole stack back to the previous release by itself. 6. **Reports.** The history in **Settings, then System** shows the version, when, who (or "auto") and the result: succeeded, failed, or rolled back. A try that didn't succeed says in plain words what happened, where your install is now and what to do next; CloudFormation's own text (for the first resource that failed) is under **Technical details**. Admins get an email when it failed or rolled back; a finished update is only in the history. diff --git a/infra/lib/native/access-pinned.json b/infra/lib/native/access-pinned.json new file mode 100644 index 000000000..7a2f70907 --- /dev/null +++ b/infra/lib/native/access-pinned.json @@ -0,0 +1,1416 @@ +{ + "about": "The parent's Boundary, DeployBoundary and DeployRole exactly as every native release from v0.8.36 to v0.8.53 carried them. Updates never change these three (an update runs as the deploy role, which may not change itself or a boundary); newer permissions reach an install through its access stack (access.json). Changing this file makes every install's next update wait for an AWS admin.", + "since": "v0.8.36", + "resources": { + "Boundary": { + "Type": "AWS::IAM::ManagedPolicy", + "DeletionPolicy": "Delete", + "UpdateReplacePolicy": "Retain", + "Properties": { + "ManagedPolicyName": { + "Fn::Sub": "coderhelm-${Stage}-boundary-stack" + }, + "Description": "CoderHelm: the most any CoderHelm role can do (docs/self-host/security.md)", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "CoderHelmServices", + "Effect": "Allow", + "Action": [ + "acm:*", + "apigateway:*", + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + "bedrock:Get*", + "bedrock:List*", + "cloudformation:*", + "cloudfront:*", + "cloudwatch:*", + "codebuild:*", + "cognito-idp:*", + "dynamodb:*", + "events:*", + "kms:*", + "lambda:*", + "logs:*", + "s3:*", + "scheduler:*", + "secretsmanager:*", + "ses:*", + "sns:*", + "sqs:*", + "ssm:*", + "sts:AssumeRole", + "sts:GetCallerIdentity" + ], + "Resource": "*" + }, + { + "Sid": "InstallRoleWrites", + "Effect": "Allow", + "Action": [ + "iam:CreateRole", + "iam:PutRolePolicy", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:DeleteRolePolicy", + "iam:PutRolePermissionsBoundary" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + }, + "Condition": { + "StringEquals": { + "iam:PermissionsBoundary": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-boundary-stack" + } + } + } + }, + { + "Sid": "InstallRoles", + "Effect": "Allow", + "Action": [ + "iam:Get*", + "iam:List*", + "iam:DeleteRole", + "iam:UpdateRole*", + "iam:UpdateAssumeRolePolicy", + "iam:TagRole", + "iam:UntagRole", + "iam:PassRole" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + } + }, + { + "Sid": "InstallPolicies", + "Effect": "Allow", + "Action": [ + "iam:CreatePolicy*", + "iam:DeletePolicy*", + "iam:Get*", + "iam:List*", + "iam:TagPolicy", + "iam:UntagPolicy" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-*" + } + }, + { + "Sid": "NoDnsChanges", + "Effect": "Deny", + "Action": [ + "route53:ChangeResourceRecordSets", + "route53:CreateHostedZone", + "route53:DeleteHostedZone" + ], + "Resource": "*" + }, + { + "Sid": "NoIamUsersOrKeys", + "Effect": "Deny", + "Action": [ + "iam:*User*", + "iam:*AccessKey*", + "iam:*LoginProfile*", + "iam:*Group*", + "iam:*ServiceSpecificCredential*", + "iam:*SSHPublicKey*", + "iam:Create*Provider", + "iam:UpdateAccountPasswordPolicy", + "iam:CreateAccountAlias" + ], + "Resource": "*" + }, + { + "Sid": "NoAccountGuardrailChanges", + "Effect": "Deny", + "Action": [ + "organizations:*", + "account:*", + "cloudtrail:*", + "guardduty:*" + ], + "Resource": "*" + }, + { + "Sid": "NoIamOutsideTheInstall", + "Effect": "Deny", + "Action": "iam:*", + "NotResource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "RolesOnlyWithTheBoundary", + "Effect": "Deny", + "Action": [ + "iam:CreateRole", + "iam:PutRolePolicy", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:DeleteRolePolicy", + "iam:PutRolePermissionsBoundary" + ], + "Resource": "*", + "Condition": { + "StringNotEquals": { + "iam:PermissionsBoundary": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-boundary-stack" + } + } + } + }, + { + "Sid": "TheBoundaryStays", + "Effect": "Deny", + "Action": [ + "iam:DeleteRolePermissionsBoundary", + "iam:CreatePolicy*", + "iam:DeletePolicy*", + "iam:SetDefault*", + "iam:*agPolicy" + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-*boundary-stack" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/*" + } + ] + }, + { + "Sid": "OnlyTheInstallsOwn", + "Effect": "Deny", + "Action": [ + "lambda:CreateF*", + "lambda:CreateAlias", + "lambda:Delete*", + "lambda:Update*", + "lambda:Invoke*", + "lambda:Put*", + "lambda:*Permission", + "lambda:Publish*", + "cloudformation:Create*", + "cloudformation:Update*", + "cloudformation:Delete*", + "cloudformation:Execute*", + "cloudformation:Set*", + "cloudformation:Continue*", + "s3:Put*", + "s3:Delete*", + "secretsmanager:GetSecretValue", + "secretsmanager:Put*", + "secretsmanager:Update*", + "secretsmanager:Delete*", + "ssm:Put*", + "ssm:Delete*" + ], + "NotResource": [ + { + "Fn::Sub": "arn:*:lambda:*:*:function:coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:*:lambda:*:*:layer:coderhelm-${Stage}-*" + }, + "arn:*:lambda:*:*:event-source-mapping:*", + { + "Fn::Sub": "arn:*:cloudformation:*:*:stack/coderhelm-${Stage}*" + }, + "arn:*:cloudformation:*:aws:transform/*", + { + "Fn::Sub": "arn:*:s3:::coderhelm-${Stage}-*" + }, + "arn:*:s3:::coderhelm-setup-*", + { + "Fn::Sub": "arn:*:secretsmanager:*:*:secret:coderhelm/${Stage}/*" + }, + { + "Fn::Sub": "arn:*:ssm:*:*:parameter/coderhelm-${Stage}/*" + } + ] + }, + { + "Sid": "NoCommandsOnInstances", + "Effect": "Deny", + "Action": [ + "ssm:SendCommand", + "ssm:Start*", + "ssm:*Association*" + ], + "Resource": "*" + }, + { + "Sid": "TheDeployRoleStays", + "Effect": "Deny", + "Action": [ + "iam:CreateRole", + "iam:PutRolePolicy", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:DeleteRolePolicy", + "iam:PutRolePermissionsBoundary", + "iam:DeleteRole", + "iam:UpdateRole", + "iam:UpdateAssumeRolePolicy", + "iam:TagRole", + "iam:UntagRole" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-deploy-stack" + } + }, + { + "Sid": "TheAccessStackStays", + "Effect": "Deny", + "Action": [ + "cloudformation:CreateChangeSet", + "cloudformation:ExecuteChangeSet", + "cloudformation:UpdateStack", + "cloudformation:DeleteStack", + "cloudformation:CreateStack", + "cloudformation:SetStackPolicy" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}-access/*" + } + }, + { + "Sid": "NoOtherRolesHere", + "Effect": "Deny", + "Action": [ + "sts:AssumeRole", + "sts:AssumeRoleWithWebIdentity", + "sts:AssumeRoleWithSAML", + "sts:TagSession", + "sts:SetSourceIdentity" + ], + "NotResource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderHelmLogReader" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderhelmReadOnly" + } + ], + "Condition": { + "StringEquals": { + "aws:ResourceAccount": { + "Fn::Sub": "${AWS::AccountId}" + } + } + } + }, + { + "Sid": "ReadRolesHereAssumeOnly", + "Effect": "Deny", + "Action": [ + "sts:AssumeRoleWithWebIdentity", + "sts:AssumeRoleWithSAML", + "sts:TagSession", + "sts:SetSourceIdentity" + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderHelmLogReader" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderhelmReadOnly" + } + ] + }, + { + "Sid": "ReadRolesHereOnlyGatewayAndWorker", + "Effect": "Deny", + "Action": "sts:AssumeRole", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderHelmLogReader" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderhelmReadOnly" + } + ], + "Condition": { + "StringNotEquals": { + "aws:PrincipalTag/coderhelm:role": [ + "gateway", + "worker" + ] + } + } + }, + { + "Sid": "RuntimeTagOnlyByDeploy", + "Effect": "Deny", + "Action": [ + "iam:CreateRole", + "iam:TagRole", + "iam:UntagRole" + ], + "Resource": "*", + "Condition": { + "ForAnyValue:StringEqualsIgnoreCase": { + "aws:TagKeys": [ + "coderhelm:role" + ] + }, + "ArnNotEquals": { + "aws:PrincipalArn": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-deploy-stack" + } + } + } + } + ] + } + } + }, + "DeployBoundary": { + "Type": "AWS::IAM::ManagedPolicy", + "DeletionPolicy": "Retain", + "UpdateReplacePolicy": "Retain", + "Metadata": { + "cfn-lint": { + "config": { + "ignore_checks": [ + "W3011" + ] + } + } + }, + "Properties": { + "ManagedPolicyName": { + "Fn::Sub": "coderhelm-${Stage}-deploy-boundary-stack" + }, + "Description": "CoderHelm: the auto-update role's boundary, the same as every CoderHelm role's (docs/self-host/security.md)", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "CoderHelmServices", + "Effect": "Allow", + "Action": [ + "acm:*", + "apigateway:*", + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + "bedrock:Get*", + "bedrock:List*", + "cloudformation:*", + "cloudfront:*", + "cloudwatch:*", + "codebuild:*", + "cognito-idp:*", + "dynamodb:*", + "events:*", + "kms:*", + "lambda:*", + "logs:*", + "s3:*", + "scheduler:*", + "secretsmanager:*", + "ses:*", + "sns:*", + "sqs:*", + "ssm:*", + "sts:AssumeRole", + "sts:GetCallerIdentity" + ], + "Resource": "*" + }, + { + "Sid": "InstallRoleWrites", + "Effect": "Allow", + "Action": [ + "iam:CreateRole", + "iam:PutRolePolicy", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:DeleteRolePolicy", + "iam:PutRolePermissionsBoundary" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + }, + "Condition": { + "StringEquals": { + "iam:PermissionsBoundary": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-boundary-stack" + } + } + } + }, + { + "Sid": "InstallRoles", + "Effect": "Allow", + "Action": [ + "iam:Get*", + "iam:List*", + "iam:DeleteRole", + "iam:UpdateRole*", + "iam:UpdateAssumeRolePolicy", + "iam:TagRole", + "iam:UntagRole", + "iam:PassRole" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + } + }, + { + "Sid": "InstallPolicies", + "Effect": "Allow", + "Action": [ + "iam:CreatePolicy*", + "iam:DeletePolicy*", + "iam:Get*", + "iam:List*", + "iam:TagPolicy", + "iam:UntagPolicy" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-*" + } + }, + { + "Sid": "NoDnsChanges", + "Effect": "Deny", + "Action": [ + "route53:ChangeResourceRecordSets", + "route53:CreateHostedZone", + "route53:DeleteHostedZone" + ], + "Resource": "*" + }, + { + "Sid": "NoIamUsersOrKeys", + "Effect": "Deny", + "Action": [ + "iam:*User*", + "iam:*AccessKey*", + "iam:*LoginProfile*", + "iam:*Group*", + "iam:*ServiceSpecificCredential*", + "iam:*SSHPublicKey*", + "iam:Create*Provider", + "iam:UpdateAccountPasswordPolicy", + "iam:CreateAccountAlias" + ], + "Resource": "*" + }, + { + "Sid": "NoAccountGuardrailChanges", + "Effect": "Deny", + "Action": [ + "organizations:*", + "account:*", + "cloudtrail:*", + "guardduty:*" + ], + "Resource": "*" + }, + { + "Sid": "NoIamOutsideTheInstall", + "Effect": "Deny", + "Action": "iam:*", + "NotResource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "RolesOnlyWithTheBoundary", + "Effect": "Deny", + "Action": [ + "iam:CreateRole", + "iam:PutRolePolicy", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:DeleteRolePolicy", + "iam:PutRolePermissionsBoundary" + ], + "Resource": "*", + "Condition": { + "StringNotEquals": { + "iam:PermissionsBoundary": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-boundary-stack" + } + } + } + }, + { + "Sid": "TheBoundaryStays", + "Effect": "Deny", + "Action": [ + "iam:DeleteRolePermissionsBoundary", + "iam:CreatePolicy*", + "iam:DeletePolicy*", + "iam:SetDefault*", + "iam:*agPolicy" + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-*boundary-stack" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/*" + } + ] + }, + { + "Sid": "OnlyTheInstallsOwn", + "Effect": "Deny", + "Action": [ + "lambda:CreateF*", + "lambda:CreateAlias", + "lambda:Delete*", + "lambda:Update*", + "lambda:Invoke*", + "lambda:Put*", + "lambda:*Permission", + "lambda:Publish*", + "cloudformation:Create*", + "cloudformation:Update*", + "cloudformation:Delete*", + "cloudformation:Execute*", + "cloudformation:Set*", + "cloudformation:Continue*", + "s3:Put*", + "s3:Delete*", + "secretsmanager:GetSecretValue", + "secretsmanager:Put*", + "secretsmanager:Update*", + "secretsmanager:Delete*", + "ssm:Put*", + "ssm:Delete*" + ], + "NotResource": [ + { + "Fn::Sub": "arn:*:lambda:*:*:function:coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:*:lambda:*:*:layer:coderhelm-${Stage}-*" + }, + "arn:*:lambda:*:*:event-source-mapping:*", + { + "Fn::Sub": "arn:*:cloudformation:*:*:stack/coderhelm-${Stage}*" + }, + "arn:*:cloudformation:*:aws:transform/*", + { + "Fn::Sub": "arn:*:s3:::coderhelm-${Stage}-*" + }, + "arn:*:s3:::coderhelm-setup-*", + { + "Fn::Sub": "arn:*:secretsmanager:*:*:secret:coderhelm/${Stage}/*" + }, + { + "Fn::Sub": "arn:*:ssm:*:*:parameter/coderhelm-${Stage}/*" + } + ] + }, + { + "Sid": "NoCommandsOnInstances", + "Effect": "Deny", + "Action": [ + "ssm:SendCommand", + "ssm:Start*", + "ssm:*Association*" + ], + "Resource": "*" + }, + { + "Sid": "TheDeployRoleStays", + "Effect": "Deny", + "Action": [ + "iam:CreateRole", + "iam:PutRolePolicy", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:DeleteRolePolicy", + "iam:PutRolePermissionsBoundary", + "iam:DeleteRole", + "iam:UpdateRole", + "iam:UpdateAssumeRolePolicy", + "iam:TagRole", + "iam:UntagRole" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-deploy-stack" + } + }, + { + "Sid": "TheAccessStackStays", + "Effect": "Deny", + "Action": [ + "cloudformation:CreateChangeSet", + "cloudformation:ExecuteChangeSet", + "cloudformation:UpdateStack", + "cloudformation:DeleteStack", + "cloudformation:CreateStack", + "cloudformation:SetStackPolicy" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}-access/*" + } + }, + { + "Sid": "NoOtherRolesHere", + "Effect": "Deny", + "Action": [ + "sts:AssumeRole", + "sts:AssumeRoleWithWebIdentity", + "sts:AssumeRoleWithSAML", + "sts:TagSession", + "sts:SetSourceIdentity" + ], + "NotResource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderHelmLogReader" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderhelmReadOnly" + } + ], + "Condition": { + "StringEquals": { + "aws:ResourceAccount": { + "Fn::Sub": "${AWS::AccountId}" + } + } + } + }, + { + "Sid": "ReadRolesHereAssumeOnly", + "Effect": "Deny", + "Action": [ + "sts:AssumeRoleWithWebIdentity", + "sts:AssumeRoleWithSAML", + "sts:TagSession", + "sts:SetSourceIdentity" + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderHelmLogReader" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderhelmReadOnly" + } + ] + }, + { + "Sid": "ReadRolesHereOnlyGatewayAndWorker", + "Effect": "Deny", + "Action": "sts:AssumeRole", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderHelmLogReader" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/CoderhelmReadOnly" + } + ], + "Condition": { + "StringNotEquals": { + "aws:PrincipalTag/coderhelm:role": [ + "gateway", + "worker" + ] + } + } + }, + { + "Sid": "RuntimeTagOnlyByDeploy", + "Effect": "Deny", + "Action": [ + "iam:CreateRole", + "iam:TagRole", + "iam:UntagRole" + ], + "Resource": "*", + "Condition": { + "ForAnyValue:StringEqualsIgnoreCase": { + "aws:TagKeys": [ + "coderhelm:role" + ] + }, + "ArnNotEquals": { + "aws:PrincipalArn": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-deploy-stack" + } + } + } + } + ] + } + } + }, + "DeployRole": { + "Type": "AWS::IAM::Role", + "DeletionPolicy": "Retain", + "UpdateReplacePolicy": "Retain", + "Metadata": { + "cfn-lint": { + "config": { + "ignore_checks": [ + "W3037", + "W3011" + ] + } + } + }, + "Properties": { + "RoleName": { + "Fn::Sub": "coderhelm-${Stage}-deploy-stack" + }, + "Description": "CoderHelm: applies a reviewed release's stack update when auto-update is on (docs/self-host/security.md)", + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "Service": "cloudformation.amazonaws.com" + }, + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "StringLike": { + "aws:SourceArn": [ + { + "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}/*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}-*/*" + } + ] + } + } + } + ] + }, + "PermissionsBoundary": { + "Ref": "DeployBoundary" + }, + "Policies": [ + { + "PolicyName": "deploy", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "Roles", + "Effect": "Allow", + "Action": [ + "iam:CreateRole", + "iam:PutRolePolicy", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:DeleteRolePolicy", + "iam:PutRolePermissionsBoundary" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + }, + "Condition": { + "StringEquals": { + "iam:PermissionsBoundary": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-boundary-stack" + } + } + } + }, + { + "Sid": "RolesManage", + "Effect": "Allow", + "Action": [ + "iam:DeleteRole", + "iam:GetRole", + "iam:GetRolePolicy", + "iam:ListRolePolicies", + "iam:ListAttachedRolePolicies", + "iam:ListRoleTags", + "iam:UpdateRole", + "iam:UpdateRoleDescription", + "iam:UpdateAssumeRolePolicy", + "iam:TagRole", + "iam:UntagRole" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + } + }, + { + "Sid": "Policies", + "Effect": "Allow", + "Action": [ + "iam:CreatePolicy", + "iam:DeletePolicy", + "iam:CreatePolicyVersion", + "iam:DeletePolicyVersion", + "iam:GetPolicy", + "iam:GetPolicyVersion", + "iam:ListPolicyVersions", + "iam:ListEntitiesForPolicy", + "iam:TagPolicy", + "iam:UntagPolicy" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-*" + } + }, + { + "Sid": "PassInstallRoles", + "Effect": "Allow", + "Action": "iam:PassRole", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/coderhelm-${Stage}-*" + } + }, + { + "Sid": "Functions", + "Effect": "Allow", + "Action": "lambda:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:layer:coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "FunctionEvents", + "Effect": "Allow", + "Action": [ + "lambda:CreateEventSourceMapping", + "lambda:UpdateEventSourceMapping", + "lambda:DeleteEventSourceMapping" + ], + "Resource": "*", + "Condition": { + "ArnLike": { + "lambda:FunctionArn": { + "Fn::Sub": "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:coderhelm-${Stage}-*" + } + } + } + }, + { + "Sid": "FunctionEventTags", + "Effect": "Allow", + "Action": [ + "lambda:TagResource", + "lambda:UntagResource", + "lambda:ListTags" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:event-source-mapping:*" + } + }, + { + "Sid": "Tables", + "Effect": "Allow", + "Action": "dynamodb:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/coderhelm-${Stage}" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/coderhelm-${Stage}/*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "Buckets", + "Effect": "Allow", + "Action": "s3:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:s3:::coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "Queues", + "Effect": "Allow", + "Action": "sqs:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:sqs:${AWS::Region}:${AWS::AccountId}:coderhelm-${Stage}-*" + } + }, + { + "Sid": "Topics", + "Effect": "Allow", + "Action": "sns:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:sns:${AWS::Region}:${AWS::AccountId}:coderhelm-${Stage}-*" + } + }, + { + "Sid": "Logs", + "Effect": "Allow", + "Action": "logs:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "Schedules", + "Effect": "Allow", + "Action": [ + "events:*", + "scheduler:*" + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:rule/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:scheduler:${AWS::Region}:${AWS::AccountId}:schedule-group/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:scheduler:${AWS::Region}:${AWS::AccountId}:schedule/coderhelm-${Stage}-*/*" + } + ] + }, + { + "Sid": "Alarms", + "Effect": "Allow", + "Action": "cloudwatch:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:cloudwatch:${AWS::Region}:${AWS::AccountId}:alarm:coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:cloudwatch::${AWS::AccountId}:dashboard/coderhelm-${Stage}" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:cloudwatch::${AWS::AccountId}:dashboard/coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "Builds", + "Effect": "Allow", + "Action": "codebuild:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:codebuild:${AWS::Region}:${AWS::AccountId}:project/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:codebuild:${AWS::Region}:${AWS::AccountId}:report-group/coderhelm-${Stage}-*" + } + ] + }, + { + "Sid": "Parameters", + "Effect": "Allow", + "Action": "ssm:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/coderhelm-${Stage}/*" + } + }, + { + "Sid": "Email", + "Effect": "Allow", + "Action": "ses:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:configuration-set/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:template/coderhelm-${Stage}-*" + }, + { + "Fn::Sub": [ + "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${EmailIdentity}", + { + "EmailIdentity": { + "Fn::If": [ + "HasEmailFrom", + { + "Ref": "EmailFrom" + }, + { + "Ref": "AdminEmail" + } + ] + } + } + ] + } + ] + }, + { + "Sid": "EmailTemplatesV1", + "Effect": "Allow", + "Action": [ + "ses:CreateTemplate", + "ses:UpdateTemplate", + "ses:DeleteTemplate" + ], + "Resource": "*" + }, + { + "Sid": "KeysCreate", + "Effect": "Allow", + "Action": [ + "kms:CreateKey", + "kms:TagResource" + ], + "Resource": "*", + "Condition": { + "StringEquals": { + "aws:RequestTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "Keys", + "Effect": "Allow", + "Action": "kms:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:key/*" + }, + "Condition": { + "StringEquals": { + "aws:ResourceTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "KeyAliases", + "Effect": "Allow", + "Action": [ + "kms:CreateAlias", + "kms:DeleteAlias", + "kms:UpdateAlias" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:alias/coderhelm-${Stage}-*" + } + }, + { + "Sid": "UserPoolsCreate", + "Effect": "Allow", + "Action": "cognito-idp:CreateUserPool", + "Resource": "*" + }, + { + "Sid": "UserPoolsTag", + "Effect": "Allow", + "Action": "cognito-idp:TagResource", + "Resource": "*", + "Condition": { + "StringEquals": { + "aws:RequestTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "UserPools", + "Effect": "Allow", + "Action": "cognito-idp:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/*" + }, + "Condition": { + "StringEquals": { + "aws:ResourceTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "DistributionsCreate", + "Effect": "Allow", + "Action": [ + "cloudfront:CreateDistribution", + "cloudfront:CreateDistributionWithTags" + ], + "Resource": "*" + }, + { + "Sid": "DistributionsTag", + "Effect": "Allow", + "Action": "cloudfront:TagResource", + "Resource": "*", + "Condition": { + "StringEquals": { + "aws:RequestTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "Distributions", + "Effect": "Allow", + "Action": "cloudfront:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/*" + }, + "Condition": { + "StringEquals": { + "aws:ResourceTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "EdgeFunctionsCreate", + "Effect": "Allow", + "Action": "cloudfront:CreateFunction", + "Resource": "*" + }, + { + "Sid": "EdgeFunctions", + "Effect": "Allow", + "Action": "cloudfront:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:function/coderhelm-${Stage}-*" + } + }, + { + "Sid": "EdgeSettings", + "Effect": "Allow", + "Action": [ + "cloudfront:CreateOriginAccessControl", + "cloudfront:UpdateOriginAccessControl", + "cloudfront:DeleteOriginAccessControl", + "cloudfront:GetOriginAccessControl", + "cloudfront:CreateResponseHeadersPolicy", + "cloudfront:UpdateResponseHeadersPolicy", + "cloudfront:DeleteResponseHeadersPolicy", + "cloudfront:GetResponseHeadersPolicy" + ], + "Resource": "*" + }, + { + "Sid": "HttpApi", + "Effect": "Allow", + "Action": [ + "apigateway:GET", + "apigateway:POST", + "apigateway:PUT", + "apigateway:PATCH", + "apigateway:DELETE", + "apigateway:TagResource", + "apigateway:UntagResource" + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}::/apis" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}::/apis/*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}::/tags/*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}::/domainnames" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}::/domainnames/*" + } + ] + }, + { + "Sid": "CertificatesRequest", + "Effect": "Allow", + "Action": [ + "acm:RequestCertificate", + "acm:AddTagsToCertificate" + ], + "Resource": "*", + "Condition": { + "StringEquals": { + "aws:RequestTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "Certificates", + "Effect": "Allow", + "Action": "acm:*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:acm:*:${AWS::AccountId}:certificate/*" + }, + "Condition": { + "StringEquals": { + "aws:ResourceTag/coderhelm:install": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + } + }, + { + "Sid": "NoIamUsersOrKeys", + "Effect": "Deny", + "Action": [ + "iam:CreateUser", + "iam:CreateAccessKey", + "iam:CreateLoginProfile" + ], + "Resource": "*" + }, + { + "Sid": "NoKeyDestruction", + "Effect": "Deny", + "Action": [ + "kms:ScheduleKeyDeletion", + "kms:DisableKey", + "kms:DeleteImportedKeyMaterial" + ], + "Resource": "*" + }, + { + "Sid": "Reads", + "Effect": "Allow", + "Action": [ + "cloudformation:Describe*", + "cloudformation:Get*", + "cloudformation:List*", + "cloudfront:Get*", + "cloudfront:List*", + "cloudwatch:Describe*", + "cloudwatch:Get*", + "cloudwatch:List*", + "cognito-idp:Describe*", + "cognito-idp:List*", + "dynamodb:Describe*", + "dynamodb:List*", + "events:Describe*", + "events:List*", + "kms:List*", + "lambda:Get*", + "lambda:List*", + "logs:Describe*", + "logs:List*", + "ses:Get*", + "ses:List*", + "ses:DescribeConfigurationSet", + "sqs:List*", + "sns:List*", + "ssm:Describe*", + "acm:Describe*", + "acm:List*", + "codebuild:List*", + "scheduler:List*", + "sts:GetCallerIdentity" + ], + "Resource": "*" + }, + { + "Sid": "ParentStack", + "Effect": "Allow", + "Action": [ + "cloudformation:*" + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}/*" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}-*/*" + } + ] + }, + { + "Sid": "ReleaseFiles", + "Effect": "Allow", + "Action": [ + "s3:GetObject" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:s3:::coderhelm-${Stage}-release-${AWS::AccountId}/*" + } + }, + { + "Sid": "InstallSecret", + "Effect": "Allow", + "Action": [ + "secretsmanager:DescribeSecret", + "secretsmanager:GetSecretValue", + "secretsmanager:UpdateSecret", + "secretsmanager:TagResource", + "secretsmanager:UntagResource" + ], + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:coderhelm/${Stage}/secrets-??????" + } + }, + { + "Sid": "SecretPassword", + "Effect": "Allow", + "Action": "secretsmanager:GetRandomPassword", + "Resource": "*" + }, + { + "Sid": "ProgressBucket", + "Effect": "Allow", + "Action": "s3:*", + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:s3:::coderhelm-setup-${StatusId}" + }, + { + "Fn::Sub": "arn:${AWS::Partition}:s3:::coderhelm-setup-${StatusId}/*" + } + ] + } + ] + } + } + ], + "Tags": [ + { + "Key": "coderhelm:install", + "Value": { + "Fn::Sub": "coderhelm-${Stage}" + } + } + ] + } + } + } +} diff --git a/infra/lib/native/access-stack.ts b/infra/lib/native/access-stack.ts new file mode 100644 index 000000000..48342e128 --- /dev/null +++ b/infra/lib/native/access-stack.ts @@ -0,0 +1,113 @@ +/** + * A native release's access stack template, `access.json` (published next to + * coderhelm.json and pinned by its sha256 in the parent's ReleaseAssets). + * + * Why it exists: the parent stack runs every update as its deploy role, and + * the boundary forbids that role to change itself or a boundary. An AWS + * admin who executes a parent change set in the console doesn't help: the + * stack's service role is the deploy role, so CloudFormation still runs it + * as that role (it failed exactly so on a live install). So the parent never + * changes its Boundary, DeployBoundary or DeployRole (pinned, parent.ts), + * and today's documents for them reach an install here instead: + * + * coderhelm--access, created by an AWS admin from Settings, System + * (one Launch link, a quick-create of this template), with the admin's own + * permissions: the stack has no service role. No CoderHelm role may + * create, change or delete a stack of that name (TheAccessStackStays). + * + * Its custom resource (lambda/native-access/handler.py) writes each document + * that differs: a new default version of each boundary, the deploy role's + * inline policy. Its function and role are named outside the install's + * prefix, so no CoderHelm role can invoke, pass or change them + * (NoIamOutsideTheInstall, OnlyTheInstallsOwn). + */ +import * as fs from "fs"; +import { repoPath } from "../paths"; +import { Json } from "./package"; +import { DEPLOY_BOUNDARY_ARN, deployRolePolicy, nativeBoundaryDoc, nativeNames, parameters, sub, subInstall } from "./parent"; + +/** The admin's stack: the name every native boundary already reserves for it (access.ts accessStackName). */ +export const ACCESS_STACK_NAME = "coderhelm-${Stage}-access"; +/** Its writer's function and role: outside coderhelm--*, so no install role reaches them. */ +export const ACCESS_WRITER_NAME = "CoderHelmAccess-${Stage}"; + +/** The launch parameters the documents use; the updater's Launch link fills them from the parent stack. */ +export const ACCESS_PARAMETERS = ["Stage", "AdminEmail", "EmailFrom", "StatusId"]; + +export function writerPolicy(): Json { + const n = nativeNames(); + return sub({ + Version: "2012-10-17", + Statement: [ + { + Sid: "Boundaries", + Effect: "Allow", + Action: ["iam:GetPolicy", "iam:GetPolicyVersion", "iam:ListPolicyVersions", "iam:CreatePolicyVersion", "iam:DeletePolicyVersion", "iam:SetDefaultPolicyVersion"], + Resource: [n.boundaryArn, DEPLOY_BOUNDARY_ARN], + }, + { Sid: "DeployRolePolicy", Effect: "Allow", Action: ["iam:GetRolePolicy", "iam:PutRolePolicy"], Resource: n.deployRoleArn }, + { + Sid: "OwnLog", + Effect: "Allow", + Action: ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], + Resource: `arn:\${AWS::Partition}:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:/aws/lambda/${ACCESS_WRITER_NAME}:*`, + }, + ], + }); +} + +export function buildAccess(version: string, writerCode?: string): Json { + const n = nativeNames(); + const all = parameters(); + const code = writerCode ?? fs.readFileSync(repoPath("lambda/native-access/handler.py"), "utf8"); + const boundary = nativeBoundaryDoc(); + return { + AWSTemplateFormatVersion: "2010-09-09", + Description: + `CoderHelm ${version}: the permissions of the install's own deploy role and its boundary, applied with your permissions ` + + "(an install's updates can't change them). It writes a new version of coderhelm--boundary-stack and " + + "coderhelm--deploy-boundary-stack and the deploy role's policy, only where they differ. Deleting this stack changes nothing. " + + "docs.coderhelm.com/self-host/security", + Metadata: { CoderHelm: { version, kind: "access" } }, + Parameters: Object.fromEntries(ACCESS_PARAMETERS.map((p) => [p, all[p]])), + Conditions: { HasEmailFrom: { "Fn::Not": [{ "Fn::Equals": [{ Ref: "EmailFrom" }, ""] }] } }, + Resources: { + WriterRole: { + Type: "AWS::IAM::Role", + Properties: { + RoleName: sub(ACCESS_WRITER_NAME), + Description: "CoderHelm: writes the install's boundary and deploy role policy from the access stack (made by an AWS admin)", + AssumeRolePolicyDocument: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole" }] }, + Policies: [{ PolicyName: "write-access", PolicyDocument: writerPolicy() }], + }, + }, + Writer: { + Type: "AWS::Lambda::Function", + Properties: { + FunctionName: sub(ACCESS_WRITER_NAME), + Description: "CoderHelm: the access stack's writer (lambda/native-access)", + Runtime: "python3.12", + Handler: "index.handler", + Timeout: 120, + Role: { "Fn::GetAtt": ["WriterRole", "Arn"] }, + Code: { ZipFile: code }, + }, + }, + Access: { + Type: "Custom::Access", + Properties: { + ServiceToken: { "Fn::GetAtt": ["Writer", "Arn"] }, + Version: version, + Boundary: { Arn: sub(n.boundaryArn), Document: boundary }, + DeployBoundary: { Arn: sub(DEPLOY_BOUNDARY_ARN), Document: boundary }, + DeployRole: { RoleName: sub(n.deployRoleName), PolicyName: "deploy", Document: subInstall(deployRolePolicy(n)) }, + }, + }, + }, + Outputs: { + Version: { Description: "The CoderHelm release whose permissions this stack applied", Value: version }, + Written: { Description: "What it wrote (none: already as this release has them)", Value: { "Fn::GetAtt": ["Access", "Written"] } }, + }, + }; +} + diff --git a/infra/lib/native/build.ts b/infra/lib/native/build.ts index 839752415..d68402d21 100644 --- a/infra/lib/native/build.ts +++ b/infra/lib/native/build.ts @@ -11,6 +11,8 @@ * coderhelm-public/launch//): * * coderhelm.json the parent template (Launch Stack opens it) + * access.json the access stack's template (an AWS admin applies + * newer boundary and deploy role permissions with it) * stacks/.json one per part * assets/.zip the code, by CDK's content hash * files.txt every file, relative, for SHA256SUMS @@ -24,7 +26,8 @@ import { buildApp } from "../app"; import { repoPath } from "../paths"; import { nativeConfig } from "./config"; import { Json, checkLimits, readAssembly, sha256File } from "./package"; -import { buildParent, childKey } from "./parent"; +import { buildAccess } from "./access-stack"; +import { ACCESS_FILE, buildParent, childKey } from "./parent"; export interface NativeRelease { parent: Json; @@ -93,10 +96,14 @@ export function buildNative(version: string, outDir: string, opts: { dashboardDi problems.push(...checkLimits(c.name, c.template)); } const helperCode = fs.readFileSync(repoPath("lambda/native-helper/handler.py"), "utf8"); - const parent = buildParent({ version, children, assets, childSha, helperCode }); + const access = buildAccess(version); + fs.writeFileSync(path.join(outDir, ACCESS_FILE), JSON.stringify(access, null, 1)); + problems.push(...checkLimits(ACCESS_FILE, access)); + const accessSha = sha256File(path.join(outDir, ACCESS_FILE)); + const parent = buildParent({ version, children, assets, childSha, helperCode, accessSha }); fs.writeFileSync(path.join(outDir, "coderhelm.json"), JSON.stringify(parent, null, 1)); problems.push(...checkLimits("coderhelm.json", parent)); - const files = ["coderhelm.json", ...children.map((c) => childKey(version, c.name).key), ...assets.map((a) => a.key)]; + const files = ["coderhelm.json", ACCESS_FILE, ...children.map((c) => childKey(version, c.name).key), ...assets.map((a) => a.key)]; fs.writeFileSync(path.join(outDir, "files.txt"), files.join("\n") + "\n"); return { parent, children: out, files, problems }; } diff --git a/infra/lib/native/parent.ts b/infra/lib/native/parent.ts index 993dbd9ba..272f52b40 100644 --- a/infra/lib/native/parent.ts +++ b/infra/lib/native/parent.ts @@ -8,9 +8,38 @@ * stack update to the next release's coderhelm.json updates it, Delete * stack removes it. */ +import * as fs from "fs"; import { accessNames, AccessNames, boundaryPolicy, deployPolicy, INSTALL_TAG, PolicyDocument } from "../access"; +import { repoPath } from "../paths"; import { Asset, Child, Json, KEEP_PARAM } from "./package"; +/** The access resources' logical ids in the parent: the deploy role and the two boundaries. */ +export const ACCESS_RESOURCES = ["Boundary", "DeployBoundary", "DeployRole"] as const; + +/** + * The parent's Boundary, DeployBoundary and DeployRole, exactly as every + * native release from v0.8.36 on carried them (infra/lib/native/access-pinned.json). + * + * An update runs as the deploy role, and the boundary forbids that role to + * change itself or a boundary (TheBoundaryStays, TheDeployRoleStays): a + * parent whose copy of these differed from an install's would be an update + * nothing can apply, not even an AWS admin in the console (the stack's + * service role is the deploy role, so CloudFormation runs it as that role). + * So the parent never changes them. Today's documents (access.ts) reach an + * install through its access stack instead (access.json, applied by an AWS + * admin with their own permissions), and the updater keeps each install's + * own copy of these three in every update it prepares (lambda/updater, "held"). + */ +export function pinnedAccess(): Record<(typeof ACCESS_RESOURCES)[number], Json> { + const f = JSON.parse(fs.readFileSync(repoPath("infra/lib/native/access-pinned.json"), "utf8")); + return f.resources; +} + +/** Today's boundary document, for the parent's names (the access stack applies it). */ +export function nativeBoundaryDoc(): Json { + return subInstall(boundaryPolicy(nativeNames(), [DEPLOY_BOUNDARY_ARN])); +} + /** A string with substitutions becomes Fn::Sub; objects and arrays recursively. */ export function sub(v: unknown): any { if (typeof v === "string") return v.includes("${") ? { "Fn::Sub": v } : v; @@ -183,6 +212,9 @@ export function installValue(name: string): Json { /** The admin's "delete everything when uninstalled" switch: the updater writes it, the helper reads it on delete. */ export const UNINSTALL_SWITCH = "/coderhelm-${Stage}/uninstall/delete-data"; +/** The helper's one read of the root stack's template (stage_held). */ +export const ROOT_TEMPLATE_SID = "RootStackTemplate"; + export function helperPolicy(): PolicyDocument { const p = "coderhelm-${Stage}"; const at = (svc: string) => `arn:\${AWS::Partition}:${svc}:\${AWS::Region}:\${AWS::AccountId}`; @@ -200,6 +232,8 @@ export function helperPolicy(): PolicyDocument { { Sid: "TableKey", Effect: "Allow", Action: ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey*", "kms:DescribeKey"], Resource: "*", Condition: { StringEquals: { [`aws:ResourceTag/${INSTALL_TAG}`]: p } } }, { Sid: "Domain", Effect: "Allow", Action: "lambda:InvokeFunction", Resource: `${at("lambda")}:function:${p}-updater` }, { Sid: "RootStack", Effect: "Allow", Action: ["cloudformation:DescribeStacks", "cloudformation:DescribeStackEvents"], Resource: "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${AWS::StackName}/*" }, + // stage_held: the root stack's own deploy role and boundaries, read from its current template (read-only, that stack only). + { Sid: ROOT_TEMPLATE_SID, Effect: "Allow", Action: "cloudformation:GetTemplate", Resource: "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${AWS::StackName}/*" }, { Sid: "LogGroupsOnDelete", Effect: "Allow", Action: ["logs:DescribeLogGroups"], Resource: "*" }, // Only log groups tagged for this install (every one the stack declares is). { Sid: "InstallLogGroupsOnDelete", Effect: "Allow", Action: ["logs:DeleteLogGroup", "logs:ListTagsForResource"], Resource: [`${at("logs")}:log-group:/aws/lambda/${p}-*`, `${at("logs")}:log-group:/aws/codebuild/${p}-*`] }, @@ -253,8 +287,13 @@ export interface ParentInput { /** Child templates: name -> sha256 of the published file. */ childSha: Record; helperCode: string; + /** sha256 of the release's access.json (the access stack's template), when built. */ + accessSha?: string; } +/** The access stack's template in a release, next to coderhelm.json. */ +export const ACCESS_FILE = "access.json"; + export function childKey(version: string, name: string): { key: string; dest: string } { return { key: `stacks/${name}.json`, dest: `releases/${version}/stacks/${name}.json` }; } @@ -266,6 +305,8 @@ export function buildParent(input: ParentInput): Json { const files = [ ...children.map((c) => ({ Key: childKey(version, c.name).key, Dest: childKey(version, c.name).dest, Sha256: input.childSha[c.name] })), ...input.assets.map((a) => ({ Key: a.key, Dest: a.dest, Sha256: a.sha256 })), + // Published with the release and pinned here like every file (the updater checks it before it links to it). + ...(input.accessSha ? [{ Key: ACCESS_FILE, Dest: `releases/${version}/${ACCESS_FILE}`, Sha256: input.accessSha }] : []), ]; const root = { RootStackId: { Ref: "AWS::StackId" } }; const helper = { ServiceToken: { "Fn::GetAtt": ["Helper", "Arn"] }, ...root }; @@ -275,32 +316,11 @@ export function buildParent(input: ParentInput): Json { // that transform already resolved, so a later "use the current template" // update would silently keep every old parameter value (KeepDataOnDelete // included). Every policy in this template is a literal. - const boundaryDoc = subInstall(boundaryPolicy(n, [DEPLOY_BOUNDARY_ARN])); - R.Boundary = { - Type: "AWS::IAM::ManagedPolicy", - // Only roles the stack deletes carry it (the kept auto-update role has its own copy). - DeletionPolicy: "Delete", - UpdateReplacePolicy: "Retain", - Properties: { - ManagedPolicyName: sub(n.boundaryName), - Description: "CoderHelm: the most any CoderHelm role can do (docs/self-host/security.md)", - PolicyDocument: boundaryDoc, - }, - }; - // The same boundary for the auto-update role. That role is kept on delete, - // and IAM refuses to delete a policy a role still carries: kept with it, - // and both listed by the leftover check. - R.DeployBoundary = { - Type: "AWS::IAM::ManagedPolicy", - DeletionPolicy: "Retain", - UpdateReplacePolicy: "Retain", - Metadata: { "cfn-lint": { config: { ignore_checks: ["W3011"] } } }, - Properties: { - ManagedPolicyName: sub(DEPLOY_BOUNDARY_NAME), - Description: "CoderHelm: the auto-update role's boundary, the same as every CoderHelm role's (docs/self-host/security.md)", - PolicyDocument: boundaryDoc, - }, - }; + // The boundary (Boundary), the auto-update role's own copy (DeployBoundary, + // kept with that role on delete): pinned, see pinnedAccess(). + const pinned = pinnedAccess(); + R.Boundary = pinned.Boundary; + R.DeployBoundary = pinned.DeployBoundary; R.AssetsBucket = { Type: "AWS::S3::Bucket", Properties: { BucketName: sub(ASSETS_BUCKET_NAME), ...s3Secure, Tags: [{ Key: INSTALL_TAG, Value: sub("coderhelm-${Stage}") }] }, @@ -370,8 +390,9 @@ export function buildParent(input: ParentInput): Json { Role: { "Fn::GetAtt": ["HelperRole", "Arn"] }, LoggingConfig: { LogGroup: { Ref: "HelperLogs" } }, Code: { ZipFile: input.helperCode }, - // stage: the only bucket it copies a release's child templates to. - Environment: { Variables: { ASSETS_BUCKET: { Ref: "AssetsBucket" } } }, + // stage: the only bucket it copies a release's child templates to. stage_held: + // the stack whose own deploy role and boundaries it keeps (read, never taken from the caller). + Environment: { Variables: { ASSETS_BUCKET: { Ref: "AssetsBucket" }, ROOT_STACK: { Ref: "AWS::StackName" } } }, Tags: [{ Key: INSTALL_TAG, Value: sub("coderhelm-${Stage}") }], }, }; @@ -405,33 +426,9 @@ export function buildParent(input: ParentInput): Json { }, }; // On every install, whatever AutoUpdate says: an admin's Update in Settings, - // System applies through it too (AutoUpdate only schedules). Its - // Description stays as it was so an install that had it sees no change. - R.DeployRole = { - Type: "AWS::IAM::Role", - // A role can't delete itself, and CloudFormation keeps using a stack's - // role for later operations: kept on delete (the leftover check lists it). - DeletionPolicy: "Retain", - UpdateReplacePolicy: "Retain", - Metadata: { "cfn-lint": { config: { ignore_checks: ["W3037", "W3011"] } } }, - Properties: { - RoleName: sub(n.deployRoleName), - Description: "CoderHelm: applies a reviewed release's stack update when auto-update is on (docs/self-host/security.md)", - AssumeRolePolicyDocument: { - Version: "2012-10-17", - Statement: [{ - Effect: "Allow", Principal: { Service: "cloudformation.amazonaws.com" }, Action: "sts:AssumeRole", - Condition: { - StringEquals: { "aws:SourceAccount": { Ref: "AWS::AccountId" } }, - StringLike: { "aws:SourceArn": [{ "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}/*" }, { "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}-*/*" }] }, - }, - }], - }, - PermissionsBoundary: { Ref: "DeployBoundary" }, - Policies: [{ PolicyName: "deploy", PolicyDocument: subInstall(deployRolePolicy(n)) }], - Tags: [{ Key: INSTALL_TAG, Value: sub("coderhelm-${Stage}") }], - }, - }; + // System applies through it too (AutoUpdate only schedules). Kept on delete + // (a role can't delete itself). Pinned like the boundaries. + R.DeployRole = pinned.DeployRole; for (const c of children) { const params: Json = {}; diff --git a/infra/lib/updates-stack.ts b/infra/lib/updates-stack.ts index 164a2e86c..7d20d86e3 100644 --- a/infra/lib/updates-stack.ts +++ b/infra/lib/updates-stack.ts @@ -578,7 +578,12 @@ function nativeUpdates(scope: Construct, cfg: ResolvedConfig, fn: lambda.Functio actions: ["cloudformation:CreateChangeSet"], resources: [root], conditions: { - StringLike: { "cloudformation:TemplateUrl": [`${NATIVE_TEMPLATE_BASE}/v*.*.*/${NATIVE_TEMPLATE_FILE}`] }, + StringLike: { "cloudformation:TemplateUrl": [ + `${NATIVE_TEMPLATE_BASE}/v*.*.*/${NATIVE_TEMPLATE_FILE}`, + // The same release with the install's own Boundary, DeployBoundary and DeployRole kept (the helper + // writes it, checked against the verified template; lambda/updater "held"): an update never changes those. + `https://${cfg.prefix}-release-${stack.account}.s3.${stack.region}.${stack.urlSuffix}/releases/v*.*.*/held/${NATIVE_TEMPLATE_FILE}`, + ] }, // A role only the stack's own deploy role (none only on an older parent without it). StringEqualsIfExists: { "cloudformation:RoleArn": deployRole }, }, @@ -617,6 +622,23 @@ function nativeUpdates(scope: Construct, cfg: ResolvedConfig, fn: lambda.Functio // The parts' nested change sets too (each data change is checked before auto-update applies it). resources: [root, parts], })); + // A stack whose rollback failed (UPDATE_ROLLBACK_FAILED) can't be updated at + // all: the updater continues the rollback itself, skipping only resources + // it has checked are exactly as the rollback would leave them. + fn.addToRolePolicy(new iam.PolicyStatement({ + sid: "RecoverFailedRollback", + actions: ["cloudformation:ContinueUpdateRollback"], + resources: [root], + })); + // Read-only: what the deploy role may do (its policy and its boundary, as IAM + // has them now), so a prepared update that it couldn't apply is refused + // before it starts; and whether the boundaries are already the release's. + const iamArn = `arn:${stack.partition}:iam::${stack.account}`; + fn.addToRolePolicy(new iam.PolicyStatement({ + sid: "ReadDeployRoleAccess", + actions: ["iam:GetRole", "iam:GetRolePolicy", "iam:ListRolePolicies", "iam:ListAttachedRolePolicies", "iam:GetPolicy", "iam:GetPolicyVersion"], + resources: [deployRole, `${iamArn}:policy/${cfg.prefix}-boundary-stack`, `${iamArn}:policy/${cfg.prefix}-deploy-boundary-stack`], + })); fn.addToRolePolicy(new iam.PolicyStatement({ sid: "AutoUpdateThroughDeployRole", actions: ["iam:PassRole"], diff --git a/infra/test/native-access.test.ts b/infra/test/native-access.test.ts new file mode 100644 index 000000000..4f3b73dda --- /dev/null +++ b/infra/test/native-access.test.ts @@ -0,0 +1,160 @@ +// The deploy role's own access on a native install (infra/lib/native/parent.ts +// pinnedAccess, infra/lib/native/access-stack.ts, lambda/updater "held"). +// +// Every update runs as the parent's deploy role, and the boundary forbids that +// role to change itself or a boundary; an AWS admin's Execute in the console +// runs as that role too (the stack's service role). So: +// +// - the parent carries Boundary, DeployBoundary and DeployRole exactly as +// installs have them (v0.8.36 to v0.8.53), and a change to them fails here; +// - today's documents ship in access.json, which an AWS admin applies with +// their own permissions, and no CoderHelm role can reach its writer; +// - every call CloudFormation makes for a release through the deploy role +// (the simulator's table) is allowed under the pinned boundary too, so an +// update that keeps an install's older boundary still installs; +// - a change to today's boundary or deploy policy is flagged (ACCESS_DOCS): +// it reaches installs only through an admin, so it is a deliberate, +// batched decision. +// +// npm test + +import { test } from "node:test"; +import * as assert from "node:assert/strict"; +import * as crypto from "node:crypto"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { accessNames, boundaryPolicy, PolicyDocument } from "../lib/access"; +import { ACCESS_PARAMETERS, ACCESS_WRITER_NAME, buildAccess, writerPolicy } from "../lib/native/access-stack"; +import { buildNative } from "../lib/native/build"; +import { ACCESS_FILE, deployRolePolicy, nativeNames, pinnedAccess, subInstall } from "../lib/native/parent"; +import { sha256File } from "../lib/native/package"; +import { prodValues, resolveValue } from "../lib/native/resolve"; +import { decision } from "./iam-eval"; + +const STUBS = fs.mkdtempSync(path.join(os.tmpdir(), "chacc-")); +for (const d of ["gateway", "worker", "mcp"]) { + fs.mkdirSync(path.join(STUBS, d), { recursive: true }); + fs.writeFileSync(path.join(STUBS, d, d === "mcp" ? "handler.js" : "bootstrap"), "stub"); +} +const DASH = path.join(STUBS, "dash"); +fs.mkdirSync(DASH, { recursive: true }); +fs.writeFileSync(path.join(DASH, "index.html"), ""); +process.env.GATEWAY_ZIP = path.join(STUBS, "gateway"); +process.env.WORKER_ZIP = path.join(STUBS, "worker"); +process.env.MCP_PROXY_DIR = path.join(STUBS, "mcp"); +const OUT = fs.mkdtempSync(path.join(os.tmpdir(), "chaccrel-")); +const rel = buildNative("v9.8.7", OUT, { dashboardDir: DASH, commit: "0".repeat(40), releasedAt: "2026-11-08T00:00:00Z" }); +const R = rel.parent.Resources; +const ACCESS = JSON.parse(fs.readFileSync(path.join(OUT, ACCESS_FILE), "utf8")); + +const canon = (v: unknown) => JSON.stringify(v, (_k, x) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x)); +const sha = (v: unknown) => crypto.createHash("sha256").update(canon(v)).digest("hex"); + +/** + * Today's boundary and deploy role policy, as their sha256. A change here + * reaches no install by itself: an AWS admin applies it through the access + * stack (Settings, System, Permissions). Before changing these two values, + * batch it with whatever else needs the same admin step, and say so in the + * release notes; the dashboard then offers it as one optional item. + */ +const ACCESS_DOCS = { + boundary: "e336aa5d3446090ae84ae7b36ab55953455d662b997ab0947aabb5a091ec555e", + deployRole: "d11f40637e639812ba5408d153351341bc593cb604726f6cb4193861c2dd7b1f", +}; + +test("the parent carries the deploy role and both boundaries exactly as installs have them, so no update ever changes them", () => { + const pinned = pinnedAccess(); + for (const k of ["Boundary", "DeployBoundary", "DeployRole"] as const) assert.deepEqual(R[k], pinned[k], k); + // The pinned file is v0.8.36 to v0.8.53's: a change to it holds every install's next update. + const f = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "lib", "native", "access-pinned.json"), "utf8")); + assert.equal(sha(f.resources), "bf5ec8ae9432f9468256ff208b3b40e782742f25a36b57f935740d583ce32c78", "access-pinned.json changed: every install's next update would wait for an AWS admin"); +}); + +test("access.json is built, pinned by sha256 in the parent and published with the release", () => { + const files = R.ReleaseAssets.Properties.Files as { Key: string; Dest: string; Sha256: string }[]; + const f = files.find((x) => x.Key === ACCESS_FILE)!; + assert.ok(f, "access.json is in ReleaseAssets"); + assert.equal(f.Sha256, sha256File(path.join(OUT, ACCESS_FILE))); + assert.equal(f.Dest, "releases/v9.8.7/access.json"); + assert.ok(rel.files.includes(ACCESS_FILE)); +}); + +test("access.json writes today's boundary to both boundaries and today's deploy policy to the deploy role", () => { + const p = ACCESS.Resources.Access.Properties; + const n = nativeNames(); + const today = subInstall(boundaryPolicy(n, ["arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-deploy-boundary-stack"])); + assert.deepEqual(p.Boundary.Document, today); + assert.deepEqual(p.DeployBoundary.Document, today); + assert.deepEqual(p.Boundary.Arn, { "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-boundary-stack" }); + assert.deepEqual(p.DeployBoundary.Arn, { "Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-deploy-boundary-stack" }); + assert.deepEqual(p.DeployRole.Document, subInstall(deployRolePolicy(n))); + assert.deepEqual(p.DeployRole.RoleName, { "Fn::Sub": "coderhelm-${Stage}-deploy-stack" }); + // Every ${Name} the template uses is a parameter it declares (the Launch link fills them) or a pseudo parameter. + const used = new Set([...JSON.stringify(ACCESS).matchAll(/\$\{([A-Za-z]+)\}/g)].map((m) => m[1])); + for (const u of used) assert.ok(ACCESS_PARAMETERS.includes(u) || u === "EmailIdentity", u); + assert.deepEqual(Object.keys(ACCESS.Parameters).sort(), [...ACCESS_PARAMETERS].sort()); + // Its writer's code is in the signed template. + assert.match(ACCESS.Resources.Writer.Properties.Code.ZipFile, /def write_policy/); +}); + +test("today's boundary and deploy policy are the reviewed ones (a change is a deliberate, batched admin step)", () => { + const n = nativeNames(); + const now = { boundary: sha(subInstall(boundaryPolicy(n, ["arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-deploy-boundary-stack"]))), deployRole: sha(subInstall(deployRolePolicy(n))) }; + assert.deepEqual(now, ACCESS_DOCS, + "This changes the permissions boundary or the deploy role's policy. No update can apply that: installs get it only when an AWS admin " + + "applies the access stack (Settings, System, Permissions). Batch it with other such changes, then set ACCESS_DOCS in this test to the new values."); +}); + +/** A policy document for stage prod in the simulator fixture's account. */ +const F = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "test", "fixtures", "native-sim.json"), "utf8")); +function resolved(v: unknown): PolicyDocument { + const values: Record = { ...prodValues(F.account, F.region), EmailFrom: "owner@example.org" }; + return resolveValue(v as any, { values, conditions: { HasEmailFrom: true } }) as PolicyDocument; +} + +test("a release installs through the deploy role under the pinned boundary too: every call it may make today, it may make with the boundary installs have", () => { + const pinned = pinnedAccess(); + const boundary = resolved((pinned.Boundary as any).Properties.PolicyDocument); + const deploy = resolved((pinned.DeployRole as any).Properties.Policies[0].PolicyDocument); + assert.ok(!JSON.stringify([boundary, deploy]).includes("Fn::"), "fully resolved"); + const pairs = (F.rows as any[]).flatMap((r) => Object.entries(r.actions as Record).map(([action, verdict]) => ({ action, verdict, resource: r.resource, context: r.context }))); + const lost = pairs.filter((p) => p.verdict === "allowed" && decision([deploy], boundary, p) !== "allowed").map((p) => `${p.action} on ${p.resource}`); + assert.deepEqual(lost, [], "the deploy needs more than the pinned boundary allows: such a release can't install until an admin applies the access stack"); +}); + +test("no CoderHelm role can reach the access stack, its writer or the writer's role", () => { + const names = { ...accessNames({ account: "111122223333", region: "us-east-1", prefix: "coderhelm-prod", suffix: "-111122223333", secretName: "coderhelm/prod/secrets", id: "stack" }), emailIdentity: "owner@example.org" }; + const boundary = boundaryPolicy(names, ["arn:aws:iam::111122223333:policy/coderhelm-prod-deploy-boundary-stack"]); + const anything: PolicyDocument = { Version: "2012-10-17", Statement: [{ Sid: "All", Effect: "Allow", Action: "*", Resource: "*" }] }; + const writer = ACCESS_WRITER_NAME.replace("${Stage}", "prod"); + const calls: [string, string][] = [ + ["lambda:InvokeFunction", `arn:aws:lambda:us-east-1:111122223333:function:${writer}`], + ["lambda:UpdateFunctionCode", `arn:aws:lambda:us-east-1:111122223333:function:${writer}`], + ["iam:PassRole", `arn:aws:iam::111122223333:role/${writer}`], + ["iam:UpdateAssumeRolePolicy", `arn:aws:iam::111122223333:role/${writer}`], + ["iam:PutRolePolicy", `arn:aws:iam::111122223333:role/${writer}`], + ["cloudformation:CreateChangeSet", "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod-access/abc"], + ["cloudformation:ExecuteChangeSet", "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod-access/abc"], + ["cloudformation:UpdateStack", "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod-access/abc"], + ["cloudformation:DeleteStack", "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod-access/abc"], + ]; + for (const [action, resource] of calls) { + assert.notEqual(decision([anything], boundary, { action, resource, context: { "iam:PermissionsBoundary": names.boundaryArn } }), "allowed", `${action} on ${resource}`); + } + // The writer may write exactly the two boundaries and the deploy role's policy, nothing else. + const w = resolveValue(writerPolicy(), { values: prodValues("111122223333", "us-east-1") }) as PolicyDocument; + const can = (action: string, resource: string) => decision([w], null, { action, resource }) === "allowed"; + assert.ok(can("iam:CreatePolicyVersion", "arn:aws:iam::111122223333:policy/coderhelm-prod-boundary-stack")); + assert.ok(can("iam:CreatePolicyVersion", "arn:aws:iam::111122223333:policy/coderhelm-prod-deploy-boundary-stack")); + assert.ok(can("iam:PutRolePolicy", "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack")); + assert.ok(!can("iam:CreatePolicyVersion", "arn:aws:iam::111122223333:policy/coderhelm-prod-other")); + assert.ok(!can("iam:PutRolePolicy", "arn:aws:iam::111122223333:role/coderhelm-prod-gateway")); + assert.ok(!can("iam:CreateRole", "arn:aws:iam::111122223333:role/anything")); +}); + +test("the access stack has no service role and changes nothing on delete", () => { + assert.equal(ACCESS.RoleARN, undefined); + for (const r of Object.values(ACCESS.Resources)) assert.equal(r.DeletionPolicy, undefined); + assert.match(fs.readFileSync(path.join(__dirname, "..", "..", "..", "lambda", "native-access", "handler.py"), "utf8"), /On Delete it changes nothing/); +}); diff --git a/infra/test/native-sim.test.ts b/infra/test/native-sim.test.ts index 93251ac77..0b9e7cf64 100644 --- a/infra/test/native-sim.test.ts +++ b/infra/test/native-sim.test.ts @@ -15,7 +15,7 @@ import * as assert from "node:assert/strict"; import * as fs from "node:fs"; import * as path from "node:path"; import { accessNames, boundaryPolicy, PolicyDocument } from "../lib/access"; -import { deployRolePolicy, helperPolicy, nativeNames } from "../lib/native/parent"; +import { deployRolePolicy, helperPolicy, nativeNames, ROOT_TEMPLATE_SID } from "../lib/native/parent"; import { prodValues, resolveValue } from "../lib/native/resolve"; import { decision } from "./iam-eval"; @@ -70,7 +70,13 @@ test("the fixture is AWS's verdict on thousands of calls, for the native policie const t = today(); assert.deepEqual(F.policies.deploy, t.deploy, "the auto-update role changed: run deploy-role-sim.py --native again"); assert.deepEqual(F.policies.boundary, t.boundary, "the boundary changed: run deploy-role-sim.py --native again"); - assert.deepEqual(F.helper.policy, t.helper, "the helper's policy changed: run deploy-role-sim.py --native again"); + // The helper's one read of the root stack's template (stage_held) came after the simulator's last run: + // it is a single read-only GetTemplate on the root stack, checked here; everything else is what the simulator saw. + // Run deploy-role-sim.py --native again to fold it in. + const added = t.helper.Statement.filter((s) => s.Sid === ROOT_TEMPLATE_SID); + assert.deepEqual(added, [{ Sid: ROOT_TEMPLATE_SID, Effect: "Allow", Action: "cloudformation:GetTemplate", Resource: "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod/*" }]); + const seen = F.helper.policy.Statement.some((s: any) => s.Sid === ROOT_TEMPLATE_SID) ? t.helper : { ...t.helper, Statement: t.helper.Statement.filter((s) => s.Sid !== ROOT_TEMPLATE_SID) }; + assert.deepEqual(F.helper.policy, seen, "the helper's policy changed: run deploy-role-sim.py --native again"); }); test("the local evaluator gives the simulator's verdict on every call", () => { diff --git a/lambda/native-access/handler.py b/lambda/native-access/handler.py new file mode 100644 index 000000000..ccb95c966 --- /dev/null +++ b/lambda/native-access/handler.py @@ -0,0 +1,144 @@ +"""The access stack's one custom resource (infra/lib/native/access-stack.ts). + +A native install's parent stack runs every update as its deploy role, and +the boundary forbids that role to change itself or a boundary. So a newer +boundary or deploy policy reaches an install only through this stack: +coderhelm--access, created by an AWS admin from the release's +access.json with the admin's own permissions (the stack has no service +role, and no CoderHelm role may create, change or delete it: +TheAccessStackStays). + +On Create and Update it writes the documents the template gives it: + - each boundary (Boundary, DeployBoundary): a new default policy version + when the document differs (the oldest non-default version goes first + when IAM's five are used up); + - the deploy role's inline policy "deploy", when it differs. +On Delete it changes nothing: the documents stay as they are. + +Its code is inline in the signed access.json; its role is the only one that +may write these three documents, and it carries no CoderHelm boundary. +""" + +import json +import re +import urllib.request + +RESPONSE_URL_RE = re.compile(r"^https://cloudformation-custom-resource-response-[a-z0-9-]+\.s3(\.[a-z0-9-]+)?\.amazonaws\.com/") +LISTS = ("Action", "NotAction", "Resource", "NotResource") + +_iam = None + + +def iam(): + global _iam + if _iam is None: + import boto3 + _iam = boto3.client("iam") + return _iam + + +def canonical(doc): + """A policy document as IAM means it: one value or a list of one are the + same, and the order of actions or resources doesn't matter.""" + if isinstance(doc, str): + doc = json.loads(doc) + + def walk(v, key=None): + if isinstance(v, dict): + return {k: walk(x, k) for k, x in sorted(v.items())} + if isinstance(v, list): + items = [walk(x) for x in v] + if key in LISTS: + return sorted(items, key=lambda x: json.dumps(x, sort_keys=True)) + return items + if key in LISTS and isinstance(v, str): + return [v] + return v + + out = walk(doc) + if isinstance(out, dict): + sts = out.get("Statement") + out["Statement"] = sts if isinstance(sts, list) else ([sts] if sts else []) + for st in out["Statement"]: + for op in (st.get("Condition") or {}).values(): + for k, val in list(op.items()): + op[k] = sorted(val) if isinstance(val, list) else [val] + # The order of statements doesn't matter either. + out["Statement"] = sorted(out["Statement"], key=lambda x: json.dumps(x, sort_keys=True)) + return json.dumps(out, sort_keys=True, separators=(",", ":")) + + +def same(a, b): + return canonical(a) == canonical(b) + + +def write_policy(arn, doc, client=None): + """The policy's default version becomes `doc` (False when it already is).""" + c = client or iam() + current = c.get_policy(PolicyArn=arn)["Policy"]["DefaultVersionId"] + have = c.get_policy_version(PolicyArn=arn, VersionId=current)["PolicyVersion"]["Document"] + if same(have, doc): + return False + versions = c.list_policy_versions(PolicyArn=arn)["Versions"] + if len(versions) >= 5: + old = sorted((v for v in versions if not v.get("IsDefaultVersion")), key=lambda v: str(v.get("CreateDate"))) + c.delete_policy_version(PolicyArn=arn, VersionId=old[0]["VersionId"]) + c.create_policy_version(PolicyArn=arn, PolicyDocument=json.dumps(doc), SetAsDefault=True) + return True + + +def write_role_policy(role, name, doc, client=None): + c = client or iam() + try: + have = c.get_role_policy(RoleName=role, PolicyName=name)["PolicyDocument"] + except Exception as e: + if "NoSuchEntity" not in type(e).__name__ + str(e): + raise + have = None + if have is not None and same(have, doc): + return False + c.put_role_policy(RoleName=role, PolicyName=name, PolicyDocument=json.dumps(doc)) + return True + + +def apply(props, client=None): + """Writes what differs; returns the names written.""" + done = [] + for key in ("DeployBoundary", "Boundary"): + p = props.get(key) or {} + if p.get("Arn") and p.get("Document") and write_policy(p["Arn"], p["Document"], client): + done.append(key) + r = props.get("DeployRole") or {} + if r.get("RoleName") and r.get("Document") and write_role_policy(r["RoleName"], r.get("PolicyName") or "deploy", r["Document"], client): + done.append("DeployRole") + return done + + +def respond(event, status, reason="", data=None): + body = json.dumps({ + "Status": status, "Reason": (reason or status)[:3500], + "PhysicalResourceId": event.get("PhysicalResourceId") or "access", + "StackId": event["StackId"], "RequestId": event["RequestId"], + "LogicalResourceId": event["LogicalResourceId"], "Data": data or {}, + }).encode() + if not RESPONSE_URL_RE.match(str(event.get("ResponseURL", ""))): + print("not answering: the response URL is not CloudFormation's", flush=True) + return + req = urllib.request.Request(event["ResponseURL"], data=body, method="PUT", headers={"Content-Type": "", "Content-Length": str(len(body))}) + urllib.request.urlopen(req, timeout=30).read() + + +def handler(event, context=None): + status, reason, data = "SUCCESS", "", {} + try: + if event.get("RequestType") in ("Create", "Update"): + done = apply(event.get("ResourceProperties") or {}) + data = {"Written": ",".join(done) or "none"} + reason = "written: " + (", ".join(done) or "nothing (already as this release has them)") + else: + reason = "nothing changed: the documents stay as they are" + print(reason, flush=True) + except Exception as e: + status, reason = "FAILED", f"{type(e).__name__}: {e}" + print(reason, flush=True) + respond(event, status, reason, data) diff --git a/lambda/native-helper/handler.py b/lambda/native-helper/handler.py index 04db2ae2a..0d03d03be 100644 --- a/lambda/native-helper/handler.py +++ b/lambda/native-helper/handler.py @@ -52,6 +52,17 @@ release location, checks it against the sha256 (from the signed SHA256SUMS), and copies only the files that template lists, each checked. +{"action": "stage_held", "version", "template_sha256", "keep"} from the +updater: the same release's coderhelm.json with the install's own Boundary, +DeployBoundary and DeployRole definitions in place of the release's, written +to releases//held/. The helper reads those definitions itself from +the root stack's current template (cloudformation:GetTemplate): what the +updater sends as "keep" must be exactly that, or nothing is written, so a +caller can never put a role or a boundary of its own into the template. +An update runs as the deploy role, which may never change those three, so +the rest of the release installs while a newer boundary waits for an AWS +admin (the access stack). Nothing else of the verified template changes. + Delete-time work runs only when the ROOT stack is being deleted (or its first create is rolling back), never when an update removes or replaces one of these resources. Every step and every AWS error is printed (CloudWatch) and @@ -337,6 +348,89 @@ def stage_release(event, bucket, s3=None, opener=None): return {"ok": True, "version": version, "staged": int(data["Files"]), "copied": int(data["Copied"])} +HELD_RESOURCES = ("Boundary", "DeployBoundary", "DeployRole") + + +def canonical_sha(obj): + return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def held_template(release, keep): + """`release` with each of HELD_RESOURCES replaced by the install's own + definition (lambda/updater/handler.py has the same function). Only those + three, only of the same type, never one with a condition.""" + out = json.loads(json.dumps(release)) + res = out.get("Resources") or {} + for k, v in (keep or {}).items(): + if k not in HELD_RESOURCES: + raise ValueError(f"{k} is not a resource an update keeps") + if k not in res or not isinstance(v, dict) or v.get("Type") != res[k].get("Type") or "Condition" in v: + raise ValueError(f"the install's {k} can't be kept in this release") + res[k] = v + return out + + +def keep_for(release, deployed): + """The root stack's own definitions of HELD_RESOURCES that differ from the + release's (lambda/updater/handler.py has the same function).""" + rr = (release or {}).get("Resources") or {} + dr = (deployed or {}).get("Resources") or {} + keep = {} + for k in HELD_RESOURCES: + mine, theirs = dr.get(k), rr.get(k) + if not isinstance(mine, dict) or not isinstance(theirs, dict) or mine == theirs: + continue + if mine.get("Type") != theirs.get("Type") or "Condition" in mine: + continue + keep[k] = mine + return keep + + +def deployed_template(stack, cfn=None): + """The root stack's current template, as CloudFormation stored it.""" + if not stack: + raise ValueError("the helper doesn't know its root stack") + body = (cfn or client("cloudformation")).get_template(StackName=stack, TemplateStage="Original").get("TemplateBody") + if isinstance(body, str): + body = json.loads(body) + if not isinstance(body, dict) or not body.get("Resources"): + raise ValueError("the root stack's template couldn't be read") + return body + + +def stage_held(event, bucket, s3=None, opener=None, cfn=None, stack=None): + """The release's coderhelm.json, verified, with the root stack's own + access resources kept, written to releases//held/coderhelm.json. + The kept definitions come from the root stack itself, never the caller.""" + version = str(event.get("version") or "") + want = str(event.get("template_sha256") or "").lower() + if not VERSION_RE.match(version): + raise ValueError(f"not a release version: {version!r}") + if not SHA_RE.match(want): + raise ValueError("the template's sha256 is missing") + if not bucket: + raise ValueError("no assets bucket") + path = download_verified(release_url(f"https://{RELEASE_HOST}/launch/{version}", RELEASE_FILE), want, opener) + try: + with open(path, "rb") as fh: + release = json.load(fh) + finally: + os.unlink(path) + keep = keep_for(release, deployed_template(stack if stack is not None else os.environ.get("ROOT_STACK", ""), cfn)) + asked = event.get("keep") + if asked is not None and canonical_sha(asked) != canonical_sha(keep): + raise ValueError("the definitions to keep aren't the root stack's own: refused") + if not keep: + raise ValueError("this release doesn't change the install's deploy role or boundaries: nothing to keep") + held = held_template(release, keep) + body = json.dumps(held, sort_keys=True, separators=(",", ":")).encode() + sha = hashlib.sha256(body).hexdigest() + key = f"releases/{version}/held/{RELEASE_FILE}" + (s3 or client("s3")).put_object(Bucket=bucket, Key=key, Body=body, ChecksumSHA256=b64(sha), ContentType="application/json") + log("held template written:", key, sha) + return {"ok": True, "version": version, "key": key, "sha256": sha, "canonical": canonical_sha(held)} + + def delete_secret(secret_id, sm=None): """The install's secret, without the recovery window (CloudFormation's own delete does the same); one already gone is fine.""" @@ -873,14 +967,15 @@ def handle(event, context=None): def handler(event, context): - if event.get("action") == "stage": + if event.get("action") in ("stage", "stage_held"): # The updater, directly (CloudFormation's events have no "action"). try: - r = stage_release(event, os.environ.get("ASSETS_BUCKET", "")) + fn = stage_release if event["action"] == "stage" else stage_held + r = fn(event, os.environ.get("ASSETS_BUCKET", "")) except Exception as e: log("stage FAILED:", type(e).__name__, e) r = {"ok": False, "error": f"{type(e).__name__}: {e}"} - log("stage", json.dumps(r)) + log(event["action"], json.dumps(r)) return r if not RESPONSE_URL_RE.match(str(event.get("ResponseURL", ""))): # Only CloudFormation asks with its own presigned answer URL: anything else is not a stack, so nothing is done. diff --git a/lambda/tests/test_updater_access.py b/lambda/tests/test_updater_access.py new file mode 100644 index 000000000..37acfce5d --- /dev/null +++ b/lambda/tests/test_updater_access.py @@ -0,0 +1,594 @@ +"""A native install's deploy role and boundaries during updates. + +Every update runs as the parent stack's deploy role, and CloudFormation keeps +that service role for every operation on the stack, an AWS admin's Execute +in the console included. The boundary forbids that role to change itself or +a boundary. These tests pin what the updater does about it: + +- the incident: a change set that changes Boundary and DeployBoundary, + prepared with the deploy role, is refused by the preflight before it can + run (and it is never offered for an admin to execute); +- a release whose only admin-only parts are those installs the rest, with + the install's own copies kept (the helper writes the same "held" template + the updater expects); +- a release without such a change is prepared exactly as before; +- the newer permissions are a separate item: an AWS admin's access stack + writes them, and the item then reads as applied; +- a stack left in UPDATE_ROLLBACK_FAILED is rolled back the rest of the way, + skipping only resources checked to be as the rollback leaves them. + +Run: python3 -m unittest discover -s lambda/tests +""" + +import copy +import hashlib +import importlib.util +import io +import json +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import test_updater_native as base # noqa: E402 + +u = base.u +ROOT = pathlib.Path(__file__).resolve().parents[2] + + +def load(name, rel): + spec = importlib.util.spec_from_file_location(name, ROOT / rel) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +helper = load("native_helper_for_access", "lambda/native-helper/handler.py") +writer = load("native_access_writer", "lambda/native-access/handler.py") + +PINNED = json.loads((ROOT / "infra/lib/native/access-pinned.json").read_text())["resources"] +ACCOUNT, ROLE = "1", "arn:aws:iam::1:role/coderhelm-prod-deploy-stack" +BOUNDARY_ARN = "arn:aws:iam::1:policy/coderhelm-prod-boundary-stack" +DEPLOY_BOUNDARY_ARN = "arn:aws:iam::1:policy/coderhelm-prod-deploy-boundary-stack" +PARAMS = {"Stage": "prod", "AdminEmail": "owner@example.org", "EmailFrom": "", "StatusId": "", "KeepDataOnDelete": "true"} +CONDITIONS = {"HasEmailFrom": {"Fn::Not": [{"Fn::Equals": [{"Ref": "EmailFrom"}, ""]}]}} +VALUES = dict(PARAMS, **{"AWS::AccountId": ACCOUNT, "AWS::Partition": "aws", "AWS::Region": "us-east-1", + "AWS::StackName": "coderhelm-prod", "AWS::URLSuffix": "amazonaws.com"}) + + +def resolved(v): + return u.cfn_resolve(v, VALUES, CONDITIONS) + + +OLD_BOUNDARY = resolved(PINNED["Boundary"]["Properties"]["PolicyDocument"]) +OLD_DEPLOY = resolved(PINNED["DeployRole"]["Properties"]["Policies"][0]["PolicyDocument"]) + + +def newer(doc): + """The pinned boundary as v0.8.54 changed it: Airflow, ECS and ECR reads, and the log analyzer's tag.""" + d = copy.deepcopy(doc) + for s in d["Statement"]: + if s["Sid"] == "CoderHelmServices": + s["Action"] = s["Action"][:1] + ["airflow:Get*", "airflow:List*", "airflow:InvokeRestApi", "ecs:Describe*", "ecs:List*", + "ecr:BatchGetImage", "ecr:List*"] + s["Action"][1:] + if s["Sid"] == "ReadRolesHereOnlyGatewayAndWorker": + s["Sid"] = "ReadRolesHereOnlyCoderHelmRuntime" + s["Condition"]["StringNotEquals"]["aws:PrincipalTag/coderhelm:role"] = ["gateway", "worker", "log-analyzer"] + return d + + +def release_template(boundary_doc): + """A parent template with the three access resources (others as the base tests have them).""" + t = json.loads(base.TEMPLATE) + t["Conditions"] = CONDITIONS + t["Resources"] = copy.deepcopy(PINNED) + for k in ("Boundary", "DeployBoundary"): + t["Resources"][k]["Properties"]["PolicyDocument"] = boundary_doc + t["Resources"]["Api"] = {"Type": "AWS::CloudFormation::Stack", "Properties": {"TemplateURL": "x"}} + return t + + +class Stack(base.FakeCfn): + """The parent stack with its parameters' values, events and a deployed template.""" + + def __init__(self): + super().__init__() + self.deployed = {} + self.access_stack = None + + def describe_stacks(self, StackName): + if StackName.endswith("-access"): + if not self.access_stack: + raise Exception(f"Stack with id {StackName} does not exist") + return {"Stacks": [self.access_stack]} + return {"Stacks": [{"StackId": "arn:aws:cloudformation:us-east-1:1:stack/coderhelm-prod/abc", "StackName": "coderhelm-prod", + "StackStatus": self.stack_status, "RoleARN": ROLE, + "Parameters": [{"ParameterKey": k, "ParameterValue": v} for k, v in PARAMS.items()], + "Outputs": [{"OutputKey": "Version", "OutputValue": "v1.0.0"}]}]} + + +class HeldLambda(base.FakeLambda): + """The install helper: "stage" as before, "stage_held" through the helper's own code.""" + + def __init__(self, release_body, cfn): + super().__init__() + self.release_body = release_body + self.cfn = cfn + self.put = [] + + def invoke(self, FunctionName, InvocationType, Payload): + ev = json.loads(Payload) + self.calls.append((FunctionName, ev)) + if ev["action"] != "stage_held": + return {"Payload": io.BytesIO(json.dumps(self.answer).encode())} + body = self.release_body + + class S3: + def __init__(s): + s.objects = {} + + def put_object(s, **kw): + s.objects[kw["Key"]] = kw["Body"] + self.put.append(kw) + + def opener(req, timeout=0): + return io.BytesIO(body) + try: + r = helper.stage_held(ev, "coderhelm-prod-release-1", s3=S3(), opener=opener, cfn=self.cfn, stack="coderhelm-prod") + except ValueError as e: + r = {"ok": False, "error": str(e)} + return {"Payload": io.BytesIO(json.dumps(r).encode())} + + +class Base(unittest.TestCase): + def setUp(self): + self.store = u.Store(base.FakeDynamo(), "t") + self.cfn = Stack() + self.iam = base.FakeIam(deploy=OLD_DEPLOY, boundary=OLD_BOUNDARY, policies={BOUNDARY_ARN: OLD_BOUNDARY, DEPLOY_BOUNDARY_ARN: OLD_BOUNDARY}) + self.sent = [] + self._saved = (u.fetch_template, u.notify, dict(u._clients)) + u.notify = lambda *a, **k: self.sent.append(a) + u._clients.update({"cloudformation": self.cfn, "iam": self.iam}) + self.env = dict(base.ENV, DEPLOY_ROLE_ARN=ROLE) + + def tearDown(self): + u.fetch_template, u.notify = self._saved[0], self._saved[1] + u._clients.clear() + u._clients.update(self._saved[2]) + + def release(self, t): + body = json.dumps(t).encode() + self.store.put("MANIFEST#v1.1.0", {"verified": True, "manifest": None, "template_sha256": hashlib.sha256(body).hexdigest()}) + u.fetch_template = lambda url, opener=None: body + self.lam = HeldLambda(body, self.cfn) + u._clients["lambda"] = self.lam + return body + + +class TheIncident(Base): + """v0.8.54 on a live install: the change set changed Boundary and + DeployBoundary; an AWS admin executed it in the console; it ran as the + deploy role (the stack's RoleARN), was denied, and so was its rollback.""" + + def test_a_boundary_change_set_made_with_the_deploy_role_is_refused_before_anyone_can_run_it(self): + self.release(json.loads(base.TEMPLATE)) + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE", "Changes": [ + {"ResourceChange": {"Action": "Modify", "LogicalResourceId": "Boundary", "ResourceType": "AWS::IAM::ManagedPolicy", + "PhysicalResourceId": BOUNDARY_ARN, "Replacement": "False"}}, + {"ResourceChange": {"Action": "Modify", "LogicalResourceId": "DeployBoundary", "ResourceType": "AWS::IAM::ManagedPolicy", + "PhysicalResourceId": DEPLOY_BOUNDARY_ARN, "Replacement": "False"}}, + ]} + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["status"], "failed") + self.assertEqual(self.cfn.executed, [], "never executed") + self.assertEqual(self.cfn.deleted, ["arn:cs/1"], "and never left for someone to execute in the console") + h = self.store.history()[0] + # Exactly what AWS refused live, from the deploy role's own policies as IAM has them. + for call in (f"parent.Boundary: iam:CreatePolicyVersion on {BOUNDARY_ARN} (denied by TheBoundaryStays)", + f"parent.DeployBoundary: iam:CreatePolicyVersion on {DEPLOY_BOUNDARY_ARN} (denied by TheBoundaryStays)", + f"parent.Boundary: iam:DeletePolicyVersion on {BOUNDARY_ARN} (denied by TheBoundaryStays)"): + self.assertIn(call, h["technical"]) + self.assertIn("Permissions", h["fix"]) + status = u.handle({"action": "status"}, self.env, self.store, base.NOW, fetch=lambda repo: []) + self.assertIsNone(status["native"]["pending"]) + + def test_an_update_an_older_updater_left_waiting_for_an_aws_admin_ends_instead(self): + self.release(json.loads(base.TEMPLATE)) + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + hid = self.store.get("UPDATE_STATE")["running_id"] + # As an older updater left it: checked, waiting for review, admin_changes and no preflight. + e = self.store.get(hid) + e.update({"status": "review", "checked": True, "admin_changes": ["DeployBoundary (Modify)"], "data_changes": [], "permission_changes": []}) + e.pop("role_arn", None) + self.store.put(hid, e) + st = self.store.get("UPDATE_STATE") + st.pop("running_id", None) + st["review_id"] = hid + self.store.put("UPDATE_STATE", st) + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE"} + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["status"], "failed") + self.assertEqual(self.cfn.deleted, ["arn:cs/1"]) + self.assertEqual(self.cfn.executed, []) + + def test_the_preflight_lets_through_what_the_deploy_role_may_do(self): + self.release(json.loads(base.TEMPLATE)) + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update", consent=True) + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE", "Changes": [ + {"ResourceChange": {"Action": "Modify", "LogicalResourceId": "Api", "ResourceType": "AWS::CloudFormation::Stack", "ChangeSetId": "nested-api"}}]} + self.cfn.nested["nested-api"] = {"Changes": [{"ResourceChange": { + "Action": "Modify", "LogicalResourceId": "GatewayRole", "ResourceType": "AWS::IAM::Role", "PhysicalResourceId": "coderhelm-prod-gateway", + "AfterContext": json.dumps({"Properties": {"PermissionsBoundary": BOUNDARY_ARN}}), + "Details": [{"Target": {"Name": "Policies"}}, {"Target": {"Name": "Tags"}}]}}]} + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["native"], "executing") + self.assertEqual(self.store.get(self.store.get("UPDATE_STATE")["running_id"])["preflight"], []) + + def test_a_role_without_the_boundary_is_refused_by_the_preflight(self): + self.release(json.loads(base.TEMPLATE)) + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE", "Changes": [ + {"ResourceChange": {"Action": "Add", "LogicalResourceId": "Loose", "ResourceType": "AWS::IAM::Role", + "AfterContext": json.dumps({"Properties": {"RoleName": "coderhelm-prod-loose", "PermissionsBoundary": "arn:aws:iam::1:policy/other"}})}}]} + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["status"], "failed") + self.assertIn("iam:CreateRole on arn:aws:iam::1:role/coderhelm-prod-loose (denied by RolesOnlyWithTheBoundary)", self.store.history()[0]["technical"]) + + +class HeldAccess(Base): + def test_a_release_with_a_boundary_change_installs_the_rest_with_the_installs_own_kept(self): + new = release_template(newer(PINNED["Boundary"]["Properties"]["PolicyDocument"])) + self.release(new) + self.cfn.deployed = release_template(PINNED["Boundary"]["Properties"]["PolicyDocument"]) + e = u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.assertEqual(e["held"], ["Boundary", "DeployBoundary"]) + kw = self.cfn.created[0] + self.assertEqual(kw["TemplateURL"], "https://coderhelm-prod-release-1.s3.us-east-1.amazonaws.com/releases/v1.1.0/held/coderhelm.json") + self.assertEqual(kw["RoleARN"], ROLE) + # What the helper wrote is the release with only those two replaced by the install's own. + written = json.loads(self.lam.put[0]["Body"]) + self.assertEqual(written["Resources"]["Boundary"], self.cfn.deployed["Resources"]["Boundary"]) + self.assertEqual({k: v for k, v in written["Resources"].items() if k not in u.HELD}, + {k: v for k, v in new["Resources"].items() if k not in u.HELD}) + # CloudFormation fetched that template: it runs, the rest of the release installs. + self.cfn.fetched = written + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE"} + self.assertEqual(u.native_poll(self.store, self.env, base.NOW)["native"], "executing") + self.assertEqual(self.cfn.executed, ["arn:cs/1"]) + status = u.handle({"action": "status"}, self.env, self.store, base.NOW, fetch=lambda repo: []) + self.assertEqual(status["native"]["pending"]["held"], ["Boundary", "DeployBoundary"]) + + def test_a_release_without_a_boundary_change_is_prepared_as_before(self): + same = release_template(PINNED["Boundary"]["Properties"]["PolicyDocument"]) + self.release(same) + self.cfn.deployed = copy.deepcopy(same) + e = u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.assertEqual(e["held"], []) + self.assertEqual(self.cfn.created[0]["TemplateURL"], "https://coderhelm-public.s3.amazonaws.com/launch/v1.1.0/coderhelm.json") + self.assertEqual([c[1]["action"] for c in self.lam.calls], ["stage"]) + self.cfn.fetched = same + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE"} + self.assertEqual(u.native_poll(self.store, self.env, base.NOW)["native"], "executing") + + def test_a_held_template_that_isnt_the_one_expected_is_never_proposed(self): + new = release_template(newer(PINNED["Boundary"]["Properties"]["PolicyDocument"])) + self.release(new) + self.cfn.deployed = release_template(PINNED["Boundary"]["Properties"]["PolicyDocument"]) + self.lam.invoke = lambda **kw: {"Payload": io.BytesIO(json.dumps({"ok": True, "canonical": "0" * 64}).encode())} + with self.assertRaisesRegex(ValueError, "isn't the one the updater made"): + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.assertEqual(self.cfn.created, []) + + def test_the_helper_never_takes_what_to_keep_from_its_caller(self): + """A compromised updater role asks the helper to keep a deploy role of its own + (another name, trusted by anyone, Allow *): the helper reads the stack's own and refuses.""" + new = release_template(newer(PINNED["Boundary"]["Properties"]["PolicyDocument"])) + body = self.release(new) + self.cfn.deployed = release_template(PINNED["Boundary"]["Properties"]["PolicyDocument"]) + evil = copy.deepcopy(PINNED["DeployRole"]) + evil["Properties"]["RoleName"] = "coderhelm-prod-mine" + evil["Properties"]["AssumeRolePolicyDocument"]["Statement"][0]["Principal"] = {"AWS": "*"} + evil["Properties"]["Policies"] = [{"PolicyName": "all", "PolicyDocument": {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}}] + for keep in ({"DeployRole": evil}, dict(u.keep_for(new, self.cfn.deployed), DeployRole=evil), {}): + out = self.lam.invoke(FunctionName="h", InvocationType="RequestResponse", Payload=json.dumps( + {"action": "stage_held", "version": "v1.1.0", "template_sha256": hashlib.sha256(body).hexdigest(), "keep": keep}).encode()) + r = json.loads(out["Payload"].read()) + self.assertFalse(r["ok"]) + self.assertIn("aren't the root stack's own", r["error"]) + self.assertEqual(self.lam.put, [], "nothing written") + # Without a "keep" it uses the stack's own: never the caller's. + out = self.lam.invoke(FunctionName="h", InvocationType="RequestResponse", Payload=json.dumps( + {"action": "stage_held", "version": "v1.1.0", "template_sha256": hashlib.sha256(body).hexdigest()}).encode()) + written = json.loads(self.lam.put[0]["Body"]) + self.assertEqual(written["Resources"]["DeployRole"], PINNED["DeployRole"]) + self.assertEqual(written["Resources"]["Boundary"], self.cfn.deployed["Resources"]["Boundary"]) + + def test_the_helper_keeps_only_the_three_and_only_of_the_same_type(self): + t = release_template(PINNED["Boundary"]["Properties"]["PolicyDocument"]) + with self.assertRaisesRegex(ValueError, "not a resource an update keeps"): + helper.held_template(t, {"Api": {"Type": "AWS::CloudFormation::Stack"}}) + with self.assertRaisesRegex(ValueError, "can't be kept"): + helper.held_template(t, {"Boundary": {"Type": "AWS::IAM::Role"}}) + with self.assertRaisesRegex(ValueError, "can't be kept"): + helper.held_template(t, {"Boundary": dict(t["Resources"]["Boundary"], Condition="X")}) + + +class AccessItem(Base): + """The newer permissions: a separate, optional item an AWS admin applies.""" + + def access_json(self): + return { + "Parameters": {p: {"Type": "String"} for p in ("Stage", "AdminEmail", "EmailFrom", "StatusId")}, + "Conditions": CONDITIONS, + "Resources": {"Access": {"Type": "Custom::Access", "Properties": { + "Boundary": {"Arn": {"Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-boundary-stack"}, + "Document": newer(PINNED["Boundary"]["Properties"]["PolicyDocument"])}, + "DeployBoundary": {"Arn": {"Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/coderhelm-${Stage}-deploy-boundary-stack"}, + "Document": newer(PINNED["Boundary"]["Properties"]["PolicyDocument"])}, + "DeployRole": {"RoleName": {"Fn::Sub": "coderhelm-${Stage}-deploy-stack"}, "PolicyName": "deploy", + "Document": PINNED["DeployRole"]["Properties"]["Policies"][0]["PolicyDocument"]}, + }}}, + } + + def setUp(self): + super().setUp() + self.body = json.dumps(self.access_json()).encode() + self.cfn.deployed = {"Resources": {"ReleaseAssets": {"Properties": {"Files": [ + {"Key": "access.json", "Dest": "releases/v1.0.0/access.json", "Sha256": hashlib.sha256(self.body).hexdigest()}]}}}} + self.urls = [] + u.fetch_template = lambda url, opener=None: self.urls.append(url) or self.body + + def test_pending_names_the_change_in_plain_words_with_one_link(self): + v = u.access_compute(self.env) + self.assertEqual(v["state"], "pending") + self.assertEqual(v["resources"], ["Boundary", "DeployBoundary"]) + self.assertIn("adds read access to Airflow, ECR and ECS (airflow:Get*, airflow:List*, airflow:InvokeRestApi, ecs:Describe*, ecs:List*, ecr:BatchGetImage, ecr:List*)", v["summary"]) + self.assertIn("lets the log analyzer take on CoderHelm's read roles in this account, like the gateway and worker", v["summary"]) + self.assertEqual(self.urls, ["https://coderhelm-public.s3.amazonaws.com/launch/v1.0.0/access.json"]) + self.assertIn("#/stacks/quickcreate?stackName=coderhelm-prod-access&templateURL=https%3A%2F%2Fcoderhelm-public.s3.amazonaws.com%2Flaunch%2Fv1.0.0%2Faccess.json", v["link"]) + self.assertIn("param_Stage=prod", v["link"]) + self.assertIsNone(v["existing"]) + + def test_a_changed_access_json_is_never_linked(self): + self.body = self.body + b" " + self.assertEqual(u.access_compute(self.env)["state"], "unknown") + + def test_the_admins_access_stack_applies_it_cleanly_and_then_it_reads_applied(self): + # What CloudFormation hands the writer: the documents resolved. + props = resolved(self.access_json()["Resources"]["Access"]["Properties"]) + + class Iam(base.FakeIam): + def __init__(s, outer): + super().__init__(deploy=OLD_DEPLOY, boundary=OLD_BOUNDARY, policies=dict(outer.iam.policies)) + s.versions = {a: [{"VersionId": f"v{i}", "IsDefaultVersion": i == 5, "CreateDate": f"2026-11-0{i}"} for i in range(1, 6)] for a in s.policies} + s.deleted, s.created, s.put = [], [], [] + + def list_policy_versions(s, PolicyArn): + return {"Versions": s.versions[PolicyArn]} + + def delete_policy_version(s, PolicyArn, VersionId): + s.deleted.append((PolicyArn, VersionId)) + + def create_policy_version(s, PolicyArn, PolicyDocument, SetAsDefault): + assert SetAsDefault + s.created.append(PolicyArn) + s.policies[PolicyArn] = json.loads(PolicyDocument) + + def put_role_policy(s, RoleName, PolicyName, PolicyDocument): + s.put.append(RoleName) + + iam = Iam(self) + self.assertEqual(writer.apply(props, iam), ["DeployBoundary", "Boundary"]) + # IAM's five versions were used up: the oldest that isn't the default went first. + self.assertEqual(sorted(iam.deleted), [(BOUNDARY_ARN, "v1"), (DEPLOY_BOUNDARY_ARN, "v1")]) + self.assertEqual(iam.put, [], "the deploy policy was already this release's") + # Run again (a stack update with the same release): nothing to write. + self.assertEqual(writer.apply(props, iam), []) + u._clients["iam"] = iam + self.assertEqual(u.access_compute(self.env)["state"], "applied") + + def test_the_status_carries_it_and_reads_it_at_most_every_five_minutes(self): + u.handle({"action": "status"}, self.env, self.store, base.NOW, fetch=lambda repo: []) + u.handle({"action": "status"}, self.env, self.store, base.NOW, fetch=lambda repo: []) + st = u.handle({"action": "status"}, self.env, self.store, base.NOW, fetch=lambda repo: []) + self.assertEqual(st["native"]["access"]["state"], "pending") + self.assertEqual(len(self.urls), 1) + + +class StuckBase(Base): + def setUp(self): + super().setUp() + self.cfn.stack_status = "UPDATE_ROLLBACK_FAILED" + self.cfn.events = [ + {"LogicalResourceId": "DeployBoundary", "ResourceType": "AWS::IAM::ManagedPolicy", "ResourceStatus": "UPDATE_FAILED", + "ResourceStatusReason": "not authorized to perform: iam:CreatePolicyVersion ... explicit deny in a permissions boundary"}, + {"LogicalResourceId": "Boundary", "ResourceType": "AWS::IAM::ManagedPolicy", "ResourceStatus": "UPDATE_FAILED", + "ResourceStatusReason": "not authorized to perform: iam:DeletePolicyVersion ... explicit deny in a permissions boundary"}, + {"LogicalResourceId": "coderhelm-prod", "ResourceStatus": "UPDATE_ROLLBACK_IN_PROGRESS"}, + {"LogicalResourceId": "Boundary", "ResourceType": "AWS::IAM::ManagedPolicy", "ResourceStatus": "UPDATE_FAILED"}, + ] + old = release_template(PINNED["Boundary"]["Properties"]["PolicyDocument"]) + self.old_body = json.dumps(old).encode() + self.store.put("MANIFEST#v1.0.0", {"template_sha256": hashlib.sha256(self.old_body).hexdigest()}) + u.fetch_template = lambda url, opener=None: self.old_body + + + +class StuckRollback(StuckBase): + def test_it_continues_the_rollback_skipping_only_what_it_checked_unchanged(self): + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["native"], "recovering") + self.assertEqual(self.cfn.continued, [{"StackName": "coderhelm-prod", "ResourcesToSkip": ["DeployBoundary", "Boundary"], "RoleARN": ROLE}]) + rec = u.handle({"action": "status"}, self.env, self.store, base.NOW, fetch=lambda repo: [])["native"]["recovery"] + self.assertEqual(rec["status"], "continuing") + self.assertIn("each checked to be exactly as v1.0.0 has it", rec["reason"]) + self.cfn.stack_status = "UPDATE_ROLLBACK_COMPLETE" + u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(self.store.get("UPDATE_STATE")["recovery"]["status"], "recovered") + + def test_a_policy_that_differs_is_never_skipped(self): + self.iam.policies[BOUNDARY_ARN] = newer(OLD_BOUNDARY) + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["native"], "recovering") + self.assertEqual(r["recovery"]["status"], "stuck") + self.assertFalse(hasattr(self.cfn, "continued")) + self.assertIn("Boundary: its policy differs from the release it rolls back to", r["recovery"]["reason"]) + self.assertEqual(len(self.sent), 1) + u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(len(self.sent), 1, "told once") + + def test_an_update_while_stuck_is_refused_in_words(self): + self.release(json.loads(base.TEMPLATE)) + u.fetch_template = lambda url, opener=None: json.dumps(json.loads(base.TEMPLATE)).encode() + with self.assertRaisesRegex(ValueError, "still stuck"): + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + + def test_an_update_whose_rollback_stops_ends_rolled_back_once_recovered(self): + self.release(json.loads(base.TEMPLATE)) + self.cfn.stack_status = "UPDATE_COMPLETE" + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "EXECUTE_FAILED"} + self.cfn.stack_status = "UPDATE_ROLLBACK_FAILED" + u.fetch_template = lambda url, opener=None: self.old_body + self.store.put("UPDATE#0", {}) # unrelated history keeps working + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["native"], "recovering") + self.cfn.stack_status = "UPDATE_ROLLBACK_COMPLETE" + r = u.native_poll(self.store, self.env, base.NOW) + self.assertEqual(r["status"], "rolled_back") + h = [x for x in self.store.history() if x.get("version") == "v1.1.0"][0] + self.assertIn("AWS put everything back", h["summary"]) + + +class FailsClosed(Base): + """The preflight never lets an update start unchecked.""" + + def prepare(self, changes): + self.release(json.loads(base.TEMPLATE)) + u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update", consent=True) + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE", "Changes": changes} + return u.native_poll(self.store, self.env, base.NOW) + + def technical(self): + return self.store.history()[0]["technical"] + + def test_unreadable_policies_hold_it(self): + class Broken(base.FakeIam): + def get_role(self, RoleName): + raise Exception("AccessDenied: iam:GetRole") + u._clients["iam"] = Broken() + r = self.prepare([{"ResourceChange": {"Action": "Add", "LogicalResourceId": "Q", "ResourceType": "AWS::SQS::Queue"}}]) + self.assertEqual(r["status"], "failed") + self.assertIn("couldn't check: the deploy role's policies couldn't be read", self.technical()) + self.assertEqual(self.cfn.executed, []) + + def test_an_unknown_condition_operator_holds_it(self): + weird = copy.deepcopy(OLD_DEPLOY) + weird["Statement"].append({"Sid": "Odd", "Effect": "Deny", "Action": "iam:*", "Resource": "*", "Condition": {"NumericLessThan": {"aws:MultiFactorAuthAge": "1"}}}) + self.iam.deploy = weird + r = self.prepare([{"ResourceChange": {"Action": "Modify", "LogicalResourceId": "GatewayRole", "ResourceType": "AWS::IAM::Role", + "PhysicalResourceId": "coderhelm-prod-gateway", "Details": [{"Target": {"Name": "Tags"}}]}}]) + self.assertEqual(r["status"], "failed") + self.assertIn("couldn't check: the preflight can't evaluate the condition operator NumericLessThan", self.technical()) + + def test_a_deny_on_a_key_it_doesnt_supply_counts_as_applying(self): + d = copy.deepcopy(OLD_DEPLOY) + d["Statement"].append({"Sid": "NoTagsHere", "Effect": "Deny", "Action": "iam:TagRole", "Resource": "*", "Condition": {"StringEquals": {"aws:RequestTag/x": "y"}}}) + self.iam.deploy = d + r = self.prepare([{"ResourceChange": {"Action": "Modify", "LogicalResourceId": "GatewayRole", "ResourceType": "AWS::IAM::Role", + "PhysicalResourceId": "coderhelm-prod-gateway", "Details": [{"Target": {"Name": "Tags"}}]}}]) + self.assertEqual(r["status"], "failed") + self.assertIn("iam:TagRole on arn:aws:iam::1:role/coderhelm-prod-gateway (denied by NoTagsHere)", self.technical()) + + def test_an_older_entry_that_couldnt_be_checked_is_never_run(self): + self.assertIn("couldn't check", u.never_runs({"role_arn": ROLE, "preflight": None})) + + def test_replacements_attachments_inline_policies_passrole_and_unnamed_adds_are_checked(self): + arn = "arn:aws:iam::1" + calls = lambda rc: [(a, r) for a, r, _ in u.iam_calls(rc, "1", "aws", f"{arn}:policy/coderhelm-prod-boundary-stack", "coderhelm-prod")] + self.assertEqual(calls({"Action": "Modify", "Replacement": "True", "LogicalResourceId": "R", "ResourceType": "AWS::IAM::Role", "PhysicalResourceId": "coderhelm-prod-old", + "AfterContext": json.dumps({"Properties": {"RoleName": "coderhelm-prod-new"}})})[:2], + [("iam:CreateRole", f"{arn}:role/coderhelm-prod-new"), ("iam:DeleteRole", f"{arn}:role/coderhelm-prod-old")]) + self.assertIn(("iam:DeletePolicy", f"{arn}:policy/coderhelm-prod-old"), calls({"Action": "Modify", "Replacement": "True", "LogicalResourceId": "P", "ResourceType": "AWS::IAM::ManagedPolicy", + "PhysicalResourceId": f"{arn}:policy/coderhelm-prod-old", "AfterContext": json.dumps({"Properties": {"ManagedPolicyName": "coderhelm-prod-new"}})})) + self.assertIn(("iam:AttachRolePolicy", f"{arn}:role/coderhelm-prod-gateway"), calls({"Action": "Add", "LogicalResourceId": "P", "ResourceType": "AWS::IAM::ManagedPolicy", + "AfterContext": json.dumps({"Properties": {"Roles": ["coderhelm-prod-gateway"]}})})) + self.assertEqual(calls({"Action": "Add", "LogicalResourceId": "P", "ResourceType": "AWS::IAM::RolePolicy", "AfterContext": json.dumps({"Properties": {"RoleName": "coderhelm-prod-x"}})}), + [("iam:PutRolePolicy", f"{arn}:role/coderhelm-prod-x")]) + self.assertIn(("iam:PassRole", f"{arn}:role/coderhelm-prod-fn"), calls({"Action": "Add", "LogicalResourceId": "F", "ResourceType": "AWS::Lambda::Function", + "AfterContext": json.dumps({"Properties": {"Role": f"{arn}:role/coderhelm-prod-fn"}})})) + self.assertEqual(calls({"Action": "Add", "LogicalResourceId": "Anon", "ResourceType": "AWS::IAM::Role", "AfterContext": "{}"}), [("iam:CreateRole", f"{arn}:role/coderhelm-prod-Anon-GENERATED")]) + + def test_statement_order_is_not_a_change(self): + a = {"Version": "2012-10-17", "Statement": [{"Sid": "A", "Effect": "Allow", "Action": "s3:Get*", "Resource": "*"}, {"Sid": "B", "Effect": "Deny", "Action": ["iam:*"], "Resource": "*"}]} + b = {"Version": "2012-10-17", "Statement": list(reversed(a["Statement"]))} + self.assertTrue(u.same_policy(a, b)) + self.assertTrue(writer.same(a, b)) + + +class RecoveryChecks(StuckBase): + def test_a_role_is_compared_whole(self): + old = release_template(PINNED["Boundary"]["Properties"]["PolicyDocument"]) + values = dict(VALUES) + + class Iam(base.FakeIam): + def __init__(s, trust): + super().__init__(deploy=OLD_DEPLOY, boundary=OLD_BOUNDARY, policies={DEPLOY_BOUNDARY_ARN: OLD_BOUNDARY}) + s.trust = trust + + def get_role(s, RoleName): + return {"Role": {"RoleName": RoleName, "AssumeRolePolicyDocument": s.trust, + "PermissionsBoundary": {"PermissionsBoundaryArn": DEPLOY_BOUNDARY_ARN}, + "Tags": [{"Key": "coderhelm:install", "Value": "coderhelm-prod"}]}} + trust = resolved(PINNED["DeployRole"]["Properties"]["AssumeRolePolicyDocument"]) + self.assertEqual(u.unchanged_by_rollback("DeployRole", "AWS::IAM::Role", old, values, Iam(trust)), "") + anyone = copy.deepcopy(trust) + anyone["Statement"][0]["Principal"] = {"AWS": "*"} + self.assertEqual(u.unchanged_by_rollback("DeployRole", "AWS::IAM::Role", old, values, Iam(anyone)), + "its trust policy differs from the release it rolls back to") + self.assertIn("isn't one CoderHelm checks", u.unchanged_by_rollback("Api", "AWS::CloudFormation::Stack", old, values, Iam(trust))) + + def test_an_unverified_target_is_never_compared(self): + self.store.put("MANIFEST#v1.0.0", {}) + r = u.recover_stuck(self.store, self.env, base.NOW) + self.assertEqual(r["status"], "stuck") + self.assertIn("isn't verified on this install", r["reason"]) + self.assertFalse(hasattr(self.cfn, "continued")) + + def test_a_refused_continue_is_recorded_counted_and_told_at_the_last_try(self): + def refuse(**kw): + raise Exception("ValidationError: throttled") + self.cfn.continue_update_rollback = refuse + for n in (1, 2): + r = u.recover_stuck(self.store, self.env, base.NOW) + self.assertEqual((r["status"], r["tries"]), ("retrying", n)) + self.assertIn("throttled", r["error"]) + self.assertEqual(self.sent, []) + r = u.recover_stuck(self.store, self.env, base.NOW) + self.assertEqual((r["status"], r["tries"]), ("stuck", 3)) + self.assertEqual(len(self.sent), 1) + + def test_every_page_of_events_is_read(self): + events = self.cfn.events + pages = [events[:1], events[1:]] + + def page(StackName, NextToken=None): + i = int(NextToken or 0) + return dict({"StackEvents": pages[i]}, **({"NextToken": "1"} if i == 0 else {})) + self.cfn.describe_stack_events = page + self.assertEqual([f[0] for f in u.rollback_failures(self.cfn, "coderhelm-prod")], ["DeployBoundary", "Boundary"]) + + def test_a_held_update_rolls_back_to_the_installs_own_boundaries(self): + # The install ran v1.0.0 with the newer boundary kept (held): that is what the rollback restores. + mine = release_template(newer(PINNED["Boundary"]["Properties"]["PolicyDocument"]))["Resources"] + self.iam.policies[BOUNDARY_ARN] = newer(OLD_BOUNDARY) + self.iam.policies[DEPLOY_BOUNDARY_ARN] = newer(OLD_BOUNDARY) + self.store.put("UPDATE#2026-10-31T11:00:00Z#a", {"version": "v1.1.0", "from_version": "v1.0.0", "executed_at": "2026-10-31T11:00:00Z", + "deployed_access": {k: mine[k] for k in u.HELD}}) + r = u.recover_stuck(self.store, self.env, base.NOW) + self.assertEqual(r["status"], "continuing") + + +if __name__ == "__main__": + unittest.main() diff --git a/lambda/tests/test_updater_native.py b/lambda/tests/test_updater_native.py index ae28d2907..56a6ce116 100644 --- a/lambda/tests/test_updater_native.py +++ b/lambda/tests/test_updater_native.py @@ -90,8 +90,12 @@ def create_change_set(self, **kw): self.log.append("change set") return {"Id": "arn:cs/1"} - def get_template(self, StackName, ChangeSetName, TemplateStage): - return {"TemplateBody": self.fetched} + def get_template(self, StackName, ChangeSetName=None, TemplateStage="Original"): + # A change set's template (what CloudFormation fetched), or the stack's own. + return {"TemplateBody": self.fetched if ChangeSetName else getattr(self, "deployed", {})} + + def continue_update_rollback(self, **kw): + self.continued = getattr(self, "continued", []) + [kw] def delete_change_set(self, ChangeSetName, StackName): self.deleted.append(ChangeSetName) @@ -120,6 +124,45 @@ def describe_stack_events(self, StackName): return {"StackEvents": self.events} +class FakeIam: + """The deploy role as IAM has it: its inline policies and its boundary.""" + + def __init__(self, deploy=None, boundary=None, policies=None): + self.deploy = deploy or {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]} + self.boundary = boundary + # Managed policies by ARN (the boundaries), as their default version. + self.policies = dict(policies or {}) + self.role_policies = {} + + def get_role(self, RoleName): + r = {"RoleName": RoleName} + if self.boundary is not None: + r["PermissionsBoundary"] = {"PermissionsBoundaryArn": "arn:aws:iam::1:policy/coderhelm-prod-deploy-boundary-stack"} + self.policies.setdefault("arn:aws:iam::1:policy/coderhelm-prod-deploy-boundary-stack", self.boundary) + return {"Role": r} + + def list_role_policies(self, RoleName): + return {"PolicyNames": ["deploy"]} + + def get_role_policy(self, RoleName, PolicyName): + return {"PolicyDocument": self.role_policies.get((RoleName, PolicyName), self.deploy)} + + def list_attached_role_policies(self, RoleName): + return {"AttachedPolicies": []} + + def get_policy(self, PolicyArn): + if PolicyArn not in self.policies: + raise Exception(f"NoSuchEntity: {PolicyArn}") + return {"Policy": {"DefaultVersionId": "v1"}} + + def get_policy_version(self, PolicyArn, VersionId): + return {"PolicyVersion": {"Document": self.policies[PolicyArn]}} + + +# Every test that doesn't set its own: a deploy role that may do anything. +u._clients["iam"] = FakeIam() + + class FakeCodeBuild: """CodeBuild's own record of each release check build.""" @@ -698,7 +741,9 @@ def ok(env, payload): class AdminOnlyChanges(unittest.TestCase): """The auto-update role can't change itself or a boundary (the boundary - refuses it): such a change set waits for an admin instead of failing.""" + refuses it), and a change set made with it runs as it whoever executes it + (the stack's service role): such a change set is never offered to anyone, + it ends before it starts.""" def setUp(self): self.store = u.Store(FakeDynamo(), "t") @@ -723,8 +768,12 @@ def test_a_change_to_the_deploy_role_or_a_boundary_is_held_for_an_admin(self): {"ResourceChange": {"Action": "Add", "LogicalResourceId": "DeployBoundary", "ResourceType": "AWS::IAM::ManagedPolicy"}}, ]} r = u.native_poll(self.store, env, NOW) - self.assertEqual(r["native"], "review") + self.assertEqual(r["status"], "failed") self.assertEqual(self.cfn.executed, []) + self.assertEqual(self.cfn.deleted, ["arn:cs/1"]) + h = self.store.history()[0] + self.assertIn("update role doesn't have", h["summary"]) + self.assertIn("DeployBoundary", h["technical"]) def test_admin_changes_names_only_those(self): cs = {"Changes": [{"ResourceChange": {"Action": "Modify", "LogicalResourceId": "Boundary"}}, @@ -899,9 +948,9 @@ def test_the_press_never_agrees_to_data_changes(self): def test_the_press_never_agrees_to_a_role_or_boundary_change(self): r = self.prepare(parent=[{"ResourceChange": {"Action": "Modify", "LogicalResourceId": "DeployBoundary", "ResourceType": "AWS::IAM::ManagedPolicy"}}], consent=True) - self.assertEqual(r["native"], "review") + self.assertEqual(r["status"], "failed") self.assertEqual(self.cfn.executed, []) - self.assertFalse(self.pending()["can_apply"]) + self.assertIsNone(self.pending()) def test_the_window_never_carries_a_press_consent(self): self.store.put("AUTO_UPDATE", {"auto": True}) @@ -936,15 +985,14 @@ def test_a_confirmation_for_another_prepared_update_is_refused(self): self.apply(confirm=other) self.assertEqual(self.cfn.executed, []) - def test_a_change_to_the_role_or_a_boundary_is_never_applied_here(self): + def test_a_change_to_the_role_or_a_boundary_is_never_applied_or_offered(self): r = self.prepare(parent=[{"ResourceChange": {"Action": "Modify", "LogicalResourceId": "DeployBoundary", "ResourceType": "AWS::IAM::ManagedPolicy"}}]) - self.assertEqual(r["native"], "review") - p = self.pending() - self.assertFalse(p["can_apply"]) - self.assertIn("DeployBoundary", p["admin_changes"][0]) - self.assertIn("AWS console", self.sent[-1]) - with self.assertRaisesRegex(ValueError, "can't apply for you"): - self.apply(confirm=p["confirm"]) + self.assertEqual(r["status"], "failed") + self.assertIsNone(self.pending()) + # Nobody is sent to the AWS console to execute it: it would run as the deploy role there too. + self.assertFalse(any("choose Execute" in m for m in self.sent)) + with self.assertRaisesRegex(ValueError, "no prepared update"): + self.apply() self.assertEqual(self.cfn.executed, []) def test_a_change_set_prepared_with_the_role_applies(self): diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 78bddb63d..08c0cc174 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -731,6 +731,7 @@ def relay_credentials(env): "domain_failed": "the address change failed", "domain_removed": "back on the AWS address", "review": "update to {version} needs your OK", + "stuck": "the last update couldn't be rolled back", "digest": "what's new, up to {version}", } # The relay refuses an email whose text reads as CoderHelm staff speaking @@ -2165,6 +2166,12 @@ def native_propose(store, env, version, mode, extra=None, cfn=None, opener=None) # fetched could never be compared with what was verified. raise ValueError(f"{version}'s stack template uses a transform, which the updater can't check after CloudFormation reads it; update it in the console with a change set") stack = cfn.describe_stacks(StackName=env["NATIVE_STACK"])["Stacks"][0] + st = stack.get("StackStatus") or "" + if st == STUCK: + raise ValueError("the install's stack is still stuck after an earlier update's rollback stopped; CoderHelm finishes " + "that rollback by itself (Settings, System says how far it is), then press Update again") + if st.endswith("_IN_PROGRESS"): + raise ValueError(f"AWS is still working on the install's stack ({st}); press Update again once it has finished") overrides = {} if mode == "domain" and extra: attach = extra.get("DOMAIN_ACTION") != "remove" @@ -2193,10 +2200,820 @@ def native_propose(store, env, version, mode, extra=None, cfn=None, opener=None) # nested change sets: the helper copies them into the install's bucket # first, each checked against this verified template. stage_release(env, version, want) + proposed, held, deployed_access = template, [], {} + if role: + # The update runs as the deploy role, which may never change itself or + # a boundary: the install's own copies of those stay as they are, and + # a newer one waits as a separate item for an AWS admin (access). + deployed = deployed_template(cfn, env["NATIVE_STACK"]) + # What a rollback of this update restores (recover_stuck compares with it). + deployed_access = {k: v for k, v in (deployed.get("Resources") or {}).items() if k in HELD} + keep = keep_for(template, deployed) + if keep: + proposed = held_template(template, keep) + r = stage_held(env, version, want, keep) + if r.get("canonical") != canonical_sha(proposed): + raise ValueError(f"{version}'s template with the install's own permissions kept isn't the one the updater made, so it was not proposed") + kwargs["TemplateURL"] = held_url(env, stack, version) + held = sorted(keep) r = cfn.create_change_set(**kwargs) # DescribeChangeSet never returns the role a change set was made with, so # the entry records it: apply checks it against the deploy role. - return {"change_set_id": r["Id"], "apply": bool(role), "role_arn": role, "template_canonical": canonical_sha(template)} + return {"change_set_id": r["Id"], "apply": bool(role), "role_arn": role, "template_canonical": canonical_sha(proposed), "held": held, + "deployed_access": deployed_access} + + +# ── The deploy role's own access ────────────────────────────────────────── +# +# Every update runs as the parent stack's deploy role. CloudFormation keeps +# a stack's service role for every later operation, so even an AWS admin who +# executes a change set in the console runs it as that role. The boundary +# forbids that role to change itself or a boundary (TheBoundaryStays, +# TheDeployRoleStays): a change set that touches them can never succeed, and +# its rollback fails the same way (UPDATE_ROLLBACK_FAILED). So: +# +# - held: every update keeps the install's own Boundary, DeployBoundary and +# DeployRole (the helper writes the verified release with those three +# replaced; nothing else differs), and the rest of the release installs. +# - preflight: before a prepared update runs, each IAM call its changes need +# is evaluated against the deploy role's policies and boundary as IAM has +# them now; one it would be refused ends the update before it starts. +# - access: a newer boundary or deploy policy is a separate, optional item an +# AWS admin applies with their own permissions, through the access stack +# (the release's access.json; infra/lib/native/access-stack.ts). +# - recovery: a stack left in UPDATE_ROLLBACK_FAILED is rolled back the rest +# of the way, skipping only resources checked to be exactly as the rollback +# would leave them. + +HELD = ("Boundary", "DeployBoundary", "DeployRole") +HELD_FILE = "held/coderhelm.json" +ACCESS_FILE = "access.json" +ACCESS_CACHE_SECONDS = 300 + + +def held_template(release, keep): + """`release` with each of HELD replaced by the install's own definition + (lambda/native-helper/handler.py has the same function).""" + out = json.loads(json.dumps(release)) + res = out.get("Resources") or {} + for k, v in (keep or {}).items(): + if k not in HELD: + raise ValueError(f"{k} is not a resource an update keeps") + if k not in res or not isinstance(v, dict) or v.get("Type") != res[k].get("Type") or "Condition" in v: + raise ValueError(f"the install's {k} can't be kept in this release") + res[k] = v + return out + + +def keep_for(release, deployed): + """The install's own definitions of HELD that differ from the release's: + what an update keeps (an update can never change them).""" + rr = (release or {}).get("Resources") or {} + dr = (deployed or {}).get("Resources") or {} + keep = {} + for k in HELD: + mine, theirs = dr.get(k), rr.get(k) + if not isinstance(mine, dict) or not isinstance(theirs, dict) or mine == theirs: + continue + if mine.get("Type") != theirs.get("Type") or "Condition" in mine: + continue # can't be kept: preflight says what it would need + keep[k] = mine + return keep + + +def deployed_template(cfn, stack_name): + """The stack's current template, as CloudFormation stored it ({} when unreadable).""" + body = cfn.get_template(StackName=stack_name, TemplateStage="Original").get("TemplateBody") + if isinstance(body, str): + try: + body = json.loads(body) + except ValueError: + return {} + return body if isinstance(body, dict) else {} + + +def stack_account(stack): + parts = str(stack.get("StackId") or "").split(":") + return parts[4] if len(parts) > 5 else "" + + +def stack_partition(stack): + parts = str(stack.get("StackId") or "").split(":") + return parts[1] if len(parts) > 5 else "aws" + + +def held_url(env, stack, version): + prefix = env.get("RESOURCE_PREFIX") or env["NATIVE_STACK"] + region = env.get("AWS_REGION") or "" + return f"https://{prefix}-release-{stack_account(stack)}.s3.{region}.amazonaws.com/releases/{version}/{HELD_FILE}" + + +def stage_held(env, version, template_sha256, keep, lam=None): + """Asks the install's helper ("stage_held") to write the verified release + with `keep` in place; returns its answer ({key, sha256, canonical}).""" + fn = env.get("NATIVE_HELPER_FUNCTION") or "" + if not fn: + raise ValueError("this install has no helper to stage the release's files") + out = (lam or client("lambda")).invoke( + FunctionName=fn, InvocationType="RequestResponse", + Payload=json.dumps({"action": "stage_held", "version": version, "template_sha256": template_sha256, "keep": keep}).encode(), + ) + raw = out["Payload"].read() or b"{}" + try: + r = json.loads(raw) + except ValueError: + r = {} + if out.get("FunctionError") or not r.get("ok"): + err = r.get("error") or raw[:300] + if "unknown resource type" in str(err) or "response URL" in str(err) or r == {}: + # A helper from before "stage_held" (it answers only "stage"). + raise ValueError(f"{version} changes the deploy role or its boundary, and this install's helper can't keep them yet; " + "update to the release before it first, or apply the permission change in Settings, System") + raise ValueError(f"{version}'s template couldn't be staged with the install's own permissions kept: {err!r}") + return r + + +def policy_doc(raw): + """A policy document as a dict (IAM returns it URL-encoded, boto3 decoded).""" + if isinstance(raw, str): + from urllib.parse import unquote + try: + return json.loads(raw) + except ValueError: + return json.loads(unquote(raw)) + return raw or {} + + +_LISTS = ("Action", "NotAction", "Resource", "NotResource") + + +def canonical_policy(doc): + """A policy as IAM means it: one value or a list of one are the same, and + the order of actions, resources and condition values doesn't matter + (lambda/native-access/handler.py has the same).""" + doc = policy_doc(doc) + + def walk(v, key=None): + if isinstance(v, dict): + return {k: walk(x, k) for k, x in sorted(v.items())} + if isinstance(v, list): + items = [walk(x) for x in v] + return sorted(items, key=lambda x: json.dumps(x, sort_keys=True)) if key in _LISTS else items + if key in _LISTS and isinstance(v, str): + return [v] + return v + + out = walk(doc) + if isinstance(out, dict): + out["Statement"] = _as_list(out.get("Statement")) + for st in out["Statement"]: + for op in (st.get("Condition") or {}).values(): + for k, val in list(op.items()): + op[k] = sorted(val) if isinstance(val, list) else [val] + # The order of statements doesn't matter either. + out["Statement"] = sorted(out["Statement"], key=lambda x: json.dumps(x, sort_keys=True)) + return json.dumps(out, sort_keys=True, separators=(",", ":")) + + +def same_policy(a, b): + return canonical_policy(a) == canonical_policy(b) + + +# A small IAM evaluator: identity policies AND the permissions boundary, +# explicit denies first (infra/test/iam-eval.ts is the same, checked against +# AWS's policy simulator). + +def _iam_glob(pattern, value, ci=False): + rx = "^" + ".*".join(".".join(re.escape(q) for q in p.split("?")) for p in str(pattern).split("*")) + "$" + return re.match(rx, str(value), re.I if ci else 0) is not None + + +def _as_list(v): + return [] if v is None else (v if isinstance(v, list) else [v]) + + +POSITIVE_OPS = ("StringEquals", "StringEqualsIgnoreCase", "StringLike", "ArnEquals", "ArnLike", "Bool", + "ForAnyValue:StringEquals", "ForAnyValue:StringEqualsIgnoreCase", "ForAnyValue:StringLike") + + +def _condition_holds(cond, ctx, deny=False): + """Whether a statement's condition holds for the request. Fails closed: + an operator it doesn't know raises; a Deny whose positive operator names a + key the request doesn't carry counts as applying (it may well apply in + AWS), while an Allow with such a key doesn't.""" + for op, kv in (cond or {}).items(): + for key, want in kv.items(): + have = ctx.get(key) + if have is None: + have = next((v for k, v in ctx.items() if k.lower() == key.lower()), None) + wants, haves = _as_list(want), _as_list(have) + + def any_(f): + return any(f(h, w) for h in haves for w in wants) + base = op[:-len("IfExists")] if op.endswith("IfExists") else op + if op.endswith("IfExists") and have is None: + continue + if have is None and base in POSITIVE_OPS: + if deny: + continue # unknown here: a deny counts as applying + return False + if base in ("StringEquals", "ArnEquals", "ForAnyValue:StringEquals"): + ok = any_(lambda h, w: h == w) + elif base in ("StringEqualsIgnoreCase", "ForAnyValue:StringEqualsIgnoreCase"): + ok = any_(lambda h, w: h.lower() == w.lower()) + elif base in ("StringNotEquals", "ArnNotEquals"): + ok = have is None or not any_(lambda h, w: h == w) + elif base in ("StringLike", "ArnLike", "ForAnyValue:StringLike"): + ok = any_(lambda h, w: _iam_glob(w, h)) + elif base in ("StringNotLike", "ArnNotLike"): + ok = have is None or not any_(lambda h, w: _iam_glob(w, h)) + elif base == "ForAllValues:StringEquals": + ok = all(h in wants for h in haves) + elif base == "ForAllValues:StringLike": + ok = all(any(_iam_glob(w, h) for w in wants) for h in haves) + elif base == "Null": + ok = (have is None) == (str(wants[0]).lower() == "true") + elif base == "Bool": + ok = any_(lambda h, w: str(h).lower() == str(w).lower()) + else: + raise ValueError(f"the preflight can't evaluate the condition operator {op}") + if not ok: + return False + return True + + +def _statement_matches(s, action, resource, ctx): + if "Action" in s: + hit = any(_iam_glob(a, action, True) for a in _as_list(s["Action"])) + else: + hit = not any(_iam_glob(a, action, True) for a in _as_list(s.get("NotAction"))) + if not hit: + return False + if "Resource" in s: + hit = any(_iam_glob(r, resource) for r in _as_list(s["Resource"])) + else: + hit = not any(_iam_glob(r, resource) for r in _as_list(s.get("NotResource"))) + return hit and _condition_holds(s.get("Condition"), ctx, deny=s.get("Effect") == "Deny") + + +def iam_decision(identity, boundary, action, resource, ctx=None): + """("allowed" | "explicitDeny" | "implicitDeny", the Sid that decided or "").""" + ctx = ctx or {} + docs = list(identity) + ([boundary] if boundary else []) + for d in docs: + for s in _as_list(policy_doc(d).get("Statement")): + if s.get("Effect") == "Deny" and _statement_matches(s, action, resource, ctx): + return "explicitDeny", s.get("Sid") or "" + by_identity = any(s.get("Effect") == "Allow" and _statement_matches(s, action, resource, ctx) + for d in identity for s in _as_list(policy_doc(d).get("Statement"))) + by_boundary = not boundary or any(s.get("Effect") == "Allow" and _statement_matches(s, action, resource, ctx) + for s in _as_list(policy_doc(boundary).get("Statement"))) + return ("allowed", "") if by_identity and by_boundary else ("implicitDeny", "" if by_identity else "its own policy") + + +def managed_policy_doc(iam, arn): + v = iam.get_policy(PolicyArn=arn)["Policy"]["DefaultVersionId"] + return policy_doc(iam.get_policy_version(PolicyArn=arn, VersionId=v)["PolicyVersion"]["Document"]) + + +def deploy_role_access(env, iam=None): + """The deploy role's policies and boundary as IAM has them now.""" + iam = iam or client("iam") + arn = env["DEPLOY_ROLE_ARN"] + name = arn.split("/")[-1] + role = iam.get_role(RoleName=name)["Role"] + identity = [policy_doc(iam.get_role_policy(RoleName=name, PolicyName=p)["PolicyDocument"]) + for p in iam.list_role_policies(RoleName=name).get("PolicyNames") or []] + for a in iam.list_attached_role_policies(RoleName=name).get("AttachedPolicies") or []: + identity.append(managed_policy_doc(iam, a["PolicyArn"])) + b = ((role.get("PermissionsBoundary") or {}).get("PermissionsBoundaryArn")) or "" + return {"role_arn": arn, "identity": identity, "boundary_arn": b, "boundary": managed_policy_doc(iam, b) if b else None} + + +def _known(v): + return isinstance(v, str) and v and "{{" not in v and "KNOWN_AFTER_APPLY" not in v + + +ROLE_PROPERTY_CALLS = { + "Policies": ["iam:PutRolePolicy", "iam:DeleteRolePolicy"], + "AssumeRolePolicyDocument": ["iam:UpdateAssumeRolePolicy"], + "PermissionsBoundary": ["iam:PutRolePermissionsBoundary"], + "Tags": ["iam:TagRole", "iam:UntagRole"], + "ManagedPolicyArns": ["iam:AttachRolePolicy", "iam:DetachRolePolicy"], + "Description": ["iam:UpdateRole"], + "MaxSessionDuration": ["iam:UpdateRole"], +} + + +def _role_names(v): + return [r for r in _as_list(v) if _known(r)] + + +def _passed_roles(props, account): + """Role ARNs a resource hands to a service (its Role, RoleArn, ServiceRole, ExecutionRoleArn, ...): iam:PassRole.""" + out = set() + + def walk(v, key=""): + if isinstance(v, dict): + for k, x in v.items(): + walk(x, k) + elif isinstance(v, list): + for x in v: + walk(x, key) + elif isinstance(v, str) and re.match(r"^arn:[\w-]+:iam::\d+:role/", v) and re.search(r"Role(Arn)?$", key or ""): + out.add(v) + walk(props) + return sorted(out) + + +def iam_calls(rc, account, partition, install_boundary, prefix="coderhelm"): + """[(action, resource ARN, context)] the IAM calls CloudFormation makes for + one resource change: IAM resources (a replacement is a create and a + delete), managed policy attachments, inline policies, and iam:PassRole + for a role a resource hands to a service. A role or policy whose name + isn't known yet gets the name CloudFormation would make (the stack's + name, the logical id, a suffix), which is inside the install's names.""" + t, act = rc.get("ResourceType") or "", rc.get("Action") or "" + lid = rc.get("LogicalResourceId") or "x" + phys = rc.get("PhysicalResourceId") or "" + after = context(rc.get("AfterContext")) + after = after.get("Properties", after) if isinstance(after, dict) else {} + targets = {(d.get("Target") or {}).get("Name") for d in rc.get("Details") or []} - {None} + replaced = act == "Modify" and rc.get("Replacement") in ("True", "Conditional") + iam_arn = f"arn:{partition}:iam::{account}" + generated = f"{prefix}-{lid}-GENERATED" + calls = [] + if act in ("Add", "Modify"): + calls += [("iam:PassRole", r, {"iam:PassedToService": "cloudformation.amazonaws.com"}) for r in _passed_roles(after, account)] + if t == "AWS::IAM::ManagedPolicy": + name = after.get("ManagedPolicyName") + new = f"{iam_arn}:policy/{name if _known(name) else generated}" + old = phys if phys.startswith("arn:") else new + if act == "Add" or replaced: + calls.append(("iam:CreatePolicy", new, {})) + if replaced: + calls += [("iam:DeletePolicy", old, {}), ("iam:DeletePolicyVersion", old, {})] + elif act == "Modify": + calls += [(a, old, {}) for a in ("iam:CreatePolicyVersion", "iam:DeletePolicyVersion", "iam:ListPolicyVersions")] + elif act == "Remove": + calls += [(a, old, {}) for a in ("iam:DeletePolicy", "iam:DeletePolicyVersion", "iam:ListPolicyVersions")] + if act in ("Add", "Modify"): + ctx = {"iam:PolicyARN": new} + calls += [("iam:AttachRolePolicy", f"{iam_arn}:role/{r}", dict(ctx, **{"iam:PermissionsBoundary": install_boundary})) for r in _role_names(after.get("Roles"))] + calls += [("iam:DetachRolePolicy", f"{iam_arn}:role/{r}", dict(ctx, **{"iam:PermissionsBoundary": install_boundary})) for r in _role_names(after.get("Roles")) if act == "Modify"] + calls += [("iam:AttachUserPolicy", f"{iam_arn}:user/{u}", ctx) for u in _role_names(after.get("Users"))] + calls += [("iam:AttachGroupPolicy", f"{iam_arn}:group/{g}", ctx) for g in _role_names(after.get("Groups"))] + return calls + if t == "AWS::IAM::Role": + name = after.get("RoleName") + new_name = name if _known(name) else generated + old_name = phys or new_name + pb = after.get("PermissionsBoundary") + ctx = {"iam:PermissionsBoundary": pb if _known(pb) and pb.startswith("arn:") else install_boundary} + if act == "Add" or replaced: + acts = ["iam:CreateRole"] + (["iam:PutRolePolicy"] if after.get("Policies") else []) + (["iam:AttachRolePolicy"] if after.get("ManagedPolicyArns") else []) + calls += [(a, f"{iam_arn}:role/{new_name}", ctx) for a in acts] + if replaced or act == "Remove": + calls += [(a, f"{iam_arn}:role/{old_name}", ctx) for a in ("iam:DeleteRole", "iam:DeleteRolePolicy", "iam:DetachRolePolicy")] + elif act == "Modify": + acts = sorted({a for k in targets for a in ROLE_PROPERTY_CALLS.get(k, ["iam:UpdateRole"])}) + calls += [(a, f"{iam_arn}:role/{old_name}", ctx) for a in acts] + return calls + if t in ("AWS::IAM::Policy", "AWS::IAM::RolePolicy"): + roles = _role_names(after.get("Roles")) + _role_names(after.get("RoleName")) + if act in ("Add", "Modify"): + calls += [("iam:PutRolePolicy", f"{iam_arn}:role/{r}", {"iam:PermissionsBoundary": install_boundary}) for r in roles] + if not roles: + calls.append(("iam:PutRolePolicy", f"{iam_arn}:role/{generated}", {"iam:PermissionsBoundary": install_boundary})) + elif act == "Remove": + calls += [("iam:DeleteRolePolicy", f"{iam_arn}:role/{r}", {"iam:PermissionsBoundary": install_boundary}) for r in roles] + return calls + return calls + + +class Unchecked(Exception): + """The preflight couldn't check the change set: it holds the update.""" + + +def preflight(cfn, env, cs_id, stack, iam=None): + """Each IAM call the change set (and its parts') needs that the deploy role + would be refused, in words; [] when it may make them all. When it can't + tell (the role's policies unreadable, a condition it can't evaluate), it + says so as a refused call: an update is never started unchecked.""" + if not env.get("DEPLOY_ROLE_ARN"): + return [] + try: + access = deploy_role_access(env, iam) + except Exception as e: # noqa: BLE001 + return [f"couldn't check: the deploy role's policies couldn't be read ({type(e).__name__}: {str(e)[:160]})"] + account, partition = stack_account(stack), stack_partition(stack) + prefix = env.get("RESOURCE_PREFIX") or env["NATIVE_STACK"] + install_boundary = f"arn:{partition}:iam::{account}:policy/{prefix}-boundary-stack" + out, seen = [], set() + + def walk(cid, part, stack_name): + for ch in change_set_pages(cfn, cid, stack_name): + rc = ch.get("ResourceChange") or {} + for action, arn, ctx in iam_calls(rc, account, partition, install_boundary, prefix): + try: + verdict, sid = iam_decision(access["identity"], access["boundary"], action, arn, + dict(ctx, **{"aws:PrincipalArn": access["role_arn"]})) + except ValueError as e: + out.append(f"{part}.{rc.get('LogicalResourceId')}: {action} on {arn} (couldn't check: {e})") + continue + if verdict != "allowed": + why = f"denied by {sid}" if verdict == "explicitDeny" else f"not allowed by {sid or 'its boundary'}" + out.append(f"{part}.{rc.get('LogicalResourceId')}: {action} on {arn} ({why})") + nested = rc.get("ChangeSetId") + if rc.get("ResourceType") == "AWS::CloudFormation::Stack" and nested and nested not in seen: + seen.add(nested) + walk(nested, rc.get("LogicalResourceId"), None) + try: + walk(cs_id, "parent", env["NATIVE_STACK"]) + except Exception as e: # noqa: BLE001 + out.append(f"couldn't check: the change set couldn't be read in full ({type(e).__name__}: {str(e)[:160]})") + return out + + +PREFLIGHT_MARK = "the deploy role CoderHelm's updates run as may not make these calls" + + +# ── Template values (the few intrinsics policies use) ───────────────────── + +def cfn_values(stack, env): + """Parameter and pseudo parameter values of the stack, for cfn_resolve.""" + vals = {p.get("ParameterKey"): p.get("ParameterValue") for p in stack.get("Parameters") or [] if "ParameterValue" in p} + vals.update({"AWS::AccountId": stack_account(stack), "AWS::Partition": stack_partition(stack), + "AWS::Region": env.get("AWS_REGION") or "", "AWS::StackName": stack.get("StackName") or env.get("NATIVE_STACK") or "", + "AWS::URLSuffix": "amazonaws.com", "AWS::StackId": stack.get("StackId") or ""}) + return vals + + +def cfn_resolve(v, values, conditions=None): + """Ref, Fn::Sub, Fn::If, Fn::Join and conditions of Fn::Equals, Fn::Not, + Fn::And, Fn::Or. Raises ValueError on anything it can't resolve.""" + conditions = conditions or {} + + def cond(name): + if name not in conditions: + raise ValueError(f"unknown condition {name}") + return bool(r(conditions[name])) + + def r(x): + if isinstance(x, list): + return [r(i) for i in x] + if not isinstance(x, dict): + return x + if len(x) == 1: + (k, a), = x.items() + if k == "Ref": + if a in values: + return values[a] + raise ValueError(f"no value for {a}") + if k == "Fn::Sub": + text, vars_ = (a, {}) if isinstance(a, str) else (a[0], r(a[1])) + + def one(m): + name = m.group(1) + if name.startswith("!"): + return "${" + name[1:] + "}" + if name in vars_: + return str(vars_[name]) + if name in values: + return str(values[name]) + raise ValueError(f"no value for ${{{name}}}") + return re.sub(r"\$\{([^}]+)\}", one, text) + if k == "Fn::If": + return r(a[1] if cond(a[0]) else a[2]) + if k == "Fn::Join": + return str(a[0]).join(str(p) for p in r(a[1])) + if k == "Fn::Equals": + return r(a[0]) == r(a[1]) + if k == "Fn::Not": + return not r(a[0]) + if k == "Fn::And": + return all(r(i) for i in a) + if k == "Fn::Or": + return any(r(i) for i in a) + if k == "Condition": + return cond(a) + return {k: r(i) for k, i in x.items()} + return r(v) + + +# ── The access stack: newer permissions, applied by an AWS admin ────────── + +SERVICE_NAMES = {"airflow": "Airflow", "ecs": "ECS", "ecr": "ECR", "iam": "IAM", "sts": "STS", "logs": "CloudWatch Logs", + "bedrock": "Bedrock", "lambda": "Lambda", "s3": "S3", "dynamodb": "DynamoDB", "cloudwatch": "CloudWatch", + "ssm": "Systems Manager", "sqs": "SQS", "sns": "SNS", "ses": "SES", "kms": "KMS", "events": "EventBridge"} +READ_VERBS = ("Get", "List", "Describe", "BatchGet", "Simulate", "InvokeRestApi") +# What a statement means, for the few that change who may do what. +STATEMENT_WORDS = { + "ReadRolesHereOnlyCoderHelmRuntime": "lets the log analyzer take on CoderHelm's read roles in this account, like the gateway and worker", + "ReadRolesHereOnlyGatewayAndWorker": "lets only the gateway and worker take on CoderHelm's read roles in this account", +} + + +def _names(services): + names = [SERVICE_NAMES.get(s, s) for s in sorted(set(services), key=lambda s: SERVICE_NAMES.get(s, s))] + return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1] + + +def describe_policy_change(have, want): + """What changes from `have` to `want`, in a few plain lines.""" + hs = {s.get("Sid"): s for s in _as_list(policy_doc(have).get("Statement"))} + ws = {s.get("Sid"): s for s in _as_list(policy_doc(want).get("Statement"))} + lines = [] + added = [] + for sid, s in ws.items(): + if s.get("Effect") == "Allow" and "Action" in s: + old = set(_as_list((hs.get(sid) or {}).get("Action"))) + added += [a for a in _as_list(s["Action"]) if a not in old] + if added: + svcs = [a.split(":")[0] for a in added] + read = all(any(a.split(":", 1)[1].startswith(v) for v in READ_VERBS) for a in added if ":" in a) + lines.append(f"adds {'read ' if read else ''}access to {_names(svcs)} ({', '.join(added)})") + for sid in ws.keys() - hs.keys(): + if ws[sid].get("Effect") == "Deny" or sid in STATEMENT_WORDS: + lines.append(STATEMENT_WORDS.get(sid) or f"adds the rule {sid}") + for sid in hs.keys() - ws.keys(): + if sid not in STATEMENT_WORDS or not any(STATEMENT_WORDS.get(n) for n in ws.keys() - hs.keys()): + lines.append(f"replaces the rule {sid}") + for sid in hs.keys() & ws.keys(): + a, b = dict(hs[sid]), dict(ws[sid]) + if a.get("Effect") == "Allow" and "Action" in a: + a.pop("Action", None), b.pop("Action", None) + if canonical_policy({"Statement": [a]}) != canonical_policy({"Statement": [b]}): + lines.append(STATEMENT_WORDS.get(sid) or f"rewrites the rule {sid}") + return lines or ["rewrites the policy (the same rules)"] + + +def access_link(region, stack_name, template_url, params): + from urllib.parse import quote, urlencode + q = {"stackName": f"{stack_name}-access", "templateURL": template_url} + q.update({f"param_{k}": v for k, v in params.items()}) + return (f"https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks/quickcreate?" + + urlencode(q, quote_via=quote, safe="")) + + +def access_compute(env, cfn=None, iam=None, opener=None): + """The install's access against what its release's access.json gives: the + pending permission change, if any, and the one link that applies it.""" + cfn = cfn or client("cloudformation") + root = env["NATIVE_STACK"] + stack = cfn.describe_stacks(StackName=root)["Stacks"][0] + deployed = deployed_template(cfn, root) + files = ((((deployed.get("Resources") or {}).get("ReleaseAssets") or {}).get("Properties") or {}).get("Files")) or [] + pin = next((f for f in files if f.get("Key") == ACCESS_FILE), None) + version = stack_version(stack) or env.get("CODERHELM_VERSION") or "" + if not pin or not parse_version(version): + return {"state": "none"} + url = f"https://{NATIVE_HOST}/launch/{version}/{ACCESS_FILE}" + body = fetch_template(url, opener) + if hashlib.sha256(body).hexdigest() != pin.get("Sha256"): + return {"state": "unknown", "reason": f"{version}'s access.json doesn't match the sha256 its signed template pins"} + access = json.loads(body) + props = ((access.get("Resources") or {}).get("Access") or {}).get("Properties") or {} + values = cfn_values(stack, env) + conds = access.get("Conditions") or {} + iam = iam or client("iam") + changes = [] + for key in ("Boundary", "DeployBoundary"): + want = cfn_resolve(props[key]["Document"], values, conds) + have = managed_policy_doc(iam, cfn_resolve(props[key]["Arn"], values, conds)) + if not same_policy(have, want): + changes.append({"resource": key, "lines": describe_policy_change(have, want)}) + role = props.get("DeployRole") or {} + if role: + name = cfn_resolve(role["RoleName"], values, conds) + want = cfn_resolve(role["Document"], values, conds) + have = policy_doc(iam.get_role_policy(RoleName=name, PolicyName=role.get("PolicyName") or "deploy")["PolicyDocument"]) + if not same_policy(have, want): + changes.append({"resource": "DeployRole", "lines": describe_policy_change(have, want)}) + params = {p: values.get(p, "") for p in (access.get("Parameters") or {})} + try: + st = cfn.describe_stacks(StackName=f"{root}-access")["Stacks"][0] + existing = {"status": st.get("StackStatus"), "link": f"https://{env.get('AWS_REGION')}.console.aws.amazon.com/cloudformation/home?region={env.get('AWS_REGION')}#/stacks/stackinfo?stackId={st.get('StackId')}"} + except Exception as e: # noqa: BLE001 + if "does not exist" not in str(e): + raise + existing = None + lines = [] + for c in changes: + for ln in c["lines"]: + if ln not in lines: + lines.append(ln) + return { + "state": "pending" if changes else "applied", + "version": version, + "summary": lines, + "resources": [c["resource"] for c in changes], + "link": access_link(env.get("AWS_REGION") or "", root, url, params) if changes else None, + "template_url": url, + "stack": f"{root}-access", + "existing": existing, + } + + +def access_view(store, env, now, force=False, **kw): + """access_compute, at most every ACCESS_CACHE_SECONDS (never fails the route).""" + rec = store.get("ACCESS") or {} + try: + fresh = rec.get("at") and (now - datetime.fromisoformat(rec["at"])).total_seconds() < ACCESS_CACHE_SECONDS + except ValueError: + fresh = False + if fresh and not force: + return rec.get("view") + try: + view = access_compute(env, **kw) + except Exception as e: # noqa: BLE001 + logger.warning(f"access not read: {e}") + view = dict(rec.get("view") or {"state": "unknown"}, error=str(e)[:300]) + store.put("ACCESS", {"at": now.isoformat(), "view": view}) + return view + + +# ── A stack whose rollback stopped (UPDATE_ROLLBACK_FAILED) ────────────── + +STUCK = "UPDATE_ROLLBACK_FAILED" +RECOVERY_TRIES = 3 + + +def rollback_failures(cfn, stack_name): + """The resources whose rollback failed in the stack's last rollback: [(id, type, reason)], every page read.""" + out, seen, token = [], set(), None + while True: + kw = {"StackName": stack_name} + if token: + kw["NextToken"] = token + page = cfn.describe_stack_events(**kw) + for e in page.get("StackEvents") or []: # newest first + if e.get("LogicalResourceId") == stack_name and e.get("ResourceStatus") == "UPDATE_ROLLBACK_IN_PROGRESS": + return out + lid = e.get("LogicalResourceId") + if str(e.get("ResourceStatus", "")).endswith("_FAILED") and lid != stack_name and lid not in seen: + seen.add(lid) + out.append((lid, e.get("ResourceType") or "", e.get("ResourceStatusReason") or "")) + token = page.get("NextToken") + if not token: + return out + + +def _resource_values(old, values, conds): + """Ref to a managed policy of the template resolves to its ARN (by its name).""" + out = dict(values) + for lid, r in (old.get("Resources") or {}).items(): + if r.get("Type") == "AWS::IAM::ManagedPolicy" and "ManagedPolicyName" in (r.get("Properties") or {}): + try: + out[lid] = f"arn:{values['AWS::Partition']}:iam::{values['AWS::AccountId']}:policy/{cfn_resolve(r['Properties']['ManagedPolicyName'], values, conds)}" + except ValueError: + pass + return out + + +def _tags(v): + return sorted((t.get("Key"), t.get("Value")) for t in v or []) + + +def unchanged_by_rollback(lid, rtype, old, values, iam): + """'' when the resource is exactly as the rollback would leave it (so it + may be skipped), else why not. A managed policy: its default document. A + role: its trust policy, boundary, tags, managed policies, and the names + and documents of its inline policies. Anything else is never skipped.""" + r = ((old.get("Resources") or {}).get(lid)) or {} + if not r: + return "the release it rolls back to doesn't have it" + props = r.get("Properties") or {} + conds = old.get("Conditions") or {} + vals = _resource_values(old, values, conds) + try: + if rtype == "AWS::IAM::ManagedPolicy": + arn = f"arn:{values['AWS::Partition']}:iam::{values['AWS::AccountId']}:policy/{cfn_resolve(props['ManagedPolicyName'], vals, conds)}" + if same_policy(managed_policy_doc(iam, arn), cfn_resolve(props["PolicyDocument"], vals, conds)): + return "" + return "its policy differs from the release it rolls back to" + if rtype == "AWS::IAM::Role": + p = cfn_resolve(props, vals, conds) + name = p["RoleName"] + role = iam.get_role(RoleName=name)["Role"] + if not same_policy(role.get("AssumeRolePolicyDocument"), p.get("AssumeRolePolicyDocument")): + return "its trust policy differs from the release it rolls back to" + if ((role.get("PermissionsBoundary") or {}).get("PermissionsBoundaryArn") or "") != (p.get("PermissionsBoundary") or ""): + return "its permissions boundary differs from the release it rolls back to" + if _tags(role.get("Tags")) != _tags(p.get("Tags")): + return "its tags differ from the release it rolls back to" + attached = sorted(a["PolicyArn"] for a in iam.list_attached_role_policies(RoleName=name).get("AttachedPolicies") or []) + if attached != sorted(p.get("ManagedPolicyArns") or []): + return "its managed policies differ from the release it rolls back to" + inline = sorted(iam.list_role_policies(RoleName=name).get("PolicyNames") or []) + if inline != sorted(x["PolicyName"] for x in p.get("Policies") or []): + return "its inline policies differ from the release it rolls back to" + for x in p.get("Policies") or []: + have = policy_doc(iam.get_role_policy(RoleName=name, PolicyName=x["PolicyName"])["PolicyDocument"]) + if not same_policy(have, x["PolicyDocument"]): + return f"its policy {x['PolicyName']} differs from the release it rolls back to" + return "" + except Exception as e: # noqa: BLE001 + return f"it couldn't be checked ({type(e).__name__}: {str(e)[:120]})" + return f"a {rtype} isn't one CoderHelm checks by itself" + + +def rollback_target(store, env): + """(release, the install's own access resources as that update found them) a + failed rollback goes back to: the last executed update's from_version, else + the running one. A held update kept the install's own deploy role and + boundaries, so those are what the rollback restores, not the release's.""" + for h in store.history(10): + if h.get("executed_at") and parse_version(h.get("from_version") or ""): + return h["from_version"], h.get("deployed_access") or {} + return env.get("CODERHELM_VERSION") or "", {} + + +def _stuck_notice(store, env, now, stack, rec): + notify_once(store, f"stuck:{stack.get('LastUpdatedTime') or now.date().isoformat()}", now, + "your CoderHelm install's last update couldn't be rolled back", + "AWS stopped while putting the previous release back, and CoderHelm couldn't safely finish it by itself: " + f"{rec['reason']}. CoderHelm keeps running. Settings, System says what stopped it:\n{app_url(env)}/settings/system/#version", + env, what="stuck", version=rec.get("target"), facts={"reason": rec["reason"], "action": rec.get("link")}) + + +def recover_stuck(store, env, now, cfn=None, iam=None, opener=None): + """Moves a stack out of UPDATE_ROLLBACK_FAILED by itself, when it safely + can; returns the recovery record (None when the stack isn't stuck).""" + cfn = cfn or client("cloudformation") + root = env["NATIVE_STACK"] + stack = cfn.describe_stacks(StackName=root)["Stacks"][0] + st = stack.get("StackStatus") or "" + state = store.get("UPDATE_STATE", {}) + rec = state.get("recovery") or {} + if st != STUCK: + if rec.get("status") in ("continuing", "retrying") and not st.endswith("_IN_PROGRESS"): + rec.update({"status": "recovered" if st == "UPDATE_ROLLBACK_COMPLETE" else "failed", "finished_at": now.isoformat(), + "stack_status": st}) + state["recovery"] = rec + store.put("UPDATE_STATE", state) + return None + tries = int(rec.get("tries") or 0) if rec.get("status") in ("continuing", "retrying", "stuck") else 0 + failed = rollback_failures(cfn, root) + target, kept = rollback_target(store, env) + why = {} + if tries >= RECOVERY_TRIES: + why = {"": f"continuing the rollback didn't finish after {tries} tries" + (f" (last: {rec.get('error')})" if rec.get("error") else "")} + elif not failed: + why = {"": "AWS doesn't say which resource stopped the rollback"} + else: + try: + want = (store.get(f"MANIFEST#{target}") or {}).get("template_sha256") + if not want: + raise ValueError(f"{target}'s template isn't verified on this install, so it can't be compared") + body = fetch_template(native_template_url(env, target), opener) + if hashlib.sha256(body).hexdigest() != want: + raise ValueError("it doesn't match its signed checksum") + old = json.loads(body) + for k, v in kept.items(): + if k in HELD and k in (old.get("Resources") or {}): + old["Resources"][k] = v + values = cfn_values(stack, env) + iam = iam or client("iam") + for lid, rtype, _ in failed: + w = unchanged_by_rollback(lid, rtype, old, values, iam) + if w: + why[lid] = w + except Exception as e: # noqa: BLE001 + why = {"": f"{target}'s template couldn't be read to check them ({type(e).__name__}: {str(e)[:160]})"} + region = env.get("AWS_REGION") or "" + link = f"https://{region}.console.aws.amazon.com/cloudformation/home?region={region}#/stacks/events?stackId={stack.get('StackId', '')}" + if why: + rec = {"status": "stuck", "at": now.isoformat(), "failed": [f[0] for f in failed], "target": target, "tries": tries, + "reason": "; ".join(f"{k}: {v}" if k else v for k, v in why.items())[:600], "link": link} + state["recovery"] = rec + store.put("UPDATE_STATE", state) + _stuck_notice(store, env, now, stack, rec) + return rec + skip = [f[0] for f in failed] + kw = {"StackName": root, "ResourcesToSkip": skip} + if env.get("DEPLOY_ROLE_ARN"): + kw["RoleARN"] = env["DEPLOY_ROLE_ARN"] + try: + cfn.continue_update_rollback(**kw) + except Exception as e: # noqa: BLE001 recorded and counted, never swallowed + err = f"{type(e).__name__}: {str(e)[:200]}" + rec = {"status": "retrying", "at": now.isoformat(), "failed": skip, "target": target, "tries": tries + 1, "error": err, "link": link, + "reason": f"AWS refused to continue the rollback ({err}); CoderHelm tries again in 5 minutes"} + if tries + 1 >= RECOVERY_TRIES: + rec.update({"status": "stuck", "reason": f"AWS refused to continue the rollback {tries + 1} times ({err})"}) + _stuck_notice(store, env, now, stack, rec) + state["recovery"] = rec + store.put("UPDATE_STATE", state) + logger.warning(f"continue rollback refused: {err}") + return rec + rec = {"status": "continuing", "at": now.isoformat(), "skipped": skip, "target": target, "tries": tries + 1, + "reason": f"AWS stopped while putting {target} back; CoderHelm continued the rollback, skipping " + f"{', '.join(skip)}, each checked to be exactly as {target} has it"} + state["recovery"] = rec + store.put("UPDATE_STATE", state) + logger.info(f"continued the rollback of {root}, skipping {skip}") + return rec DATA_TYPES = ("AWS::DynamoDB::GlobalTable", "AWS::DynamoDB::Table", "AWS::S3::Bucket", "AWS::KMS::Key", "AWS::Cognito::UserPool", "AWS::SecretsManager::Secret") @@ -2381,7 +3198,10 @@ def native_status(store, env, state): pending = dict(entry.get("change_set") or {}, version=entry.get("version"), status=entry.get("status"), id=hid, # Who started it, and who applied it (an admin here, or someone in the AWS console). actor=entry.get("actor"), started_at=entry.get("started_at"), - applied_by=entry.get("applied_by"), executed_at=entry.get("executed_at")) + applied_by=entry.get("applied_by"), executed_at=entry.get("executed_at"), + # The install's own deploy role and boundaries, kept as they are (a newer + # version of them is the separate `access` item below). + held=entry.get("held") or []) if entry.get("status") == "review": # What an admin confirms in Settings, System before it applies. pending.update({ @@ -2389,6 +3209,7 @@ def native_status(store, env, state): "data_changes": entry.get("data_changes") or [], "permission_changes": entry.get("permission_changes") or [], "admin_changes": entry.get("admin_changes") or [], + "preflight": entry.get("preflight") or [], "can_apply": can_apply_here(env, entry), "confirm": confirm_token(hid, entry), }) @@ -2399,6 +3220,11 @@ def native_status(store, env, state): "can_apply": role, "auto_apply": role, "pending": pending, + # A newer boundary or deploy role policy than the install has: optional, + # applied by an AWS admin through the access stack (one link). + "access": (store.get("ACCESS") or {}).get("view"), + # A stack whose rollback stopped, and what CoderHelm did about it. + "recovery": state.get("recovery"), } @@ -2477,7 +3303,8 @@ def native_poll(store, env, now, cfn=None): state = store.get("UPDATE_STATE", {}) hid = state.get("running_id") or state.get("review_id") if not hid: - return {"native": "idle"} + rec = safe_recover(store, env, now, cfn) + return {"native": "recovering", "recovery": rec} if rec else {"native": "idle"} entry = store.get(hid, {}) cs_id = entry.get("change_set_id") if entry.get("status") in ENDED: @@ -2528,9 +3355,25 @@ def keep(e): entry["data_changes"] = data_changes(cfn, cs) entry["admin_changes"] = admin_changes(cs) entry["permission_changes"] = permission_changes(cfn, cs_id, env["NATIVE_STACK"]) + if prepared_role(entry) or (prepared_role(entry) is None and entry.get("apply")): + stack = cfn.describe_stacks(StackName=env["NATIVE_STACK"])["Stacks"][0] + entry["preflight"] = preflight(cfn, env, cs_id, stack) entry["checked"] = True summary["data_changes"] = entry["data_changes"] entry["change_set"] = summary + never = never_runs(entry) if execution == "AVAILABLE" and entry.get("checked") else "" + if never and not entry.get("executed_at"): + # It runs as the deploy role whoever executes it (the stack's service + # role), and that role would be refused: never offered, never started. + # An update an older updater left waiting "for an AWS admin" ends here too. + try: + cfn.delete_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"]) + except Exception as e: # noqa: BLE001 + logger.warning(f"change set not deleted: {e}") + if (store.get(hid, {}) or {}).get("status") != was: + return {"native": "moved on"} + store.put(hid, entry) + return native_finish(store, env, now, hid, "failed", never, PREPARE) if execution == "AVAILABLE" and entry.get("executed_at"): # Executed a moment ago: CloudFormation can still answer AVAILABLE # for a few seconds. It runs; it never goes back to waiting for an OK. @@ -2595,6 +3438,23 @@ def keep(e): st = stack["StackStatus"] if st.endswith("_IN_PROGRESS"): return {"native": "running", "stack": st} + if st == STUCK: + # AWS stopped while putting the previous release back: CoderHelm + # finishes that rollback itself when it safely can, and the update + # ends once the stack says how it ended. + if not entry.get("rollback_failed_at"): + entry["rollback_failed_at"] = now.isoformat() + entry["first_failure"] = first_failure(cfn, env["NATIVE_STACK"], entry.get("executed_at")) + store.put(hid, entry) + rec = safe_recover(store, env, now, cfn) + if rec and rec.get("status") == "continuing": + return {"native": "recovering", "recovery": rec} + reason = entry.get("first_failure") or "the stack's rollback stopped" + return native_finish(store, env, now, hid, "failed", f"{reason}. {(rec or {}).get('reason') or ''}".strip()) + if st == "UPDATE_ROLLBACK_COMPLETE" and entry.get("rollback_failed_at"): + reason = entry.get("first_failure") or first_failure(cfn, env["NATIVE_STACK"], entry.get("executed_at")) or "the stack rolled back" + rec = (store.get("UPDATE_STATE", {}) or {}).get("recovery") or {} + return native_finish(store, env, now, hid, "rolled_back", f"{reason}. {rec.get('reason') or ''}".strip()) if st in ("UPDATE_COMPLETE",): ran = stack_version(stack) if ran and entry.get("version") and ran != entry.get("version"): @@ -2611,6 +3471,35 @@ def keep(e): return {"native": str(execution or status).lower()} +def safe_recover(store, env, now, cfn): + """recover_stuck, never failing the poll.""" + try: + return recover_stuck(store, env, now, cfn) + except Exception as e: # noqa: BLE001 + logger.warning(f"stuck stack not recovered: {e}") + return None + + +def never_runs(entry): + """Why a change set prepared with the deploy role can never apply ("" when it can). + + The stack's service role is the deploy role, so CloudFormation runs the + change set as that role whoever executes it, an AWS admin in the console + included. A change to the role or a boundary, or a call the preflight + found it would be refused, fails, and then its rollback fails too.""" + if not (entry.get("role_arn") or (entry.get("role_arn") is None and entry.get("apply"))): + return "" + if "preflight" in entry and entry["preflight"] is None: + # Never unchecked: an older entry that couldn't be checked is checked as refused. + return f"{PREFLIGHT_MARK}: couldn't check them" + calls = list(entry.get("preflight") or []) + if entry.get("admin_changes") and not calls: + calls = [f"parent.{c}" for c in entry["admin_changes"]] + if not calls: + return "" + return (f"{PREFLIGHT_MARK}: " + "; ".join(calls))[:900] + + def stack_version(stack): """The release the parent stack says it runs (its Version output), or None.""" for o in stack.get("Outputs") or []: @@ -2807,10 +3696,13 @@ def reconcile(store, env, now, cfn=None): any older prepared update left open marked superseded. Never fails the route: what can't be read stays as stored, and the scheduled poll retries.""" try: + if env.get("DEPLOY_ROLE_ARN"): + access_view(store, env, now) state = store.get("UPDATE_STATE", {}) hid = state.get("running_id") or state.get("review_id") opened = open_updates(store, state) if not hid and not opened: + safe_recover(store, env, now, cfn or client("cloudformation")) return cfn = cfn or client("cloudformation") entry = (store.get(hid, {}) or {}) if hid else {} @@ -2872,6 +3764,9 @@ def _cause(raw): "Press Update again. If it happens again, send the technical details to CoderHelm support.") if ("does not exist" in low and "change set" in low) or "change set was deleted" in low: return ("the prepared change was deleted in AWS before it ran", "Press Update again.") + if PREFLIGHT_MARK.lower() in low: + return ("it needs permissions CoderHelm's update role doesn't have, so it was stopped before anything ran", + "An AWS admin applies the permission change shown under Version, Permissions (one link to the AWS console), then press Update again.") if "can no longer run" in low or "stack changed since" in low: return ("the install changed after the update was prepared", "Press Update again.") return (None, None) diff --git a/services/common/src/live/airflow.rs b/services/common/src/live/airflow.rs index da6bd4e6b..08d59fa85 100644 --- a/services/common/src/live/airflow.rs +++ b/services/common/src/live/airflow.rs @@ -373,6 +373,13 @@ where use aws_sdk_mwaa::error::ProvideErrorMetadata as _; let code = e.code().unwrap_or("").to_string(); let msg = e.message().unwrap_or("").to_string(); + if code.contains("AccessDenied") && super::boundary_refusal(&msg) { + return StepError::new( + "sign_in", + "This install's permission limit doesn't allow reading Airflow yet: the release that reads it needs a permission change an AWS admin hasn't applied.", + super::PENDING_PERMISSION_FIX, + ); + } if code.contains("AccessDenied") { return StepError::new( "sign_in", diff --git a/services/common/src/live/mod.rs b/services/common/src/live/mod.rs index eb1019930..74e49aa6f 100644 --- a/services/common/src/live/mod.rs +++ b/services/common/src/live/mod.rs @@ -87,6 +87,20 @@ pub fn error_detail(code: &str, message: &str) -> String { crate::truncate_str(&text, 300).to_string() } +/// AWS refused a call because of a permissions boundary (its message says +/// so: "no permissions boundary allows" or "explicit deny in a permissions +/// boundary"). On a self-hosted install reading its own account, that is the +/// install's own boundary: a newer release needs read access the install +/// doesn't have until an AWS admin applies the pending permission change. +pub fn boundary_refusal(message: &str) -> bool { + message + .to_ascii_lowercase() + .contains("permissions boundary") +} + +/// What to do when the install's own boundary refused a read. +pub const PENDING_PERMISSION_FIX: &str = "An AWS admin applies the pending permission change: Settings, System, Version, Permissions (one link to the AWS console). Nothing else waits on it."; + /// A failure a person can act on: which step failed, what happened, what to do. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct StepError { @@ -120,6 +134,18 @@ impl std::fmt::Display for StepError { #[cfg(test)] mod tests { + use super::*; + + #[test] + fn a_boundary_refusal_is_told_apart_from_a_missing_role_permission() { + assert!(boundary_refusal("User: arn:aws:sts::1:assumed-role/coderhelm-prod-worker/x is not authorized to perform: airflow:InvokeRestApi on resource: y because no permissions boundary allows the airflow:InvokeRestApi action")); + assert!(boundary_refusal( + "... with an explicit deny in a permissions boundary" + )); + assert!(!boundary_refusal("User is not authorized to perform: airflow:InvokeRestApi because no identity-based policy allows it")); + assert!(PENDING_PERMISSION_FIX.contains("Settings, System")); + } + #[test] fn counts_read_naturally() { assert_eq!(super::count(1, "row"), "1 row");