From f2be906554808c14fc427de03c58979212263496 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 19 Nov 2026 10:18:08 -0500 Subject: [PATCH] The install's own AWS account gets each release's reads with the release, and no alert ever The daily AWS permissions sweep pushed "AWS account X needs N new read-only permissions" for the install's own account: PermissionCheck.install_account was only ever set in tests, so that account was treated like any other. And since every team read there goes through CoderHelmLogReader, that role really fell behind each release. - The check's builder sets install_account from the install's read role, on one-stack installs (INSTALL_READER_KEPT); saved checks are corrected on read. - The sweep sends nothing: the message and its told and claim records are gone. Another account is the AWS page's quiet item with its one-click stack. - The access stack's reader update (lambda/native-reader) creates or updates CoderHelmLogReaderUpdate-release from the running release's update template after each update of the install's stack, daily and on its own create, with read-only groups only. Its role may only do that, only from a release's update template and only through CloudFormation. - The updater asks for the access stack once when it lacks the reader update. - Docs and incident rq_reader_reads_arrive_with_the_release. --- ...rq_reader_reads_arrive_with_the_release.md | 12 ++ docs/self-host/integrations.md | 6 +- docs/self-host/security.md | 15 +- docs/self-host/updates.md | 2 + infra/lib/native/access-stack.ts | 136 +++++++++++- infra/lib/service-env.ts | 5 + infra/test/native-access.test.ts | 93 ++++++++- infra/test/synth.test.ts | 3 + lambda/native-reader/handler.py | 183 ++++++++++++++++ lambda/tests/test_native_reader.py | 197 ++++++++++++++++++ lambda/tests/test_updater_access.py | 48 +++++ lambda/updater/handler.py | 22 +- services/common/src/live/aws.rs | 41 ++++ services/common/src/live/aws_account.rs | 15 +- services/common/src/live/permissions.rs | 46 +++- services/common/src/notify/messages.rs | 65 ------ services/gateway/src/routes/integrations.rs | 13 +- services/worker/src/passes/aws_permissions.rs | 157 +++----------- ...rq_reader_reads_arrive_with_the_release.rs | 197 ++++++++++++++++++ 19 files changed, 1030 insertions(+), 226 deletions(-) create mode 100644 docs/incidents/rq_reader_reads_arrive_with_the_release.md create mode 100644 lambda/native-reader/handler.py create mode 100644 lambda/tests/test_native_reader.py create mode 100644 services/worker/src/passes/incidents/rq_reader_reads_arrive_with_the_release.rs diff --git a/docs/incidents/rq_reader_reads_arrive_with_the_release.md b/docs/incidents/rq_reader_reads_arrive_with_the_release.md new file mode 100644 index 000000000..bbf7fff45 --- /dev/null +++ b/docs/incidents/rq_reader_reads_arrive_with_the_release.md @@ -0,0 +1,12 @@ +# rq. `rq_reader_reads_arrive_with_the_release` + +**What happened:** The owner of a self-hosted install got a push alert in their team's channel: "AWS account (the install's own account) needs 1 new read-only permission. This CoderHelm release reads a little more from your AWS accounts... Until an admin updates the CoderHelmLogReader role, the parts that need it are skipped." The account was the install's own. The daily sweep (`passes::aws_permissions`) skipped the install's own account only when the check's `install_account` was true, but the check's builder always wrote false; only tests ever set it. So that account was treated like any other: the alert went out, and the AWS page offered the one-click update stack for it. And since every team read is made as the account's `CoderHelmLogReader` (case `rk`), that role in the install's own account really did fall behind each release: nothing in the release updated it. + +**The guarantee:** +- No push alert for new read-only permissions, ever: the daily sweep only checks every account and saves the result for the AWS page. Its told and claim records and the message are gone. +- Another account shows it only as the AWS page's quiet item, **Update needed**, with its one-click update stack, and as the install's **AWS role reads** setup item. +- The install's own account on a one-stack install is marked by the check's own builder (`PermissionCheck::new`, from the install's read role and `INSTALL_READER_KEPT`). It gets no update stack, no setup item, and the page says it updates with the release. +- The release brings the reads itself: the access stack's reader update (`lambda/native-reader`, `infra/lib/native/access-stack.ts`) runs after each update of the install's stack, once a day, and when an admin applies the access stack. It creates or updates `CoderHelmLogReaderUpdate-release` from the running release's published update template, with read-only groups only. Its role may do only that, only from that template, and may write only that role's policy, only through CloudFormation. +- An access stack made before the reader update asks an AWS admin once (Settings, System, Permissions). From then on, no release needs anyone for that role's reads. + +**Test:** `services/worker/src/passes/incidents/rq_reader_reads_arrive_with_the_release.rs` diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index c89a926b8..1e662a2b7 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -21,9 +21,9 @@ Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alar - **Making the role by hand**\ The AWS page lists every action the role needs, grouped by what CoderHelm reads with it, and your install's account id. Create the role named `CoderHelmLogReader`, let your install's account assume it only with the team's External ID, and allow those actions. - **Reading the install's own account**\ - Connect it the same way: the `CoderHelmLogReader` role there, with the team's External ID. Every read of the account (logs, metrics, WAF, settings and the rest) is made as that role, exactly as in any other account, so AWS records every read under the team's role and the permission check looks at the same role. When a release adds a read, the account shows **Update in AWS** like any other. Knowledge bases in the install's account are the one exception: the install's own role searches them (see [bedrock.md](bedrock.md)). + Connect it the same way: the `CoderHelmLogReader` role there, with the team's External ID. Every read of the account (logs, metrics, WAF, settings and the rest) is made as that role, exactly as in any other account, so AWS records every read under the team's role and the permission check looks at the same role. When a release adds a read, a one-stack install (Launch Stack) brings it to that role by itself: its access stack's reader update runs after each update of the install's stack, and creates or updates the stack `CoderHelmLogReaderUpdate-release` from that release's update template, with the read-only groups only (see [security.md](security.md#the-reader-update)). So the account shows **Updates with the release** and nothing to do: no **Update in AWS**, no setup item. An install from the CLI has no reader update, so there its own account shows **Update in AWS** like any other. Knowledge bases in the install's account are the one exception: the install's own role searches them (see [bedrock.md](bedrock.md)). - **When a release needs new permissions**\ - Each AWS connection shows **Permissions up to date** or **Update needed: N new read-only permissions**. The check runs live: it asks IAM's policy simulator about the role (`iam:SimulatePrincipalPolicy` on that one role), or, for roles made before that, tries the cheapest read of each kind. **Update in AWS** opens a stack (`CoderHelmLogReaderUpdate-`) that adds exactly this release's permissions to the existing role. Sign in to the role's account, review it and press **Create stack**. When you come back, the page checks again by itself. If something went wrong, it names the reason and the fix: the stack failed, it isn't in the role's account, a permissions boundary or an organization policy (SCP) blocks the permissions. Once a day the install checks every account, and each team's Slack or Teams channel hears once per release that needs an update. Until then, features that need a missing permission say so where they are used, skip that step and keep working with the rest. + Each AWS connection shows **Permissions up to date** or **Update needed: N new read-only permissions**. The check runs live: it asks IAM's policy simulator about the role (`iam:SimulatePrincipalPolicy` on that one role), or, for roles made before that, tries the cheapest read of each kind. **Update in AWS** opens a stack (`CoderHelmLogReaderUpdate-`) that adds exactly this release's permissions to the existing role. Sign in to the role's account, review it and press **Create stack**. When you come back, the page checks again by itself. If something went wrong, it names the reason and the fix: the stack failed, it isn't in the role's account, a permissions boundary or an organization policy (SCP) blocks the permissions. Once a day the install checks every account again. None of this is ever sent to Slack, Teams or email: it is only the account's line on the AWS page and the **AWS role reads** setup item. Until the role is updated, features that need a missing permission say so where they are used, skip that step and keep working with the rest. - **One template for every read**\ Every read CoderHelm has in a team's account is declared in the role stack's one template, `coderhelm-log-reader.yaml`, published with each release (`launch//`). Reads that only some teams need are named groups, each switched on by a stack parameter. The update template next to it (`coderhelm-log-reader-update.yaml`) has the same groups and parameters: @@ -41,7 +41,7 @@ Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alar - **Roles the older script made**\ Before this, the data-source script made a role named `CoderhelmReadOnly` and wrote its permissions by hand, so no release could reach it. Those connections keep working. The account's update link names every database and warehouse the team's data sources read there, and the **AWS role reads** item says how many still use the older role. Once an AWS admin creates that update, the daily permissions check tries each such source with the stack's role: the same database, user and secret. Only a source whose own connection check passes end to end (the role is taken on, the read-only user signs in, tables are listed) is switched; the rest stay on the older role and are tried again the next day. CoderHelm never changes or deletes `CoderhelmReadOnly`; delete it once no data source uses it. - **How a release's new reads reach a team**\ - A release can't add a read to a team's role by itself: CoderHelm's own roles have a permissions boundary that forbids changing IAM, so a person always approves a wider role. When a release changes the template, or an alert route or data source needs a group the role lacks, the install shows one setup item for the whole install, **AWS role reads** (`aws_role_reads` in Settings, then **Setup**). For each account it says why: a read a run was refused (for example `glue:GetDatabases` for a WAF alarm's logs), a role older than this release, or data sources still on the older role. Its link is the one-click update of that account's role (**Create stack** on `CoderHelmLogReaderUpdate-`), from this release's template with the account's groups and what CoderHelm found filled in. An AWS admin of that account opens it signed in there, reviews it and creates it. Until then, runs read what the role allows, name the item in one line and go on: no run asks a person for access, and none waits on it. On a self-hosted install, the install's own account is no exception for these groups: WAF logs, databases and warehouses are read through the connected `CoderHelmLogReader` role there too, never through the install's gateway and worker roles, so the install's permission limit and its access stack don't grow for them. + A release can't add a read to a team's role by itself: CoderHelm's own roles have a permissions boundary that forbids changing IAM, so a person always approves a wider role. The one exception is the install's own account on a one-stack install, where the access stack an AWS admin applied does it after each update (the reader update), with this release's read-only groups only; the groups a team chose there (knowledge bases, imports, WAF logs, databases, warehouses) still come from the team's own update stack. When a release changes the template, or an alert route or data source needs a group the role lacks, the install shows one setup item for the whole install, **AWS role reads** (`aws_role_reads` in Settings, then **Setup**). For each account it says why: a read a run was refused (for example `glue:GetDatabases` for a WAF alarm's logs), a role older than this release, or data sources still on the older role. Its link is the one-click update of that account's role (**Create stack** on `CoderHelmLogReaderUpdate-`), from this release's template with the account's groups and what CoderHelm found filled in. An AWS admin of that account opens it signed in there, reviews it and creates it. Until then, runs read what the role allows, name the item in one line and go on: no run asks a person for access, and none waits on it. On a self-hosted install, the install's own account is no exception for these groups: WAF logs, databases and warehouses are read through the connected `CoderHelmLogReader` role there too, never through the install's gateway and worker roles, so the install's permission limit and its access stack don't grow for them. - **Alert routes (SNS)**\ **Settings, Alerts** shows the subscription endpoint, `https://coderhelm.example.com/webhooks/alerts/sns`. Save and turn on the route before you subscribe the topic: CoderHelm only confirms subscriptions for topics with a route that's on. If you subscribed first, press **Request confirmation** on the subscription in SNS. Every message's signature is checked before anything else. - **Alarms that keep firing**\ diff --git a/docs/self-host/security.md b/docs/self-host/security.md index 00ef64b9f..1e99200e7 100644 --- a/docs/self-host/security.md +++ b/docs/self-host/security.md @@ -37,7 +37,7 @@ order: 11 - Each function has its own role with only the tables, queues, keys and actions it uses. - The build sandbox runs a repository's own build scripts, which are untrusted: its CodeBuild role can only read and write one bucket of short-lived source tarballs and write its logs. No GitHub token, no tables, no KMS. -- Roles in teams' AWS accounts are assumed only by name (`CoderHelmLogReader`, `CoderhelmReadOnly*`) and with an external id. Every read they have is declared in one template, `coderhelm-log-reader.yaml`, as named groups a stack parameter switches on (see [Integrations](./integrations.md#connected-aws-accounts)), and a release reaches a team's role only through the one-click update an AWS admin of that account creates: CoderHelm can't widen a team's role by itself. The WAF log group's one write is `s3:PutObject` for Athena query results, only under the results location the stack names and denied everywhere else; its `kms:Decrypt` is on the named key, only through S3. Roles named `CoderhelmReadOnly` were made by an older setup script; CoderHelm moves data sources off them once the stack's role reads them, and never changes them. When the data is in the install's own account, see the exception in [The permissions boundary](#the-permissions-boundary). +- Roles in teams' AWS accounts are assumed only by name (`CoderHelmLogReader`, `CoderhelmReadOnly*`) and with an external id. Every read they have is declared in one template, `coderhelm-log-reader.yaml`, as named groups a stack parameter switches on (see [Integrations](./integrations.md#connected-aws-accounts)), and a release reaches a team's role only through the one-click update an AWS admin of that account creates: CoderHelm can't widen a team's role by itself. The one exception is `CoderHelmLogReader` in a one-stack install's own account, which the access stack an AWS admin applied brings up to each release's read-only groups ([The reader update](#the-reader-update)). The WAF log group's one write is `s3:PutObject` for Athena query results, only under the results location the stack names and denied everywhere else; its `kms:Decrypt` is on the named key, only through S3. Roles named `CoderhelmReadOnly` were made by an older setup script; CoderHelm moves data sources off them once the stack's role reads them, and never changes them. When the data is in the install's own account, see the exception in [The permissions boundary](#the-permissions-boundary). - An install made with Launch Stack holds no broad standing rights in your account: see [What an install can do in your account](#what-an-install-can-do-in-your-account). ## What an install can do in your account @@ -148,6 +148,19 @@ It can't choose the code: only a published release's template. It does choose th **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, and the EC2 and log calls CloudFormation makes for a private network's security group, function and log group, against the deploy role before it runs. When the deploy role is behind (its access stack is at an older release than the one running), such an update never starts: it says to apply the access stack update first, and Settings, System, Permissions shows it as needed. 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`: created once, then updated in place with each newer release's `access.json`, never deleted and made again (Settings, System, Permissions; [Updates](./updates.md#permissions)). CoderHelm asks for it only when what is new matters to something the install uses: a read that only one switch of the AWS card uses counts only while that switch is on. 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. +### The reader update + +Every read of a team's data in the install's own account is made as the team's `CoderHelmLogReader` role there, and the install's own roles may never change IAM. So the same access stack carries one more function, `CoderHelmReader-` (lambda/native-reader), which brings each release's read-only permissions to that role with no step of anyone's: + +- it runs when the install's stack finishes an update (CloudFormation's stack status event: a version update or a switch of the AWS card), once a day, and when an admin creates or updates the access stack; +- when the role `CoderHelmLogReader` exists in the account, it creates or updates one stack, `CoderHelmLogReaderUpdate-release`, from the running release's published update template (`https://coderhelm-public.s3.amazonaws.com/launch//coderhelm-log-reader-update.yaml`), the same template every **Update in AWS** link opens; +- with read-only groups only: the three switches of the AWS card as the install's stack has them, and every other parameter empty or off. It never names a knowledge base, a bucket, WAF logs, a database or a warehouse, never copies into Bedrock and never turns on database maintenance; a team's choices there stay on its own update stacks; +- its role may create and update only that stack, and only from a release's update template (`cloudformation:TemplateUrl`); it may write only that role's inline policies, and only through CloudFormation (`aws:CalledVia`); its other calls are reads (the install's stack, the role, a template's parameters) and its own log; +- like the writer it is named outside the install's names, so no CoderHelm role can invoke, pass or change it, and it never reads the event it is sent; +- deleting the access stack leaves `CoderHelmLogReaderUpdate-release` in place. + +An access stack made before the reader update asks for it once (Settings, System, Permissions: "adds the reader update"). An install from the CLI has none, so its own account's role is updated like any other account's. + - 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). - Its policy is the deploy policy from `infra/lib/access.ts`, plus every CloudFormation action on the parent stack and its parts, reading the release bucket, reading and updating (never deleting) the install's secret, and the install guide's progress bucket. `infra/test/fixtures/native-sim.json` holds AWS's IAM policy simulator verdict on every call CloudFormation makes through it. The deploy policy lets it: diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index 5a66bee04..a42fd68cb 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -152,6 +152,8 @@ The CloudFormation console has no link that opens an update with a new template A stack of that name that something else made, like the boundary stack of an install hardened from the CLI, is never updated or deleted from here; the card says to ask CoderHelm support. No CoderHelm role can create, change or delete a stack of that name. +The access stack also carries the reader update ([security.md](./security.md#the-reader-update)): after each update of the install's stack it brings that release's read-only permissions to `CoderHelmLogReader` in your install's own account, so that account never needs an **Update in AWS**. An access stack from before it shows **adds the reader update** once. + Updates never wait for this item, and it never waits for an update. ### An install launched from v0.8.54-beta.20261108 diff --git a/infra/lib/native/access-stack.ts b/infra/lib/native/access-stack.ts index bffbe1559..0f02eb356 100644 --- a/infra/lib/native/access-stack.ts +++ b/infra/lib/native/access-stack.ts @@ -23,6 +23,17 @@ * custom resource's Version is the release, so every update with a newer * template runs the writer again. * + * The same stack keeps CoderHelmLogReader in the install's own account + * current (lambda/native-reader/handler.py, the reader update): every team + * read there is made as that role, and the install's own roles may never + * change IAM. After each update of the install's stack (CloudFormation's + * stack status event), once a day, and when the admin creates or updates + * this stack, its function creates or updates one stack, + * CoderHelmLogReaderUpdate-release, from the running release's published + * update template, with read-only groups only. Its role may do exactly that + * (READER_TEMPLATE_URL, aws:CalledVia) and nothing else, and like the + * writer it is named outside the install's prefix. + * * 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 @@ -40,6 +51,15 @@ 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 reader update's function, role and rules: outside coderhelm--*, like the writer. */ +export const READER_UPDATE_NAME = "CoderHelmReader-${Stage}"; +/** The role it updates (infra/cfn/coderhelm-log-reader.yaml, RoleName). */ +export const LOG_READER_ROLE = "CoderHelmLogReader"; +/** The one stack it creates and updates: its inline policy on that role is named after it. */ +export const READER_UPDATE_STACK = "CoderHelmLogReaderUpdate-release"; +/** The only templates it may create that stack from: a release's published update template. */ +export const READER_TEMPLATE_URL = "https://coderhelm-public.s3.amazonaws.com/launch/v*/coderhelm-log-reader-update.yaml"; + /** 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"]; @@ -53,8 +73,117 @@ export const ACCESS_SHAPE = { WriterRole: { Type: "AWS::IAM::Role", RoleName: ACCESS_WRITER_NAME }, Writer: { Type: "AWS::Lambda::Function", FunctionName: ACCESS_WRITER_NAME }, Access: { Type: "Custom::Access" }, + ReaderRole: { Type: "AWS::IAM::Role", RoleName: READER_UPDATE_NAME }, + Reader: { Type: "AWS::Lambda::Function", FunctionName: READER_UPDATE_NAME }, + ReaderAfterUpdate: { Type: "AWS::Events::Rule" }, + ReaderDaily: { Type: "AWS::Events::Rule" }, + ReaderFromUpdate: { Type: "AWS::Lambda::Permission" }, + ReaderFromDaily: { Type: "AWS::Lambda::Permission" }, + ReaderNow: { Type: "Custom::ReaderUpdate" }, } as const; +/** + * The reader update's own permissions: read the install's stack (its release + * and switches), find CoderHelmLogReader, and create, update or remove the + * one stack CoderHelmLogReaderUpdate-release, only from a release's update + * template; that stack's inline policy on the role is written only through + * CloudFormation. No other IAM call, no other stack, no other role. + */ +export function readerPolicy(): Json { + const stack = `arn:\${AWS::Partition}:cloudformation:\${AWS::Region}:\${AWS::AccountId}:stack/${READER_UPDATE_STACK}/*`; + const role = `arn:\${AWS::Partition}:iam::\${AWS::AccountId}:role/${LOG_READER_ROLE}`; + return sub({ + Version: "2012-10-17", + Statement: [ + { Sid: "InstallStack", Effect: "Allow", Action: "cloudformation:DescribeStacks", Resource: "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}/*" }, + { Sid: "FindTheReader", Effect: "Allow", Action: "iam:GetRole", Resource: role }, + // A template's parameter names, so only the ones it declares are given. + { Sid: "TemplateParameters", Effect: "Allow", Action: "cloudformation:GetTemplateSummary", Resource: "*" }, + { + Sid: "ReleaseTemplateOnly", + Effect: "Allow", + Action: ["cloudformation:CreateStack", "cloudformation:UpdateStack"], + Resource: stack, + Condition: { StringLike: { "cloudformation:TemplateUrl": READER_TEMPLATE_URL } }, + }, + // A first create that rolled back can't be updated: it is removed and made again. + { Sid: "ReaderStack", Effect: "Allow", Action: ["cloudformation:DescribeStacks", "cloudformation:DeleteStack"], Resource: stack }, + { + Sid: "ReaderPolicyThroughCloudFormation", + Effect: "Allow", + Action: ["iam:GetRolePolicy", "iam:PutRolePolicy", "iam:DeleteRolePolicy"], + Resource: role, + Condition: { "ForAnyValue:StringEquals": { "aws:CalledVia": ["cloudformation.amazonaws.com"] } }, + }, + { + Sid: "OwnLog", + Effect: "Allow", + Action: ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], + Resource: `arn:\${AWS::Partition}:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:/aws/lambda/${READER_UPDATE_NAME}:*`, + }, + ], + }); +} + +/** The reader update's resources (the file's comment: the reader update). */ +export function readerResources(version: string, code: string): Json { + const target = [{ Id: "reader", Arn: { "Fn::GetAtt": ["Reader", "Arn"] } }]; + const allow = (rule: string) => ({ + Type: "AWS::Lambda::Permission", + Properties: { FunctionName: { Ref: "Reader" }, Action: "lambda:InvokeFunction", Principal: "events.amazonaws.com", SourceArn: { "Fn::GetAtt": [rule, "Arn"] } }, + }); + return { + ReaderRole: { + Type: "AWS::IAM::Role", + Properties: { + RoleName: sub(READER_UPDATE_NAME), + Description: "CoderHelm: brings each release's read-only permissions to CoderHelmLogReader in this account (made by an AWS admin)", + AssumeRolePolicyDocument: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole" }] }, + Policies: [{ PolicyName: "reader-update", PolicyDocument: readerPolicy() }], + }, + }, + Reader: { + Type: "AWS::Lambda::Function", + Properties: { + FunctionName: sub(READER_UPDATE_NAME), + Description: "CoderHelm: the access stack's reader update (lambda/native-reader)", + Runtime: "python3.12", + Handler: "index.handler", + Timeout: 300, + Role: { "Fn::GetAtt": ["ReaderRole", "Arn"] }, + Environment: { Variables: { ROOT_STACK: sub("coderhelm-${Stage}") } }, + Code: { ZipFile: code }, + }, + }, + // After each update of the install's stack: a version update or a switch of the AWS card. + ReaderAfterUpdate: { + Type: "AWS::Events::Rule", + Properties: { + Name: sub(`${READER_UPDATE_NAME}-updated`), + Description: "CoderHelm: the install's stack finished an update", + EventPattern: { + source: ["aws.cloudformation"], + "detail-type": ["CloudFormation Stack Status Change"], + detail: { + "stack-id": [{ prefix: sub("arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}/") }], + "status-details": { status: ["UPDATE_COMPLETE"] }, + }, + }, + Targets: target, + }, + }, + // A reader made after the last update, or an event that never came. + ReaderDaily: { + Type: "AWS::Events::Rule", + Properties: { Name: sub(`${READER_UPDATE_NAME}-daily`), Description: "CoderHelm: the reader update, once a day", ScheduleExpression: "rate(1 day)", Targets: target }, + }, + ReaderFromUpdate: allow("ReaderAfterUpdate"), + ReaderFromDaily: allow("ReaderDaily"), + // At once, when the admin creates or updates this stack (its Version changes with every release). + ReaderNow: { Type: "Custom::ReaderUpdate", Properties: { ServiceToken: { "Fn::GetAtt": ["Reader", "Arn"] }, Version: version } }, + }; +} + export function writerPolicy(): Json { const n = nativeNames(); return sub({ @@ -77,17 +206,19 @@ export function writerPolicy(): Json { }); } -export function buildAccess(version: string, writerCode?: string): Json { +export function buildAccess(version: string, writerCode?: string, readerCode?: string): Json { const n = nativeNames(); const all = parameters(); const code = writerCode ?? fs.readFileSync(repoPath("lambda/native-access/handler.py"), "utf8"); + const reader = readerCode ?? fs.readFileSync(repoPath("lambda/native-reader/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. " + + "coderhelm--deploy-boundary-stack and the deploy role's policy, only where they differ, and after each update it brings the " + + "release's read-only permissions to CoderHelmLogReader in this account (the stack CoderHelmLogReaderUpdate-release). Deleting this stack changes nothing. " + "docs.coderhelm.com/self-host/security", // reads: the boundary's reads only one switch of the AWS card uses (access.ts), // so the updater asks an admin for them only when that switch is on. @@ -128,6 +259,7 @@ export function buildAccess(version: string, writerCode?: string): Json { DeployRole: { RoleName: sub(n.deployRoleName), PolicyName: "deploy", Document: subInstall(deployRolePolicy(n)) }, }, }, + ...readerResources(version, reader), }, Outputs: { Version: { Description: "The CoderHelm release whose permissions this stack applied", Value: version }, diff --git a/infra/lib/service-env.ts b/infra/lib/service-env.ts index 1eada79db..ce548cf6d 100644 --- a/infra/lib/service-env.ts +++ b/infra/lib/service-env.ts @@ -43,6 +43,11 @@ export function serviceEnvironment(cfg: ResolvedConfig, account: string): Record // Whether "Sign in with Google" is on (Settings, then Setup checks it). env.GOOGLE_SIGN_IN = cfg.integrations.googleSignIn ? "true" : "false"; if (cfg.updates.enabled) env.UPDATER_FUNCTION_NAME = `${cfg.prefix}-updater`; + // A one-stack install's access stack brings each release's read-only + // permissions to CoderHelmLogReader in its own account (the reader + // update, native/access-stack.ts): that account's role is never a + // person's update (services/common/src/live/aws.rs, READER_KEPT_ENV). + if (cfg.native) env.INSTALL_READER_KEPT = "1"; } // Hybrid: a self-hosted install's hosted API (used only once an admin turns // a hybrid part on), and the zone `{name}.` addresses live in. diff --git a/infra/test/native-access.test.ts b/infra/test/native-access.test.ts index bcf3c3c86..5b1953da7 100644 --- a/infra/test/native-access.test.ts +++ b/infra/test/native-access.test.ts @@ -25,7 +25,7 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import { accessNames, BOUNDARY_OPTION_READS, boundaryPolicy, PolicyDocument } from "../lib/access"; -import { ACCESS_PARAMETERS, ACCESS_SHAPE, ACCESS_WRITER_NAME, buildAccess, writerPolicy } from "../lib/native/access-stack"; +import { ACCESS_PARAMETERS, ACCESS_SHAPE, ACCESS_WRITER_NAME, buildAccess, READER_UPDATE_NAME, readerPolicy, writerPolicy } from "../lib/native/access-stack"; import { buildNative } from "../lib/native/build"; import { ACCESS_FILE, deployRolePolicy, nativeBoundaryDoc, nativeNames, pinnedAccess, subInstall } from "../lib/native/parent"; import { plainStatements } from "../lib/own-account-read"; @@ -207,7 +207,9 @@ test("an admin's update of the access stack with a newer access.json changes eve const older = buildAccess("v9.8.6", "def write_policy(): pass\n"); const newer = buildAccess("v9.8.7", "def write_policy(): pass # newer\n"); // The same logical ids, types and fixed names as every earlier release: nothing is replaced. - assert.deepEqual(Object.keys(newer.Resources).sort(), Object.keys(EARLIER).sort()); + // What a release adds (the reader update) is added beside them, and kept from then on (ACCESS_SHAPE). + for (const id of Object.keys(EARLIER)) assert.ok(id in newer.Resources, id); + assert.deepEqual(Object.keys(newer.Resources).sort(), Object.keys(ACCESS_SHAPE).sort()); for (const [id, want] of Object.entries(EARLIER)) { const r = newer.Resources[id]; assert.equal(r.Type, want.Type, id); @@ -283,3 +285,90 @@ test("every read the install's permission check expects is granted to the roles assert.deepEqual(refused, [], `${part}.${id}`); } }); + +// ── The reader update: the release brings its reads to CoderHelmLogReader here ── + +test("after each update of the install's stack, the access stack's reader update brings the release's reads to CoderHelmLogReader in this account", () => { + const r = ACCESS.Resources; + // Its code is the signed template's, inline: lambda/native-reader/handler.py. + assert.equal(r.Reader.Properties.Code.ZipFile, fs.readFileSync(path.join(__dirname, "..", "..", "..", "lambda", "native-reader", "handler.py"), "utf8")); + assert.deepEqual(r.Reader.Properties.Environment.Variables.ROOT_STACK, { "Fn::Sub": "coderhelm-${Stage}" }); + assert.match(r.Reader.Properties.Code.ZipFile, /STACK = "CoderHelmLogReaderUpdate-release"/); + assert.match(r.Reader.Properties.Code.ZipFile, /TEMPLATE = "coderhelm-log-reader-update.yaml"/); + // It runs when the install's stack finishes an update (a version update or a switch), once a day, and at once. + const pattern = r.ReaderAfterUpdate.Properties.EventPattern; + assert.deepEqual(pattern.source, ["aws.cloudformation"]); + assert.deepEqual(pattern.detail["status-details"].status, ["UPDATE_COMPLETE"]); + assert.deepEqual(pattern.detail["stack-id"], [{ prefix: { "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/coderhelm-${Stage}/" } }]); + assert.equal(r.ReaderDaily.Properties.ScheduleExpression, "rate(1 day)"); + for (const rule of ["ReaderAfterUpdate", "ReaderDaily"]) assert.deepEqual(r[rule].Properties.Targets, [{ Id: "reader", Arn: { "Fn::GetAtt": ["Reader", "Arn"] } }]); + assert.deepEqual(r.ReaderFromUpdate.Properties.SourceArn, { "Fn::GetAtt": ["ReaderAfterUpdate", "Arn"] }); + assert.deepEqual(r.ReaderFromDaily.Properties.SourceArn, { "Fn::GetAtt": ["ReaderDaily", "Arn"] }); + assert.equal(r.ReaderNow.Properties.Version, "v9.8.7"); + assert.equal(r.ReaderNow.Type, "Custom::ReaderUpdate"); +}); + +test("the reader update may write only CoderHelmLogReader's policy, only through CloudFormation, only from a release's update template", () => { + const p = resolveValue(readerPolicy(), { values: prodValues("111122223333", "us-east-1") }) as PolicyDocument; + const role = "arn:aws:iam::111122223333:role/CoderHelmLogReader"; + const stack = "arn:aws:cloudformation:us-east-1:111122223333:stack/CoderHelmLogReaderUpdate-release/abc"; + const release = { "cloudformation:TemplateUrl": "https://coderhelm-public.s3.amazonaws.com/launch/v9.8.7/coderhelm-log-reader-update.yaml" }; + const via = { "aws:CalledVia": ["cloudformation.amazonaws.com"] }; + const can = (action: string, resource: string, context: Record = {}) => decision([p], null, { action, resource, context }) === "allowed"; + // From the release's own update template: allowed. + assert.ok(can("cloudformation:CreateStack", stack, release)); + assert.ok(can("cloudformation:UpdateStack", stack, release)); + // Any other template, or none: refused. + for (const url of ["https://coderhelm-public.s3.amazonaws.com/launch/v9.8.7/coderhelm-log-reader.yaml", "https://example.com/launch/v9.8.7/coderhelm-log-reader-update.yaml", "https://coderhelm-public.s3.amazonaws.com/cfn/coderhelm-log-reader-update.yaml"]) { + assert.ok(!can("cloudformation:UpdateStack", stack, { "cloudformation:TemplateUrl": url }), url); + } + assert.ok(!can("cloudformation:CreateStack", stack)); + // Any other stack: refused, the install's own included. + for (const other of ["arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod/abc", "arn:aws:cloudformation:us-east-1:111122223333:stack/CoderHelmLogReader/abc", "arn:aws:cloudformation:us-east-1:111122223333:stack/CoderHelmLogReaderUpdate-1a2b3c4d/abc"]) { + assert.ok(!can("cloudformation:UpdateStack", other, release), other); + } + // The role's policy: through CloudFormation only, on that one role only. + assert.ok(can("iam:PutRolePolicy", role, via)); + assert.ok(!can("iam:PutRolePolicy", role), "never directly"); + assert.ok(!can("iam:PutRolePolicy", "arn:aws:iam::111122223333:role/coderhelm-prod-worker", via)); + for (const a of ["iam:AttachRolePolicy", "iam:UpdateAssumeRolePolicy", "iam:CreateRole", "iam:PassRole", "iam:CreatePolicy", "iam:PutRolePermissionsBoundary", "iam:DeleteRolePermissionsBoundary"]) { + assert.ok(!can(a, role, via), a); + } + // No IAM action outside that role (GetRole is the one read). + for (const st of p.Statement) { + const acts = ([] as string[]).concat(st.Action ?? []); + if (acts.some((a) => a.startsWith("iam:"))) assert.equal(st.Resource, role, st.Sid); + } +}); + +test("no CoderHelm role can reach the reader update, its role or its rules", () => { + 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 reader = READER_UPDATE_NAME.replace("${Stage}", "prod"); + const calls: [string, string][] = [ + ["lambda:InvokeFunction", `arn:aws:lambda:us-east-1:111122223333:function:${reader}`], + ["lambda:UpdateFunctionCode", `arn:aws:lambda:us-east-1:111122223333:function:${reader}`], + ["lambda:UpdateFunctionConfiguration", `arn:aws:lambda:us-east-1:111122223333:function:${reader}`], + ["lambda:AddPermission", `arn:aws:lambda:us-east-1:111122223333:function:${reader}`], + ["iam:PassRole", `arn:aws:iam::111122223333:role/${reader}`], + ["iam:PutRolePolicy", `arn:aws:iam::111122223333:role/${reader}`], + ["iam:UpdateAssumeRolePolicy", `arn:aws:iam::111122223333:role/${reader}`], + // And the reader role itself stays out of the install's reach, as before. + ["iam:PutRolePolicy", "arn:aws:iam::111122223333:role/CoderHelmLogReader"], + ["iam:AttachRolePolicy", "arn:aws:iam::111122223333:role/CoderHelmLogReader"], + ["cloudformation:UpdateStack", "arn:aws:cloudformation:us-east-1:111122223333:stack/CoderHelmLogReaderUpdate-release/abc"], + ]; + for (const [action, resource] of calls) { + assert.notEqual(decision([anything], boundary, { action, resource, context: { "iam:PermissionsBoundary": names.boundaryArn } }), "allowed", `${action} on ${resource}`); + } +}); + +test("a one-stack install's gateway and worker know the release keeps their own account's reader current", () => { + for (const part of ["Api", "Worker"]) { + const t = JSON.parse(fs.readFileSync(path.join(OUT, "stacks", `${part}.json`), "utf8")); + const fns = Object.values(t.Resources).filter((r) => r.Type === "AWS::Lambda::Function" && r.Properties?.Environment?.Variables?.INSTALL_OWN_ROLE_ARN); + assert.ok(fns.length > 0, part); + for (const f of fns) assert.equal(f.Properties.Environment.Variables.INSTALL_READER_KEPT, "1", part); + } +}); diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 9c2c75148..dac278944 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -370,6 +370,9 @@ test("updates: on by default for self-host, with a least-privilege build role; o // The gateway knows the updater and may call it. assert.equal(envOf(t["coderhelm-prod-api"], "coderhelm-prod-gateway").UPDATER_FUNCTION_NAME, "coderhelm-prod-updater"); assert.ok(json(t["coderhelm-prod-api"]).includes("function:coderhelm-prod-updater")); + // An install from the CLI has no access stack's reader update: its own account's + // CoderHelmLogReader is updated like any other account's (native-access.test.ts has the one-stack install). + assert.equal(envOf(t["coderhelm-prod-api"], "coderhelm-prod-gateway").INSTALL_READER_KEPT, undefined); const off = synth(selfHost({ updates: { enabled: false } })); assert.equal(off["coderhelm-prod-updates"], undefined); diff --git a/lambda/native-reader/handler.py b/lambda/native-reader/handler.py new file mode 100644 index 000000000..80694ee0e --- /dev/null +++ b/lambda/native-reader/handler.py @@ -0,0 +1,183 @@ +"""The access stack's reader update (infra/lib/native/access-stack.ts). + +Every read of a team's data in a native install's own AWS account is made +as the team's CoderHelmLogReader role there, and each release may read a +little more. The install's own roles may never change IAM, so on their own +they can't bring those reads to that role. This function does, with exactly +the release's published update template and nothing else: + + - when the install's stack finishes an update (CloudFormation's stack + status event), once a day, and when an AWS admin creates or updates the + access stack; + - only when the role CoderHelmLogReader exists in the account; + - it creates or updates one stack, CoderHelmLogReaderUpdate-release, from + https://coderhelm-public.s3.amazonaws.com/launch//coderhelm-log-reader-update.yaml, + the template every Update link of the AWS page opens; + - with only the release's read-only groups: the three switches of the AWS + card as the install's stack has them (InfrastructureVulnerabilities, + InspectorFindings, HealthEvents) and every other parameter empty or + off, so no knowledge base, bucket, WAF log, database or warehouse, no + copying into Bedrock and no database maintenance. What a team chose in + the account stays on its own update stacks. + +Its role (outside the install's names, so no CoderHelm role can invoke, +pass or change it) may create and update only that stack, only from that +template URL (cloudformation:TemplateUrl), and may write only that role's +inline policies, only through CloudFormation (aws:CalledVia). It never +reads the event it is sent: every run does the same thing. + +As a custom resource it always answers SUCCESS: a reader it couldn't update +never fails the admin's access stack (the next run tries again, and the AWS +page says what the role lacks). +""" + +import json +import os +import re +import urllib.request + +ROLE = "CoderHelmLogReader" +STACK = "CoderHelmLogReaderUpdate-release" +HOST = "coderhelm-public.s3.amazonaws.com" +TEMPLATE = "coderhelm-log-reader-update.yaml" +VERSION_RE = re.compile(r"^v\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$") +RESPONSE_URL_RE = re.compile(r"^https://cloudformation-custom-resource-response-[a-z0-9-]+\.s3(\.[a-z0-9-]+)?\.amazonaws\.com/") +# The AWS card's switches: the install's stack parameter, and its default +# when the stack has none (infra/lib/own-account-read.ts, OWN_OPTIONS). +SWITCHES = {"InfrastructureVulnerabilities": "on", "InspectorFindings": "off", "HealthEvents": "off"} +# Every other parameter of the update template: empty or off. A parameter a +# later template adds and this list doesn't know keeps the template's own +# default (each template's opt-ins default to off). +FIXED = { + "RoleName": ROLE, + "KnowledgeBases": "", + "ImportBuckets": "", + "SyncKnowledgeBases": "", + "ApplyMaintenance": "off", + "WafLogs": "off", + "WafLogResults": "", + "WafLogKey": "", + "DatabaseClusters": "", + "Warehouses": "", +} +# A stack in one of these can't be updated: it is removed (only this stack, +# whose one resource is this function's inline policy) and made again. +DEAD = ("ROLLBACK_COMPLETE", "ROLLBACK_FAILED", "CREATE_FAILED", "DELETE_FAILED") + +_clients = {} + + +def client(name): + if name not in _clients: + import boto3 + _clients[name] = boto3.client(name) + return _clients[name] + + +def _missing(e): + text = type(e).__name__ + str(e) + return "NoSuchEntity" in text or "does not exist" in text + + +def template_url(version): + if not VERSION_RE.match(str(version or "")): + raise ValueError(f"not a release version: {version!r}") + return f"https://{HOST}/launch/{version}/{TEMPLATE}" + + +def running(cfn, root): + """(version, switches) of the install's stack, or (None, reason) while it can't be read as finished.""" + st = cfn.describe_stacks(StackName=root)["Stacks"][0] + status = st.get("StackStatus") or "" + if status.endswith("_IN_PROGRESS"): + return None, f"the install's stack is busy ({status})" + out = {o.get("OutputKey"): o.get("OutputValue") for o in st.get("Outputs") or []} + version = out.get("Version") + if not VERSION_RE.match(str(version or "")): + return None, "the install's stack names no release (its Version output)" + have = {p.get("ParameterKey"): p.get("ParameterValue") for p in st.get("Parameters") or []} + switches = {k: (have.get(k) if have.get(k) in ("on", "off") else d) for k, d in SWITCHES.items()} + return version, switches + + +def parameters(declared, switches): + """The stack's parameters: only ones the template declares, read-only groups only.""" + values = dict(FIXED, **switches) + return [{"ParameterKey": k, "ParameterValue": values[k]} for k in sorted(declared) if k in values] + + +def keep(cfn=None, iam=None, root=None): + """Brings CoderHelmLogReader up to the running release. Returns what it did, in a few words.""" + cfn = cfn or client("cloudformation") + iam = iam or client("iam") + root = root or os.environ["ROOT_STACK"] + try: + iam.get_role(RoleName=ROLE) + except Exception as e: # noqa: BLE001 + if _missing(e): + return "no CoderHelmLogReader role in this account: nothing to update" + raise + version, switches = running(cfn, root) + if version is None: + return f"not now: {switches}" + url = template_url(version) + declared = [p["ParameterKey"] for p in cfn.get_template_summary(TemplateURL=url).get("Parameters") or []] + params = parameters(declared, switches) + try: + st = cfn.describe_stacks(StackName=STACK)["Stacks"][0] + except Exception as e: # noqa: BLE001 + if not _missing(e): + raise + st = None + status = (st or {}).get("StackStatus") or "" + if status.endswith("_IN_PROGRESS"): + return f"{STACK} is busy ({status}): the next run updates it" + if status in DEAD: + cfn.delete_stack(StackName=STACK) + cfn.get_waiter("stack_delete_complete").wait(StackName=STACK, WaiterConfig={"Delay": 5, "MaxAttempts": 30}) + st = None + args = { + "StackName": STACK, + "TemplateURL": url, + "Parameters": params, + "Capabilities": ["CAPABILITY_IAM"], + } + if st is None: + cfn.create_stack(**args) + return f"creating {STACK} from {version}'s update template" + try: + cfn.update_stack(**args) + except Exception as e: # noqa: BLE001 + if "No updates are to be performed" in str(e): + return f"{ROLE} already has {version}'s reads" + raise + return f"updating {STACK} to {version}'s update template" + + +def respond(event, status, reason): + body = json.dumps({ + "Status": status, "Reason": (reason or status)[:3500], + "PhysicalResourceId": event.get("PhysicalResourceId") or "reader-update", + "StackId": event["StackId"], "RequestId": event["RequestId"], + "LogicalResourceId": event["LogicalResourceId"], "Data": {}, + }).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, **kw): + custom = isinstance(event, dict) and "ResponseURL" in event and "RequestType" in event + if custom and event.get("RequestType") == "Delete": + reason = "nothing changed: the reader keeps what it has" + else: + try: + reason = keep(**kw) + except Exception as e: # noqa: BLE001 + reason = f"not updated ({type(e).__name__}: {e}); the next run tries again" + print(reason, flush=True) + if custom: + respond(event, "SUCCESS", reason) + return {"result": reason} diff --git a/lambda/tests/test_native_reader.py b/lambda/tests/test_native_reader.py new file mode 100644 index 000000000..40e7880e3 --- /dev/null +++ b/lambda/tests/test_native_reader.py @@ -0,0 +1,197 @@ +"""The access stack's reader update (lambda/native-reader): after each +release update, CoderHelmLogReader in the install's own account gets that +release's read-only permissions, from the release's own update template, +with no person doing anything. + +Run: python3 -m unittest discover -s lambda/tests +""" + +import importlib.util +import pathlib +import unittest + +HANDLER = pathlib.Path(__file__).resolve().parents[1] / "native-reader" / "handler.py" +spec = importlib.util.spec_from_file_location("native_reader", HANDLER) +reader = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reader) + +TEMPLATE = pathlib.Path(__file__).resolve().parents[2] / "infra" / "cfn" / "coderhelm-log-reader-update.yaml" + + +def declared(): + """The parameters the update template in this repo declares (top-level keys under Parameters:).""" + out, inside = [], False + for line in TEMPLATE.read_text().splitlines(): + if line.startswith("Parameters:"): + inside = True + continue + if inside and line and not line.startswith(" "): + break + if inside and line.startswith(" ") and not line.startswith(" ") and line.rstrip().endswith(":"): + out.append(line.strip()[:-1]) + return out + + +class Missing(Exception): + pass + + +class FakeIam: + def __init__(self, role=True): + self.role = role + + def get_role(self, RoleName): + assert RoleName == "CoderHelmLogReader" + if not self.role: + raise Missing("An error occurred (NoSuchEntity): The role with name CoderHelmLogReader cannot be found.") + return {"Role": {"RoleName": RoleName}} + + +class Waiter: + def wait(self, **kw): + pass + + +class FakeCfn: + def __init__(self, root_status="UPDATE_COMPLETE", version="v0.9.4", reader_status=None, params=None, no_updates=False): + self.root = {"StackName": "coderhelm-acme", "StackStatus": root_status, + "Outputs": [{"OutputKey": "Version", "OutputValue": version}], + "Parameters": params if params is not None else [ + {"ParameterKey": "InfrastructureVulnerabilities", "ParameterValue": "on"}, + {"ParameterKey": "InspectorFindings", "ParameterValue": "on"}, + {"ParameterKey": "HealthEvents", "ParameterValue": "off"}]} + self.reader_status = reader_status + self.no_updates = no_updates + self.calls = [] + + def describe_stacks(self, StackName): + if StackName == "coderhelm-acme": + return {"Stacks": [self.root]} + assert StackName == reader.STACK + if self.reader_status is None: + raise Missing(f"An error occurred (ValidationError): Stack with id {StackName} does not exist") + return {"Stacks": [{"StackName": StackName, "StackStatus": self.reader_status}]} + + def get_template_summary(self, TemplateURL): + self.calls.append(("summary", TemplateURL)) + return {"Parameters": [{"ParameterKey": k} for k in declared()]} + + def create_stack(self, **kw): + self.calls.append(("create", kw)) + + def update_stack(self, **kw): + self.calls.append(("update", kw)) + if self.no_updates: + raise Exception("An error occurred (ValidationError): No updates are to be performed.") + + def delete_stack(self, StackName): + self.calls.append(("delete", StackName)) + + def get_waiter(self, name): + assert name == "stack_delete_complete" + return Waiter() + + +def written(cfn): + return [c for c in cfn.calls if c[0] in ("create", "update")] + + +class ReaderUpdateTests(unittest.TestCase): + def test_after_a_release_update_the_reader_gets_that_releases_update_template(self): + cfn = FakeCfn() + r = reader.keep(cfn, FakeIam(), "coderhelm-acme") + self.assertIn("creating", r) + [(kind, kw)] = written(cfn) + self.assertEqual(kind, "create") + self.assertEqual(kw["StackName"], "CoderHelmLogReaderUpdate-release") + # The release's own published update template, the one every Update link opens. + self.assertEqual(kw["TemplateURL"], "https://coderhelm-public.s3.amazonaws.com/launch/v0.9.4/coderhelm-log-reader-update.yaml") + self.assertEqual(kw["Capabilities"], ["CAPABILITY_IAM"]) + p = {x["ParameterKey"]: x["ParameterValue"] for x in kw["Parameters"]} + self.assertEqual(p["RoleName"], "CoderHelmLogReader") + # The AWS card's switches as the install's stack has them. + self.assertEqual((p["InfrastructureVulnerabilities"], p["InspectorFindings"], p["HealthEvents"]), ("on", "on", "off")) + + def test_only_read_only_groups_are_ever_switched_on(self): + cfn = FakeCfn() + reader.keep(cfn, FakeIam(), "coderhelm-acme") + p = {x["ParameterKey"]: x["ParameterValue"] for x in written(cfn)[0][1]["Parameters"]} + # Every parameter the template declares is given, and only those. + self.assertEqual(sorted(p), sorted(declared())) + for off in ("ApplyMaintenance", "WafLogs"): + self.assertEqual(p[off], "off", off) + for empty in ("KnowledgeBases", "ImportBuckets", "SyncKnowledgeBases", "WafLogResults", "WafLogKey", "DatabaseClusters", "Warehouses"): + self.assertEqual(p[empty], "", empty) + + def test_a_template_without_a_parameter_never_gets_it(self): + cfn = FakeCfn() + cfn.get_template_summary = lambda TemplateURL: {"Parameters": [{"ParameterKey": "RoleName"}, {"ParameterKey": "InfrastructureVulnerabilities"}]} + reader.keep(cfn, FakeIam(), "coderhelm-acme") + self.assertEqual([x["ParameterKey"] for x in written(cfn)[0][1]["Parameters"]], ["InfrastructureVulnerabilities", "RoleName"]) + + def test_the_next_release_updates_the_same_stack(self): + cfn = FakeCfn(version="v0.9.5", reader_status="UPDATE_COMPLETE") + self.assertIn("updating", reader.keep(cfn, FakeIam(), "coderhelm-acme")) + [(kind, kw)] = written(cfn) + self.assertEqual(kind, "update") + self.assertTrue(kw["TemplateURL"].endswith("/launch/v0.9.5/coderhelm-log-reader-update.yaml")) + + def test_already_current_is_not_a_failure(self): + cfn = FakeCfn(reader_status="CREATE_COMPLETE", no_updates=True) + self.assertIn("already has v0.9.4's reads", reader.keep(cfn, FakeIam(), "coderhelm-acme")) + + def test_no_reader_role_changes_nothing(self): + cfn = FakeCfn() + self.assertIn("nothing to update", reader.keep(cfn, FakeIam(role=False), "coderhelm-acme")) + self.assertEqual(cfn.calls, []) + + def test_a_busy_install_or_reader_waits_for_the_next_run(self): + cfn = FakeCfn(root_status="UPDATE_IN_PROGRESS") + self.assertIn("busy", reader.keep(cfn, FakeIam(), "coderhelm-acme")) + self.assertEqual(written(cfn), []) + cfn = FakeCfn(reader_status="UPDATE_IN_PROGRESS") + self.assertIn("busy", reader.keep(cfn, FakeIam(), "coderhelm-acme")) + self.assertEqual(written(cfn), []) + + def test_a_failed_first_create_is_removed_and_made_again(self): + cfn = FakeCfn(reader_status="ROLLBACK_COMPLETE") + reader.keep(cfn, FakeIam(), "coderhelm-acme") + self.assertEqual([c[0] for c in cfn.calls if c[0] != "summary"], ["delete", "create"]) + + def test_only_a_release_version_names_a_template(self): + cfn = FakeCfn(version="main") + self.assertIn("names no release", reader.keep(cfn, FakeIam(), "coderhelm-acme")) + for bad in ("../x", "v1.2", "", None): + with self.assertRaises(ValueError): + reader.template_url(bad) + + def test_switches_the_stack_lacks_take_their_defaults(self): + cfn = FakeCfn(params=[]) + reader.keep(cfn, FakeIam(), "coderhelm-acme") + p = {x["ParameterKey"]: x["ParameterValue"] for x in written(cfn)[0][1]["Parameters"]} + self.assertEqual((p["InfrastructureVulnerabilities"], p["InspectorFindings"], p["HealthEvents"]), ("on", "off", "off")) + + +class HandlerTests(unittest.TestCase): + def test_the_event_is_never_read_and_a_failure_never_raises(self): + class Broken(FakeCfn): + def describe_stacks(self, StackName): + raise RuntimeError("throttled") + r = reader.handler({"detail": {"anything": "at all"}}, None, cfn=Broken(), iam=FakeIam(), root="coderhelm-acme") + self.assertIn("next run tries again", r["result"]) + + def test_as_a_custom_resource_it_always_answers_success(self): + sent = [] + orig = reader.respond + reader.respond = lambda event, status, reason: sent.append(status) + try: + ev = {"RequestType": "Create", "ResponseURL": "https://x", "StackId": "s", "RequestId": "r", "LogicalResourceId": "ReaderNow"} + reader.handler(ev, None, cfn=FakeCfn(root_status="UPDATE_IN_PROGRESS"), iam=FakeIam(), root="coderhelm-acme") + reader.handler(dict(ev, RequestType="Delete"), None, cfn=FakeCfn(), iam=FakeIam(), root="coderhelm-acme") + finally: + reader.respond = orig + self.assertEqual(sent, ["SUCCESS", "SUCCESS"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/lambda/tests/test_updater_access.py b/lambda/tests/test_updater_access.py index d527b65cd..8753f9326 100644 --- a/lambda/tests/test_updater_access.py +++ b/lambda/tests/test_updater_access.py @@ -446,6 +446,54 @@ def test_a_pending_change_is_read_again_within_a_minute(self): self.assertEqual(len(self.urls), 2, "an admin's finished access stack shows within a minute") +class ReaderUpdate(Base): + """A release's access.json carries the reader update (lambda/native-reader): + an access stack made before it asks an admin to apply it once; after that, + no release asks anyone for CoderHelmLogReader's reads in this account.""" + + def access_json(self): + t = AccessItem.access_json(self) + t["Resources"]["Reader"] = {"Type": "AWS::Lambda::Function", "Properties": {"FunctionName": {"Fn::Sub": "CoderHelmReader-${Stage}"}}} + return t + + def setUp(self): + Base.setUp(self) + 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()}]}}}} + u.fetch_template = lambda url, opener=None: self.body + + def stack(self, with_reader): + self.cfn.access_stack = {"StackId": "arn:aws:cloudformation:us-east-1:1:stack/coderhelm-prod-access/x", "StackName": "coderhelm-prod-access", "StackStatus": "UPDATE_COMPLETE"} + self.cfn.access_template = {"Metadata": {"CoderHelm": {"version": "v0.9.0", "kind": "access"}}, + "Resources": {"Access": {}, **({"Reader": {}} if with_reader else {})}} + + def test_an_access_stack_without_the_reader_update_is_asked_for_once(self): + self.stack(with_reader=False) + v = u.access_compute(self.env) + self.assertEqual(v["state"], "pending") + self.assertIn("Reader", v["resources"]) + self.assertIn(u.READER_LINE, v["summary"]) + self.assertEqual(v["apply"], "update") + + def test_once_applied_the_reader_update_is_never_asked_for_again(self): + self.stack(with_reader=True) + v = u.access_compute(self.env) + self.assertNotIn("Reader", v["resources"]) + self.assertNotIn(u.READER_LINE, v["summary"]) + + def test_an_install_without_an_access_stack_gets_it_with_the_one_link(self): + v = u.access_compute(self.env) + self.assertIn("Reader", v["resources"]) + self.assertTrue(v["link"]) + + def test_an_access_json_without_it_asks_nothing_about_it(self): + self.body = json.dumps(AccessItem.access_json(self)).encode() + self.cfn.deployed["Resources"]["ReleaseAssets"]["Properties"]["Files"][0]["Sha256"] = hashlib.sha256(self.body).hexdigest() + self.stack(with_reader=False) + self.assertNotIn("Reader", u.access_compute(self.env)["resources"]) + + class AccessForWhatIsUsed(Base): """A newer release's access, offered only for what the install uses, as an update of the access stack an admin already made (never a delete).""" diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 523cd265b..b3bbec045 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -3461,15 +3461,17 @@ def access_stack_origin(cfn, st): boundary stack of an install hardened from the CLI, which is never touched. Unreadable counts as something else.""" try: - meta = (deployed_template(cfn, st.get("StackId") or st.get("StackName")).get("Metadata") or {}).get("CoderHelm") or {} + template = deployed_template(cfn, st.get("StackId") or st.get("StackName")) except Exception as e: # noqa: BLE001 logger.warning(f"access stack template not read: {e}") - meta = {} + template = {} + meta = (template.get("Metadata") or {}).get("CoderHelm") or {} if meta.get("kind") == "access": out = {o.get("OutputKey"): o.get("OutputValue") for o in st.get("Outputs") or []} # The Version output is the release whose permissions the stack applied # (its template's metadata changes before an update has finished). - return {"kind": "access", "version": out.get("Version") or meta.get("version") or None} + return {"kind": "access", "version": out.get("Version") or meta.get("version") or None, + "reader": READER_RESOURCE in (template.get("Resources") or {})} return {"kind": "other", "version": None} @@ -3477,6 +3479,17 @@ def _iso(t): return t.isoformat() if hasattr(t, "isoformat") else (str(t) if t else None) +# The access stack's reader update (infra/lib/native/access-stack.ts, +# lambda/native-reader): after each update of the install's stack it brings +# the release's read-only permissions to CoderHelmLogReader in this account. +# An access stack made before it has none, so applying a release's access +# stack once is what adds it; from then on no release needs a person for +# that role's reads. +READER_RESOURCE = "Reader" +READER_LINE = ("adds the reader update: from then on each release brings its read-only permissions to " + "CoderHelmLogReader in this account by itself, with no update stack for anyone to create") + + def access_compute(env, cfn=None, iam=None, opener=None): """The install's access against what its release's access.json gives: what it would add, grouped by what uses it, what the install already has (and @@ -3544,6 +3557,9 @@ def access_compute(env, cfn=None, iam=None, opener=None): raise existing = None ours = bool(existing) and existing.get("kind") == "access" + if READER_RESOURCE in (access.get("Resources") or {}) and not (ours and existing.get("reader")): + changes.append({"resource": READER_RESOURCE, "lines": [READER_LINE]}) + rules.append(READER_LINE) view = { "state": "pending" if changes else "applied", "version": version, diff --git a/services/common/src/live/aws.rs b/services/common/src/live/aws.rs index 36c43bc78..aca382ac1 100644 --- a/services/common/src/live/aws.rs +++ b/services/common/src/live/aws.rs @@ -513,6 +513,35 @@ pub fn in_install_account(role_arn: &str, own: Option<&str>) -> bool { }) } +/// On a one-stack (native) self-hosted install: "1" when its access stack +/// keeps the `CoderHelmLogReader` role in the install's own account current +/// with each release (infra/lib/native/access-stack.ts, the reader update; +/// lambda/native-reader). Set by infra/lib/service-env.ts. +pub const READER_KEPT_ENV: &str = "INSTALL_READER_KEPT"; + +/// This install brings each release's read-only permissions to the +/// `CoderHelmLogReader` role in its own account by itself. +pub fn reader_kept_by_release() -> bool { + std::env::var(READER_KEPT_ENV).is_ok_and(|v| v.trim() == "1") +} + +/// Pure: `role_arn` is a reader whose permissions arrive with the release: +/// it is in the install's own account (`own`, the install's read role) and +/// the install keeps that account's reader current (`kept`). Nobody is ever +/// asked to update such a role. +pub fn reader_updates_with_release(role_arn: &str, own: Option<&str>, kept: bool) -> bool { + kept && in_install_account(role_arn, own) +} + +/// [`reader_updates_with_release`] for this process (its environment). +pub fn updates_with_release(role_arn: &str) -> bool { + reader_updates_with_release( + role_arn, + install_read_role().as_deref(), + reader_kept_by_release(), + ) +} + /// A session on the function's own role (its environment's credentials), /// in `region`. `None` outside Lambda. pub fn own_session(region: &str) -> Option { @@ -767,6 +796,18 @@ mod tests { assert!(in_install_account(&team, Some(OWN))); } + #[test] + fn only_a_reader_the_install_keeps_updates_with_the_release() { + let own = reader("111122223333").role_arn; + let other = reader("999988887777").role_arn; + assert!(reader_updates_with_release(&own, Some(OWN), true)); + // An install that doesn't keep the reader (installed from the CLI): + // its own account is updated like any other. + assert!(!reader_updates_with_release(&own, Some(OWN), false)); + assert!(!reader_updates_with_release(&other, Some(OWN), true)); + assert!(!reader_updates_with_release(&own, None, true)); + } + #[test] fn log_groups_must_be_names_or_real_prefixes() { let v = diff --git a/services/common/src/live/aws_account.rs b/services/common/src/live/aws_account.rs index 29ce02486..3de170341 100644 --- a/services/common/src/live/aws_account.rs +++ b/services/common/src/live/aws_account.rs @@ -173,6 +173,16 @@ impl AwsAccount { return None; } let region = s(item, "region"); + let permissions = item + .get("permissions_check") + .and_then(|v| v.as_s().ok()) + .and_then(|j| serde_json::from_str::(j).ok()) + .map(|mut c| { + // A check saved before the flag was set: the account is still + // the install's own, whose reader the release keeps current. + c.install_account |= super::aws::updates_with_release(&role_arn); + c + }); Some(AwsAccount { account, role_arn, @@ -190,10 +200,7 @@ impl AwsAccount { waf_log_key: s(item, "waf_log_key"), database_clusters: Vec::new(), warehouses: Vec::new(), - permissions: item - .get("permissions_check") - .and_then(|v| v.as_s().ok()) - .and_then(|j| serde_json::from_str(j).ok()), + permissions, abilities: Abilities { checked_at: s(item, "abilities_checked_at"), check_error: s(item, "abilities_error"), diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index 615f5b1d0..92248b66a 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -66,6 +66,9 @@ pub struct PermissionCheck { /// permissions arrive with the install's version updates, never from a /// stack a person launches. #[serde(default)] + /// Set only where the install keeps that account's CoderHelmLogReader + /// current with each release ([`super::aws::reader_updates_with_release`]), + /// so nobody is asked to update it and no update stack is offered. pub install_account: bool, /// Checked on the install's own read role (its stack keeps it current). #[serde(default)] @@ -96,7 +99,21 @@ pub struct Problem { } impl PermissionCheck { + /// A check of `target`'s role in this process: whether its account is + /// the install's own, with a reader the release keeps current + /// ([`super::aws::updates_with_release`]), is decided here, once. pub fn new(target: &AwsTarget, now: &str) -> Self { + Self::for_install( + target, + now, + super::aws::install_read_role().as_deref(), + super::aws::reader_kept_by_release(), + ) + } + + /// [`Self::new`] with the install's read role (`own`) and whether the + /// install keeps its own account's reader current (`kept`) given. + pub fn for_install(target: &AwsTarget, now: &str, own: Option<&str>, kept: bool) -> Self { PermissionCheck { account: target.account().to_string(), region: target.region.clone(), @@ -109,7 +126,7 @@ impl PermissionCheck { scp_blocks: Vec::new(), update_stack: UpdateStack::Unknown, error: String::new(), - install_account: false, + install_account: super::aws::reader_updates_with_release(&target.role_arn, own, kept), install_role: false, optional_missing: Vec::new(), optional_checked: false, @@ -220,7 +237,7 @@ impl PermissionCheck { "IAM's policy simulator says {role} isn't allowed {}.", self.missing.join(", "), ), - fix: "A version update that grants it adds it to the install's own role; nothing is needed in AWS.".into(), + fix: "Nothing to do: the release brings its read-only permissions to this role in the install's own account (the reader update in the access stack, run after each version update).".into(), }); } if !self.scp_blocks.is_empty() { @@ -637,7 +654,18 @@ pub async fn check( // The role every read of the account is made with ([`assume`]), also in // a self-hosted install's own account: the check and the reads can't // disagree about which role lacks what. - let mut c = PermissionCheck::new(target, now); + check_for(sts, target, actor, PermissionCheck::new(target, now)).await +} + +/// [`check`] filling in `c`, made for `target` ([`PermissionCheck::new`] or +/// [`PermissionCheck::for_install`]): what it says about the account (the +/// install's own or not) is kept whatever the role answers. +pub async fn check_for( + sts: &aws_sdk_sts::Client, + target: &AwsTarget, + actor: &str, + mut c: PermissionCheck, +) -> PermissionCheck { let session = match assume(sts, target, actor).await { Ok(s) => s, Err(e) => { @@ -645,12 +673,15 @@ pub async fn check( return c; } }; - check_with(session, target, now).await + check_with(session, target, c).await } /// [`check`] with a session on `target`'s role. -async fn check_with(session: TeamSession, target: &AwsTarget, now: &str) -> PermissionCheck { - let mut c = PermissionCheck::new(target, now); +async fn check_with( + session: TeamSession, + target: &AwsTarget, + mut c: PermissionCheck, +) -> PermissionCheck { c.works = true; match simulate(&session, target).await { Ok(results) => apply_simulation(&mut c, &results), @@ -720,7 +751,8 @@ mod tests { assert_eq!(v["install_account"], true); let p = c.problem(true).expect("says what happens"); assert_eq!(p.code, "install_update"); - assert!(p.fix.contains("version update that grants it")); + assert!(p.fix.starts_with("Nothing to do")); + assert!(p.fix.contains("the release brings")); assert!(!p.fix.contains("Update in AWS")); } diff --git a/services/common/src/notify/messages.rs b/services/common/src/notify/messages.rs index 245aad40e..1c7bdd109 100644 --- a/services/common/src/notify/messages.rs +++ b/services/common/src/notify/messages.rs @@ -73,47 +73,6 @@ pub fn release_notes_failed(owner: &str, repo: &str, tag: &str, error: &str) -> } } -/// Pure: this release needs new read-only permissions on the team's AWS -/// role in these accounts (account, how many are missing). Sent once per -/// set of permissions. -pub fn aws_permissions_update(accounts: &[(String, usize)], url: &str) -> Message { - let title = if accounts.len() == 1 { - format!( - "AWS account {} needs {} new read-only permission{}", - accounts[0].0, - accounts[0].1, - if accounts[0].1 == 1 { "" } else { "s" } - ) - } else { - format!( - "{} AWS accounts need new read-only permissions", - accounts.len() - ) - }; - let mut blocks = vec![ - Block::Text(Text::new(title.clone()).bold().color(Tone::Attention)), - Block::Text(Text::new( - "This CoderHelm release reads a little more from your AWS accounts (still read-only: it can list, describe and query, never change anything). Until an admin updates the CoderHelmLogReader role, the parts that need it are skipped and everything else keeps working.", - )), - ]; - if accounts.len() > 1 { - for (a, n) in accounts { - blocks.push(Block::Text( - Text::new(format!("Account {a}: {n} missing")).subtle(), - )); - } - } - blocks.push(Block::Text( - Text::new("An admin can update each account with one click on the AWS page.").subtle(), - )); - Message { - summary: title, - blocks, - buttons: vec![Button::new("Update permissions", url)], - full_width: false, - } -} - /// Pure: the message "Send test message" posts for a destination. pub fn test_message(destination: &str, dashboard_url: &str) -> Message { Message { @@ -163,30 +122,6 @@ mod tests { ) } - #[test] - fn the_permissions_notice_names_the_accounts_and_stays_read_only() { - let one = aws_permissions_update( - &[("111122223333".into(), 3)], - "https://coderhelm.example.com/settings/integrations/aws", - ); - assert_eq!( - one.summary, - "AWS account 111122223333 needs 3 new read-only permissions" - ); - assert_eq!( - one.buttons[0].url, - "https://coderhelm.example.com/settings/integrations/aws" - ); - let two = aws_permissions_update( - &[("111122223333".into(), 1), ("444455556666".into(), 2)], - "/x", - ); - assert!(two.summary.starts_with("2 AWS accounts")); - let text = format!("{:?}", two.blocks); - assert!(text.contains("444455556666") && text.contains("read-only")); - assert!(!text.contains('\u{2192}')); - } - #[test] fn the_review_reminder_teams_card_is_unchanged() { let m = reminder(&["ana".to_string(), "bo".to_string()]); diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index f927fd289..99cfbba24 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -268,12 +268,12 @@ pub fn aws_state(a: &AwsAccount) -> CardState { { let n = p.missing.len(); let s_ = if n == 1 { "" } else { "s" }; - // The install's own account gets them with the next version update: - // nothing to do in AWS. + // The install's own account: the release brings them to its reader + // (the access stack's reader update), so there is nothing to do. if install_account(a) { return cs( "connected", - format!("{n} read-only permission{s_} arrive with the next Coderhelm update. Nothing is needed in AWS."), + format!("Updates with the release: {n} read-only permission{s_} arrive with this install's version updates. Nothing to do."), "manage", ); } @@ -314,10 +314,9 @@ pub fn aws_missing(a: &AwsAccount) -> Vec<&'static str> { out } -/// The account's last check ran on the install's own role (a check from -/// before every read went through the team's role). Reads of the account, -/// the install's own included, are made with the team's role, so its update -/// stack is offered everywhere once the account is checked again. +/// The account is the install's own, whose CoderHelmLogReader the release +/// keeps current (`live::aws::updates_with_release`): never an update stack, +/// never a person's step. pub fn install_account(a: &AwsAccount) -> bool { a.permissions.as_ref().is_some_and(|p| p.install_account) } diff --git a/services/worker/src/passes/aws_permissions.rs b/services/worker/src/passes/aws_permissions.rs index cf0ed4d31..7f94ac2b0 100644 --- a/services/worker/src/passes/aws_permissions.rs +++ b/services/worker/src/passes/aws_permissions.rs @@ -1,8 +1,13 @@ //! Daily: checks every connected AWS account's CoderHelmLogReader role //! against the permissions this release uses -//! (`common::live::permissions`), saves the result for the AWS page, and -//! tells each team once per new set of permissions when an account needs -//! the update (where the team's notifications post: Slack, Teams). +//! (`common::live::permissions`) and saves the result for the AWS page. +//! +//! It never sends a message. An account that needs new read-only +//! permissions is one quiet item on the AWS page, with its one-click update +//! stack; the install's own account on a one-stack install needs nothing at +//! all, because the release brings them there itself (the access stack's +//! reader update, lambda/native-reader). A push for this was the incident +//! `rq_reader_reads_arrive_with_the_release`. //! //! The same sweep moves data sources off the script-made //! `CoderhelmReadOnly` role onto the account's role stack @@ -12,27 +17,20 @@ //! The same sweep sends a re-check of every run waiting for the role's //! reads (`role_wait`), so a run whose fast re-checks are over still goes //! on the day the role stack is updated. -//! -//! "Once" is a team record (`AWS_PERMS_NOTICE`) holding the permissions id -//! it was told about, written with a condition before the message is sent, -//! so two sweeps never post twice. use std::collections::BTreeMap; use aws_sdk_dynamodb::types::AttributeValue; use common::live::aws_account::{self, AwsAccount}; -use common::live::permissions::{self, PermissionCheck}; +use common::live::permissions; use tracing::{info, warn}; use crate::WorkerState; -pub const NOTICE_SK: &str = "AWS_PERMS_NOTICE"; - #[derive(Debug, Default)] pub struct Report { pub accounts: usize, pub need_update: usize, - pub teams_told: usize, /// Data sources moved onto their account's role stack. pub sources_moved: usize, } @@ -72,57 +70,6 @@ async fn accounts_by_team( Ok(out) } -/// Pure: whether a team that was last told about `told` should be told now. -pub fn should_tell(checks: &[PermissionCheck], told: Option<&str>) -> bool { - let id = common::log_reader::permissions_id(); - told != Some(id.as_str()) && checks.iter().any(needs_people) -} - -/// An account a person has to update: the install's own gets its -/// permissions with the next Coderhelm update, so it is never asked. -fn needs_people(c: &PermissionCheck) -> bool { - c.status() == "update_needed" && !c.install_account -} - -/// Claims this permissions id for the team: true only for the one sweep that -/// writes it first. -async fn claim_notice(state: &WorkerState, team_id: &str) -> bool { - let id = common::log_reader::permissions_id(); - state - .dynamo - .put_item() - .table_name(&state.config.aws_insights_table_name) - .item("pk", AttributeValue::S(team_id.into())) - .item("sk", AttributeValue::S(NOTICE_SK.into())) - .item("permissions_id", AttributeValue::S(id.clone())) - .item( - "told_at", - AttributeValue::S(chrono::Utc::now().to_rfc3339()), - ) - .condition_expression("attribute_not_exists(pk) OR permissions_id <> :id") - .expression_attribute_values(":id", AttributeValue::S(id)) - .send() - .await - .is_ok() -} - -async fn told(state: &WorkerState, team_id: &str) -> Option { - state - .dynamo - .get_item() - .table_name(&state.config.aws_insights_table_name) - .key("pk", AttributeValue::S(team_id.into())) - .key("sk", AttributeValue::S(NOTICE_SK.into())) - .send() - .await - .ok()? - .item()? - .get("permissions_id")? - .as_s() - .ok() - .cloned() -} - /// Moves each of the team's data sources that still reads through a /// script-made role onto its account's role stack, when the stack's role /// reads it end to end; the rest stay as they are and are tried again on @@ -170,7 +117,6 @@ pub async fn run(state: &WorkerState) -> Result { let mut report = Report::default(); let now = chrono::Utc::now().to_rfc3339(); for (team_id, accounts) in &teams { - let mut checks = Vec::new(); for a in accounts { let c = permissions::check(&state.sts, &a.target(), "permissions-check", &now).await; if let Err(e) = aws_account::save_permissions( @@ -184,59 +130,20 @@ pub async fn run(state: &WorkerState) -> Result { warn!(team_id, account = %a.account, error = %e, "Could not save the permissions check"); } report.accounts += 1; - if c.status() == "update_needed" { + // The install's own account, whose reader the release keeps + // current, never needs a person. + if c.status() == "update_needed" && !c.install_account { report.need_update += 1; } - checks.push(c); } report.sources_moved += move_sources(state, team_id, accounts).await; // Runs waiting for the role's reads (`awaiting_setup`) check the // role again now: the daily check after their fast re-checks. super::role_wait::wake(state, team_id, None).await; - let last = told(state, team_id).await; - if !should_tell(&checks, last.as_deref()) || !claim_notice(state, team_id).await { - continue; - } - let cipher = common::mcp_credentials::Kms { - client: &state.kms, - key_id: "", - }; - let channels = common::log_findings::channels( - &state.dynamo, - &cipher, - &state.config.settings_table_name, - team_id, - ) - .await; - if channels.is_empty() { - continue; - } - let needing: Vec<(String, usize)> = checks - .iter() - .filter(|c| needs_people(c)) - .map(|c| (c.account.clone(), c.missing.len())) - .collect(); - let url = format!( - "{}/settings/integrations/aws", - super::skills::app_url(&state.config.stage) - ); - let msg = common::notify::messages::aws_permissions_update(&needing, &url); - common::notify::deliver_recorded( - &common::notify::Http(&state.http), - &channels, - &msg, - "aws_permissions", - &state.dynamo, - &state.config.settings_table_name, - team_id, - ) - .await; - report.teams_told += 1; } info!( accounts = report.accounts, need_update = report.need_update, - teams_told = report.teams_told, sources_moved = report.sources_moved, "AWS permissions sweep" ); @@ -245,33 +152,19 @@ pub async fn run(state: &WorkerState) -> Result { #[cfg(test)] mod tests { - use super::*; - use common::live::aws::AwsTarget; - - fn check(missing: &[&str]) -> PermissionCheck { - let t = AwsTarget { - role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), - external_id: "x".into(), - region: "us-east-1".into(), - ..Default::default() - }; - let mut c = PermissionCheck::new(&t, "t"); - c.works = true; - c.missing = missing.iter().map(|s| s.to_string()).collect(); - c - } - + /// The sweep only checks and saves: no message of any kind, on any + /// channel, for an account that needs new read-only permissions. #[test] - fn a_team_is_told_once_per_set_of_permissions() { - let id = common::log_reader::permissions_id(); - let need = vec![check(&[]), check(&["ecs:ListTasks"])]; - assert!(should_tell(&need, None)); - assert!(should_tell(&need, Some("00000000"))); - assert!(!should_tell(&need, Some(&id))); - assert!(!should_tell(&[check(&[])], None)); - // The install's own account is never asked to update. - let mut own = need[0].clone(); - own.install_account = true; - assert!(!should_tell(&[own], None)); + fn the_sweep_sends_nothing() { + let src = include_str!("aws_permissions.rs"); + let code = &src[..src.find("#[cfg(test)]").unwrap()]; + for gone in [ + "notify::", + "deliver", + "log_findings::channels", + "aws_permissions_update", + ] { + assert!(!code.contains(gone), "{gone}"); + } } } diff --git a/services/worker/src/passes/incidents/rq_reader_reads_arrive_with_the_release.rs b/services/worker/src/passes/incidents/rq_reader_reads_arrive_with_the_release.rs new file mode 100644 index 000000000..27dfccaec --- /dev/null +++ b/services/worker/src/passes/incidents/rq_reader_reads_arrive_with_the_release.rs @@ -0,0 +1,197 @@ +//! rq. A self-hosted install's owner got a push alert: "AWS account needs 1 new read-only permission ... Until an +//! admin updates the CoderHelmLogReader role, the parts that need it are +//! skipped." The account was the install's own. `PermissionCheck`'s +//! `install_account` was only ever set in tests (the builder always wrote +//! false), so the daily sweep treated that account like any other: it +//! posted the alert and the AWS page offered the one-click update stack. +//! And nothing in the release brought the reads to that role: since every +//! team read is made as CoderHelmLogReader (rk), it fell behind each release. +//! +//! Guarantee: no push for new read-only permissions, ever (the sweep sends +//! nothing); another account shows them only as the AWS page's quiet item +//! with its one-click stack; the install's own account on a one-stack +//! install is marked by the check's own builder, shows nothing to do, and +//! gets the reads from the access stack's reader update after each update +//! of the install's stack (lambda/native-reader). + +use common::aws_role_reads; +use common::live::aws::AwsTarget; +use common::live::aws_account::AwsAccount; +use common::live::permissions::{self, PermissionCheck, Simulated}; + +const OWN_ACCOUNT: &str = "111122223333"; +const OTHER_ACCOUNT: &str = "999988887777"; +/// The install's own gateway role (INSTALL_OWN_ROLE_ARN), in its account. +const INSTALL_ROLE: &str = "arn:aws:iam::111122223333:role/coderhelm-prod-ServiceRole-EXAMPLE"; +const TEMPLATE: &str = + "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml"; +const NOW: &str = "2026-11-19T09:00:00Z"; + +fn reader(account: &str) -> AwsTarget { + AwsTarget { + role_arn: format!("arn:aws:iam::{account}:role/CoderHelmLogReader"), + external_id: "team-private-id".into(), + region: "us-east-1".into(), + ..Default::default() + } +} + +/// An STS that answers nothing (a closed local port), as in rk. +fn dead_sts() -> aws_sdk_sts::Client { + use aws_sdk_sts::config::{BehaviorVersion, Credentials, Region}; + aws_sdk_sts::Client::from_conf( + aws_sdk_sts::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new("us-east-1")) + .endpoint_url("http://127.0.0.1:9") + .retry_config(aws_sdk_sts::config::retry::RetryConfig::disabled()) + .credentials_provider(Credentials::new("caller", "caller", None, None, "test")) + .build(), + ) +} + +/// What the live check found once the role could be taken on: this +/// release's `ecs:DescribeTasks` is missing, as in the alert (1 new). +fn behind(mut c: PermissionCheck) -> PermissionCheck { + c.works = true; + permissions::apply_simulation( + &mut c, + &[Simulated { + action: "ecs:DescribeTasks".into(), + allowed: false, + boundary_allows: None, + org_allows: None, + }], + ); + c +} + +fn account_with(t: &AwsTarget, c: PermissionCheck) -> AwsAccount { + AwsAccount { + account: t.account().to_string(), + role_arn: t.role_arn.clone(), + external_id: t.external_id.clone(), + region: t.region.clone(), + status: "connected".into(), + permissions: Some(c), + ..Default::default() + } +} + +#[tokio::test] +async fn the_checks_own_builder_marks_the_install_account() { + // The real path the sweep, the AWS page and a waiting run's re-check + // take (`permissions::check` is `check_for` with this process's install + // role): before, `install_account` came back false for the install's + // own account whatever happened. + let own = reader(OWN_ACCOUNT); + let c = permissions::check_for( + &dead_sts(), + &own, + "permissions-check", + PermissionCheck::for_install(&own, NOW, Some(INSTALL_ROLE), true), + ) + .await; + assert!(!c.works, "the closed STS took the role on"); + assert!( + c.install_account, + "the install's own account, kept by the release" + ); + // Another account, and an install that doesn't keep its reader (from + // the CLI): updated by a person like any other. + let other = reader(OTHER_ACCOUNT); + let c = permissions::check_for( + &dead_sts(), + &other, + "permissions-check", + PermissionCheck::for_install(&other, NOW, Some(INSTALL_ROLE), true), + ) + .await; + assert!(!c.install_account); + assert!(!PermissionCheck::for_install(&own, NOW, Some(INSTALL_ROLE), false).install_account); + assert!(!PermissionCheck::for_install(&own, NOW, None, true).install_account); +} + +#[test] +fn the_install_account_shows_nothing_to_do() { + let own = reader(OWN_ACCOUNT); + let c = behind(PermissionCheck::for_install( + &own, + NOW, + Some(INSTALL_ROLE), + true, + )); + assert_eq!(c.status(), "update_needed"); + // No update stack to launch, on the account or on any optional read. + let v = c.view(false, TEMPLATE); + assert!(v["update"].is_null(), "{v}"); + assert_eq!(v["install_account"], true); + for a in v["abilities"].as_array().unwrap() { + assert!(a["turn_on_url"].is_null(), "{a}"); + } + let p = c.problem(false).expect("says what happens"); + assert!(p.fix.starts_with("Nothing to do"), "{}", p.fix); + assert!(p.fix.contains("the release brings")); + // And no setup item: the role's own reads are the release's job. + assert!(aws_role_reads::role_update(&account_with(&own, c), None, 0, TEMPLATE).is_none()); +} + +#[test] +fn another_account_is_one_quiet_item_with_its_one_click_stack() { + let other = reader(OTHER_ACCOUNT); + let c = behind(PermissionCheck::for_install( + &other, + NOW, + Some(INSTALL_ROLE), + true, + )); + let v = c.view(false, TEMPLATE); + let url = v["update"]["url"] + .as_str() + .expect("the one-click update stack"); + assert!(url.contains("coderhelm-log-reader-update.yaml"), "{url}"); + assert_eq!(v["update"]["sign_in_account"], OTHER_ACCOUNT); + let item = aws_role_reads::role_update(&account_with(&other, c), None, 0, TEMPLATE) + .expect("the AWS role reads item"); + assert!(item + .reasons + .iter() + .any(|r| r.contains("older than this release"))); +} + +#[test] +fn the_daily_sweep_sends_no_message_of_any_kind() { + let src = include_str!("../aws_permissions.rs"); + let code = &src[..src.find("#[cfg(test)]").unwrap()]; + for push in [ + "notify::", + "deliver", + "log_findings::channels", + "aws_permissions_update", + "AWS_PERMS_NOTICE", + ] { + assert!(!code.contains(push), "the sweep still pushes: {push}"); + } + // It still checks and saves every account for the AWS page. + assert!(code.contains("permissions::check(") && code.contains("save_permissions(")); +} + +#[test] +fn the_release_brings_the_reads_to_the_install_accounts_reader() { + // The access stack's reader update, as the release ships it: after each + // update of the install's stack it creates or updates + // CoderHelmLogReaderUpdate-release from the running release's update + // template (lambda/tests/test_native_reader.py and + // infra/test/native-access.test.ts check it end to end). + let keeper = include_str!("../../../../../lambda/native-reader/handler.py"); + assert!(keeper.contains(r#"STACK = "CoderHelmLogReaderUpdate-release""#)); + assert!(keeper.contains(r#"TEMPLATE = "coderhelm-log-reader-update.yaml""#)); + let stack = include_str!("../../../../../infra/lib/native/access-stack.ts"); + assert!(stack.contains(r#"status: ["UPDATE_COMPLETE"]"#)); + assert!(stack.contains("lambda/native-reader/handler.py")); + // The services learn it from the one-stack install's environment. + let env = include_str!("../../../../../infra/lib/service-env.ts"); + assert!(env.contains(r#"if (cfg.native) env.INSTALL_READER_KEPT = "1";"#)); + assert_eq!(common::live::aws::READER_KEPT_ENV, "INSTALL_READER_KEPT"); +}